Beispiel #1
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));
        }
        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 }));
        }
        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));
        }
        public ActionResult PreservationUploadFiles(Guid idPreservation, string preservationPath)
        {
            var errorMessage = string.Empty;

            if (Request.Files != null)
            {
                try
                {
                    var                service = new PreservationService();
                    var                preservation = service.GetPreservation(idPreservation, false);
                    string             fileName, type;
                    HttpPostedFileBase file;

                    foreach (string formName in Request.Files)
                    {
                        file     = Request.Files[formName];
                        fileName = Path.Combine(preservationPath, Path.GetFileName(file.FileName));
                        type     = file.ContentType;

                        file.SaveAs(fileName);

                        //try
                        //{
                        //    if (fileName.ToUpper().Contains("CHIUSURA_"))
                        //    {
                        //        if (!checkPreservationFilesIntegrity(idPreservation, fileName, null, false))
                        //            throw new Exception("La verifica del file di chiusura ha avuto esito negativo");
                        //    }
                        //}
                        //catch
                        //{
                        //    throw;
                        //}
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex);
                    errorMessage = ex.ToString();
                }
            }
            else
            {
                errorMessage = "Nessun file passato.";
            }

            return(Content(errorMessage));
        }
Beispiel #6
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));
        }
Beispiel #7
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
                    }
                });
            }
        }
Beispiel #8
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 }));
        }
        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);
            }
        }