Ejemplo n.º 1
0
        /// <summary>
        /// Finds all GameObjects that overlap the collider in the specified layermask and makes a preservation object
        /// </summary>
        private void CollectObjects()
        {
            var filter = new ContactFilter2D();

            filter.SetLayerMask(layers);

            var colliders = new List <Collider2D>();

            Physics2D.OverlapCollider(region, filter, colliders);

            var objects = new List <GameObject>();

            foreach (var collider in colliders)
            {
                objects.Add(collider.gameObject);
            }

            foreach (var obj in objects)
            {
                var preservation = new Preservation
                {
                    gameObject = obj,
                    offset     = obj.transform.position - currentLevel.transform.position
                };
                preservation.offset.z = 0;
                preservations.Add(preservation);
            }
        }
Ejemplo n.º 2
0
        private void SignDocuments(Preservation preservation, ISignService _signService, Models.ArubaSignModel model)
        {
            string currentFilePath = Directory.GetFiles(preservation.Path, "IPDA*.xml").FirstOrDefault();

            if (currentFilePath != null)
            {
                //get file content
                byte[] content = System.IO.File.ReadAllBytes(currentFilePath);

                //sign document with aruba automatic
                VecompSoftware.Sign.ArubaSignService.ArubaSignModel arubaModel = new VecompSoftware.Sign.ArubaSignService.ArubaSignModel()
                {
                    DelegatedDomain   = model.DelegatedDomain,
                    DelegatedPassword = model.DelegatedPassword,
                    DelegatedUser     = model.DelegatedUser,
                    OTPPassword       = model.OTPPassword,
                    OTPAuthType       = model.OTPAuthType,
                    User          = model.User,
                    CertificateId = model.CertificateId,
                    TSAUser       = model.TSAUser,
                    TSAPassword   = model.TSAPassword
                };

                content = _signService.SignDocument(arubaModel, content, Path.GetFileName(currentFilePath), true);

                //save signed file back to disk
                ByteArrayToFile(currentFilePath, content);

                //update CloseDate field so that we can close the preservation
                _preservationService.ClosePreservation(preservation.IdPreservation);
            }
        }
Ejemplo n.º 3
0
        public ActionResult Index(Guid id)
        {
            return(ActionResultHelper.TryCatchWithLogger(() =>
            {
                Preservation preservation = _preservationService.GetPreservation(id, false);
                if (preservation == null)
                {
                    _loggerService.Warn(string.Format("Nessuna conservazione trovata con id {0}", id));
                    return HttpNotFound();
                }

                IpdaIndexViewModel model = new IpdaIndexViewModel()
                {
                    Preservation = preservation
                };
                string preservationPath = preservation.Path;
                string closeFile = IpdaUtil.GetCloseFile(preservationPath);
                string ipdaXmlFile = IpdaUtil.GetIpdaXmlFile(preservationPath);
                string ipdaTsdFile = IpdaUtil.GetIpdaTsdFile(preservationPath);
                model.ToCreate = (!string.IsNullOrEmpty(closeFile) && string.IsNullOrEmpty(ipdaXmlFile) && string.IsNullOrEmpty(ipdaTsdFile));
                model.ToSign = !model.ToCreate && (!string.IsNullOrEmpty(ipdaXmlFile) && string.IsNullOrEmpty(ipdaTsdFile));
                model.ToClose = !model.ToCreate && !model.ToSign && (!string.IsNullOrEmpty(ipdaXmlFile) && !string.IsNullOrEmpty(ipdaTsdFile) && !preservation.CloseDate.HasValue);
                return View(model);
            }, _loggerService));
        }
Ejemplo n.º 4
0
        public ActionResult CreateIpda(Guid id)
        {
            return(ActionResultHelper.TryCatchWithLogger(() =>
            {
                try
                {
                    Preservation preservation = _preservationService.GetPreservation(id, false);
                    if (preservation == null)
                    {
                        _loggerService.Error(string.Format("Nessuna conservazione trovata con id {0}", id));
                        return Content("Errore: Conservazione non valida");
                    }

                    string closeFile = IpdaUtil.GetCloseFile(preservation.Path);
                    if (string.IsNullOrEmpty(closeFile))
                    {
                        return Content("Errore: Conservazione non valida");
                    }

                    IpdaConverter converter = new IpdaConverter();
                    Ipda ipda = converter.ConvertCloseFile(closeFile, "NomeFileInArchivio");
                    ipda.SaveAs(IpdaUtil.Close2IpdaFilename(closeFile));

                    return Content("Il file IPDA è stato generato con successo");
                }
                catch (Exception ex)
                {
                    _loggerService.Error(ex.Message, ex);
                    return Content(string.Concat("Errore durante la conversione del file di chiusura.<br/>", ex.Message));
                }
            }, _loggerService));
        }
