Exemplo n.º 1
0
        public async Task <FileStreamResult> Download(long documentId, string clientId, string secret, string userId)
        {
            //Validate clientId & secret
            if ((!Repository.AppManagement.IsValidUser(userId)) || (!Repository.AppManagement.IsValidClientSecret(clientId, secret)))
            {
                return(null);
            }

            Models.Document document = Repository.Documents.Get(documentId);

            AzureBlobStorage azure = new AzureBlobStorage();

            using (MemoryStream memStream = new MemoryStream())
            {
                MemoryStream output = await azure.DownloadSingleFileAsync(document);

                byte[] file = memStream.ToArray();
                if (output != null)
                {
                    output.Write(file, 0, file.Length);
                    output.Position = 0;

                    HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + document.Name);

                    return(File(output, MIMEAssistant.GetMIMEType(document.Name)));
                }
                else
                {
                    //What to do here? If Azure blob storage connection settings are not valid then this is where code will land
                    return(null);
                }
            }
        }
Exemplo n.º 2
0
        public async Task <IActionResult> DownloadAttachment(string filename, string id)
        {
            ErrorResponse errorResponse = new ErrorResponse();

            byte[] array;
            try
            {
                array = await _mailService.DownloadAttachment(id + filename);
            }
            catch (Exception ex)
            {
                errorResponse.Errors.Add(new ErrorModel {
                    FieldName = ex.Message, Message = ex.InnerException.Message
                });
                Response.StatusCode = 400;
                return(new JsonResult(errorResponse));
            }

            string extension;

            try
            {
                extension = filename.Substring(filename.LastIndexOf('.'));
            }
            catch (Exception)
            {
                extension = "";
            }
            return(new JsonResult(File(array, MIMEAssistant.GetMIMEType(extension), filename)));
        }
Exemplo n.º 3
0
        public void Download(int id)
        {
            FeedingSource fs = this.feedingSourceTasks.GetFeedingSource(id);

            if (fs != null && fs.FileData != null)
            {
                if (((PrfPrincipal)User).CanAccess(fs))
                {
                    if ((fs.ApprovedBy != null || fs.RejectedBy != null) && fs.IsReadOnly)
                    {
                        Response.StatusCode        = (int)HttpStatusCode.Unauthorized;
                        Response.StatusDescription = "Source has been marked read only and has already been approved or rejected, so is not available for download.";
                    }
                    else
                    {
                        string contentType = MIMEAssistant.GetMIMEType(fs.Name);
                        Response.ContentType = contentType;
                        Response.AddHeader("Content-Disposition", "attachment; filename=\"" + fs.Name + "\"");
                        Response.OutputStream.Write(fs.FileData, 0, fs.FileData.Length);
                    }
                }
                else
                {
                    Response.StatusCode        = (int)HttpStatusCode.Unauthorized;
                    Response.StatusDescription = "You are not authorized to download this source.";
                }
            }
            else
            {
                Response.StatusCode        = (int)HttpStatusCode.NotFound;
                Response.StatusDescription = "That feeding source doesn't exist.";
            }
        }
