Projekt

Obecné

Profil

Stáhnout (6.79 KB) Statistiky
| Větev: | Tag: | Revize:
1 24e1c89d Vojtěch Bartička
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 5a08541d Vojtěch Bartička
using AutoMapper;
13
using Models.Users;
14 3c185841 Vojtěch Bartička
using Ganss.XSS;
15 24e1c89d Vojtěch Bartička
16
namespace Core.Services.DocumentService
17
{
18
    public class DocumentServiceEF : IDocumentService
19
    {
20
        private readonly DatabaseContext databaseContext;
21
        private readonly ILogger logger;
22 5a08541d Vojtěch Bartička
        private readonly IMapper mapper;
23 24e1c89d Vojtěch Bartička
24 5a08541d Vojtěch Bartička
        public DocumentServiceEF(DatabaseContext databaseContext, ILogger logger, IMapper mapper)
25 24e1c89d Vojtěch Bartička
        {
26
            this.databaseContext = databaseContext;
27
            this.logger = logger;
28 5a08541d Vojtěch Bartička
            this.mapper = mapper;
29 24e1c89d Vojtěch Bartička
        }
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 ceb95b98 Vojtěch Bartička
            int requiredAnnotations = int.Parse(databaseContext.ConfigurationItems.Single(ci => ci.Key == Constants.Constants.RequiredAnnotationsKey).Value);
44 005202c6 Vojtěch Bartička
45 24e1c89d Vojtěch Bartička
            foreach (var documentInfo in request.Documents)
46
            {
47 52fe46f9 Vojtěch Bartička
                if (documentInfo.Format == Models.Enums.EAddDocumentFormat.TEXTFILE)
48 24e1c89d Vojtěch Bartička
                {
49 7b2e66d3 Vojtěch Bartička
                    // TODO hardcoded UTF-8 - maybe do something smarter
50
                    var documentContent = Encoding.UTF8.GetString(Convert.FromBase64String(documentInfo.Content));
51 ceb95b98 Vojtěch Bartička
                    SaveDocument(documentContent, user, documentInfo.Name, requiredAnnotations);
52 24e1c89d Vojtěch Bartička
                }
53 7b2e66d3 Vojtěch Bartička
                else if (documentInfo.Format == Models.Enums.EAddDocumentFormat.ZIP)
54 24e1c89d Vojtěch Bartička
                {
55
                    var (names, contents) = UnzipDocuments(documentInfo.Content);
56
                    for (int i = 0; i < names.Count; i++)
57
                    {
58 ceb95b98 Vojtěch Bartička
                        SaveDocument(contents[i], user, names[i], requiredAnnotations);
59 24e1c89d Vojtěch Bartička
                    }
60
                }
61
            }
62
        }
63
64
        /// <summary>
65
        /// 
66
        /// </summary>
67
        /// <param name="base64encoded"></param>
68
        /// <returns></returns>
69
        private (List<string> Names, List<string> Contents) UnzipDocuments(string base64encoded)
70
        {
71
            List<string> names = new();
72
            List<string> contents = new();
73
74
            byte[] decoded = Convert.FromBase64String(base64encoded);
75
76
            using (var zipStream = new MemoryStream(decoded))
77
            using (var zipArchive = new ZipArchive(zipStream))
78
            {
79
                foreach (var entry in zipArchive.Entries)
80
                {
81
                    names.Add(entry.Name);
82
                    using (var streamReader = new StreamReader(entry.Open()))
83
                    {
84
                        string text = streamReader.ReadToEnd();
85
                        contents.Add(text);
86
                    }
87
                }
88
            }
89
90
            return (names, contents);
91
        }
92
93 ceb95b98 Vojtěch Bartička
        private void SaveDocument(string content, User userAdded, string documentName, int requiredAnnotations)
94 24e1c89d Vojtěch Bartička
        {
95
            DocumentContent documentContent = new DocumentContent()
96
            {
97
                Content = content
98
            };
99
100
            Document document = new Document()
101
            {
102
                DateAdded = DateTime.Now,
103
                Content = documentContent,
104
                UserAdded = userAdded,
105
                Name = documentName,
106
                Length = documentContent.Content.Length,
107 ceb95b98 Vojtěch Bartička
                RequiredAnnotations = requiredAnnotations
108 24e1c89d Vojtěch Bartička
            };
109
110
            databaseContext.DocumentContents.Add(documentContent);
111
            databaseContext.Documents.Add(document);
112 5adba4c4 Vojtěch Bartička
            databaseContext.SaveChanges();
113 24e1c89d Vojtěch Bartička
        }
114
115 42c654f6 Vojtěch Bartička
        public DocumentListResponse GetDocuments(int pageIndex, int pageSize)
116 24e1c89d Vojtěch Bartička
        {
117 42c654f6 Vojtěch Bartička
            var firstIndex = pageIndex * pageSize;
118 24e1c89d Vojtěch Bartička
            var documents = databaseContext.Documents.Select(d => d).ToList();
119
            var totalCount = documents.Count;
120 42c654f6 Vojtěch Bartička
            var pageCount = totalCount / pageSize;
121 24e1c89d Vojtěch Bartička
            if (pageCount == 0 && totalCount > 0)
122
            {
123
                pageCount = 1;
124
            }
125
126 7bbe8f15 Vojtěch Bartička
            if (firstIndex > documents.Count - 1)
127
            {
128
                throw new Exception("Page index or page size too large");
129
            }
130
131 42c654f6 Vojtěch Bartička
            if (firstIndex + pageSize > documents.Count - 1)
132 7bbe8f15 Vojtěch Bartička
            {
133 42c654f6 Vojtěch Bartička
                pageSize = documents.Count - firstIndex;
134 7bbe8f15 Vojtěch Bartička
            }
135
136 24e1c89d Vojtěch Bartička
            List<DocumentListInfo> documentInfos = new List<DocumentListInfo>();
137 42c654f6 Vojtěch Bartička
            foreach (var document in documents.GetRange(firstIndex, pageSize))
138 24e1c89d Vojtěch Bartička
            {
139 5a08541d Vojtěch Bartička
                var annotatingUsers = databaseContext.Annotations.Where(a => a.Document == document).Select(a => a.User).ToList();
140
                List<UserInfo> annotatingUsersDto = annotatingUsers.Select(a => mapper.Map<UserInfo>(a)).ToList();
141
142
                DocumentListInfo dai = mapper.Map<DocumentListInfo>(document);
143
                dai.AnnotatingUsers = annotatingUsersDto;
144 7bbe8f15 Vojtěch Bartička
                documentInfos.Add(dai);
145 24e1c89d Vojtěch Bartička
            }
146
147
            return new DocumentListResponse()
148
            {
149
                PageCount = pageCount,
150 42c654f6 Vojtěch Bartička
                PageIndex = pageIndex,
151 24e1c89d Vojtěch Bartička
                TotalCount = totalCount,
152
                Documents = documentInfos
153
            };
154
        }
155
156 5adba4c4 Vojtěch Bartička
        public void SetRequiredAnnotationsForDocuments(SetRequiredAnnotationsRequest request)
157
        {
158
            var documents = databaseContext.Documents.Where(d => request.DocumentIds.Contains(d.Id));
159
            foreach (var doc in documents)
160
            {
161
                doc.RequiredAnnotations = request.RequiredAnnotations;
162
            }
163
            databaseContext.SaveChanges();
164
        }
165 0a6d22b7 Vojtěch Bartička
166
        public void SetRequiredAnnotationsGlobal(int requiredAnnotations)
167
        {
168 ceb95b98 Vojtěch Bartička
            var requiredAnnotationsItem = databaseContext.ConfigurationItems.Single(ci => ci.Key == Constants.Constants.RequiredAnnotationsKey);
169
            requiredAnnotationsItem.Value = requiredAnnotations.ToString();
170
            databaseContext.SaveChanges();
171 0a6d22b7 Vojtěch Bartička
        }
172
173 ceb95b98 Vojtěch Bartička
        public int GetRequiredAnnotationsGlobal()
174
        {
175
            var requiredAnnotationsItem = databaseContext.ConfigurationItems.Single(ci => ci.Key == Constants.Constants.RequiredAnnotationsKey);
176
            return int.Parse(requiredAnnotationsItem.Value);
177
        }
178 24e1c89d Vojtěch Bartička
    }
179
}