Ejemplo n.º 5
0
        internal static BibDSModel.Preservation Convert(this Preservation pre, BibDSModel.BiblosDS2010Entities db, BibDSModel.Preservation original = null, int level = 0, int deeplevel = 5)
        {
            if (pre == null || level > deeplevel)
            {
                return(null);
            }

            var retval = (original == null) ? new BibDSModel.Preservation() : original;

            // retval.Archive = pre.Archive.ConvertPreservation(db);
            // retval.Archive = pre.Archive;
            retval.CloseContent       = pre.CloseContent;
            retval.CloseDate          = pre.CloseDate;
            retval.IndexHash          = pre.IndexHash;
            retval.Label              = pre.Label;
            retval.LastVerifiedDate   = pre.LastVerifiedDate;
            retval.Path               = pre.Path;
            retval.PreservationDate   = pre.PreservationDate;
            retval.IdPreservationUser = pre.IdPreservationUser;
            retval.IdPreservation     = pre.IdPreservation;

            //var journaling = pre.PreservationJournalings.Convert(db, (original != null) ? original.PreservationJournaling : null, level, deeplevel);
            //foreach (var journal in journaling)
            //{
            //    retval.PreservationJournaling.Add(journal);
            //}

            return(retval);
        }
Ejemplo n.º 6
0
 public ActionResult DownloadXml(Guid id)
 {
     return(ActionResultHelper.TryCatchWithLogger(() =>
     {
         Preservation preservation = _preservationService.GetPreservation(id, false);
         string xmlFile = IpdaUtil.GetIpdaXmlFile(preservation.Path);
         return File(xmlFile, System.Net.Mime.MediaTypeNames.Application.Zip, string.Concat(id, "_", Path.GetFileName(xmlFile)));
     }, _loggerService));
 }
Ejemplo n.º 7
0
 public ActionResult Check(Guid id)
 {
     return(ActionResultHelper.TryCatchWithLogger(() =>
     {
         Preservation preservation = _preservationService.GetPreservation(id, false);
         _preservationService.VerifyExistingPreservation(id);
         return RedirectToAction("PreservationCheck", "Preservation", new { id });
     }, _loggerService));
 }
        public ActionResult ExistingPreservationVerifyDoAction(Guid id)
        {
            var          service = new PreservationService();
            Preservation pres    = service.GetPreservation(id);

            service.VerifyExistingPreservation(id);
            TempData["ErrorMessages"] = service.ErrorMessages;

            return(RedirectToAction("PreservationDetails", new { id = id }));
        }
        public ActionResult ClosePreservation(Preservation preservation)
        {
            var service = new PreservationService();

            preservation = service.GetPreservation(preservation.IdPreservation, false);
            if (!preservation.CloseDate.HasValue)
            {
                service.ClosePreservation(preservation.IdPreservation);
            }
            return(RedirectToAction("PreservationDetails", new { id = preservation.IdPreservation }));
        }
Ejemplo n.º 10
0
        public ActionResult DownloadPreservationPDA(Guid id, bool includeDocuments)
        {
            return(ActionResultHelper.TryCatchWithLogger(() =>
            {
                var t = includeDocuments;
                Preservation preservation = _preservationService.GetPreservation(id, false);
                if (!Directory.Exists(preservation.Path))
                {
                    throw new DirectoryNotFoundException(string.Concat("DownloadPreservationPDA -> directory ", preservation.Path, " non trovata"));
                }

                string zipToDownload = _preservationService.GetZipPreservationPDA(preservation, includeDocuments);
                byte[] zipContent = System.IO.File.ReadAllBytes(zipToDownload);
                return File(zipContent, System.Net.Mime.MediaTypeNames.Application.Zip, Path.GetFileName(zipToDownload));
            }, _loggerService));
        }
