Beispiel #1
0
 public void DeleteFeedingSource(FeedingSource fs)
 {
     if (fs != null)
     {
         this.feedingSourceRepo.Delete(fs);
     }
 }
Beispiel #2
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.";
            }
        }
Beispiel #3
0
        public IList <FeedingSourceDTO> GetFeedingSourceDTOs(bool canViewAndSearchAll, bool includeRestricted, string uploadedByUserId)
        {
            FeedingSourceDTO output               = null;
            FeedingSource    feedingSourceAlias   = null;
            AdminUser        uploadedByAlias      = null;
            AdminUser        approvedByAlias      = null;
            AdminUser        rejectedByAlias      = null;
            Source           sourceAlias          = null;
            PersonSource     personSourceAlias    = null;
            EventSource      eventSourceAlias     = null;
            UnitSource       unitSourceAlias      = null;
            OperationSource  operationSourceAlias = null;

            var q = Session.QueryOver <FeedingSource>(() => feedingSourceAlias)
                    .JoinAlias(() => feedingSourceAlias.UploadedBy, () => uploadedByAlias, JoinType.LeftOuterJoin)
                    .JoinAlias(() => feedingSourceAlias.ApprovedBy, () => approvedByAlias, JoinType.LeftOuterJoin)
                    .JoinAlias(() => feedingSourceAlias.RejectedBy, () => rejectedByAlias, JoinType.LeftOuterJoin)
                    .JoinAlias(() => feedingSourceAlias.Source, () => sourceAlias, JoinType.LeftOuterJoin)
                    .JoinAlias(() => sourceAlias.PersonSources, () => personSourceAlias, JoinType.LeftOuterJoin)
                    .JoinAlias(() => sourceAlias.EventSources, () => eventSourceAlias, JoinType.LeftOuterJoin)
                    .JoinAlias(() => sourceAlias.UnitSources, () => unitSourceAlias, JoinType.LeftOuterJoin)
                    .JoinAlias(() => sourceAlias.OperationSources, () => operationSourceAlias, JoinType.LeftOuterJoin)
                    .SelectList(list => list
                                .Select(Projections.Group(() => feedingSourceAlias.Id)).WithAlias(() => output.Id)
                                .Select(Projections.Group(() => feedingSourceAlias.Name)).WithAlias(() => output.Name)
                                .Select(Projections.Group(() => feedingSourceAlias.Restricted)).WithAlias(() => output.Restricted)
                                .Select(Projections.Group(() => feedingSourceAlias.FileModifiedDateTime)).WithAlias(() => output.FileModifiedDateTime)
                                .Select(Projections.Group(() => uploadedByAlias.UserName)).WithAlias(() => output.UploadedBy)
                                .Select(Projections.Group(() => feedingSourceAlias.UploadDate)).WithAlias(() => output.UploadDate)
                                .Select(Projections.Group(() => approvedByAlias.UserName)).WithAlias(() => output.ApprovedBy)
                                .Select(Projections.Group(() => feedingSourceAlias.ApprovedDate)).WithAlias(() => output.ApproveDate)
                                .Select(Projections.Group(() => rejectedByAlias.UserName)).WithAlias(() => output.RejectedBy)
                                .Select(Projections.Group(() => feedingSourceAlias.RejectedDate)).WithAlias(() => output.RejectedDate)
                                .Select(Projections.Group(() => feedingSourceAlias.RejectedReason)).WithAlias(() => output.RejectedReason)
                                .Select(Projections.Group(() => feedingSourceAlias.UploadNotes)).WithAlias(() => output.UploadNotes)
                                .Select(Projections.Group(() => feedingSourceAlias.Source.Id)).WithAlias(() => output.SourceID)
                                .Select(Projections.Group(() => feedingSourceAlias.IsReadOnly)).WithAlias(() => output.IsReadOnly)
                                .Select(Projections.Group(() => feedingSourceAlias.IsPublic)).WithAlias(() => output.IsPublic)
                                .Select(Projections.Count(() => personSourceAlias.Person.Id)).WithAlias(() => output.PersonSourceCount)
                                .Select(Projections.Count(() => eventSourceAlias.Event.Id)).WithAlias(() => output.EventSourceCount)
                                .Select(Projections.Count(() => unitSourceAlias.Unit.Id)).WithAlias(() => output.UnitSourceCount)
                                .Select(Projections.Count(() => operationSourceAlias.Operation.Id)).WithAlias(() => output.OperationSourceCount)
                                );

            if (canViewAndSearchAll)
            {
                if (!includeRestricted)
                {
                    q = q.Where(() => feedingSourceAlias.Restricted == false);
                }
            }
            else
            {
                // user can access sources they uploaded as well as sources marked public
                q = q.Where(() => uploadedByAlias.UserID == uploadedByUserId || feedingSourceAlias.IsPublic);
            }

            return(q.TransformUsing(Transformers.AliasToBean <FeedingSourceDTO>())
                   .List <FeedingSourceDTO>());
        }
