public async Task <string> GenerateComponentPID(string parentId, string separator, GeneratePIDComponentType type)
        {
            await semaphoreSlim.WaitAsync();

            try
            {
                var parentInfo = await _alfrescoHttpClient.GetNodeInfo(parentId, ImmutableList <Parameter> .Empty
                                                                       .Add(new Parameter(AlfrescoNames.Headers.Include, $"{AlfrescoNames.Includes.Properties},{AlfrescoNames.Includes.IsLocked}", ParameterType.QueryString)));

                var    properties   = parentInfo.Entry.Properties.As <JObject>().ToDictionary();
                var    parentPID    = properties.GetNestedValueOrDefault(SpisumNames.Properties.Pid)?.ToString();
                string propertyName = type == GeneratePIDComponentType.Component ? SpisumNames.Properties.ComponentCounter : SpisumNames.Properties.ShipmentCounter;

                if (int.TryParse(properties.GetNestedValueOrDefault(propertyName)?.ToString(), out int counter))
                {
                    counter++;
                }
                else
                {
                    counter = 1;
                }

                await _alfrescoHttpClient.UpdateNode(parentId, new NodeBodyUpdate()
                                                     .AddProperty(propertyName, counter));

                return($"{parentPID}{separator}{counter}");
            }
            finally
            {
                semaphoreSlim.Release();
            }
        }
Exemple #2
0
        public async Task <NodeEntry> ConvertToOutputFormat(string documentId, string componentId, string reason, string organization)
        {
            var nodeEntry = await _alfrescoHttpClient.GetNodeInfo(componentId, ImmutableList <Parameter> .Empty
                                                                  .Add(new Parameter(AlfrescoNames.Headers.Include, $"{AlfrescoNames.Includes.Properties}, {AlfrescoNames.Includes.Path}", ParameterType.QueryString)));

            var extension = Path.GetExtension(nodeEntry?.Entry?.Name);

            if (!_fileExtensions.Any(x => extension.Contains(x)))
            {
                return(await _alfrescoHttpClient.UpdateNode(componentId, new NodeBodyUpdate()
                                                            .AddProperty(SpisumNames.Properties.FileIsInOutputFormat, "impossible")));
            }

            var    properties = nodeEntry?.Entry?.Properties?.As <JObject>().ToDictionary();
            string pid        = properties.GetNestedValueOrDefault(SpisumNames.Properties.Pid)?.ToString();

            var componentPid = pid.Split('/');

            FormDataParam pdf = null;

            if (nodeEntry?.Entry?.Content.MimeType != MediaTypeNames.Application.Pdf)
            {
                pdf = await _alfrescoHttpClient.GetThumbnailPdf(componentId, ImmutableList <Parameter> .Empty
                                                                .Add(new Parameter("c", "force", ParameterType.QueryString)));
            }
            else
            {
                pdf = await _alfrescoHttpClient.NodeContent(componentId);
            }

            var data = await _pdfService.ConvertToPdfA2B(new MemoryStream(pdf.File));

            if (_signerConfiguration.Base != null || _signerConfiguration.Url != null)
            {
                SealResponse signer = await _signerClient.Seal(data);

                await _signerService.CheckAndUpdateComponent(componentId, signer.Output);

                data = signer.Output;
            }

            await _componentService.UploadNewVersionComponent(documentId, componentId, data,
                                                              Path.ChangeExtension(properties.GetNestedValueOrDefault(SpisumNames.Properties.FileName)?.ToString(), ".pdf"), MediaTypeNames.Application.Pdf);

            return(await _alfrescoHttpClient.UpdateNode(componentId, new NodeBodyUpdate()
                                                        .AddProperty(SpisumNames.Properties.FileIsInOutputFormat, "yes")
                                                        .AddProperty(SpisumNames.Properties.FinalVersion, true)
                                                        .AddProperty(SpisumNames.Properties.SettleReason, reason)
                                                        .AddProperty(SpisumNames.Properties.KeepForm, SpisumNames.KeepForm.Original_InOutputFormat)
                                                        .AddProperty(SpisumNames.Properties.LinkRendering, int.Parse(componentPid[1]) + 1)
                                                        .AddProperty(SpisumNames.Properties.ListOriginalComponent, int.Parse(componentPid[1]))
                                                        .AddProperty(SpisumNames.Properties.CompanyImplementingDataFormat, organization)
                                                        .AddProperty(SpisumNames.Properties.AuthorChangeOfDataFormat, $"{_identityUser.FirstName} {_identityUser.LastName}")
                                                        .AddProperty(SpisumNames.Properties.OriginalDataFormat, nodeEntry?.Entry?.Content?.MimeType)
                                                        .AddProperty(SpisumNames.Properties.ImprintFile, Hashes.Sha256CheckSum(new MemoryStream(data)))
                                                        .AddProperty(SpisumNames.Properties.DataCompleteVerificationItem, DateTime.Now)
                                                        .AddProperty(SpisumNames.Properties.UsedAlgorithm, "SHA-256")));
        }
        public async Task CheckCreatePermissions(string nodeId, List <Permission> permissions)
        {
            if (permissions == null)
            {
                return;
            }

            try
            {
                var parameters = ImmutableList <Parameter> .Empty
                                 .Add(new Parameter(AlfrescoNames.Headers.Include, AlfrescoNames.Includes.Permissions, ParameterType.QueryString));

                var info = await _alfrescoHttpClient.GetNodeInfo(nodeId, parameters);

                if (info?.Entry?.Id == null)
                {
                    return;
                }

                var locallySet = info?.Entry?.Permissions?.LocallySet == null ? new List <PermissionElement>() : info.Entry.Permissions.LocallySet.ToList();
                var changed    = false;

                foreach (var permission in permissions)
                {
                    if (!locallySet.Exists(x => x.AuthorityId == permission.Id))
                    {
                        changed = true;
                        locallySet.Add(new PermissionElement
                        {
                            AccessStatus = PermissionElementAccessStatus.ALLOWED,
                            AuthorityId  = permission.Id,
                            Name         = permission.Role
                        });
                    }
                }

                if (changed)
                {
                    await _alfrescoHttpClient.UpdateNode(nodeId, new NodeBodyUpdate { Permissions = new PermissionsBody {
                                                                                          LocallySet = locallySet
                                                                                      } }, parameters);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "CheckCreatePermissions Fail");
            }
        }
