DocumentService.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.IO.Abstractions;
  5. using System.Linq;
  6. using System.Security.Principal;
  7. using System.Threading.Tasks;
  8. using BO.AppServer.Business.Exceptions;
  9. using BO.AppServer.Business.Mapper;
  10. using BO.AppServer.Business.Services.Base;
  11. using BO.AppServer.Data.Entity;
  12. using BO.AppServer.Data.Repository;
  13. using BO.AppServer.Metadata.Dto;
  14. using BO.AppServer.Metadata.Enums;
  15. using Microsoft.AspNetCore.Identity;
  16. using Microsoft.Extensions.Logging;
  17. using Microsoft.Extensions.Options;
  18. using Quadarax.Foundation.Core.Data;
  19. using Quadarax.Foundation.Core.Data.Interface;
  20. using Quadarax.Foundation.Core.Data.Interface.Entity.Dto;
  21. namespace BO.AppServer.Business.Services
  22. {
  23. public class DocumentService : UserContextService
  24. {
  25. #region *** Private fields ***
  26. private IFileSystem _fileSystem;
  27. private WorkspaceRepo _repoWorkspace;
  28. private MetadocumentRepo _repoDocument;
  29. private MimeTypeRepo _repoMType;
  30. private ArtifactRepo _repoArtifact;
  31. private StorageService _srvStorage;
  32. #endregion
  33. #region *** Constructors ***
  34. public DocumentService(
  35. WorkspaceRepo repoWorkspace,
  36. MetadocumentRepo repoDocument,
  37. MimeTypeRepo repoMType,
  38. ArtifactRepo repoArtifact,
  39. StorageService srvStorage,
  40. IFileSystem fileSystem,
  41. IOptions<Configuration.Configuration> config,
  42. UserRepo repoUser,
  43. UserManager<IdentityUser> userManager,
  44. IPrincipal currentPrincipal,
  45. ILoggerFactory logger) : base(config, repoUser, userManager, currentPrincipal, logger)
  46. {
  47. _repoWorkspace = repoWorkspace ?? throw new ArgumentNullException(nameof(repoWorkspace));
  48. _repoDocument = repoDocument ?? throw new ArgumentNullException(nameof(repoDocument));
  49. _repoMType = repoMType ?? throw new ArgumentNullException(nameof(repoMType));
  50. _repoArtifact = repoArtifact ?? throw new ArgumentNullException(nameof(repoArtifact));
  51. _fileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem));
  52. _srvStorage = srvStorage ?? throw new ArgumentNullException(nameof(srvStorage));
  53. }
  54. #endregion
  55. #region *** Public Operations ***
  56. public async Task<ResultValueDto<DocumentRDto>> GetDocumentAsync(long workspaceId, long documentId)
  57. {
  58. var document = CheckAndGetDocument(workspaceId, documentId);
  59. return new ResultValueDto<DocumentRDto>(document.Map<Metadocument, DocumentRDto>());
  60. }
  61. public async Task<ResultsValueDto<DocumentRDto>> GetAllDocumentsAsync(long workspaceId, DocumentsScopeEnums scope, PagingDto paging)
  62. {
  63. CheckAndGetWorkspace(workspaceId);
  64. IList<Metadocument> documents = new List<Metadocument>();
  65. switch (scope)
  66. {
  67. case DocumentsScopeEnums.All:
  68. documents = _repoDocument.Query(paging).Where(x => x.Structure.WorkspaceId == workspaceId).OrderBy(x => x.Name).ToList();
  69. break;
  70. case DocumentsScopeEnums.Pending:
  71. documents = _repoDocument.Query(paging).Where(x => x.Structure.WorkspaceId == workspaceId && x.Status == (int)DocumentStatusEnum.Pending).OrderBy(x => x.Name).ToList();
  72. break;
  73. case DocumentsScopeEnums.Done:
  74. documents = _repoDocument.Query(paging).Where(x => x.Structure.WorkspaceId == workspaceId && x.Status == (int)DocumentStatusEnum.DoneOk).OrderBy(x => x.Name).ToList();
  75. break;
  76. case DocumentsScopeEnums.Working:
  77. documents = _repoDocument.Query(paging).Where(x => x.Structure.WorkspaceId == workspaceId && x.Status == (int)DocumentStatusEnum.Processing).OrderBy(x => x.Name).ToList();
  78. break;
  79. case DocumentsScopeEnums.Failed:
  80. documents = _repoDocument.Query(paging).Where(x => x.Structure.WorkspaceId == workspaceId && x.Status == (int)DocumentStatusEnum.DoneFail).OrderBy(x => x.Name).ToList();
  81. break;
  82. }
  83. return new ResultsValueDto<DocumentRDto>(documents.MapList<Metadocument, DocumentRDto>());
  84. }
  85. public async Task<ResultValueDto<DocumentRDto>> GetDocumentByNameAsync(long workspaceId, string name)
  86. {
  87. CheckAndGetWorkspace(workspaceId);
  88. IList<Metadocument> documents = new List<Metadocument>();
  89. var document = _repoDocument.GetByName(workspaceId, name);
  90. if (document == null)
  91. throw new NoDataException();
  92. return new ResultValueDto<DocumentRDto>(document.Map<Metadocument, DocumentRDto>());
  93. }
  94. public async Task<ResultsValueDto<DocumentRDto>> GetAllDocumentsAsync(DocumentsScopeEnums scope, PagingDto paging)
  95. {
  96. IList<Metadocument> documents = new List<Metadocument>();
  97. switch (scope)
  98. {
  99. case DocumentsScopeEnums.All:
  100. documents = _repoDocument.Query(paging).OrderBy(x => x.Name).ToList();
  101. break;
  102. case DocumentsScopeEnums.Pending:
  103. documents = _repoDocument.Query(paging).Where(x => x.Status == (int)DocumentStatusEnum.Pending).OrderBy(x => x.Name).ToList();
  104. break;
  105. case DocumentsScopeEnums.Done:
  106. documents = _repoDocument.Query(paging).Where(x => x.Status == (int)DocumentStatusEnum.DoneOk).OrderBy(x => x.Name).ToList();
  107. break;
  108. case DocumentsScopeEnums.Working:
  109. documents = _repoDocument.Query(paging).Where(x => x.Status == (int)DocumentStatusEnum.Processing).OrderBy(x => x.Name).ToList();
  110. break;
  111. case DocumentsScopeEnums.Failed:
  112. documents = _repoDocument.Query(paging).Where(x => x.Status == (int)DocumentStatusEnum.DoneFail).OrderBy(x => x.Name).ToList();
  113. break;
  114. }
  115. return new ResultsValueDto<DocumentRDto>(documents.MapList<Metadocument, DocumentRDto>());
  116. }
  117. public async Task<ResultValueDto<DocumentRDto>> CreateDocumentAsync(long workspaceId, DocumentCDto document)
  118. {
  119. var workspace = CheckAndGetWorkspace(workspaceId);
  120. var exists = _repoDocument.Query(new Paging())
  121. .Any(x => x.Structure.WorkspaceId == workspaceId && x.Name == document.Name);
  122. if (exists)
  123. {
  124. var exc = new EntityAlreadyExistsException(typeof(Metadocument), document.Name);
  125. Log.LogWarning(exc.Message);
  126. throw exc;
  127. }
  128. var newDocument = _repoDocument.New();
  129. document.CopyToDto(newDocument);
  130. newDocument.Created = DateTime.Now;
  131. newDocument.CreatedByUser = GetCurrentUser();
  132. newDocument.Status = (int)DocumentStatusEnum.New;
  133. newDocument.StructureId = workspace.Structures.First().Id;
  134. _repoDocument.Set(newDocument);
  135. _repoDocument.Commit();
  136. return new ResultValueDto<DocumentRDto>(newDocument.Map<Metadocument, DocumentRDto>());
  137. }
  138. public async Task<ResultsValueDto<ArtifactRDto>> ClearDocumentArtifactsAsync(long workspaceId, long documentId, bool force)
  139. {
  140. var document = CheckAndGetDocument(workspaceId, documentId);
  141. CheckDocumentStatusForUpdate(document, force);
  142. var artifacts = _repoArtifact.GetArtifacts(documentId).ToArray(); // must be to array
  143. foreach (var artifact in artifacts)
  144. {
  145. await _srvStorage.DeleteContent(artifact.Id);
  146. _repoArtifact.Remove(artifact.Id);
  147. Log.LogInformation($"Document '{document.Name}' ({documentId}) artifact '{artifact.Name + artifact.Extension}' ({artifact.Id}) removed.");
  148. }
  149. document.Modified = DateTime.Now;
  150. document.ModifiedByUser = GetCurrentUser();
  151. _repoDocument.Set(document);
  152. _repoArtifact.Commit();
  153. _repoDocument.Commit();
  154. return new ResultsValueDto<ArtifactRDto>(artifacts.MapList<Artifact, ArtifactRDto>());
  155. }
  156. public async Task<ResultValueDto<ArtifactRDto>> AppendArtifactAsync(long workspaceId, long documentId,
  157. ArtifactCDto artifact,bool replace, ArtifactTypeEnum type, Stream content)
  158. {
  159. //TODO: Rewrite better way - mainly rollback scenario
  160. var document = CheckAndGetDocument(workspaceId, documentId);
  161. var existingArtifact = _repoArtifact.GetArtifactByName(documentId, artifact.Name, artifact.Extension);
  162. if (existingArtifact!=null && !replace)
  163. {
  164. var exc = new EntityAlreadyExistsException(typeof(Artifact), artifact.Name + "." + artifact.Extension);
  165. Log.LogWarning(exc.Message);
  166. throw exc;
  167. }
  168. var mtype = _repoMType.GetByMimeType(artifact.MimeType);
  169. if (mtype == null)
  170. {
  171. var exc = new EntityNotExistsException(typeof(MimeType), artifact.MimeType, 0);
  172. Log.LogWarning(exc.Message);
  173. throw exc;
  174. }
  175. var newArtifact = (existingArtifact != null && replace) ? existingArtifact : _repoArtifact.New();
  176. newArtifact.Name = artifact.Name;
  177. newArtifact.Extension = artifact.Extension;
  178. newArtifact.Length = content.Length;
  179. newArtifact.Metadocument = document;
  180. newArtifact.MimeType = mtype;
  181. newArtifact.Created = DateTime.Now;
  182. newArtifact.CreatedByUser = GetCurrentUser();
  183. newArtifact.Type = (int)type;
  184. _repoArtifact.Set(newArtifact);
  185. document = _repoDocument.Get(documentId);
  186. document.Modified = DateTime.Now;
  187. document.ModifiedByUser = GetCurrentUser();
  188. _repoDocument.Set(document);
  189. _repoArtifact.Commit();
  190. _repoDocument.Commit();
  191. await _srvStorage.PushContentAsync(newArtifact.Id, content);
  192. return new ResultValueDto<ArtifactRDto>(newArtifact.Map<Artifact, ArtifactRDto>());
  193. }
  194. public async Task<Tuple<Stream, string>> GetArtifactAsync(long workspaceId, long documentId, long artifactId)
  195. {
  196. var artifact = CheckAndGetArtifact(workspaceId, documentId, artifactId);
  197. var result = await _srvStorage.PopContentAsync(artifact.Id);
  198. return new Tuple<Stream, string>(result.Item1, artifact.MimeType.Mimetype1);
  199. }
  200. public ArtifactCDto CreateArtifactDto(string fileName, string contentType)
  201. {
  202. var result = new ArtifactCDto();
  203. result.Extension = _fileSystem.Path.GetExtension(fileName);
  204. result.MimeType = contentType;
  205. result.Name = _fileSystem.Path.GetFileNameWithoutExtension(fileName);
  206. return result;
  207. }
  208. #endregion
  209. #region *** Private Operations ***
  210. private Workspace CheckAndGetWorkspace(long workspaceId)
  211. {
  212. var workspace = _repoWorkspace.Get(workspaceId);
  213. if (workspace == null)
  214. {
  215. var exc = new EntityNotExistsException(typeof(Workspace), nameof(Workspace.Id), workspaceId);
  216. Log.LogWarning(exc.Message);
  217. throw exc;
  218. }
  219. return workspace;
  220. }
  221. private Metadocument CheckAndGetDocument(long workspaceId, long documentId)
  222. {
  223. CheckAndGetWorkspace(workspaceId);
  224. var document = _repoDocument.Get(workspaceId ,documentId);
  225. if (document == null)
  226. {
  227. var exc = new EntityNotExistsException(typeof(Metadocument), nameof(Metadocument.Id), documentId);
  228. Log.LogWarning(exc.Message);
  229. throw exc;
  230. }
  231. return document;
  232. }
  233. private void CheckDocumentStatusForUpdate(Metadocument document, bool force)
  234. {
  235. if (document == null)
  236. throw new ArgumentNullException(nameof(document));
  237. var currentStatus = (DocumentStatusEnum)document.Status;
  238. var allowedStatus = new DocumentStatusEnum[]
  239. {
  240. DocumentStatusEnum.New,
  241. DocumentStatusEnum.Pending,
  242. };
  243. if (!allowedStatus.Contains(currentStatus))
  244. {
  245. var message = $"Document '{document.Name}' [{document.Id}] has not allowed status '{currentStatus}' for operation UPDATE. Allowed statuses are {string.Join(",", allowedStatus)}.";
  246. Log.LogWarning(message + (force ? " Skip due Force flag." : string.Empty));
  247. if (!force)
  248. throw new InvalidDocumentStateException(document.Name, document.Id, currentStatus, "update");
  249. }
  250. }
  251. private Artifact CheckAndGetArtifact(long workspaceId, long documentId, long artifactId)
  252. {
  253. CheckAndGetWorkspace(workspaceId);
  254. CheckAndGetDocument(workspaceId, documentId);
  255. var artifact = _repoArtifact.GetArtifact(documentId, artifactId);
  256. if (artifact == null)
  257. {
  258. var exc = new EntityNotExistsException(typeof(Artifact), nameof(Artifact.Id), artifactId);
  259. Log.LogWarning(exc.Message);
  260. throw exc;
  261. }
  262. return artifact;
  263. }
  264. #endregion
  265. }
  266. }