Beispiel #4
0
        public void SendFeedingSourceUploadedEmail(FeedingSource fs)
        {
            if (fs != null && fs.UploadedBy != null)
            {
                string subject = "[feeding] A file was just uploaded and is awaiting approval";
                string body    = "This is an automated notification.<br /><br />";
                body += fs.UploadedBy.Headline
                        + " just uploaded the file <a href='" + APPLICATION_URL + "Sources/Feeding/Details/" + fs.Id.ToString() + "'>" + fs.Name + "</a>";
                if (fs.Restricted)
                {
                    body += " (restricted)";
                }
                body += ", which is awaiting approval.";
                if (!string.IsNullOrEmpty(fs.UploadNotes))
                {
                    body += "<br /><br />Notes from uploader:";
                    body += "<br /><br />" + fs.UploadNotes.Replace("\r\n", "<br />").Replace("\n", "<br />");
                }

                this.SendMailMessage(this.userTasks.GetUsersWithPermission(AdminPermission.CanApproveAndRejectSources),
                                     this.userTasks.GetAdminUser(fs.UploadedBy.UserID),
                                     subject, body, true);
            }
            else
            {
                log.Error("Problem with FeedingSource(ID=" + fs.Id + "), didn't send 'FeedingSourceUploaded' email.");
            }
        }
Beispiel #5
0
        public void SendFeedingSourceApprovedEmail(FeedingSource fs)
        {
            if (fs != null && fs.ApprovedBy != null && fs.Source != null)
            {
                string subject = "[feeding] Your uploaded file was just approved and is available for attaching";
                string body    = "This is an automated notification.<br /><br />";
                body += fs.ApprovedBy.Headline
                        + " just approved the file <a href='" + APPLICATION_URL + "Sources/Feeding/Details/" + fs.Id.ToString() + "'>"
                        + fs.Name + "</a>";
                if (fs.Restricted)
                {
                    body += " (restricted)";
                }
                body += ", which is available for attaching to persons, events or units.  Source ID is <a href='" + APPLICATION_URL + "Profiling/Sources#info/" + fs.Source.Id + "'>" + fs.Source.Id + "</a>.";

                this.SendMailMessage(new List <AdminUser>()
                {
                    this.userTasks.GetAdminUser(fs.UploadedBy.UserID)
                },
                                     this.userTasks.GetAdminUser(fs.ApprovedBy.UserID),
                                     subject, body, true);
            }
            else
            {
                log.Error("Problem with FeedingSource(ID=" + fs.Id + "), didn't send 'FeedingSourceApproved' email.");
            }
        }
Beispiel #6
0
        public void SendFeedingSourceRejectedEmail(FeedingSource fs)
        {
            if (fs != null && fs.RejectedBy != null)
            {
                string subject = "[feeding] Your uploaded file was just rejected";
                string body    = "This is an automated notification.<br /><br />";
                body += fs.RejectedBy.Headline
                        + " just rejected the file <a href='" + APPLICATION_URL + "Sources/Feeding/Details/" + fs.Id.ToString() + "'>" + fs.Name + "</a>";
                if (fs.Restricted)
                {
                    body += " (restricted)";
                }
                body += ".";
                if (!string.IsNullOrEmpty(fs.RejectedReason))
                {
                    body += "<br /><br />Reason:";
                    body += "<br /><br />" + fs.RejectedReason;
                }

                this.SendMailMessage(new List <AdminUser>()
                {
                    this.userTasks.GetAdminUser(fs.UploadedBy.UserID)
                },
                                     this.userTasks.GetAdminUser(fs.RejectedBy.UserID),
                                     subject, body, true);
            }
            else
            {
                log.Error("Problem with FeedingSource(ID=" + fs.Id + "), didn't send 'FeedingSourceRejected' email.");
            }
        }