Ejemplo n.º 11
0
 public ActionResult UploadSignedFile(IEnumerable <HttpPostedFileBase> filesUpload)
 {
     return(ActionResultHelper.TryCatchWithLogger(() =>
     {
         StringBuilder result = new StringBuilder();
         if (filesUpload != null)
         {
             foreach (HttpPostedFileBase file in filesUpload)
             {
                 string fileName = Path.GetFileName(file.FileName);
                 string preservationIdStr = fileName.Split('_').FirstOrDefault();
                 if (Guid.TryParse(preservationIdStr, out Guid preservationId))
                 {
                     Preservation preservation = _preservationService.GetPreservation(preservationId, false);
                     if (preservation != null)
                     {
                         if (preservation.CloseDate.HasValue)
                         {
                             string pattern = "Conservazione <b>{0}</b> del {1} <b>CHIUSA</b> il {2}.<br/>";
                             result.AppendFormat(pattern, preservation.IdPreservation, preservation.StartDate, preservation.CloseDate);
                             continue;
                         }
                         else
                         {
                             string strNewFile = Path.Combine(preservation.Path, fileName.Split('_').LastOrDefault());
                             if (System.IO.File.Exists(strNewFile))
                             {
                                 result.AppendFormat("File già presente!<br/>Il file verrà ignorato: {0}<br/>",
                                                     Path.Combine(preservation.Path, preservation.Label, fileName.Split('_').LastOrDefault()));
                             }
                             else
                             {
                                 file.SaveAs(strNewFile);
                             }
                         }
                     }
                 }
                 else
                 {
                     _loggerService.Warn(string.Format("Il file {0} non è corretto e non corrisponde ad una conservazione valida", fileName));
                     throw new Exception(string.Format("Il file {0} non è corretto e non corrisponde ad una conservazione valida", fileName));
                 }
             }
         }
         return Content(JsonConvert.SerializeObject(new { status = result }));
     }, _loggerService));
 }
Ejemplo n.º 12
0
        public ActionResult ExportPDD(string data)
        {
            return(ActionResultHelper.TryCatchWithLogger(() =>
            {
                ICollection <Guid> ids = JsonConvert.DeserializeObject <ICollection <Guid> >(HttpUtility.UrlDecode(data));
                Guid processId = Guid.NewGuid();
                string path = Path.Combine(ConfigurationHelper.GetAppDataPath(), processId.ToString());
                Directory.CreateDirectory(path);
                try
                {
                    foreach (Guid id in ids)
                    {
                        Document document = DocumentService.GetDocument(id);
                        using (DocumentsClient client = new DocumentsClient())
                        {
                            document.Content = client.GetDocumentContentById(id);
                        }

                        //Copied from preservation logic
                        document.AttributeValues = AttributeService.GetAttributeValues(document.IdDocument);
                        var fileName = string.Concat(_preservationService.PreservationDocumentFileName(document), (Path.GetExtension(document.Name)));
                        System.IO.File.WriteAllBytes(Path.Combine(path, fileName), document.Content.Blob);

                        if (document.IdPreservation.HasValue)
                        {
                            Preservation preservation = _preservationService.GetPreservation(document.IdPreservation.Value, false);
                            string[] files = Directory.GetFiles(preservation.Path).Where(x => x.Contains("INDICE_") || x.Contains("CHIUSURA_") || x.Contains("IPDA_") || x.Contains("LOTTI_")).ToArray();
                            foreach (string file in files.Where(f => !System.IO.File.Exists(Path.Combine(path, Path.GetFileName(f)))))
                            {
                                System.IO.File.Copy(file, Path.Combine(path, Path.GetFileName(file)), true);
                            }
                        }
                    }
                    string zipPath = CreatePDDZip(path);
                    return File(System.IO.File.ReadAllBytes(zipPath), System.Net.Mime.MediaTypeNames.Application.Zip);
                }
                finally
                {
                    if (Directory.Exists(path))
                    {
                        Directory.Delete(path, true);
                    }
                }
            }, _loggerService));
        }
 public IActionResult Preservation(Preservation preservation)
 {
     //MailMessage mail = new MailMessage("*****@*****.**", "*****@*****.**");
     //SmtpClient client = new SmtpClient();
     //client.Port = 25;
     //client.DeliveryMethod = SmtpDeliveryMethod.Network;
     //client.UseDefaultCredentials = false;
     //client.Host = "smtp.gmail.com";
     //mail.Subject = "this is a test email.";
     //mail.Body = "this is my test email body";
     //client.Send(mail);
     using (var db = new DbConnect())
     {
         db.preservation.Add(preservation);
         db.SaveChanges();
     }
     return(RedirectToAction("Index"));
 }
Ejemplo n.º 14
0
        public PreservationModel Add(Preservation entity)
        {
            string sql = "INSERT INTO Preservation (Description,CreatedAt,UpdatedAt)"
                         + " Values (@Description,@CreatedAt,@UpdatedAt);"
                         + " SELECT * From Preservation Where Id = CAST(SCOPE_IDENTITY() as int)";

            using (var connection = Connection)
            {
                var result = connection.QuerySingleOrDefault <PreservationModel>(sql,
                                                                                 new
                {
                    Description = entity.Description.Value,
                    CreatedAt   = DateTime.Now,
                    UpdatedAt   = DateTime.Now
                });
                return(result);
            }
        }
