Projekt

Obecné

Profil

Stáhnout (5.68 KB) Statistiky
| Větev: | Tag: | Revize:
1
using Core.Contexts;
2
using Core.Entities;
3
using Models.Documents;
4
using Serilog;
5
using System;
6
using System.Collections.Generic;
7
using System.IO.Compression;
8
using System.Linq;
9
using System.Text;
10
using System.Threading.Tasks;
11
using System.Web;
12
using AutoMapper;
13
using Models.Users;
14
using Ganss.XSS;
15

    
16
namespace Core.Services.DocumentService
17
{
18
    public class DocumentServiceEF : IDocumentService
19
    {
20
        private readonly DatabaseContext databaseContext;
21
        private readonly ILogger logger;
22
        private readonly IMapper mapper;
23

    
24
        public DocumentServiceEF(DatabaseContext databaseContext, ILogger logger, IMapper mapper)
25
        {
26
            this.databaseContext = databaseContext;
27
            this.logger = logger;
28
            this.mapper = mapper;
29
        }
30

    
31
        /// <summary>
32
        /// Adds the documents in request to the database
33
        /// </summary>
34
        /// <param name="request">request</param>
35
        /// <param name="userId">GUID of the user</param>
36
        /// <exception cref="InvalidOperationException">No User with passed GUID</exception>
37
        /// <exception cref="FormatException">Error decoding BASE64 content</exception>
38
        /// <exception cref="InvalidDataException">Zip file has wrong format</exception>
39
        /// <exception cref="IOException">Error reading entries from the zip file</exception>
40
        public void AddDocuments(DocumentAddRequest request, Guid userId)
41
        {
42
            User user = databaseContext.Users.Single(u => u.Id == userId);
43

    
44
            foreach (var documentInfo in request.Documents)
45
            {
46
                if (documentInfo.Format == Models.Enums.EAddDocumentFormat.TEXTFILE)
47
                {
48
                    // TODO hardcoded UTF-8 - maybe do something smarter
49
                    var documentContent = Encoding.UTF8.GetString(Convert.FromBase64String(documentInfo.Content));
50
                    SaveDocument(documentContent, user, documentInfo.Name);
51
                }
52
                else if (documentInfo.Format == Models.Enums.EAddDocumentFormat.ZIP)
53
                {
54
                    var (names, contents) = UnzipDocuments(documentInfo.Content);
55
                    for (int i = 0; i < names.Count; i++)
56
                    {
57
                        SaveDocument(contents[i], user, names[i]);
58
                    }
59
                }
60
            }
61
        }
62

    
63
        /// <summary>
64
        /// 
65
        /// </summary>
66
        /// <param name="base64encoded"></param>
67
        /// <returns></returns>
68
        private (List<string> Names, List<string> Contents) UnzipDocuments(string base64encoded)
69
        {
70
            List<string> names = new();
71
            List<string> contents = new();
72

    
73
            byte[] decoded = Convert.FromBase64String(base64encoded);
74

    
75
            using (var zipStream = new MemoryStream(decoded))
76
            using (var zipArchive = new ZipArchive(zipStream))
77
            {
78
                foreach (var entry in zipArchive.Entries)
79
                {
80
                    names.Add(entry.Name);
81
                    using (var streamReader = new StreamReader(entry.Open()))
82
                    {
83
                        string text = streamReader.ReadToEnd();
84
                        contents.Add(text);
85
                    }
86
                }
87
            }
88

    
89
            return (names, contents);
90
        }
91

    
92
        private void SaveDocument(string content, User userAdded, string documentName)
93
        {
94
            DocumentContent documentContent = new DocumentContent()
95
            {
96
                Content = content
97
            };
98

    
99
            Document document = new Document()
100
            {
101
                DateAdded = DateTime.Now,
102
                Content = documentContent,
103
                UserAdded = userAdded,
104
                Name = documentName,
105
                Length = documentContent.Content.Length,
106
                RequiredAnnotations = 3                     // TODO this is only for beta testing purposes
107
            };
108

    
109
            databaseContext.DocumentContents.Add(documentContent);
110
            databaseContext.Documents.Add(document);
111
            databaseContext.SaveChanges();                  // Maybe do this after all the documents are added
112
        }
113

    
114
        public DocumentListResponse GetDocuments(int pageIndex, int pageSize)
115
        {
116
            var firstIndex = pageIndex * pageSize;
117
            var documents = databaseContext.Documents.Select(d => d).ToList();
118
            var totalCount = documents.Count;
119
            var pageCount = totalCount / pageSize;
120
            if (pageCount == 0 && totalCount > 0)
121
            {
122
                pageCount = 1;
123
            }
124

    
125
            if (firstIndex > documents.Count - 1)
126
            {
127
                throw new Exception("Page index or page size too large");
128
            }
129

    
130
            if (firstIndex + pageSize > documents.Count - 1)
131
            {
132
                pageSize = documents.Count - firstIndex;
133
            }
134

    
135
            List<DocumentListInfo> documentInfos = new List<DocumentListInfo>();
136
            foreach (var document in documents.GetRange(firstIndex, pageSize))
137
            {
138
                var annotatingUsers = databaseContext.Annotations.Where(a => a.Document == document).Select(a => a.User).ToList();
139
                List<UserInfo> annotatingUsersDto = annotatingUsers.Select(a => mapper.Map<UserInfo>(a)).ToList();
140

    
141
                DocumentListInfo dai = mapper.Map<DocumentListInfo>(document);
142
                dai.AnnotatingUsers = annotatingUsersDto;
143
                documentInfos.Add(dai);
144
            }
145

    
146
            return new DocumentListResponse()
147
            {
148
                PageCount = pageCount,
149
                PageIndex = pageIndex,
150
                TotalCount = totalCount,
151
                Documents = documentInfos
152
            };
153
        }
154

    
155
    }
156
}
(1-1/2)