Beispiel #7
0
        public Source FeedSource(int feedingSourceId)
        {
            FeedingSource fs = this.GetFeedingSource(feedingSourceId);

            if (fs != null && fs.FileData != null)
            {
                Source s = new Source();
                s.SourceName    = fs.Name;
                s.SourcePath    = fs.Name;
                s.SourceDate    = DateTime.Now;
                s.FileExtension = FileUtil.GetExtension(fs.Name);
                s.FileData      = fs.FileData;
                s.IsRestricted  = fs.Restricted;
                s.IsReadOnly    = fs.IsReadOnly;
                s.Notes         = "Fed from FeedingSourceID=" + fs.Id;
                if (!string.IsNullOrEmpty(fs.UploadNotes))
                {
                    s.Notes += "\n\n" + fs.UploadNotes;
                }
                s.FileDateTimeStamp = fs.FileModifiedDateTime;
                foreach (SourceAuthor a in fs.SourceAuthors)
                {
                    s.AddSourceAuthor(a);
                }
                foreach (SourceOwningEntity e in fs.SourceOwningEntities)
                {
                    s.AddSourceOwningEntity(e);
                }

                // persist Source
                s = this.sourceTasks.SaveSource(s);

                // link FeedingSource with Source
                fs.Source = s;
                s.AddFeedingSource(fs);

                // persist the join
                fs = this.SaveFeedingSource(fs);

                // queue ocr scan of new source
                var jobId = BackgroundJob.Enqueue <ISourceContentTasks>(x => x.OcrScanAndSetSourceQueueable(s.Id));

                // queue indexing of the new Source
                BackgroundJob.ContinueWith <ISourceTasks>(jobId, x =>
                                                          x.IndexSourceQueueable(s.Id,
                                                                                 s.HasUploadedBy() ? s.GetUploadedBy().UserID : string.Empty,
                                                                                 s.SourceAuthors.Select(y => y.Author).ToList(),
                                                                                 s.SourceOwningEntities.Select(y => y.Name).ToList(),
                                                                                 s.JhroCase != null ? s.JhroCase.CaseNumber : string.Empty,
                                                                                 this.sourceTasks.GetSourceDTO(s.Id).FileSize)
                                                          );

                return(s);
            }
            return(null);
        }
Beispiel #8
0
 public virtual bool CanAccess(FeedingSource fs)
 {
     if (fs != null)
     {
         return(this.CanAccess(fs.Restricted,
                               fs.UploadedBy != null ? fs.UploadedBy.UserID : null,
                               fs.SourceAuthors.Select(x => x.Author).ToArray(),
                               fs.SourceOwningEntities.Select(x => x.Name).ToArray(),
                               fs.IsPublic));
     }
     return(false);
 }
Beispiel #9
0
        public ActionResult Details(int id)
        {
            FeedingSource fs = this.feedingSourceTasks.GetFeedingSource(id);

            if (fs != null)
            {
                if (!((PrfPrincipal)User).CanAccess(fs))
                {
                    return(new HttpUnauthorizedResult());
                }
                return(View(fs));
            }
            return(new HttpNotFoundResult());
        }
Beispiel #10
0
        public ActionResult Rename(int id)
        {
            FeedingSource fs = this.feedingSourceTasks.GetFeedingSource(id);

            if (fs != null)
            {
                if (!((PrfPrincipal)User).CanAccess(fs))
                {
                    return(new HttpUnauthorizedResult());
                }

                return(View(new FeedingSourceViewModel(fs)));
            }
            return(RedirectToAction("Index"));
        }