Exemple #4
0
        public async Task SendEmail([FromRoute] EmailSend parameters)
        {
            var emlNode = await _alfrescoHttpClient.GetNodeInfo(parameters.NodeId, ImmutableList <Parameter> .Empty
                                                                .Add(new Parameter(AlfrescoNames.Headers.Include, AlfrescoNames.Includes.Path, ParameterType.QueryString)));

            if (emlNode?.Entry?.Path?.Name.StartsWith(AlfrescoNames.Prefixes.Path + SpisumNames.Paths.MailRoomEmail, StringComparison.OrdinalIgnoreCase) == false)
            {
                throw new BadRequestException("", "Node is not in Mailroom");
            }

            var emailProperties = emlNode.Entry.Properties.As <JObject>().ToDictionary();

            if (emailProperties.GetNestedValueOrDefault(SpisumNames.Properties.EmailSender) == null)
            {
                throw new BadRequestException(ErrorCodes.V_EMAIL_NO_SENDER);
            }

            if (emailProperties.GetNestedValueOrDefault(SpisumNames.Properties.EmailRecipient) == null)
            {
                throw new BadRequestException(ErrorCodes.V_EMAIL_NO_RECIPIENT);
            }

            string senderEmail    = emailProperties.GetNestedValueOrDefault(SpisumNames.Properties.EmailSender).ToString();
            string recipientEmail = emailProperties.GetNestedValueOrDefault(SpisumNames.Properties.EmailRecipient).ToString();

            if (!EmailUtils.IsValidEmail(senderEmail))
            {
                throw new BadRequestException(ErrorCodes.V_EMAIL_INVALID_SENDER);
            }
            if (!EmailUtils.IsValidEmail(recipientEmail))
            {
                throw new BadRequestException(ErrorCodes.V_EMAIL_INVALID_RECIPIENT);
            }

            var emailConfiguration = (await _emailHttpClient.Accounts())?.FirstOrDefault(x => x?.Username?.ToLower() == recipientEmail?.ToLower());

            if (emailConfiguration == null)
            {
                throw new BadRequestException(ErrorCodes.V_EMAIL_NO_CONFIGURATION);
            }

            if (emlNode?.Entry?.Path?.Name?.Equals(AlfrescoNames.Prefixes.Path + SpisumNames.Paths.MailRoomEmailUnprocessed) != true)
            {
                throw new BadRequestException("", "Node is not in expected path");
            }

            await _emailHttpClient.Send(senderEmail, emailConfiguration.Username, parameters.Subject, parameters.Body, parameters.Files);

            // Move eml and children
            await _nodesService.MoveChildrenByPath(emlNode.Entry.Id, SpisumNames.Paths.MailRoomEmailNotRegistered);

            await _alfrescoHttpClient.UpdateNode(parameters.NodeId, new NodeBodyUpdate
            {
                Properties = new Dictionary <string, object>
                {
                    { SpisumNames.Properties.EmailNotRegisteredReason, "EM_VAL_01" }
                }
            }
                                                 );
        }
        public async Task <NodeEntry> ChangeRetention(string rmNodeId, string retentionMark, string retentionPeriod)
        {
            try { await UndoCutOff(rmNodeId); } catch { }

            await UncompleteRecord(rmNodeId);

            var node = await _alfrescoHttpClient.UpdateNode(rmNodeId, new NodeBodyUpdate()
                                                            .AddProperty(SpisumNames.Properties.RetentionMark, retentionMark)
                                                            .AddProperty(SpisumNames.Properties.RetentionMode, $"{retentionMark}/{retentionPeriod}")
                                                            .AddProperty(SpisumNames.Properties.RetentionPeriod, retentionPeriod)
                                                            );

            await CompleteRecord(rmNodeId);

            try { await CutOff(rmNodeId); } catch { }

            return(node);
        }