Ejemplo n.º 15
0
        public ExecutePreservationVerifyResponseModel Process(ExecutePreservationVerifyRequestModel request)
        {
            try
            {
                _logger.Info($"Process -> execute verify for preservation {request.IdPreservation}");
                ExecutePreservationVerifyResponseModel responseModel = new ExecutePreservationVerifyResponseModel(request.IdPreservation);
                if (request.IdPreservation == Guid.Empty)
                {
                    return(responseModel);
                }

                Preservation preservation = _preservationService.GetPreservation(request.IdPreservation, false);
                if (preservation == null)
                {
                    _logger.Warn($"Process -> preservation with id {request.IdPreservation} not found");
                    responseModel.Status = PreservationVerifyStatus.Error;
                    responseModel.Errors.Add($"Nessuna conservazione trovata con ID {request.IdPreservation}");
                    return(responseModel);
                }

                bool isVerified = _preservationService.VerifyExistingPreservation(request.IdPreservation);

                string[] tokens = Path.GetFileName(_preservationService.VerifyFile).Split(' ');
                string   title  = Path.GetFileNameWithoutExtension(String.Join(" ", tokens, 1, tokens.Length - 1));

                responseModel.Status      = isVerified ? PreservationVerifyStatus.Ok : PreservationVerifyStatus.Error;
                responseModel.VerifyTitle = title;
                responseModel.Errors      = _preservationService.ErrorMessages;
                _logger.Info($"Process -> preservation is verified with status {responseModel.Status.ToString()}");
                return(responseModel);
            }
            catch (Exception ex)
            {
                _logger.Error($"Error on verify preservation {request.IdPreservation}", ex);
                return(new ExecutePreservationVerifyResponseModel(request.IdPreservation)
                {
                    Status = PreservationVerifyStatus.Error,
                    Errors = new List <string>()
                    {
                        ex.Message
                    }
                });
            }
        }
Ejemplo n.º 16
0
        public ActionResult ClosePreservation(Preservation preservation)
        {
            var service = new PreservationService();

            preservation = service.GetPreservation(preservation.IdPreservation, false);
            if (!preservation.CloseDate.HasValue)
            {
                if (service.VerifyExistingPreservation(preservation.IdPreservation))
                {
                    service.ClosePreservation(preservation.IdPreservation);
                    TempData["ErrorMessages"] = new string[] { "Conservazione eseguita e chiusa con successo" }.ToList();
                }
                else
                {
                    TempData["ErrorMessages"] = service.ErrorMessages;
                }
            }

            return(RedirectToAction("PreservationCheck", "Preservation", new { id = preservation.IdPreservation }));
        }
Ejemplo n.º 17
0
        public ActionResult PreservationCheck(Guid id)
        {
            return(ActionResultHelper.TryCatchWithLogger(() =>
            {
                Preservation preservation = _preservationService.GetPreservation(id, false);
                if (preservation == null)
                {
                    throw new Exception(string.Format("PreservationCheck -> conservazione con id {0} non trovata", id));
                }

                PreservationCheckViewModel model = new PreservationCheckViewModel()
                {
                    IdArchive = preservation.IdArchive,
                    IdPreservation = preservation.IdPreservation,
                    ArchiveName = preservation.Archive.Name,
                    ConservationDescription = string.Concat("dal <b>", preservation.StartDate.GetValueOrDefault().ToString("dd/MM/yyyy"), "</b> al <b>", preservation.EndDate.GetValueOrDefault().ToString("dd/MM/yyyy"), "</b>"),
                    Path = preservation.Path,
                    Manager = preservation.User != null ? string.Concat(preservation.User.Name, " ", preservation.User.Surname) : string.Empty,
                    CloseDateLabel = preservation.CloseDate.HasValue ? preservation.CloseDate.Value.ToString("dd/MM/yyyy") : "#",
                    LastVerifiedDateLabel = preservation.LastVerifiedDate.HasValue ? preservation.LastVerifiedDate.Value.ToString("dd/MM/yyyy") : "#",
                    PathExist = !string.IsNullOrEmpty(preservation.Path) && Directory.Exists(preservation.Path),
                    IsClosed = preservation.CloseDate.HasValue
                };

                if (model.PathExist)
                {
                    DirectoryInfo directoryInfo = new DirectoryInfo(model.Path);
                    FileInfo[] files = directoryInfo.GetFiles("*verifica conservazione*", SearchOption.TopDirectoryOnly).OrderByDescending(t => t.LastWriteTime).ToArray();
                    model.VerifyFiles = files.Select(s => new PreservationCheckVerifyFileViewModel()
                    {
                        FileName = s.Name,
                        Success = !s.Name.Contains("negativo"),
                        DateCreatedLabel = string.Concat(s.LastWriteTime.ToShortDateString(), " ", s.LastWriteTime.ToShortTimeString())
                    }).ToList();
                }

                return View(model);
            }, _loggerService));
        }