Beispiel #11
0
        public ActionResult Reject(FeedingSourceViewModel vm)
        {
            if (vm != null && vm.Id > 0)
            {
                AdminUser user = this.userTasks.GetAdminUser(User.Identity.Name);
                if (user != null)
                {
                    FeedingSource fs = this.feedingSourceTasks.GetFeedingSource(vm.Id);
                    if (fs != null)
                    {
                        if (!((PrfPrincipal)User).CanAccess(fs))
                        {
                            return(new HttpUnauthorizedResult());
                        }

                        if (fs.UploadedBy != user)
                        {
                            fs.RejectedBy     = user;
                            fs.RejectedDate   = DateTime.Now;
                            fs.RejectedReason = vm.RejectedReason;
                            this.feedingSourceTasks.SaveFeedingSource(fs);

                            this.emailTasks.SendFeedingSourceRejectedEmail(fs);

                            return(RedirectToAction("Index"));
                        }
                        else
                        {
                            ModelState.AddModelError("RejectedBy", "User should delete rather than reject a source they uploaded themselves.");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("Id", "Feeding source doesn't exist.");
                    }
                }

                else
                {
                    ModelState.AddModelError("RejectedBy", "Logged-in user doesn't exist.");
                }
            }
            else
            {
                ModelState.AddModelError("Id", "No Id was sent.");
            }
            return(Approve(vm.Id));
        }
Beispiel #12
0
        public ActionResult Rename(FeedingSourceViewModel vm)
        {
            if (ModelState.IsValid)
            {
                FeedingSource fs = this.feedingSourceTasks.GetFeedingSource(vm.Id);
                if (fs != null)
                {
                    if (!((PrfPrincipal)User).CanAccess(fs))
                    {
                        return(new HttpUnauthorizedResult());
                    }

                    if (fs.ApprovedBy == null && fs.RejectedBy == null)
                    {
                        FeedingSource existing = this.feedingSourceTasks.GetFeedingSource(vm.Name);
                        if (existing == null || (existing != null && existing.Id == fs.Id))
                        {
                            Source s = this.sourceTasks.GetSource(vm.Name);
                            if (s == null)
                            {
                                fs.Name = vm.Name;
                                fs      = this.feedingSourceTasks.SaveFeedingSource(fs);

                                return(RedirectToAction("Index"));
                            }
                            else
                            {
                                ModelState.AddModelError("Name", "<a href='" + Url.Action("Index", "Sources", new { area = "Profiling" }) + "#info/" + s.Id + "' target='_blank'>" + s.SourceName + "</a> exists already with Source ID of " + s.Id + ".  If you're sure you have a different file, rename it before uploading.");
                            }
                        }
                        else
                        {
                            ModelState.AddModelError("Name", "A file has already been uploaded with this name.");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("Name", "File is already approved and imported into database, or is rejected.");
                    }
                }
            }

            return(Rename(vm.Id));
        }
Beispiel #13
0
        // for statistics purposes, hence no security permissions
        public IList <FeedingSourceDTO> GetFeedingSourceDTOs(ISession session, DateTime start, DateTime end, bool includeRestricted)
        {
            FeedingSource    fsAlias         = null;
            FeedingSourceDTO output          = null;
            AdminUser        uploadedByAlias = null;
            AdminUser        approvedByAlias = null;
            AdminUser        rejectedByAlias = null;

            ISession thisSession = session == null ? this.Session : session;

            var q = thisSession.QueryOver <FeedingSource>(() => fsAlias)
                    .JoinAlias(() => fsAlias.UploadedBy, () => uploadedByAlias, JoinType.LeftOuterJoin)
                    .JoinAlias(() => fsAlias.ApprovedBy, () => approvedByAlias, JoinType.LeftOuterJoin)
                    .JoinAlias(() => fsAlias.RejectedBy, () => rejectedByAlias, JoinType.LeftOuterJoin)
                    .Where(Restrictions.Disjunction()
                           .Add(Restrictions.On(() => fsAlias.UploadDate).IsBetween(start).And(end))
                           .Add(Restrictions.On(() => fsAlias.ApprovedDate).IsBetween(start).And(end))
                           .Add(Restrictions.On(() => fsAlias.RejectedDate).IsBetween(start).And(end))
                           )
                    .SelectList(list => list
                                .Select(() => fsAlias.Id).WithAlias(() => output.Id)
                                .Select(() => fsAlias.Name).WithAlias(() => output.Name)
                                .Select(() => fsAlias.Restricted).WithAlias(() => output.Restricted)
                                .Select(() => fsAlias.FileModifiedDateTime).WithAlias(() => output.FileModifiedDateTime)
                                .Select(() => uploadedByAlias.UserName).WithAlias(() => output.UploadedBy)
                                .Select(() => fsAlias.UploadDate).WithAlias(() => output.UploadDate)
                                .Select(() => approvedByAlias.UserName).WithAlias(() => output.ApprovedBy)
                                .Select(() => fsAlias.ApprovedDate).WithAlias(() => output.ApproveDate)
                                .Select(() => rejectedByAlias.UserName).WithAlias(() => output.RejectedBy)
                                .Select(() => fsAlias.RejectedDate).WithAlias(() => output.RejectedDate)
                                .Select(() => fsAlias.RejectedReason).WithAlias(() => output.RejectedReason)
                                .Select(() => fsAlias.UploadNotes).WithAlias(() => output.UploadNotes)
                                );

            if (!includeRestricted)
            {
                q = q.Where(() => !fsAlias.Restricted);
            }

            return(q.TransformUsing(Transformers.AliasToBean <FeedingSourceDTO>())
                   .List <FeedingSourceDTO>());
        }
Beispiel #14
0
        public ActionResult Upload(MultipleUploadViewModel vm)
        {
            if (ModelState.IsValid)
            {
                if (vm.FileData != null && vm.FileData.Length > 0)
                {
                    IList <FeedingSource> sources = new List <FeedingSource>();

                    // construct FeedingSources and gather validation errors if any
                    for (int i = 0; i < vm.FileData.Length; i++)
                    {
                        if (vm.FileData[i] != null && vm.FileData[i].ContentLength > 0)
                        {
                            FeedingSource fs = this.ProcessUpload(vm, i);

                            if (fs != null)
                            {
                                sources.Add(fs);
                            }
                        }
                    }

                    // save those without errors
                    if (sources.Any())
                    {
                        foreach (FeedingSource fs in sources)
                        {
                            this.feedingSourceTasks.SaveFeedingSource(fs);
                        }
                        TempData["SuccessfullyUploaded"] = sources;
                        this.emailTasks.SendFeedingSourcesUploadedEmail(sources);
                    }

                    if (ModelState.IsValid)
                    {
                        return(RedirectToAction("Index"));
                    }
                }
            }
            return(Upload());
        }
Beispiel #15
0
        public void SendFeedingSourcesUploadedEmail(IList <FeedingSource> sources)
        {
            if (sources != null && sources.Count > 0)
            {
                if (sources.Count == 1)
                {
                    this.SendFeedingSourceUploadedEmail(sources.First());
                }
                else
                {
                    FeedingSource firstSource = sources.First();

                    string subject = "[feeding] Several files were just uploaded and are awaiting approval";
                    string body    = "This is an automated notification.<br /><br />";
                    body += firstSource.UploadedBy.Headline + " just uploaded the following files which are awaiting approval:<br /><br />";
                    body += "<ul>";
                    foreach (FeedingSource fs in sources)
                    {
                        body += "<li><a href='" + APPLICATION_URL + "Sources/Feeding/Details/" + fs.Id.ToString() + "'>" + fs.Name + "</a>";
                        if (fs.Restricted)
                        {
                            body += " (restricted)";
                        }
                        body += "</li>";
                    }
                    body += "</ul>";
                    if (!string.IsNullOrEmpty(firstSource.UploadNotes))
                    {
                        body += "<br /><br />Notes from uploader:";
                        body += "<br /><br />" + firstSource.UploadNotes.Replace("\r\n", "<br />").Replace("\n", "<br />");
                    }

                    this.SendMailMessage(this.userTasks.GetUsersWithPermission(AdminPermission.CanApproveAndRejectSources),
                                         this.userTasks.GetAdminUser(firstSource.UploadedBy.UserID),
                                         subject, body, true);
                }
            }
        }
Beispiel #16
0
 public FeedingSourceViewModel(FeedingSource fs)
 {
     this.Id                   = fs.Id;
     this.Name                 = fs.Name;
     this.Restricted           = fs.Restricted;
     this.FileModifiedDateTime = fs.FileModifiedDateTime;
     this.UploadedBy           = fs.UploadedBy.UserName;
     this.UploadDate           = fs.UploadDate;
     this.Approved             = fs.ApprovedBy != null;
     this.Rejected             = fs.RejectedBy != null;
     this.RejectedReason       = fs.RejectedReason;
     this.UploadNotes          = fs.UploadNotes;
     this.IsReadOnly           = fs.IsReadOnly;
     this.IsPublic             = fs.IsPublic;
     if (fs.SourceAuthors != null && fs.SourceAuthors.Any())
     {
         this.AuthorIds = string.Join(",", fs.SourceAuthors.Select(x => x.Id));
     }
     if (fs.SourceOwningEntities != null && fs.SourceOwningEntities.Any())
     {
         this.OwnerIds = string.Join(",", fs.SourceOwningEntities.Select(x => x.Id));
     }
 }
Beispiel #17
0
 public FeedingSource SaveFeedingSource(FeedingSource fs)
 {
     return(this.feedingSourceRepo.SaveOrUpdate(fs));
 }
Beispiel #18
0
        public ActionResult Approve(FeedingSourceViewModel vm)
        {
            if (vm != null && vm.Id > 0)
            {
                AdminUser user = this.userTasks.GetAdminUser(User.Identity.Name);
                if (user != null)
                {
                    FeedingSource fs = this.feedingSourceTasks.GetFeedingSource(vm.Id);
                    if (fs != null)
                    {
                        if (!((PrfPrincipal)User).CanAccess(fs))
                        {
                            return(new HttpUnauthorizedResult());
                        }

                        if (fs.UploadedBy != user)
                        {
                            fs.ApprovedBy   = user;
                            fs.ApprovedDate = DateTime.Now;
                            fs.Restricted   = vm.Restricted;
                            fs.IsReadOnly   = vm.IsReadOnly;
                            fs.IsPublic     = vm.IsPublic;
                            fs.UploadNotes  = vm.UploadNotes;

                            if (!string.IsNullOrEmpty(vm.AuthorIds))
                            {
                                fs.SourceAuthors.Clear();
                                string[] ids = vm.AuthorIds.Split(',');
                                foreach (string id in ids)
                                {
                                    int result;
                                    if (int.TryParse(id, out result))
                                    {
                                        SourceAuthor a = this.sourcePermissionTasks.GetSourceAuthor(result);
                                        if (a != null)
                                        {
                                            fs.SourceAuthors.Add(a);
                                        }
                                    }
                                }
                            }

                            if (!string.IsNullOrEmpty(vm.OwnerIds))
                            {
                                fs.SourceOwningEntities.Clear();
                                string[] ids = vm.OwnerIds.Split(',');
                                foreach (string id in ids)
                                {
                                    int result;
                                    if (int.TryParse(id, out result))
                                    {
                                        SourceOwningEntity e = this.sourcePermissionTasks.GetSourceOwningEntity(result);
                                        if (e != null)
                                        {
                                            fs.SourceOwningEntities.Add(e);
                                        }
                                    }
                                }
                            }

                            fs = this.feedingSourceTasks.SaveFeedingSource(fs);
                            Source source = this.feedingSourceTasks.FeedSource(fs.Id);
                            this.emailTasks.SendFeedingSourceApprovedEmail(fs);

                            return(RedirectToAction("Index"));
                        }
                        else
                        {
                            ModelState.AddModelError("ApprovedBy", "User cannot approve a source they uploaded themselves.");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("Id", "Feeding source doesn't exist.");
                    }
                }

                else
                {
                    ModelState.AddModelError("ApprovedBy", "Logged-in user doesn't exist.");
                }
            }
            else
            {
                ModelState.AddModelError("Id", "No Id was sent.");
            }
            return(Approve(vm.Id));
        }
Beispiel #19
0
        protected FeedingSource ProcessUpload(MultipleUploadViewModel vm, int index)
        {
            // we use this flag instead of ModelState.IsValid because we need to reset this value for every file; ModelState.IsValid is a single flag for all uploaded files.
            bool hasError = false;

            using (Stream fileStream = vm.FileData[index].InputStream)
            {
                // Progressively check for duplicates, most reliable check first.  Only return one duplicate validation error if any.
                // check Source hash duplicate
                string            hash = BitConverter.ToString(MD5.Create().ComputeHash(fileStream)).Replace("-", "");
                IList <SourceDTO> dtos = this.sourceTasks.GetSources(hash);
                if (dtos != null && dtos.Count > 0)
                {
                    hasError = true;
                    ModelState.AddModelError(
                        "FileData",
                        "An identical source (<a href='" + Url.Action("Index", "Sources", new { area = "Profiling" }) + "#info/" + dtos.First().SourceID + "' target='_blank'>"
                        + dtos.First().SourceName + "</a>) exists already with Source ID of " + dtos.First().SourceID + "."
                        );
                }
                else
                {
                    // check Source name duplicate
                    Source s = this.sourceTasks.GetSource(vm.FileData[index].FileName);
                    if (s != null)
                    {
                        hasError = true;
                        ModelState.AddModelError(
                            "FileData",
                            "<a href='" + Url.Action("Index", "Sources", new { area = "Profiling" }) + "#info/" + s.Id + "' target='_blank'>"
                            + s.SourceName + "</a> exists already with Source ID of " + s.Id + ".  If you're sure you have a different file, rename it before uploading."
                            );
                    }
                    else
                    {
                        // check FeedingSource name duplicate
                        FeedingSource fs = this.feedingSourceTasks.GetFeedingSource(vm.FileData[index].FileName);
                        if (fs != null)
                        {
                            hasError = true;
                            ModelState.AddModelError(
                                "FileData",
                                "<a href='" + Url.Action("Details", "Feeding", new { area = "Sources", id = fs.Id }) + "' target='_blank'>"
                                + vm.FileData[index].FileName + "</a> was already uploaded; delete it or change your file name."
                                );
                        }
                    }
                }

                AdminUser user = this.userTasks.GetAdminUser(User.Identity.Name);
                if (user == null)
                {
                    hasError = true;
                    ModelState.AddModelError("UploadedBy", "Logged-in user doesn't appear to be exist.");
                }

                if (vm.IsReadOnly && string.IsNullOrEmpty(vm.UploadNotes))
                {
                    hasError = true;
                    ModelState.AddModelError("UploadNotes", "Read-only sources should have a justification in the notes.");
                }

                if (!hasError)
                {
                    FeedingSource fs = new FeedingSource();
                    fs.Name                 = Path.GetFileName(vm.FileData[index].FileName);
                    fs.Restricted           = vm.Restricted;
                    fs.IsReadOnly           = vm.IsReadOnly;
                    fs.IsPublic             = vm.IsPublic;
                    fs.FileModifiedDateTime = vm.FileModifiedDateTime != null && vm.FileModifiedDateTime[index] != null ? vm.FileModifiedDateTime[index] : DateTime.Now;
                    fs.UploadedBy           = user;
                    fs.UploadDate           = DateTime.Now;
                    fs.UploadNotes          = vm.UploadNotes;

                    if (!string.IsNullOrEmpty(vm.AuthorIds))
                    {
                        string[] ids = vm.AuthorIds.Split(',');
                        foreach (string id in ids)
                        {
                            int result;
                            if (int.TryParse(id, out result))
                            {
                                SourceAuthor a = this.sourcePermissionTasks.GetSourceAuthor(result);
                                if (a != null)
                                {
                                    fs.SourceAuthors.Add(a);
                                }
                            }
                        }
                    }

                    if (!string.IsNullOrEmpty(vm.OwnerIds))
                    {
                        string[] ids = vm.OwnerIds.Split(',');
                        foreach (string id in ids)
                        {
                            int result;
                            if (int.TryParse(id, out result))
                            {
                                SourceOwningEntity e = this.sourcePermissionTasks.GetSourceOwningEntity(result);
                                if (e != null)
                                {
                                    fs.SourceOwningEntities.Add(e);
                                }
                            }
                        }
                    }

                    fileStream.Position = 0;  // we read the stream earlier when computing hash
                    MemoryStream memoryStream = fileStream as MemoryStream;
                    if (memoryStream == null)
                    {
                        memoryStream = new MemoryStream();
                        fileStream.CopyTo(memoryStream);
                    }
                    fs.FileData = memoryStream.ToArray();

                    return(fs);
                }

                return(null);
            }
        }