public CopyDocument(
     DocumentHandle handle,
     DocumentHandle copiedHandle)
 {
     Handle = handle;
     CopiedHandle = copiedHandle;
 }
        public async Task <HttpResponseMessage> GetAttachmentFat(
            TenantId tenantId,
            DocumentHandle handle
            )
        {
            var documentDescriptor = _documentDescriptorReader.AllUnsorted.SingleOrDefault(d =>
                                                                                           d.Documents.Contains(handle));

            if (documentDescriptor == null)
            {
                return(DocumentNotFound(handle));
            }

            List <DocumentAttachmentsFat.AttachmentInfo> fat = new List <DocumentAttachmentsFat.AttachmentInfo>();

            if (documentDescriptor.Attachments != null && documentDescriptor.Attachments.Count > 0)
            {
                ScanAttachments(
                    tenantId,
                    documentDescriptor.Attachments,
                    fat,
                    "",
                    0,
                    5);
            }

            return(Request.CreateResponse(HttpStatusCode.OK, fat));
        }
        public async Task <HttpResponseMessage> CopyDocument(
            TenantId tenantId, DocumentHandle originalHandle, DocumentHandle copiedHandle)
        {
            var documentDescriptor = GetDocumentDescriptorByHandle(originalHandle);

            if (documentDescriptor == null)
            {
                return(DocumentNotFound(originalHandle));
            }

            documentDescriptor = GetDocumentDescriptorByHandle(copiedHandle);
            if (documentDescriptor != null)
            {
                return(Request.CreateErrorResponse(
                           HttpStatusCode.InternalServerError,
                           string.Format("Handle {0} already existing", copiedHandle)
                           ));
            }

            CommandBus.Send(new CopyDocument(originalHandle, copiedHandle), "api");

            return(Request.CreateResponse(
                       HttpStatusCode.OK,
                       string.Format("Handle {0} copied into handle {1}", originalHandle, copiedHandle)
                       ));
        }
        public HttpResponseMessage CopyDocument(
#pragma warning disable RCS1163 // Unused parameter.
#pragma warning disable IDE0060 // Remove unused parameter
            TenantId tenantId,  //do not remove, even if not used in the method, actually it is used from the infrastructure to determine tenant
#pragma warning restore IDE0060 // Remove unused parameter
#pragma warning restore RCS1163 // Unused parameter.
            DocumentHandle originalHandle,
            DocumentHandle copiedHandle)
        {
            var documentDescriptor = GetDocumentDescriptorByHandle(originalHandle);

            if (documentDescriptor == null)
            {
                return(DocumentNotFound(originalHandle));
            }

            documentDescriptor = GetDocumentDescriptorByHandle(copiedHandle);
            if (documentDescriptor != null)
            {
                return(Request.CreateErrorResponse(
                           HttpStatusCode.InternalServerError,
                           string.Format("Handle {0} already existing", copiedHandle)
                           ));
            }

            CommandBus.Send(new CopyDocument(originalHandle, copiedHandle), "api");

            return(Request.CreateResponse(
                       HttpStatusCode.OK,
                       string.Format("Handle {0} copied into handle {1}", originalHandle, copiedHandle)
                       ));
        }
 HttpResponseMessage DocumentNotFound(DocumentHandle handle)
 {
     return(Request.CreateErrorResponse(
                HttpStatusCode.NotFound,
                string.Format("Document {0} not found", handle)
                ));
 }
 HttpResponseMessage DocumentDeleted(DocumentHandle handle, IEnumerable <DocumentDeletedReadModel> deletions)
 {
     return(Request.CreateErrorResponse(
                HttpStatusCode.NotFound,
                string.Format("Document {0} was deleted at: {1}", handle, String.Join(", ", deletions.Select(d => d.DeletionDate)))
                ));
 }
 public DocumentLinked(DocumentHandle handle, DocumentDescriptorId documentId, DocumentDescriptorId previousDocumentId, FileNameWithExtension fileName)
 {
     FileName = fileName;
     PreviousDocumentId = previousDocumentId;
     Handle = handle;
     DocumentId = documentId;
 }
        public async Task <HttpResponseMessage> GetHandleInfo(
            TenantId tenantId,
            DocumentHandle handle)
        {
            var handleString = handle.ToString();
            var regex        = "/" + handleString.Replace("/", "//") + "/";
            var descriptors  = _documentDescriptorReader.Collection
                               .Find(Builders <DocumentDescriptorReadModel> .Filter.Regex("Documents", new MongoDB.Bson.BsonRegularExpression(regex)))
                               .Limit(20);

            var retValue = new List <DocumentInfo>();

            foreach (var d in descriptors.ToEnumerable())
            {
                var documentHandles = d.Documents.Where(dd => dd.ToString().Contains(handleString));
                foreach (var documentHandle in documentHandles)
                {
                    var di = new DocumentInfo()
                    {
                        DocumentHandle = documentHandle,
                        Formats        = d.Formats.Select(f => new DocumentFormatInfo()
                        {
                            FormatType = f.Key,
                            FormatUrl  = Url.Content("/" + tenantId + "/documents/" + documentHandle + "/" + f.Key)
                        }).ToList()
                    };
                    retValue.Add(di);
                }
            }

            return(Request.CreateResponse(HttpStatusCode.OK, retValue));
        }
 public DocumentDeleted(DocumentHandle handle, DocumentDescriptorId documentDescriptorId)
 {
     if (handle == null) throw new ArgumentNullException("handle");
     if (documentDescriptorId == null) throw new ArgumentNullException("documentDescriptorId");
     DocumentDescriptorId = documentDescriptorId;
     Handle = handle;
 }
 public DocumentReadModel(DocumentHandle handle, DocumentDescriptorId documentid, FileNameWithExtension fileName, DocumentCustomData customData)
 {
     Handle = handle;
     DocumentDescriptorId = documentid;
     FileName = fileName;
     CustomData = customData;
 }
 public String[] GetPending(TenantId tenantId, DocumentHandle handle)
 {
     using (Metric.Timer("queue-getPending", Unit.Requests).NewContext(handle))
     {
         if (QueueManager == null) return null;
         return QueueManager.GetPendingJobs(tenantId, handle);
     }
 }
        public HttpResponseMessage GetFormat(
#pragma warning disable RCS1163 // Unused parameter.
#pragma warning disable IDE0060 // Remove unused parameter
            TenantId tenantId,  //do not remove, even if not used in the method, actually it is used from the infrastructure to determine tenant
#pragma warning restore IDE0060 // Remove unused parameter
#pragma warning restore RCS1163 // Unused parameter.
            DocumentHandle handle,
            DocumentFormat format,
            string fname = null
            )
        {
            var mapping = _handleWriter.FindOneById(handle);

            //If mapping is not present return not found
            if (mapping == null || mapping.DocumentDescriptorId == null)
            {
                var deleted = _documentDeletedReader.AllUnsorted.Where(d => d.Handle == handle).ToList();

                if (deleted.Count == 0)
                {
                    return(GetFromSecondary(tenantId, handle, format));
                }

                return(DocumentDeleted(handle, deleted));
            }

            var document = _documentDescriptorReader.FindOneById(mapping.DocumentDescriptorId);

            if (document == null)
            {
                return(GetFromSecondary(tenantId, handle, format));
            }

            var fileName = fname != null ? new FileNameWithExtension(fname) : null;

            if (format == DocumentFormats.Original)
            {
                return(StreamFile(
                           document.GetFormatBlobId(format),
                           fileName ?? mapping.FileName
                           ));
            }

            BlobId formatBlobId = document.GetFormatBlobId(format);

            if (formatBlobId == BlobId.Null)
            {
                return(Request.CreateErrorResponse(
                           HttpStatusCode.NotFound,
                           string.Format("Document {0} doesn't have format {1}",
                                         handle,
                                         format
                                         )
                           ));
            }

            return(StreamFile(formatBlobId, fileName));
        }
 public DocumentDescriptorDeleted(
     BlobId blobId, 
     BlobId[] formats,
     DocumentHandle[] attachments)
 {
     BlobId = blobId;
     BlobFormatsId = formats;
     Attachments = attachments;
 }
 public CreateDocumentAsCopy(
     DocumentHandle handle, 
     DocumentDescriptorId descriptorId,
     DocumentHandleInfo handleInfo)
 {
     Handle = handle;
     DocumentDescriptorId = descriptorId;
     HandleInfo = handleInfo;
 }
        public void request_for_invalid_file_handle_should_404()
        {
            var documentHandle = new DocumentHandle("not_in_store");
            var format = new DocumentFormat("any_format");
            DocumentDeletedReader.AllUnsorted.Returns(new List<DocumentDeletedReadModel>().AsQueryable());
            var response = Controller.GetFormat(_tenantId, documentHandle, format).Result;

            Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode);
            Assert.AreEqual("Document not_in_store not found", response.GetError().Message);
        }
 public DocumentHandleInfo(
     DocumentHandle handle,
     FileNameWithExtension fileName,
     DocumentCustomData customData = null
     )
 {
     Handle = handle;
     FileName = fileName;
     CustomData = customData;
 }
        public async Task <HttpResponseMessage> GetFormat(
            TenantId tenantId,
            DocumentHandle handle,
            DocumentFormat format,
            string fname = null
            )
        {
            var mapping = _handleWriter.FindOneById(handle);

            //If mapping is not present return not found
            if (mapping == null || mapping.DocumentDescriptorId == null)
            {
                var deleted = _documentDeletedReader.AllUnsorted.Where(d => d.Handle == handle).ToList();

                if (deleted.Count == 0)
                {
                    return(DocumentNotFound(handle));
                }

                return(DocumentDeleted(handle, deleted));
            }


            var document = _documentDescriptorReader.FindOneById(mapping.DocumentDescriptorId);

            if (document == null)
            {
                return(DocumentNotFound(handle));
            }

            var fileName = fname != null ? new FileNameWithExtension(fname) : null;

            if (format == DocumentFormats.Original)
            {
                return(StreamFile(
                           document.GetFormatBlobId(format),
                           fileName ?? mapping.FileName
                           ));
            }

            BlobId formatBlobId = document.GetFormatBlobId(format);

            if (formatBlobId == BlobId.Null)
            {
                return(Request.CreateErrorResponse(
                           HttpStatusCode.NotFound,
                           string.Format("Document {0} doesn't have format {1}",
                                         handle,
                                         format
                                         )
                           ));
            }

            return(StreamFile(formatBlobId, fileName));
        }
        public HttpResponseMessage GetCustomData(TenantId tenantId, DocumentHandle handle)
        {
            var data = _handleWriter.FindOneById(handle);

            if (data == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Document not found"));
            }

            return(Request.CreateResponse(HttpStatusCode.OK, data.CustomData));
        }
        public HttpResponseMessage GetFileName(TenantId tenantId, DocumentHandle handle)
        {
            var data = _handleWriter.FindOneById(handle);

            if (data == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Document not found"));
            }
            var name = data.FileName != null?data.FileName.ToString() : "";

            return(Request.CreateResponse(HttpStatusCode.OK, new { FileName = name }));
        }
 public DocumentCopied(
     DocumentHandle handle, 
     DocumentDescriptorId documentDescriptorId,
     DocumentHandleInfo handleInfo)
 {
     if (handle == null) throw new ArgumentNullException("handle");
     if (documentDescriptorId == null) throw new ArgumentNullException("documentDescriptorId");
     if (handleInfo == null) throw new ArgumentNullException("handleInfo");
     DocumentDescriptorId = documentDescriptorId;
     NewHandle = handle;
     HandleInfo = handleInfo;
 }
        DocumentDescriptorReadModel GetDocumentDescriptorByHandle(DocumentHandle handle)
        {
            var mapping = _handleWriter.FindOneById(handle);

            //check if handle is not present, or if the handle still missing descriptor (still not deduplicated)
            if (mapping == null || mapping.DocumentDescriptorId == null)
            {
                return(null);
            }

            return(_documentDescriptorReader.FindOneById(mapping.DocumentDescriptorId));
        }
        public void add_attachment_to_document_descriptor()
        {
            ElaborateDocumentDescriptorInitialized(1);
            ElaborateDocumentDescriptorInitialized(2);
            var attachmentHandle = new DocumentHandle("Attachment");
            _sut.On(new DocumentDescriptorHasNewAttachment(attachmentHandle, "Path.txt")
                .AssignIdForTest(new DocumentDescriptorId(1)));

            var documentDescriptor = _documentReader.AllUnsorted.Single(d => d.Id == new DocumentDescriptorId(1));
            Assert.That(documentDescriptor.Attachments.Select(a => a.Handle),
                Is.EquivalentTo(new[] { attachmentHandle }));
        }
 public InitializeDocumentDescriptorAsAttach(
     DocumentDescriptorId aggregateId, 
     BlobId blobId, 
     DocumentHandleInfo handleInfo,
     DocumentHandle fatherHandle,
     DocumentDescriptorId fatherDocumentDescriptorId,
     FileHash hash, 
     FileNameWithExtension fileName)
     : base(aggregateId, blobId, handleInfo, hash, fileName)
 {
     FatherHandle = fatherHandle;
     FatherDocumentDescriptorId = fatherDocumentDescriptorId;
 }
        public void add_attachment_to_document_descriptor()
        {
            ElaborateDocumentDescriptorInitialized(1);
            ElaborateDocumentDescriptorInitialized(2);
            var attachmentHandle = new DocumentHandle("Attachment");

            _sut.On(new DocumentDescriptorHasNewAttachment(attachmentHandle, "Path.txt")
                    .AssignIdForTest(new DocumentDescriptorId(1)));

            var documentDescriptor = _documentReader.AllUnsorted.Single(d => d.Id == new DocumentDescriptorId(1));

            Assert.That(documentDescriptor.Attachments.Select(a => a.Handle),
                        Is.EquivalentTo(new[] { attachmentHandle }));
        }
        public async Task <HttpResponseMessage> UploadAttach(TenantId tenantId, DocumentHandle fatherHandle, DocumentHandle attachSource)
        {
            var realAttacHandle  = GetAttachHandleFromAttachSource(attachSource);
            var fatherDescriptor = _documentDescriptorReader.AllUnsorted.SingleOrDefault(dd =>
                                                                                         dd.Documents.Contains(fatherHandle));

            if (fatherDescriptor == null)
            {
                return(Request.CreateErrorResponse(
                           HttpStatusCode.NotFound,
                           string.Format("Handle {0} not found", fatherHandle)
                           ));
            }
            return(await InnerUploadDocument(tenantId, realAttacHandle, fatherHandle, fatherDescriptor.Id));
        }
        public HttpResponseMessage DeleteFile(TenantId tenantId, DocumentHandle handle)
        {
            var documentDescritptor = GetDocumentDescriptorByHandle(handle);

            if (documentDescritptor == null)
            {
                return(DocumentNotFound(handle));
            }

            CommandBus.Send(new DeleteDocument(handle), "api");

            return(Request.CreateResponse(
                       HttpStatusCode.Accepted,
                       string.Format("Document marked for deletion {0}", handle)
                       ));
        }
        private HttpResponseMessage GetFromSecondary(String tenantId, DocumentHandle handle, DocumentFormat documentFormat)
        {
            if (_configService.SecondaryAddressConfigured)
            {
                var secondaryUrl = $"{_configService.SecondaryDocumentStoreAddress}/{tenantId}/documents/{handle}/{documentFormat}";

                var response = Request.CreateResponse(HttpStatusCode.Moved);
                response.Headers.Location = new Uri(secondaryUrl);
                return(response);
            }

            return(Request.CreateErrorResponse(
                       HttpStatusCode.NotFound,
                       string.Format("Document {0} not found", handle)
                       ));
        }
        public HttpResponseMessage GetCustomData(
#pragma warning disable RCS1163 // Unused parameter.
#pragma warning disable IDE0060 // Remove unused parameter
            TenantId tenantId,  //do not remove, even if not used in the method, actually it is used from the infrastructure to determine tenant
#pragma warning restore IDE0060 // Remove unused parameter
#pragma warning restore RCS1163 // Unused parameter.
            DocumentHandle handle)
        {
            var data = _handleWriter.FindOneById(handle);

            if (data == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Document not found"));
            }

            return(Request.CreateResponse(HttpStatusCode.OK, data.CustomData));
        }
        public void request_for_missing_document_should_404()
        {
            // arrange
            var documentHandle = new DocumentHandle("doc");
            var info = new DocumentHandleInfo(
                new DocumentHandle("doc"),
                new FileNameWithExtension("a.file")
                );
            var format = new DocumentFormat("any_format");
            SetupDocumentHandle(info, new DocumentDescriptorId(1));

            // act
            var response = Controller.GetFormat(_tenantId, documentHandle, format).Result;

            // assert
            Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode);
            Assert.AreEqual("Document doc not found", response.GetError().Message);
        }
        public async Task <HttpResponseMessage> GetFormatList(
            TenantId tenantId,
            DocumentHandle handle
            )
        {
            var documentDescriptor = GetDocumentDescriptorByHandle(handle);

            if (documentDescriptor == null)
            {
                return(DocumentNotFound(handle));
            }

            var formats = documentDescriptor.Formats.ToDictionary(x =>
                                                                  (string)x.Key,
                                                                  x => Url.Content("/" + tenantId + "/documents/" + handle + "/" + x.Key)
                                                                  );

            return(Request.CreateResponse(HttpStatusCode.OK, formats));
        }
        public async Task <HttpResponseMessage> DeleteFormatFromDocument(
            TenantId tenantId,
            DocumentHandle handle,
            DocumentFormat format)
        {
            var documentDescriptor = GetDocumentDescriptorByHandle(handle);

            if (documentDescriptor == null)
            {
                return(DocumentNotFound(handle));
            }

            CommandBus.Send(new DeleteFormatFromDocumentDescriptor(documentDescriptor.Id, format), "api");

            return(Request.CreateResponse(
                       HttpStatusCode.Accepted,
                       string.Format("Format {0} marked for deletion for handle {0}", format, handle)
                       ));
        }
        private void CreateDocument(
            DocumentDescriptorId documentDescriptorId,
            BlobId blobId,
            DocumentHandle handle,
            DocumentHandle fatherHandle,
            DocumentDescriptorId fatherDocumentDescriptorId,
            FileNameWithExtension fileName,
            DocumentCustomData customData
            )
        {
            var      descriptor = _blobStore.GetDescriptor(blobId);
            ICommand createDocument;
            var      handleInfo = new DocumentHandleInfo(handle, fileName, customData);

            if (fatherHandle == null)
            {
                if (Logger.IsDebugEnabled)
                {
                    Logger.DebugFormat("Initialize DocumentDescriptor {0} ", documentDescriptorId);
                }

                createDocument = new InitializeDocumentDescriptor(documentDescriptorId, blobId, handleInfo, descriptor.Hash, fileName);
            }
            else
            {
                if (Logger.IsDebugEnabled)
                {
                    Logger.DebugFormat("Initialize DocumentDescriptor as attach {0} ", documentDescriptorId);
                }

                createDocument = new InitializeDocumentDescriptorAsAttach(
                    documentDescriptorId,
                    blobId,
                    handleInfo,
                    fatherHandle,
                    fatherDocumentDescriptorId,
                    descriptor.Hash, fileName);
            }
            CommandBus.Send(createDocument, "api");
        }
        public HttpResponseMessage DeleteFile(
#pragma warning disable RCS1163 // Unused parameter.
#pragma warning disable IDE0060 // Remove unused parameter
            TenantId tenantId,  //do not remove, even if not used in the method, actually it is used from the infrastructure to determine tenant
#pragma warning restore IDE0060 // Remove unused parameter
#pragma warning restore RCS1163 // Unused parameter.
            DocumentHandle handle)
        {
            var documentDescritptor = GetDocumentDescriptorByHandle(handle);

            if (documentDescritptor == null)
            {
                return(DocumentNotFound(handle));
            }

            CommandBus.Send(new DeleteDocument(handle), "api");

            return(Request.CreateResponse(
                       HttpStatusCode.Accepted,
                       string.Format("Document marked for deletion {0}", handle)
                       ));
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="tenantId"></param>
        /// <param name="handle"></param>
        /// <param name="fatherHandle">Different from null only when you want to upload
        /// a document that is an attachment of another document</param>
        /// <param name="fatherHandleDescriptorId">Descriptor id that contains reference
        /// to <paramref name="fatherHandle"/></param>
        /// <returns></returns>
        private async Task <HttpResponseMessage> InnerUploadDocument(
            TenantId tenantId,
            DocumentHandle handle,
            DocumentHandle fatherHandle,
            DocumentDescriptorId fatherHandleDescriptorId)
        {
            var documentId = _identityGenerator.New <DocumentDescriptorId>();

            Logger.DebugFormat("Incoming file {0}, assigned {1}", handle, documentId);
            var errorMessage = await UploadFromHttpContent(Request.Content);

            Logger.DebugFormat("File {0} processed with message {1}", _blobId, errorMessage ?? "OK");

            if (errorMessage != null)
            {
                return(Request.CreateErrorResponse(
                           HttpStatusCode.BadRequest,
                           errorMessage
                           ));
            }

            CreateDocument(documentId, _blobId, handle, fatherHandle, fatherHandleDescriptorId, _fileName, _customData);

            Logger.DebugFormat("File {0} uploaded as {1}", _blobId, documentId);

            var storedFile = _blobStore.GetDescriptor(_blobId);

            return(Request.CreateResponse(
                       HttpStatusCode.OK,
                       new UploadedDocumentResponse
            {
                Handle = handle,
                Hash = storedFile.Hash,
                HashType = "md5",
                Uri = Url.Content("/" + tenantId + "/documents/" + handle)
            }
                       ));
        }
        public async Task <HttpResponseMessage> GetAttachmentList(
            TenantId tenantId,
            DocumentHandle handle
            )
        {
            var documentDescriptor = _documentDescriptorReader.AllUnsorted.SingleOrDefault(d =>
                                                                                           d.Documents.Contains(handle));

            if (documentDescriptor == null)
            {
                return(DocumentNotFound(handle));
            }

            if (documentDescriptor.Attachments == null || documentDescriptor.Attachments.Count == 0)
            {
                return(Request.CreateResponse(HttpStatusCode.OK, new List <ClientAttachmentInfo>()));
            }

            var attachments = documentDescriptor.Attachments
                              .Select(a =>
            {
                var attachment = new ClientAttachmentInfo()
                {
                    Handle       = Url.Content("/" + tenantId + "/documents/" + a.Handle),
                    RelativePath = a.RelativePath
                };
                var hasAttachment = _documentDescriptorReader.AllUnsorted.Any(d =>
                                                                              d.Documents.Contains(a.Handle) &&
                                                                              d.Attachments.Count > 0);
                attachment.HasAttachments = hasAttachment;
                return(attachment);
            })
                              .ToList();

            return(Request.CreateResponse(HttpStatusCode.OK, attachments));
        }
        public async Task<HttpResponseMessage> GetFormat(
            TenantId tenantId,
            DocumentHandle handle,
            DocumentFormat format,
            string fname = null
        )
        {
            var mapping = _handleWriter.FindOneById(handle);

            //If mapping is not present return not found
            if (mapping == null || mapping.DocumentDescriptorId == null)
            {
                var deleted = _documentDeletedReader.AllUnsorted.Where(d => d.Handle == handle).ToList();

                if (deleted.Count == 0)
                    return DocumentNotFound(handle);

                return DocumentDeleted(handle, deleted);
            }
               

            var document = _documentDescriptorReader.FindOneById(mapping.DocumentDescriptorId);

            if (document == null)
            {
                return DocumentNotFound(handle);
            }

            var fileName = fname != null ? new FileNameWithExtension(fname) : null;

            if (format == DocumentFormats.Original)
            {
                return StreamFile(
                    document.GetFormatBlobId(format),
                    fileName ?? mapping.FileName
                );
            }

            BlobId formatBlobId = document.GetFormatBlobId(format);
            if (formatBlobId == BlobId.Null)
            {
                return Request.CreateErrorResponse(
                    HttpStatusCode.NotFound,
                    string.Format("Document {0} doesn't have format {1}",
                        handle,
                        format
                    )
                );
            }

            return StreamFile(formatBlobId, fileName);
        }
        public async Task<HttpResponseMessage> GetAttachmentFat(
            TenantId tenantId,
            DocumentHandle handle
        )
        {
            var documentDescriptor = _documentDescriptorReader.AllUnsorted.SingleOrDefault(d =>
                  d.Documents.Contains(handle));

            if (documentDescriptor == null)
            {
                return DocumentNotFound(handle);
            }

            List<DocumentAttachmentsFat.AttachmentInfo> fat = new List<DocumentAttachmentsFat.AttachmentInfo>();
            if (documentDescriptor.Attachments != null && documentDescriptor.Attachments.Count > 0)
            {
                ScanAttachments(
                    tenantId,
                    documentDescriptor.Attachments,
                    fat,
                    "",
                    0,
                    5);
            }

            return Request.CreateResponse(HttpStatusCode.OK, fat);
        }
        public async Task<HttpResponseMessage> GetAttachmentList(
            TenantId tenantId,
            DocumentHandle handle
        )
        {
            var documentDescriptor = _documentDescriptorReader.AllUnsorted.SingleOrDefault(d =>
                  d.Documents.Contains(handle));

            if (documentDescriptor == null)
            {
                return DocumentNotFound(handle);
            }

            if (documentDescriptor.Attachments == null || documentDescriptor.Attachments.Count == 0)
                return Request.CreateResponse(HttpStatusCode.OK, new List<ClientAttachmentInfo>());

            var attachments = documentDescriptor.Attachments
                .Select(a =>
                {
                    var attachment = new ClientAttachmentInfo()
                    {
                        Handle = Url.Content("/" + tenantId + "/documents/" + a.Handle),
                        RelativePath = a.RelativePath
                    };
                    var hasAttachment = _documentDescriptorReader.AllUnsorted.Any(d =>
                        d.Documents.Contains(a.Handle) &&
                        d.Attachments.Count > 0);
                    attachment.HasAttachments = hasAttachment;
                    return attachment;
                })
                .ToList();

            return Request.CreateResponse(HttpStatusCode.OK, attachments);
        }
 public async Task<HttpResponseMessage> Upload(TenantId tenantId, DocumentHandle handle)
 {
     return await InnerUploadDocument(tenantId, handle, null, null);
 }
 private void CreateDocument(
     DocumentDescriptorId documentDescriptorId,
     BlobId blobId,
     DocumentHandle handle,
     DocumentHandle fatherHandle,
     DocumentDescriptorId fatherDocumentDescriptorId,
     FileNameWithExtension fileName,
     DocumentCustomData customData
 )
 {
     var descriptor = _blobStore.GetDescriptor(blobId);
     ICommand createDocument;
     var handleInfo = new DocumentHandleInfo(handle, fileName, customData);
     if (fatherHandle == null)
     {
         if (Logger.IsDebugEnabled) Logger.DebugFormat("Initialize DocumentDescriptor {0} ", documentDescriptorId);
         createDocument = new InitializeDocumentDescriptor(documentDescriptorId, blobId, handleInfo, descriptor.Hash, fileName);
     }
     else
     {
         if (Logger.IsDebugEnabled) Logger.DebugFormat("Initialize DocumentDescriptor as attach {0} ", documentDescriptorId);
         createDocument = new InitializeDocumentDescriptorAsAttach(
             documentDescriptorId,
             blobId,
             handleInfo,
             fatherHandle,
             fatherDocumentDescriptorId,
             descriptor.Hash, fileName);
     }
     CommandBus.Send(createDocument, "api");
 }
        public HttpResponseMessage DeleteFile(TenantId tenantId, DocumentHandle handle)
        {
            var documentDescritptor = GetDocumentDescriptorByHandle(handle);
            if (documentDescritptor == null)
                return DocumentNotFound(handle);

            CommandBus.Send(new DeleteDocument(handle), "api");

            return Request.CreateResponse(
                HttpStatusCode.Accepted,
                string.Format("Document marked for deletion {0}", handle)
            );
        }
 public DocumentState(DocumentHandle handle) : this()
 {
     this.Handle = handle;
 }
예제 #43
0
 internal void AddAttachments(DocumentHandle attachmentHandle, String attachmentPath)
 {
     Attachments.Add(new DocumentAttachmentReadModel(attachmentHandle, attachmentPath));
 }
        private DocumentHandle GetAttachHandleFromAttachSource(String attachSource)
        {
            var realAttacHandle = new DocumentHandle(attachSource + "_" + _counterService.GetNext(attachSource));

            return(realAttacHandle);
        }
 public async Task <HttpResponseMessage> Upload(TenantId tenantId, DocumentHandle handle)
 {
     return(await InnerUploadDocument(tenantId, handle, null, null));
 }
예제 #46
0
 public void Remove(DocumentHandle handle)
 {
     this.Documents.Remove(handle);
 }
 HttpResponseMessage DocumentNotFound(DocumentHandle handle)
 {
     return Request.CreateErrorResponse(
         HttpStatusCode.NotFound,
         string.Format("Document {0} not found", handle)
         );
 }
 HttpResponseMessage DocumentDeleted(DocumentHandle handle, IEnumerable<DocumentDeletedReadModel> deletions)
 {
     return Request.CreateErrorResponse(
         HttpStatusCode.NotFound,
         string.Format("Document {0} was deleted at: {1}", handle, String.Join(", ", deletions.Select(d => d.DeletionDate)))
         );
 }
        public async Task <HttpResponseMessage> AddFormatToDocument(TenantId tenantId, DocumentFormat format)
        {
            var errorMessage = await AddFormatFromHttpContent(Request.Content, format);

            Logger.DebugFormat("File {0} processed with message {1}", _blobId, errorMessage);

            if (errorMessage != null)
            {
                Logger.Error("Error Adding format To Document: " + errorMessage);
                return(Request.CreateErrorResponse(
                           HttpStatusCode.BadRequest,
                           errorMessage
                           ));
            }

            String queueName = _customData[AddFormatToDocumentParameters.QueueName] as String;
            String jobId     = _customData[AddFormatToDocumentParameters.JobId] as String;
            DocumentDescriptorId documentId;

            if (String.IsNullOrEmpty(queueName))
            {
                //user ask for handle, we need to grab the handle
                var documentHandle = new DocumentHandle(_customData[AddFormatToDocumentParameters.DocumentHandle] as String);
                var handle         = _handleWriter.FindOneById(documentHandle);
                documentId = handle.DocumentDescriptorId;
                if (documentId == null)
                {
                    Logger.ErrorFormat("Trying to add a format for Handle {0} with a null DocumentId", documentHandle);
                    return(Request.CreateErrorResponse(
                               HttpStatusCode.BadRequest,
                               ""
                               ));
                }
                Logger.DebugFormat("Add format {0} to handle {1} and document id {2}", format, handle, documentId);
            }
            else
            {
                var job = _queueDispatcher.GetJob(queueName, jobId);

                if (job == null)
                {
                    Logger.WarnFormat("Job id {0} not found in queue {1}", jobId, queueName);
                    return(Request.CreateErrorResponse(
                               HttpStatusCode.BadRequest,
                               String.Format("Job id {0} not found in queue {1}", jobId, queueName)));
                }
                documentId = job.DocumentDescriptorId;
                if (documentId == null)
                {
                    Logger.ErrorFormat("Trying to add a format for Job Id {0} queue {1} - Job has DocumentDescriptorId null", jobId, queueName);
                    return(Request.CreateErrorResponse(
                               HttpStatusCode.BadRequest,
                               ""
                               ));
                }
                //need to check if the descriptor is deleted
                var exists = _documentDescriptorReader
                             .AllUnsorted
                             .Where(d => d.Id == documentId)
                             .Any();
                if (!exists)
                {
                    Logger.ErrorFormat("Trying to add a format for Job Id {0} queue {1} - DocumentDescriptor does not exists or was deleted!", jobId, queueName);
                    return(Request.CreateErrorResponse(
                               HttpStatusCode.BadRequest,
                               ""
                               ));
                }
                Logger.DebugFormat("Add format {0} to job id {1} and document id {2}", format, job.Id, documentId);
            }

            if (format == "null")
            {
                var formatFromFileName = _documentFormatTranslator.GetFormatFromFileName(_fileName);
                if (formatFromFileName == null)
                {
                    String error = "Format not specified and no known format for file: " + _fileName;
                    Logger.Error(error);
                    return(Request.CreateErrorResponse(
                               HttpStatusCode.BadRequest,
                               error
                               ));
                }
                format = new DocumentFormat(formatFromFileName);
            }

            var createdById = new PipelineId(_customData[AddFormatToDocumentParameters.CreatedBy] as String);

            Logger.DebugFormat("Incoming new format for documentId {0}", documentId);

            var command = new AddFormatToDocumentDescriptor(documentId, format, _blobId, createdById);

            CommandBus.Send(command, "api");

            return(Request.CreateResponse(
                       HttpStatusCode.OK,
                       new AddFormatToDocumentResponse
            {
                Result = true,
            }
                       ));
        }
        public async Task<HttpResponseMessage> GetHandleInfo(
            TenantId tenantId, 
            DocumentHandle handle)
        {
            var handleString = handle.ToString();
            var regex = "/" + handleString.Replace("/", "//") + "/";
            var descriptors = _documentDescriptorReader.Collection
                .Find(Builders<DocumentDescriptorReadModel>.Filter.Regex("Documents", new MongoDB.Bson.BsonRegularExpression(regex)))
                .Limit(20);

            var retValue = new List<DocumentInfo>();
            foreach (var d in descriptors.ToEnumerable())
            {
                var documentHandle = d.Documents.FirstOrDefault(dd => dd.ToString().Contains(handleString));
                var di = new DocumentInfo()
                {
                    DocumentHandle = documentHandle,
                    Formats = d.Formats.Select(f => new DocumentFormatInfo()
                    {
                        FormatType = f.Key,
                        FormatUrl = Url.Content("/" + tenantId + "/documents/" + documentHandle + "/" + f.Key)
                    }).ToList()
                };
                retValue.Add(di);
            }

            return Request.CreateResponse(HttpStatusCode.OK, retValue);
        }
        public HttpResponseMessage GetCustomData(TenantId tenantId, DocumentHandle handle)
        {
            var data = _handleWriter.FindOneById(handle);
            if (data == null)
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Document not found");

            return Request.CreateResponse(HttpStatusCode.OK, data.CustomData);
        }
        DocumentDescriptorReadModel GetDocumentDescriptorByHandle(DocumentHandle handle)
        {
            var mapping = _handleWriter.FindOneById(handle);
            //check if handle is not present, or if the handle still missing descriptor (still not deduplicated)
            if (mapping == null || mapping.DocumentDescriptorId == null)
                return null;

            return _documentDescriptorReader.FindOneById(mapping.DocumentDescriptorId);
        }
 public HttpResponseMessage GetFileName(TenantId tenantId, DocumentHandle handle)
 {
     var data = _handleWriter.FindOneById(handle);
     if (data == null)
         return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Document not found");
     var name = data.FileName != null ? data.FileName.FileName : "";
     return Request.CreateResponse(HttpStatusCode.OK, new { FileName = name });
 }
예제 #54
0
 public DocumentAttachmentReadModel(DocumentHandle attachmentHandle, string attachmentPath)
 {
     Handle       = attachmentHandle;
     RelativePath = attachmentPath;
 }
        public async Task<HttpResponseMessage> GetFormatList(
            TenantId tenantId,
            DocumentHandle handle
        )
        {
            var documentDescriptor = GetDocumentDescriptorByHandle(handle);

            if (documentDescriptor == null)
            {
                return DocumentNotFound(handle);
            }

            var formats = documentDescriptor.Formats.ToDictionary(x =>
                (string)x.Key,
                x => Url.Content("/" + tenantId + "/documents/" + handle + "/" + x.Key)
            );
            return Request.CreateResponse(HttpStatusCode.OK, formats);
        }
 public DocumentHandleDetached(DocumentHandle handle)
 {
     Handle = handle;
 }
        public async Task<HttpResponseMessage> DeleteFormatFromDocument(
            TenantId tenantId,
            DocumentHandle handle,
            DocumentFormat format)
        {
            var documentDescriptor = GetDocumentDescriptorByHandle(handle);
            if (documentDescriptor == null)
                return DocumentNotFound(handle);

            CommandBus.Send(new DeleteFormatFromDocumentDescriptor(documentDescriptor.Id, format), "api");

            return Request.CreateResponse(
                HttpStatusCode.Accepted,
                string.Format("Format {0} marked for deletion for handle {0}", format, handle)
            );
        }
 public DeleteDocument(DocumentHandle handle)
 {
     Handle = handle;
 }
예제 #59
0
 public void AddHandle(DocumentHandle handle)
 {
     this.Documents.Add(handle);
 }