Projekt

Obecné

Profil

Stáhnout (5.66 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 24e1c89d Vojtěch Bartička
15
namespace Core.Services.DocumentService
16
{
17
    public class DocumentServiceEF : IDocumentService
18
    {
19
        private readonly DatabaseContext databaseContext;
20
        private readonly ILogger logger;
21 5a08541d Vojtěch Bartička
        private readonly IMapper mapper;
22 24e1c89d Vojtěch Bartička
23 5a08541d Vojtěch Bartička
        public DocumentServiceEF(DatabaseContext databaseContext, ILogger logger, IMapper mapper)
24 24e1c89d Vojtěch Bartička
        {
25
            this.databaseContext = databaseContext;
26
            this.logger = logger;
27 5a08541d Vojtěch Bartička
            this.mapper = mapper;
28 24e1c89d Vojtěch Bartička
        }
29
30
        /// <summary>
31
        /// Adds the documents in request to the database
32
        /// </summary>
33
        /// <param name="request">request</param>
34
        /// <param name="userId">GUID of the user</param>
35
        /// <exception cref="InvalidOperationException">No User with passed GUID</exception>
36
        /// <exception cref="FormatException">Error decoding BASE64 content</exception>
37
        /// <exception cref="InvalidDataException">Zip file has wrong format</exception>
38
        /// <exception cref="IOException">Error reading entries from the zip file</exception>
39
        public void AddDocuments(DocumentAddRequest request, Guid userId)
40
        {
41
            User user = databaseContext.Users.Single(u => u.Id == userId);
42
43
            foreach (var documentInfo in request.Documents)
44
            {
45 52fe46f9 Vojtěch Bartička
                if (documentInfo.Format == Models.Enums.EAddDocumentFormat.TEXTFILE)
46 24e1c89d Vojtěch Bartička
                {
47 7b2e66d3 Vojtěch Bartička
                    // TODO hardcoded UTF-8 - maybe do something smarter
48
                    var documentContent = Encoding.UTF8.GetString(Convert.FromBase64String(documentInfo.Content));
49
                    SaveDocument(documentContent, user, documentInfo.Name);
50 24e1c89d Vojtěch Bartička
                }
51 7b2e66d3 Vojtěch Bartička
                else if (documentInfo.Format == Models.Enums.EAddDocumentFormat.ZIP)
52 24e1c89d Vojtěch Bartička
                {
53
                    var (names, contents) = UnzipDocuments(documentInfo.Content);
54
                    for (int i = 0; i < names.Count; i++)
55
                    {
56
                        SaveDocument(contents[i], user, names[i]);
57
                    }
58
                }
59
            }
60
        }
61
62
        /// <summary>
63
        /// 
64
        /// </summary>
65
        /// <param name="base64encoded"></param>
66
        /// <returns></returns>
67
        private (List<string> Names, List<string> Contents) UnzipDocuments(string base64encoded)
68
        {
69
            List<string> names = new();
70
            List<string> contents = new();
71
72
            byte[] decoded = Convert.FromBase64String(base64encoded);
73
74
            using (var zipStream = new MemoryStream(decoded))
75
            using (var zipArchive = new ZipArchive(zipStream))
76
            {
77
                foreach (var entry in zipArchive.Entries)
78
                {
79
                    names.Add(entry.Name);
80
                    using (var streamReader = new StreamReader(entry.Open()))
81
                    {
82
                        string text = streamReader.ReadToEnd();
83
                        contents.Add(text);
84
                    }
85
                }
86
            }
87
88
            return (names, contents);
89
        }
90
91
        private void SaveDocument(string content, User userAdded, string documentName)
92
        {
93
            DocumentContent documentContent = new DocumentContent()
94
            {
95
                Content = content
96
            };
97
98
            Document document = new Document()
99
            {
100
                DateAdded = DateTime.Now,
101
                Content = documentContent,
102
                UserAdded = userAdded,
103
                Name = documentName,
104
                Length = documentContent.Content.Length,
105
                RequiredAnnotations = 3                     // TODO this is only for beta testing purposes
106
            };
107
108
            databaseContext.DocumentContents.Add(documentContent);
109
            databaseContext.Documents.Add(document);
110
            databaseContext.SaveChanges();                  // Maybe do this after all the documents are added
111
        }
112
113 42c654f6 Vojtěch Bartička
        public DocumentListResponse GetDocuments(int pageIndex, int pageSize)
114 24e1c89d Vojtěch Bartička
        {
115 42c654f6 Vojtěch Bartička
            var firstIndex = pageIndex * pageSize;
116 24e1c89d Vojtěch Bartička
            var documents = databaseContext.Documents.Select(d => d).ToList();
117
            var totalCount = documents.Count;
118 42c654f6 Vojtěch Bartička
            var pageCount = totalCount / pageSize;
119 24e1c89d Vojtěch Bartička
            if (pageCount == 0 && totalCount > 0)
120
            {
121
                pageCount = 1;
122
            }
123
124 7bbe8f15 Vojtěch Bartička
            if (firstIndex > documents.Count - 1)
125
            {
126
                throw new Exception("Page index or page size too large");
127
            }
128
129 42c654f6 Vojtěch Bartička
            if (firstIndex + pageSize > documents.Count - 1)
130 7bbe8f15 Vojtěch Bartička
            {
131 42c654f6 Vojtěch Bartička
                pageSize = documents.Count - firstIndex;
132 7bbe8f15 Vojtěch Bartička
            }
133
134 24e1c89d Vojtěch Bartička
            List<DocumentListInfo> documentInfos = new List<DocumentListInfo>();
135 42c654f6 Vojtěch Bartička
            foreach (var document in documents.GetRange(firstIndex, pageSize))
136 24e1c89d Vojtěch Bartička
            {
137 5a08541d Vojtěch Bartička
                var annotatingUsers = databaseContext.Annotations.Where(a => a.Document == document).Select(a => a.User).ToList();
138
                List<UserInfo> annotatingUsersDto = annotatingUsers.Select(a => mapper.Map<UserInfo>(a)).ToList();
139
140
                DocumentListInfo dai = mapper.Map<DocumentListInfo>(document);
141
                dai.AnnotatingUsers = annotatingUsersDto;
142 7bbe8f15 Vojtěch Bartička
                documentInfos.Add(dai);
143 24e1c89d Vojtěch Bartička
            }
144
145
            return new DocumentListResponse()
146
            {
147
                PageCount = pageCount,
148 42c654f6 Vojtěch Bartička
                PageIndex = pageIndex,
149 24e1c89d Vojtěch Bartička
                TotalCount = totalCount,
150
                Documents = documentInfos
151
            };
152
        }
153
154
    }
155
}