Ejemplo n.º 18
0
        public ActionResult PreservationCheckNotification(Guid id, string fileName)
        {
            return(ActionResultHelper.TryCatchWithLogger(() =>
            {
                Preservation preservation = _preservationService.GetPreservation(id, false);
                string fullPath = Path.Combine(preservation.Path, fileName);
                if (!System.IO.File.Exists(fullPath))
                {
                    throw new FileNotFoundException("PreservationCheckNotification -> file non trovato", fullPath);
                }

                PreservationCheckNotificationViewModel model = new PreservationCheckNotificationViewModel()
                {
                    //TODO: Si può fare meglio, non è safe capire lo stato della notifica dal nome del file.
                    Success = !fileName.Contains("negativo"),
                    FileContent = new WindowFileContentViewModel()
                    {
                        Content = string.Join("<br />", System.IO.File.ReadAllLines(fullPath)),
                        Path = fullPath
                    }
                };
                return View(model);
            }, _loggerService));
        }
Ejemplo n.º 19
0
 public void Add(Preservation entity, int userId)
 {
 }
Ejemplo n.º 20
0
 public bool Update(Preservation entity)
 {
     throw new NotImplementedException();
 }
        public async Task <ActionResult> DoVerify(PreservationVerifyExecuteModel model, CancellationToken cancellationToken)
        {
            return(await Task.Factory.StartNew(() =>
            {
                return ActionResultHelper.TryCatchWithLogger(() =>
                {
                    ICollection <PreservationVerifyJob> jobResults = new List <PreservationVerifyJob>();
                    string cacheKey = $"{User.Identity.Name}_{model.executionId}";
                    if (!_cache_jobs.TryAdd(cacheKey, jobResults))
                    {
                        _loggerService.Error("E' avvenuto un errore nella fase di inizializzazione della cache per i risultati di verifica conservazione");
                        throw new Exception("Errore in inizializzazione cache risultati");
                    }

                    if (model == null || model.jobs == null || model.jobs.Length == 0)
                    {
                        _loggerService.Warn("Nessuna conservazione da verificare nel periodo indicato");
                        return Json(string.Empty);
                    }

                    ExecutePreservationVerifyInteractor interactor;
                    ExecutePreservationVerifyRequestModel requestModel;
                    foreach (PreservationVerifyJob job in model.jobs)
                    {
                        Preservation currentPreservation = _preservationService.GetPreservation(Guid.Parse(job.idPreservation), false);
                        if (currentPreservation == null)
                        {
                            jobResults.Add(new PreservationVerifyJob()
                            {
                                idArchive = job.idArchive,
                                archiveName = job.archiveName,
                                idPreservation = job.idPreservation.ToString(),
                                preservationLabel = "Nessuna conservazione da verificare nel periodo indicato",
                                verifyTitle = string.Empty,
                                result = "ok",
                                errors = string.Empty
                            });
                            _cache_jobs.AddOrUpdate(cacheKey, jobResults, (key, existingValue) => jobResults);
                            continue;
                        }

                        interactor = new ExecutePreservationVerifyInteractor(_loggerService);
                        requestModel = new ExecutePreservationVerifyRequestModel()
                        {
                            IdPreservation = Guid.Parse(job.idPreservation)
                        };
                        ExecutePreservationVerifyResponseModel responseModel = interactor.Process(requestModel);
                        jobResults.Add(new PreservationVerifyJob
                        {
                            idArchive = job.idArchive,
                            archiveName = job.archiveName,
                            idPreservation = responseModel.IdPreservation.ToString(),
                            preservationLabel = $"Conservazione {currentPreservation.Label}",
                            verifyTitle = responseModel.VerifyTitle,
                            result = responseModel.Status == PreservationVerifyStatus.Ok ? "ok" : "bad",
                            errors = string.Join("<br />", responseModel.Errors)
                        });

                        _cache_jobs.AddOrUpdate(cacheKey, jobResults, (key, existingVal) => jobResults);
                    }

                    CreatePreservationVerifyReportInteractor reportInteractor = new CreatePreservationVerifyReportInteractor(_loggerService);
                    model.jobs = jobResults.ToArray();
                    PreservationVerifyReportRequestModel reportRequestModel = new PreservationVerifyReportRequestModel()
                    {
                        VerifyModel = model
                    };
                    PreservationVerifyReportResponseModel reportResponseModel = reportInteractor.Process(reportRequestModel);
                    return Json(new
                    {
                        Jobs = jobResults,
                        Response = reportResponseModel
                    });
                }, _loggerService);
            }));
        }
        public override async Task Execute(CommandModel commandModel)
        {
            try
            {
                if (!(commandModel is CommandPurgePreservation))
                {
                    _logger.Error($"Command is not of type {nameof(CommandPurgePreservation)}");
                    await SendNotification(commandModel.ReferenceId, "E' avvenuto un errore durante la gestione del comando di pulizia storage", NotifyLevel.Error, true);

                    return;
                }

                CommandPurgePreservation @command = commandModel as CommandPurgePreservation;
                _logger.Info($"Process command {command.Id} with preservation id {command.IdPreservation}");
                await SendNotification(command.ReferenceId, "Inizio attività di pulizia archivio corrente degli elementi conservati", NotifyLevel.Info);

                if (command.IdPreservation == Guid.Empty)
                {
                    _logger.Error($"Preservation reference not setted for command {command.Id}");
                    await SendNotification(command.ReferenceId, "E' avvenuto un errore durante la gestione del comando di pulizia archivio corrente", NotifyLevel.Error, true);

                    return;
                }

                if (string.IsNullOrEmpty(command.Executor))
                {
                    _logger.Error($"Process executor not setted for command {command.Id}");
                    await SendNotification(command.ReferenceId, "E' avvenuto un errore durante la gestione del comando di pulizia archivio corrente", NotifyLevel.Error, true);

                    return;
                }

                Preservation preservation = _preservationService.GetPreservation(command.IdPreservation, false);
                if (preservation == null)
                {
                    _logger.Error($"Preservation {command.IdPreservation} not found");
                    await SendNotification(command.ReferenceId, $"Nessuna conservazione trovata con id {command.IdPreservation}", NotifyLevel.Error, true);

                    return;
                }

                if (!preservation.CloseDate.HasValue)
                {
                    _logger.Error($"Preservation {command.IdPreservation} is not closed. Please close preservation before execute this task.");
                    await SendNotification(command.ReferenceId, $"Non è possibile procedere alla pulizia dell'archivio corrente di una conservazione non chiusa", NotifyLevel.Error, true);

                    return;
                }

                Logging.AddLog(LoggingOperationType.BiblosDS_General, preservation.IdArchive,
                               Guid.Empty, preservation.IdPreservation,
                               $"Attività di pulizia storage per la conservazione {preservation.IdPreservation} richiesta dall'utente {command.Executor}",
                               command.Executor);

                int preservedDocumentsCount = _preservationService.CountPreservationDocumentsToPurge(command.IdPreservation);
                _logger.Info($"Found {preservedDocumentsCount} to process");
                if (preservedDocumentsCount == 0)
                {
                    await SendNotification(command.ReferenceId, $"Nessun documento trovato per la conservazione {command.IdPreservation}", NotifyLevel.Info, true);

                    return;
                }
                await SendNotification(command.ReferenceId, $"Trovati {preservedDocumentsCount} documenti da eliminare dall'archivio corrente", NotifyLevel.Info);

                int            processedItems       = 0;
                decimal        pulsePercentageLimit = 20;
                decimal        percentage;
                EntityProvider entityProvider;
                await SendNotification(command.ReferenceId, $"Inizio cancellazione documenti, l'attività può richiedere alcuni minuti", NotifyLevel.Info);

                Status statusToChange = new Status(DocumentStatus.MovedToPreservation);

                ICollection <Document> preservedDocuments = _preservationService.GetPreservationDocumentsToPurge(command.IdPreservation);
                string documentPath  = string.Empty;
                bool   hasMoveErrors = false;
                foreach (Document document in preservedDocuments)
                {
                    processedItems++;
                    _logger.Info($"Process document {document.IdDocument}");
                    documentPath = DocumentService.GetPreservationDocumentPath(document);
                    _logger.Info($"Document {document.IdDocument} with preservation path: {documentPath}");
                    if (string.IsNullOrEmpty(documentPath))
                    {
                        _logger.Info($"Document {document.IdDocument} hasn't preservation path defined. Document skipped");
                        await SendNotification(command.ReferenceId, $"Il documento {document.IdDocument} non ha l'indicazione del percorso di conservazione e pertanto non può essere eliminato dall'archivio corrente", NotifyLevel.Error);

                        continue;
                    }

                    if (!File.Exists(documentPath))
                    {
                        _logger.Info($"File {documentPath} not found on disk for document {document.IdDocument}");
                        await SendNotification(command.ReferenceId, $"Il documento {document.IdDocument} non esiste nel percorso di conservazione {documentPath}", NotifyLevel.Error);

                        continue;
                    }

                    entityProvider = new EntityProvider();
                    using (IDbTransaction transaction = entityProvider.BeginNoSave())
                    {
                        try
                        {
                            _logger.Info($"Document {document.IdDocument} -> change document state to {DocumentStatus.MovedToPreservation.ToString()}");
                            entityProvider.UpdateDocumentStatus(document, statusToChange);
                            entityProvider.SaveChanges();

                            _logger.Info($"Document {document.IdDocument} -> delete document from storage");
                            _storageService.DeleteDocument(document, false);
                            transaction.Commit();
                        }
                        catch (Exception ex)
                        {
                            transaction.Rollback();
                            _logger.Info($"Error on delete document {document.IdDocument} from storage. Document skipped.", ex);
                            hasMoveErrors = true;
                        }
                    }

                    percentage = ((decimal)processedItems / preservedDocumentsCount) * 100.0m;
                    if (Math.Ceiling(percentage) > pulsePercentageLimit)
                    {
                        await SendNotification(command.ReferenceId, $"Pulizia documenti nell'archivio corrente ({pulsePercentageLimit}%).", NotifyLevel.Info);

                        pulsePercentageLimit += 20;
                    }
                }

                string completeMessage = $"Il processo di pulizia archivio corrente per la conservazione {command.IdPreservation} è terminato correttamente.";
                if (hasMoveErrors)
                {
                    completeMessage = $"Il processo di pulizia archivio corrente per la conservazione {command.IdPreservation} è terminato con errori. Verificare il file di log per ulteriori dettagli.";
                }
                await SendNotification(command.ReferenceId, completeMessage, hasMoveErrors?NotifyLevel.Error : NotifyLevel.Info, true);
            }
            catch (Exception ex)
            {
                _logger.Error($"Error on purge preservation", ex);
                await SendNotification(commandModel.ReferenceId, $"E' avvenuto un errore durante l'esecuzione dell'attività corrente", NotifyLevel.Error, true);
            }
        }