Exemplo n.º 4
0
        public IList <SourceDTO> GetSourcesToIndex(IStatelessSession session, int startSourceId, int num, string prefix)
        {
            // get list of sources to index
            IList <SourceDTO> dtos = this.GetAllSourceDTOs(session, true, false);

            // filter for path prefix
            if (!string.IsNullOrEmpty(prefix))
            {
                dtos = dtos.Where(x => !string.IsNullOrEmpty(x.SourcePath) && x.SourcePath.StartsWith(prefix, StringComparison.InvariantCultureIgnoreCase)).ToList();
            }

            // filtering out non-text media files
            dtos = dtos.Where(x => !MIMEAssistant.GetMIMEType(x.SourceName).StartsWith("image") &&
                              !MIMEAssistant.GetMIMEType(x.SourceName).StartsWith("audio") &&
                              !MIMEAssistant.GetMIMEType(x.SourceName).StartsWith("video"))
                   .Where(x => !Source.IGNORED_FILE_EXTENSIONS.Contains(x.FileExtension))
                   .Where(x => x.SourceID > startSourceId)
                   .OrderBy(x => x.SourceID)
                   .ToList();

            log.Info("Found " + dtos.Count + " sources to index, starting from SourceID=" + startSourceId + " with prefix=" + prefix + "."
                     + (num > 0 ? " Taking " + num + "." : string.Empty));

            if (num > 0)
            {
                dtos = dtos.Take(num).ToList();
            }

            return(dtos);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Upload and attach a file to a parent object (Issue, Equipment, etc)
        /// </summary>
        /// <param name="original">The file to upload</param>
        /// <param name="thumbnail">A thumbnail representation of the file in png format</param>
        /// <param name="source_id">The unique ID of the parent object</param>
        /// <param name="source_type">The type of parent object (Issue, Equipment, Task)</param>
        /// <param name="caption">The caption for the attachment</param>
        /// <param name="tags">A comma separated list of tags</param>
        /// <param name="project_id">The project ID to upload the attachment to</param>
        public void createAttachment(FileInfo original, FileInfo thumbnail, string source_id, string source_type, string caption = "", string tags = "", string project_id = null)
        {
            Dictionary <string, string> p = new Dictionary <string, string>();

            p.Add("project_id", project_id == null ? DefaultProject.project_id : project_id);
            Dictionary <string, string> att = new Dictionary <string, string>();

            att["id"]             = Guid.NewGuid().ToString().ToLower();
            att["deleted"]        = "0";
            att["fcreate_date"]   = original.CreationTimeUtc.ToString(_datetime_format);
            att["fmod_date"]      = original.LastWriteTimeUtc.ToString(_datetime_format);
            att["created_at"]     = original.CreationTimeUtc.ToString(_datetime_format);
            att["updated_at"]     = original.LastWriteTimeUtc.ToString(_datetime_format);
            att["caption"]        = caption;
            att["tags"]           = tags;
            att["size"]           = original.Length.ToString();
            att["content_type"]   = MIMEAssistant.GetMIMEType(original.Name);
            att["filename"]       = original.Name;
            att["container_id"]   = source_id;
            att["container_type"] = source_type;

            p.Add("attachment", JsonConvert.SerializeObject(att));
            Dictionary <string, FileInfo> files = new Dictionary <string, FileInfo>();

            files.Add("original", original);
            files.Add("thumb", thumbnail);

            performRESTRequest(_attachment, p, Method.POST, files);
        }
Exemplo n.º 6
0
 public IList <SourceDTO> GetUnindexableMediaSources()
 {
     return(this.GetAllSourceDTOs(false, false)
            .Where(x => MIMEAssistant.GetMIMEType(x.SourceName).StartsWith("image") ||
                   MIMEAssistant.GetMIMEType(x.SourceName).StartsWith("audio") ||
                   MIMEAssistant.GetMIMEType(x.SourceName).StartsWith("video") ||
                   Source.IGNORED_FILE_EXTENSIONS.Contains(x.FileExtension))
            .OrderBy(x => x.SourceID)
            .ToList());
 }
Exemplo n.º 7
0
        // source preview references
        public ActionResult Images(string filename)
        {
            string contentType = MIMEAssistant.GetMIMEType(filename);
            string folderName  = ConfigurationManager.AppSettings["PreviewTempFolder"];

            if (!Directory.Exists(folderName))
            {
                Directory.CreateDirectory(folderName);
            }
            return(File(folderName + "\\" + filename, contentType));
        }
Exemplo n.º 8
0
        public void Download(int requestId, int id)
        {
            Attachment att = this.requestAttachmentTasks.GetAttachment(id);

            if (att != null && att.FileData != null)
            {
                string contentType = MIMEAssistant.GetMIMEType(att.FileName);
                Response.ContentType = contentType;
                Response.AddHeader("Content-Disposition", "attachment; filename=\"" + att.FileName + "\"");
                Response.OutputStream.Write(att.FileData, 0, att.FileData.Length);
            }
            else
            {
                Response.StatusCode        = (int)HttpStatusCode.NotFound;
                Response.StatusDescription = "That attachment doesn't exist.";
            }
        }
Exemplo n.º 9
0
        public ActionResult Download(int id)
        {
            DocumentationFile file = this.docTasks.GetDocumentationFile(id);

            if (file != null)
            {
                return(new FileStreamResult(
                           new MemoryStream(file.FileData),
                           MIMEAssistant.GetMIMEType(file.FileName))
                {
                    FileDownloadName = file.FileName
                });
            }
            else
            {
                return(new HttpNotFoundResult());
            }
        }
Exemplo n.º 10
0
        public JsonNetResult Upload(HttpPostedFileBase FileData)
        {
            if (FileData != null && FileData.ContentLength > 0)
            {
                string contentType = MIMEAssistant.GetMIMEType(FileData.FileName);
                if (!string.IsNullOrEmpty(contentType) && !contentType.StartsWith("image"))
                {
                    Response.StatusCode = (int)HttpStatusCode.BadRequest;
                    return(JsonNet("File received wasn't an image."));
                }

                if (this.photoTasks.GetPhoto(FileData.FileName) != null)
                {
                    Response.StatusCode = (int)HttpStatusCode.BadRequest;
                    return(JsonNet("File name already exists."));
                }

                Photo p = new Photo();
                p.PhotoName     = FileData.FileName;
                p.FileName      = FileData.FileName;
                p.FileTimeStamp = DateTime.Now;

                using (Stream inputStream = FileData.InputStream)
                {
                    MemoryStream memoryStream = inputStream as MemoryStream;
                    if (memoryStream == null)
                    {
                        memoryStream = new MemoryStream();
                        inputStream.CopyTo(memoryStream);
                    }
                    p.FileData = memoryStream.ToArray();
                }

                p = this.photoTasks.SavePhoto(p);
                return(JsonNet(new
                {
                    Id = p.Id,
                    FileName = p.FileName
                }));
            }
            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return(JsonNet("Didn't receive any file."));
        }
        public async Task <FileStreamResult> Download(long documentId)
        {
            Models.Document document = Repository.Documents.Get(documentId);

            AzureBlobStorage azure = new AzureBlobStorage();

            using (MemoryStream memStream = new MemoryStream())
            {
                MemoryStream output = await azure.DownloadSingleFileAsync(document);

                byte[] file = memStream.ToArray();
                output.Write(file, 0, file.Length);
                output.Position = 0;

                HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + document.Name);

                return(File(output, MIMEAssistant.GetMIMEType(document.Name)));
            }
        }
