Projekt

Obecné

Profil

Stáhnout (9.19 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
using Microsoft.EntityFrameworkCore;
16

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

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

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

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

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

    
75
            byte[] decoded = Convert.FromBase64String(base64encoded);
76

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

    
91
            return (names, contents);
92
        }
93

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

    
101
            Document document = new Document()
102
            {
103
                DateAdded = DateTime.Now,
104
                Content = documentContent,
105
                UserAdded = userAdded,
106
                Name = documentName,
107
                Length = documentContent.Content.Length,
108
                RequiredAnnotations = requiredAnnotations
109
            };
110

    
111
            databaseContext.DocumentContents.Add(documentContent);
112
            databaseContext.Documents.Add(document);
113
            databaseContext.SaveChanges();
114
        }
115

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

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

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

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

    
143
                // Include annotation state
144
                foreach (var annotatingUser in annotatingUsers)
145
                {
146
                    var annotation = databaseContext.Annotations
147
                        .Include(a => a.Document)
148
                        .Single(a => a.Document == document && a.User == annotatingUser);
149
                    var dui = mapper.Map<DocumentUserInfo>(annotatingUser);
150
                    dui.State = annotation.State;
151
                    annotatingUsersDto.Add(dui);
152
                }
153

    
154
                DocumentListInfo dli = mapper.Map<DocumentListInfo>(document);
155
                dli.AnnotatingUsers = annotatingUsersDto;
156

    
157
                dli.FinalizedExists = databaseContext.FinalAnnotations.Any(fa => fa.Document == document);
158
                if (dli.FinalizedExists)
159
                {
160
                    var finalizedAnnotation = databaseContext.FinalAnnotations
161
                        .Include(fa => fa.Annotations)
162
                        .ThenInclude(a => a.User)
163
                        .Single(fa => fa.Document == document);
164

    
165
                    dli.FinalizedState = finalizedAnnotation.State;
166
                    dli.FinalAnnotations = new();
167

    
168
                    foreach (var annotation in finalizedAnnotation.Annotations)
169
                    {
170
                        dli.FinalAnnotations.Add(new()
171
                        {
172
                            AnnotationId = annotation.Id,
173
                            UserId = annotation.User.Id,
174
                            Username = annotation.User.Username,
175
                            UserFirstName = annotation.User.Name,
176
                            UserSurname = annotation.User.Surname
177
                        });
178
                    }
179

    
180
                }
181

    
182
                documentInfos.Add(dli);
183
            }
184

    
185
            return new DocumentListResponse()
186
            {
187
                PageCount = pageCount,
188
                PageIndex = pageIndex,
189
                TotalCount = totalCount,
190
                Documents = documentInfos
191
            };
192
        }
193

    
194
        public void SetRequiredAnnotationsForDocuments(SetRequiredAnnotationsRequest request)
195
        {
196
            var documents = databaseContext.Documents.Where(d => request.DocumentIds.Contains(d.Id));
197
            foreach (var doc in documents)
198
            {
199
                doc.RequiredAnnotations = request.RequiredAnnotations;
200
            }
201
            databaseContext.SaveChanges();
202
        }
203

    
204
        public void SetRequiredAnnotationsGlobal(int requiredAnnotations)
205
        {
206
            var requiredAnnotationsItem = databaseContext.ConfigurationItems.Single(ci => ci.Key == Constants.Constants.RequiredAnnotationsKey);
207
            requiredAnnotationsItem.Value = requiredAnnotations.ToString();
208
            databaseContext.SaveChanges();
209
        }
210

    
211
        public int GetRequiredAnnotationsGlobal()
212
        {
213
            var requiredAnnotationsItem = databaseContext.ConfigurationItems.Single(ci => ci.Key == Constants.Constants.RequiredAnnotationsKey);
214
            return int.Parse(requiredAnnotationsItem.Value);
215
        }
216

    
217
        public DocumentPreviewResponse GetDocumentPreview(Guid documentId)
218
        {
219
            try
220
            {
221
                var document = databaseContext.Documents.Include(d => d.Content).Single(d => d.Id == documentId);
222
                HtmlSanitizer sanitizer = new HtmlSanitizer();
223
                sanitizer.AllowedAttributes.Clear();
224
                if (sanitizer.AllowedTags.Contains("img"))
225
                {
226
                    sanitizer.AllowedTags.Remove("img");
227
                }
228
                return new DocumentPreviewResponse()
229
                {
230
                    Content = sanitizer.Sanitize(document.Content.Content)
231
                };
232
            }
233
            catch (InvalidOperationException e)
234
            {
235
                throw new InvalidOperationException("Document not found");
236
            }
237
        }
238
    }
239
}
(1-1/2)