Ejemplo n.º 23
0
        internal static Preservation Convert(this BibDSModel.Preservation pre, int level = 0, int deeplevel = 5, params Type[] ignoredTypes)
        {
            if (pre == null || level > deeplevel)
            {
                return(null);
            }

            var docs = new BindingList <Document>();

            var retval = new Preservation
            {
                //Archive = pre.Archive.Convert(level + 1, deeplevel),
                CloseContent            = pre.CloseContent,
                CloseDate               = pre.CloseDate,
                Documents               = docs,
                EndDate                 = pre.EndDate,
                IdArchive               = pre.IdArchive,
                IdPreservation          = pre.IdPreservation,
                IdPreservationTaskGroup = pre.IdPreservationTaskGroup,
                IdPreservationUser      = pre.IdPreservationUser,
                IndexHash               = pre.IndexHash,
                Label                     = pre.Label,
                LastVerifiedDate          = pre.LastVerifiedDate,
                Path                      = pre.Path,
                StartDate                 = pre.StartDate,
                PreservationDate          = pre.PreservationDate,
                PreservationSize          = pre.PreservationSize,
                IdDocumentCloseFile       = pre.IdDocumentClose,
                IdDocumentIndexFile       = pre.IdDocumentIndex,
                IdDocumentIndexFileXML    = pre.IdDocumentIndexXml,
                IdDocumentIndexFileXSLT   = pre.IdDocumentIndexXSLT,
                IdDocumentSignedCloseFile = pre.IdDocumentCloseSigned,
                IdDocumentSignedIndexFile = pre.IdDocumentIndedSigned,
                LastSectionalValue        = pre.LastSectionalValue,
                IdArchiveBiblosStore      = pre.IdArchiveBiblosStore,
                LockOnDocumentInsert      = pre.LockOnDocumentInsert
                                            //TaskGroup = pre.PreservationTaskGroup.Convert(level + 1, deeplevel),
                                            //Task = pre.PreservationTask.Convert(level + 1, deeplevel),
                                            //User = pre.PreservationUser.Convert(level + 1, deeplevel),
                                            //PreservationJournalings = pre.PreservationJournaling.Convert(level, deeplevel),
            };

            if (ignoredTypes == null)
            {
                ignoredTypes = new Type[0];
            }

            if (!ignoredTypes.Contains(typeof(DocumentArchive)))
            {
                retval.Archive = pre.Archive.Convert(level + 1, deeplevel);
            }

            if (!ignoredTypes.Contains(typeof(PreservationTaskGroup)))
            {
                retval.TaskGroup = pre.PreservationTaskGroup.Convert(level + 1, deeplevel);
            }

            if (!ignoredTypes.Contains(typeof(PreservationTask)))
            {
                retval.Task = pre.PreservationTask.Convert(level + 1, deeplevel);
            }

            if (!ignoredTypes.Contains(typeof(PreservationUser)))
            {
                retval.User = pre.PreservationUser.Convert(level + 1, deeplevel);
            }

            if (!ignoredTypes.Contains(typeof(PreservationJournaling)))
            {
                retval.PreservationJournalings = pre.PreservationJournaling.Convert(level, deeplevel);
            }

            if (!ignoredTypes.Contains(typeof(Document)))
            {
                foreach (var d in pre.PreservationDocuments)
                {
                    docs.Add(d.Document.Convert(level + 1, deeplevel, null));
                }
                retval.Documents = docs;
            }

            retval.ClearModifiedField();
            return(retval);
        }