Exemplo n.º 12
0
        public JsonNetResult SetFileExtension(int id)
        {
            Source source = this.sourceTasks.GetSource(id);

            if (source != null && string.IsNullOrEmpty(source.FileExtension))
            {
                string contentType;
                try
                {
                    contentType = this.sourceContentTasks.GuessContentType(id);
                }
                catch (TextExtractionException e)
                {
                    Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    return(JsonNet(e.Message));
                }
                string ext = MIMEAssistant.GetFileExtension(contentType);
                if (!string.IsNullOrEmpty(ext))
                {
                    // required by MSSQL full-text indexing engine
                    source.FileExtension = ext;

                    // append new file extension, required for preview logic to work
                    source.SourceName = string.Join(".", new string[] { source.SourceName, ext });

                    // don't modify SourcePath, as this is currently used as a unique key to the file
                    // i.e. it may be reimported if changed
                    //source.SourcePath = string.Join(".", new string[] { source.SourcePath, ext });

                    this.sourceTasks.SaveSource(source);

                    Response.StatusCode = (int)HttpStatusCode.OK;
                    return(JsonNet(null));
                }
            }

            Response.StatusCode = (int)HttpStatusCode.NotFound;
            return(JsonNet(null));
        }
Exemplo n.º 13
0
        public ProcessingResult Process(RequestContext context)
        {
            // Init our vars.
            IRequest  request  = context.Request;
            IResponse response = context.Response;

            // Get the page.
            byte[] resource;
            string uri = request.Uri.AbsolutePath.Remove(0, 1);

            // Check if it exists.
            if (!File.Exists("Data/static/" + uri))
            {
                return(ProcessingResult.Continue);
            }
            resource = File.ReadAllBytes("Data/static/" + uri);
            response.Add(new StringHeader("Cache-Control", "max-age=28800"));
            response.Add(new StringHeader("X-Content-Class", "Static"));
            response.Body.Write(resource, 0, resource.Length);
            response.ContentType = new ContentTypeHeader(MIMEAssistant.GetMIMEType("Data/static/" + uri));
            return(ProcessingResult.SendResponse);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Just preview - doesn't record the fact like SourcesController.Preview() does. Also accessible by conditionality participants.
        /// </summary>
        /// <param name="id"></param>
        public void Preview(int id)
        {
            Source source = this.sourceTasks.GetSource(id);

            if (source == null || source.FileData == null)
            {
                Response.StatusCode        = (int)HttpStatusCode.NotFound;
                Response.StatusDescription = "That source doesn't exist.";
                return;
            }

            if (!((PrfPrincipal)User).CanAccess(source))
            {
                Response.StatusCode        = (int)HttpStatusCode.Forbidden;
                Response.StatusDescription = "You don't have permission to view this source.";
                return;
            }

            string contentType = MIMEAssistant.GetMIMEType(source.SourceName);

            if (!string.IsNullOrEmpty(contentType) && source.HasOcrText())
            {
                Response.ContentType = "text/plain";
                Response.OutputStream.Write(source.FileData, 0, source.FileData.Length);
            }
            else if (!string.IsNullOrEmpty(contentType) && (contentType.StartsWith("image") || contentType.StartsWith("text/plain")))
            {
                Response.ContentType = contentType;
                Response.OutputStream.Write(source.FileData, 0, source.FileData.Length);
            }
            else if (!string.IsNullOrEmpty(contentType) && contentType.StartsWith("text/html"))
            {
                Response.ContentType = contentType;
                Response.OutputStream.Write(source.FileData, 0, source.FileData.Length);
            }
            else
            {
                try
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        byte[] previewBytes = this.sourceContentTasks.GetHtmlPreview(source, ms);
                        if (previewBytes != null)
                        {
                            Response.ContentType = "text/html";
                            Response.OutputStream.Write(previewBytes, 0, previewBytes.Length);
                        }
                        else
                        {
                            Response.StatusCode = (int)HttpStatusCode.NotImplemented;
                            byte[] error = Encoding.UTF8.GetBytes("Preview for this file not supported.");
                            Response.OutputStream.Write(error, 0, error.Length);
                        }
                    }
                }
                catch (Exception e)
                {
                    log.Error("Problem generating HTML preview.", e);
                    byte[] error = Encoding.UTF8.GetBytes("Problem generating HTML preview: " + e.Message);
                    Response.ContentType = "text/html";
                    Response.OutputStream.Write(error, 0, error.Length);
                }
            }
        }