Exemple #6
0
        public async Task DontRegister(DontRegister parameters, EmailOrDataboxEnum type)
        {
            var emlNode = await _alfrescoHttpClient.GetNodeInfo(parameters.NodeId, ImmutableList <Parameter> .Empty
                                                                .Add(new Parameter(AlfrescoNames.Headers.Include, AlfrescoNames.Includes.Path, ParameterType.QueryString)));

            if (parameters.Body.Reason.Length < 4)
            {
                throw new BadRequestException(ErrorCodes.V_MIN_TEXT);
            }

            if (parameters.Body.Reason.Length > 30)
            {
                parameters.Body.Reason = parameters.Body.Reason.Substring(0, 30);
            }

            var body = new NodeBodyUpdate();
            var path = string.Empty;

            switch (type)
            {
            case EmailOrDataboxEnum.Email:

                if (emlNode?.Entry?.Path?.Name.StartsWith(AlfrescoNames.Prefixes.Path + SpisumNames.Paths.MailRoomEmail, StringComparison.OrdinalIgnoreCase) == false)
                {
                    throw new BadRequestException("", "Node is not in Mailbox");
                }

                body = new NodeBodyUpdate
                {
                    Properties = new Dictionary <string, object>
                    {
                        { SpisumNames.Properties.EmailNotRegisteredReason, parameters.Body.Reason }
                    }
                };
                path = SpisumNames.Paths.MailRoomEmailNotRegistered;
                break;

            case EmailOrDataboxEnum.Databox:
                if (emlNode?.Entry?.Path?.Name.StartsWith(AlfrescoNames.Prefixes.Path + SpisumNames.Paths.MailRoomDataBox, StringComparison.OrdinalIgnoreCase) == false)
                {
                    throw new BadRequestException("", "Node is not in Databox");
                }

                body = new NodeBodyUpdate
                {
                    Properties = new Dictionary <string, object>
                    {
                        { SpisumNames.Properties.DataBoxNotRegisteredReason, parameters.Body.Reason }
                    }
                };
                path = SpisumNames.Paths.MailRoomDataBoxNotRegistered;
                break;
            }

            await _alfrescoHttpClient.UpdateNode(parameters.NodeId, body);

            await _nodesService.MoveChildrenByPath(parameters.NodeId, path);
        }