Ejemplo n.º 24
0
        private string UnZipPreservationFile(string zipPath)
        {
            StringBuilder sb = new StringBuilder();

            try
            {
                if (System.IO.File.Exists(zipPath))
                {
                    using (Stream stream = System.IO.File.OpenRead(zipPath))
                        using (IReader reader = ReaderFactory.Open(stream))
                        {
                            while (reader.MoveToNextEntry())
                            {
                                if (!reader.Entry.IsDirectory)
                                {
                                    string fileName = Path.GetFileName(reader.Entry.Key);
                                    _logger.InfoFormat("UnzipPreservationFile -> Lettura file {0}", fileName);

                                    string preservationIdStr = fileName.Split('_').FirstOrDefault();
                                    if (Guid.TryParse(preservationIdStr, out Guid idPreservation))
                                    {
                                        Preservation preservation = _preservationService.GetPreservation(idPreservation, false);
                                        if (preservation == null)
                                        {
                                            _logger.WarnFormat("Nessuna conservazione trovata con Id {0}", idPreservation);
                                            continue;
                                        }

                                        if (preservation.CloseDate.HasValue)
                                        {
                                            _logger.InfoFormat("UnzipPreservationFile -> Conservazione <b>{0}</b> del {1} <b>CHIUSA</b> il {2}.<br/>", preservation.IdPreservation, preservation.StartDate, preservation.CloseDate);
                                            sb.AppendFormat("Conservazione <b>{0}</b> del {1} <b>CHIUSA</b> il {2}.<br/>", preservation.IdPreservation, preservation.StartDate, preservation.CloseDate);
                                            continue;
                                        }

                                        string toSaveFile = Path.Combine(preservation.Path, fileName.Substring(fileName.IndexOf('_') + 1));
                                        if (System.IO.File.Exists(toSaveFile))
                                        {
                                            _logger.InfoFormat("UnzipPreservationFile -> File già presente!<br/>Il file verrà ignorato: {0}<br/>", Path.Combine(preservation.Path, preservation.Label, fileName.Substring(fileName.IndexOf('_') + 1)));
                                            sb.AppendFormat("File già presente!<br/>Il file verrà ignorato: {0}<br/>", Path.Combine(preservation.Path, preservation.Label, fileName.Substring(fileName.IndexOf('_') + 1)));
                                        }
                                        else
                                        {
                                            reader.WriteEntryToFile(toSaveFile, _extractionOptions);
                                            _logger.DebugFormat("UnzipPreservationFile -> file {0} saved correctly", toSaveFile);
                                        }

                                        string ipdaSignedFile = IpdaUtil.GetIpdaTsdFile(preservation.Path);
                                        if (string.IsNullOrEmpty(ipdaSignedFile))
                                        {
                                            _logger.WarnFormat("UnzipPreservationFile -> Nessun file IPDA firmato trovato nel percorso {0}", preservation.Path);
                                            continue;
                                        }

                                        ArchiveConfiguration archiveConfiguration = JsonConvert.DeserializeObject <ArchiveConfiguration>(preservation.Archive.PreservationConfiguration);
                                        if (!archiveConfiguration.CloseWithoutVerify)
                                        {
                                            _logger.InfoFormat("UnzipPreservationFile -> Chiusura Conservazione {0} con verify", preservation.IdPreservation);
                                            if (_preservationService.VerifyExistingPreservation(preservation.IdPreservation))
                                            {
                                                _logger.InfoFormat("UnzipPreservationFile -> Verifica conservazione {0} conclusa con esito positivo", preservation.IdPreservation);
                                            }
                                            else
                                            {
                                                _logger.InfoFormat("UnzipPreservationFile -> Verifica conservazione {0} conclusa con esito negativo", preservation.IdPreservation);
                                                sb.Append(string.Join("<br/>", _preservationService.ErrorMessages));
                                                continue;
                                            }
                                        }

                                        _preservationService.ClosePreservation(preservation.IdPreservation);
                                        string pattern = "Conservazione <b>{0}</b> del {1} <b>CHIUSA</b> in questa esecuzione.<br/>";
                                        sb.AppendFormat(pattern, preservation.IdPreservation, preservation.StartDate);

                                        //aggiunge informazioni sull'ipda
                                        sb.Append(GetIpdaInfo(_preservationService.verifiedIpda));
                                    }
                                }
                            }
                        }
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                _logger.ErrorFormat("UnzipPreservationFile -> errore nello spacchettamento dello zip per la chiusura: {0}. La procedura non verrà interrotta", ex.Message);
                sb.Append(ex.Message);
            }
            return(sb.ToString());
        }