Exemplo n.º 15
0
        public async Task <List <Models.Document> > DownloadFilesToAzure(Models.DocumentLibrary docLib)
        {
            List <Models.Document> documentsSaved = new List <Models.Document>();

            try
            {
                using (ClientContext context = new ClientContext(docLib.SiteUrl))
                {
                    ListItemCollection items = GetFilesRecursively(context, docLib);

                    // For each file returned, download the file
                    foreach (var item in items)
                    {
                        // Pull file information from SharePoint
                        string fileRef  = (string)item["FileRef"];
                        var    fileName = System.IO.Path.GetFileName(fileRef);
                        var    fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, fileRef);

                        // Construct the document object to save to the db
                        Models.Document newDocument = new Models.Document();
                        newDocument.Name              = fileName;
                        newDocument.Extension         = Path.GetExtension(fileName);
                        newDocument.DocumentLibraryId = docLib.DocumentLibraryId;
                        newDocument.AudienceId        = docLib.AudienceId;

                        //Console.WriteLine("File name => " + fileName);
                        //Console.WriteLine("Mime Type => " + MIMEAssistant.GetMIMEType(fileName));
                        //ClientResult<Stream> fileStream = file.OpenBinaryStream();
                        //Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, fileRef);

                        // Save to Azure
                        AzureBlobStorage azureStorage = new AzureBlobStorage();
                        AzureFile        azureFile    = await azureStorage.UploadDocumentAsync(fileInfo.Stream, newDocument, docLib, fileName, MIMEAssistant.GetMIMEType(fileName));

                        // Set url to document object to save to db
                        newDocument.Url      = azureFile.Document.Url;
                        newDocument.Uploaded = DateTime.UtcNow;

                        documentsSaved.Add(newDocument);
                    }
                }

                return(documentsSaved);
            }
            catch (Exception e)
            {
                // TODO: add error handling here...
                Console.WriteLine("SharePoint.DownloadFilesToAzure debug, " + e.Message);
                return(null);
            }
        }
Exemplo n.º 16
0
 public ParseFile(string filePath)
 {
     LocalPath   = filePath;
     ContentType = MIMEAssistant.GetMIMEType(filePath);
 }