Exemple #7
0
        public async Task <bool> CheckAndUpdateComponent(string componentId, byte[] component)
        {
            try
            {
                var pdfValidation = await _signerClient.Validate(component);

                var certValidation = await _signerClient.ValidateCertificate(pdfValidation?.Report?.sigInfos[0]?.signCert.Data);

                await _alfrescoHttpClient.UpdateNode(componentId, GetSignerProperties(pdfValidation, certValidation, false));

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Exemple #8
0
        public async Task <NodeEntry> ToDocument(string conceptId, string authorId, string subject, int attachmentCount, GenerateSsid ssidConfiguration, DateTime?settleTo = null)
        {
            var authorInfo = await _alfrescoHttpClient.GetPerson(authorId);

            if (authorInfo == null)
            {
                throw new BadRequestException("", "Provided author does not exists");
            }

            var myNode = await _alfrescoHttpClient.GetNodeInfo(AlfrescoNames.Aliases.My);

            var conceptInfo = await _alfrescoHttpClient.GetNodeInfo(conceptId);

            // Create a copy of concept
            var conceptCopyInfo = await _alfrescoHttpClient.NodeCopy(conceptId, new NodeBodyCopy
            {
                TargetParentId = myNode?.Entry?.Id,
                Name           = IdGenerator.GenerateId()
            });

            // Copy association of components
            var conceptChildrens = await _nodesService.GetSecondaryChildren(conceptId, SpisumNames.Associations.Components);

            await conceptChildrens.ForEachAsync(async x =>
            {
                // Remove old versions old file and associate with new node
                await _nodesService.RemoveAllVersions(x?.Entry?.Id);
            });

            var properties       = conceptInfo?.Entry?.Properties?.As <JObject>().ToDictionary();
            var authorProperties = authorInfo?.Entry?.Properties?.As <JObject>().ToDictionary();

            // Save properties
            var documentInfo = await _alfrescoHttpClient.UpdateNode(conceptCopyInfo?.Entry?.Id, new NodeBodyUpdate
            {
                NodeType = SpisumNames.NodeTypes.Document
            }
                                                                    .AddProperty(SpisumNames.Properties.Pid, null)
                                                                    .AddProperty(SpisumNames.Properties.Author, authorId)
                                                                    .AddProperty(SpisumNames.Properties.Subject, subject)
                                                                    .AddProperty(SpisumNames.Properties.SettleToDate, settleTo)
                                                                    .AddProperty(SpisumNames.Properties.AttachmentsCount, attachmentCount)

                                                                    .AddProperty(SpisumNames.Properties.AuthorId, authorProperties.GetNestedValueOrDefault(SpisumNames.Properties.UserId)?.ToString())
                                                                    .AddProperty(SpisumNames.Properties.AuthorOrgId, authorProperties.GetNestedValueOrDefault(SpisumNames.Properties.UserOrgId)?.ToString())
                                                                    .AddProperty(SpisumNames.Properties.AuthorOrgName, authorProperties.GetNestedValueOrDefault(SpisumNames.Properties.UserOrgName)?.ToString())
                                                                    .AddProperty(SpisumNames.Properties.AuthorOrgUnit, authorProperties.GetNestedValueOrDefault(SpisumNames.Properties.UserOrgUnit)?.ToString())
                                                                    .AddProperty(SpisumNames.Properties.AuthorJob, authorProperties.GetNestedValueOrDefault(SpisumNames.Properties.UserJob)?.ToString())
                                                                    .AddProperty(SpisumNames.Properties.AuthorOrgAddress, authorProperties.GetNestedValueOrDefault(SpisumNames.Properties.UserOrgAddress)?.ToString())

                                                                    .AddProperty(SpisumNames.Properties.KeepForm, SpisumNames.StoreForm.Original)
                                                                    .AddProperty(SpisumNames.Properties.SenderType, SpisumNames.SenderType.Own)
                                                                    .AddProperty(SpisumNames.Properties.Sender, SpisumNames.Other.Own)
                                                                    .AddProperty(SpisumNames.Properties.Sender_Name, SpisumNames.Other.Own)
                                                                    .AddProperty(SpisumNames.Properties.Sender_Address, SpisumNames.Other.Own)
                                                                    .AddProperty(SpisumNames.Properties.Sender_Contact, SpisumNames.Other.Own)

                                                                    .AddProperty(SpisumNames.Properties.State, SpisumNames.State.Unprocessed)

                                                                    .AddProperty(AlfrescoNames.ContentModel.Owner, properties.GetNestedValueOrDefault(AlfrescoNames.ContentModel.Owner, "id")?.ToString())
                                                                    .AddProperty(SpisumNames.Properties.Version, 1)
                                                                    );

            // Create permissions for the node
            await _nodesService.CreatePermissions(conceptCopyInfo?.Entry?.Id, _identityUser.RequestGroup, _identityUser.Id);

            await _nodesService.MoveByPath(conceptCopyInfo?.Entry?.Id, SpisumNames.Paths.EvidenceDocumentsForProcessing(_identityUser.RequestGroup));

            // Generate Ssid
            var conceptEntry = await _nodesService.GenerateSsid(conceptCopyInfo?.Entry?.Id, ssidConfiguration);

            // Delete deleted components
            var deletedComponents = await _nodesService.GetSecondaryChildren(conceptId, SpisumNames.Associations.DeletedComponents);

            await deletedComponents.ForEachAsync(async x =>
            {
                await _nodesService.DeleteNodePermanent(x?.Entry?.Id);
            });

            // Delete concept
            await _nodesService.DeleteNodePermanent(conceptId);

            try
            {
                var conceptPid = conceptInfo?.GetPid();

                // Audit log for a document
                await _auditLogService.Record(documentInfo?.Entry.Id, SpisumNames.NodeTypes.Document, conceptPid, NodeTypeCodes.Dokument, EventCodes.Zalozeni,
                                              TransactinoHistoryMessages.ConceptToDocument);

                var fileId = await _documentService.GetDocumentFileId(documentInfo?.Entry.Id);

                if (fileId != null)
                {
                    await _auditLogService.Record(fileId, SpisumNames.NodeTypes.Document, conceptPid, NodeTypeCodes.Dokument, EventCodes.Zalozeni,
                                                  TransactinoHistoryMessages.ConceptToDocument);
                }
            }
            catch (Exception ex)
            {
                Log.Logger?.Error(ex, "Audit log failed");
            }

            return(conceptEntry);
        }
        public async Task <NodeEntry> ShreddingProposalCreate(string name, List <string> ids)
        {
            var nodes = new List <NodeEntry>();

            await ids.ForEachAsync(async x =>
            {
                #region Validations

                var nodeInfo = await _alfrescoHttpClient.GetNodeInfo(x);
                nodes.Add(nodeInfo);

                var properties    = nodeInfo.Entry.Properties.As <JObject>().ToDictionary();
                var discardReason = properties.GetNestedValueOrDefault(SpisumNames.Properties.DiscardReason)?.ToString();
                var discardTo     = properties.GetNestedValueOrDefault(SpisumNames.Properties.DiscardTo)?.ToString();
                var discardDate   = properties.GetNestedValueOrDefault(SpisumNames.Properties.DiscardDate)?.ToString();
                var borrower      = properties.GetNestedValueOrDefault(SpisumNames.Properties.Borrower)?.ToString();
                var proposalName  = properties.GetNestedValueOrDefault(SpisumNames.Properties.ProposalName)?.ToString();

                if (!string.IsNullOrWhiteSpace(proposalName))
                {
                    throw new BadRequestException("", "One or more of the ids cannot be used because they were used previously.");
                }

                var parentRm = await _nodesService.GetParentsByAssociation(x, new List <string>
                {
                    SpisumNames.Associations.DocumentInRepository,
                    SpisumNames.Associations.FileInRepository
                });

                var rmRef = parentRm.FirstOrDefault()?.Entry?.Id;

                if (string.IsNullOrWhiteSpace(rmRef))
                {
                    throw new BadRequestException("", "One or more of the ids are not in record management.");
                }

                var rmNodeInfo = await _alfrescoHttpClient.GetNodeInfo(rmRef);

                var propertiesRm = rmNodeInfo.Entry.Properties.As <JObject>().ToDictionary();
                var cutOffDate   = propertiesRm.GetNestedValueOrDefault(AlfrescoNames.ContentModel.CutOffDate)?.ToString();

                if (string.IsNullOrWhiteSpace(cutOffDate))
                {
                    throw new BadRequestException("", "One or more of the ids has not been cut off yet.");
                }

                if (!string.IsNullOrWhiteSpace(discardReason) ||
                    !string.IsNullOrWhiteSpace(discardTo) ||
                    !string.IsNullOrWhiteSpace(discardDate) ||
                    !string.IsNullOrWhiteSpace(borrower))
                {
                    throw new BadRequestException("", "One or more of ids is borrowed or removed of shredding plan");
                }

                #endregion
            });

            var shreddingPlanCreate = await _alfrescoHttpClient.CreateNode(AlfrescoNames.Aliases.Root, new FormDataParam(new byte[] { 01 }),
                                                                           ImmutableList <Parameter> .Empty
                                                                           .Add(new Parameter(AlfrescoNames.Headers.NodeType, SpisumNames.NodeTypes.ShreddingProposal, ParameterType.GetOrPost))
                                                                           .Add(new Parameter(AlfrescoNames.Headers.Name, IdGenerator.GenerateId(), ParameterType.GetOrPost))
                                                                           .Add(new Parameter(AlfrescoNames.Headers.RelativePath, SpisumNames.Paths.RepositoryShreddingProposal, ParameterType.GetOrPost))
                                                                           .Add(new Parameter(AlfrescoNames.Headers.Include, AlfrescoNames.Includes.Properties, ParameterType.QueryString))
                                                                           .Add(new Parameter(SpisumNames.Properties.Name, name, ParameterType.GetOrPost))
                                                                           .Add(new Parameter(SpisumNames.Properties.AssociationCount, nodes.Count, ParameterType.GetOrPost))
                                                                           .Add(new Parameter(SpisumNames.Properties.CreatedDate, DateTime.UtcNow.ToAlfrescoDateTimeString(), ParameterType.GetOrPost))
                                                                           .Add(new Parameter(SpisumNames.Properties.Author, _identityUser.Id, ParameterType.GetOrPost))
                                                                           );

            var shreddingPlan = await _alfrescoHttpClient.GetNodeInfo(shreddingPlanCreate?.Entry?.Id);

            var shredding = shreddingPlan?.Entry?.Properties.As <JObject>().ToDictionary();
            var pid       = shredding.GetNestedValueOrDefault(SpisumNames.Properties.Pid)?.ToString();

            await nodes.ForEachAsync(async x =>
            {
                await _nodesService.TryUnlockNode(x?.Entry?.Id);

                await _alfrescoHttpClient.CreateNodeSecondaryChildren(shreddingPlan?.Entry?.Id, new ChildAssociationBody
                {
                    AssocType = SpisumNames.Associations.ShreddingObjects,
                    ChildId   = x?.Entry?.Id
                });

                await _alfrescoHttpClient.UpdateNode(x?.Entry?.Id, new NodeBodyUpdate()
                                                     .AddProperty(SpisumNames.Properties.ProposalName, pid)
                                                     );

                await _alfrescoHttpClient.NodeLock(x?.Entry?.Id, new NodeBodyLock
                {
                    Type = NodeBodyLockType.FULL
                });
            });

            return(shreddingPlan);
        }