public async Task <IActionResult> RestoreFile(string key, bool includeFileDeleted = false)
        {
            try
            {
                var result = new RestoreFileResponse();
                if (key == restoreKey)
                {
                    result = await _fileService.RestoreFile(includeFileDeleted);

                    return(Ok(result));
                }

                return(Ok(result));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex));
            }
        }
Beispiel #2
0
        public async Task <RestoreFileResponse> RestoreFile(bool includeFileDeleted)
        {
            try
            {
                //First check include deleted
                if (includeFileDeleted)
                {
                    using (var transaction = _dataContext.Database.BeginTransaction())
                    {
                        try
                        {
                            var listFileDeleted = (from i in _dataContext.FileStreamInfo
                                                   join d in _dataContext.FileStreamData on i.FileId equals d.FileId
                                                   where i.Deleted == true
                                                   select i).ToList();
                            foreach (var item in listFileDeleted)
                            {
                                RestoreFileInfo(item.FileId);
                            }

                            transaction.Commit();
                            transaction.Dispose();
                        }
                        catch
                        {
                            transaction.Rollback();
                            transaction.Dispose();
                            throw;
                        }
                    }
                }

                //Start restore and report
                var res            = new RestoreFileResponse();
                var report         = new ReportModel();
                var reportLines    = new List <ReportLine>();
                var pathFileReport = string.Empty;
                var absolutePath   = _aqFileProvider.GetAbsolutePath();
                var baseHost       = MyHttpContext.AppBaseUrl;

                var totalItems       = _dataContext.FileStreamInfo.Where(x => x.Deleted == false).Count();
                var getSize          = 50;
                var skipNumber       = 0;
                var times            = totalItems / getSize;
                var totalItemSuccess = 0;
                var totalItemFail    = 0;

                var fileInfoItems = _dataContext.FileStreamInfo.Where(x => x.Deleted == false).Skip(skipNumber).Take(getSize).ToList();

                while (times >= 0)
                {
                    res.TotalItems = totalItems;
                    foreach (var fileInfo in fileInfoItems)
                    {
                        var reportLine = new ReportLine();
                        if (fileInfo != null)
                        {
                            reportLine.ReportTime = DateTime.Now;
                            reportLine.FileId     = fileInfo.FileId;
                            reportLine.FileName   = fileInfo.FileName;
                            reportLine.FileEx     = fileInfo.FileExtentions;
                            reportLine.FileSize   = fileInfo.FileSize;
                            reportLine.FileType   = (int)fileInfo.FileTypeFid;
                            reportLine.Path       = fileInfo.Path;

                            var relativePath = fileInfo.Path.Replace("/", @"\");

                            if (string.IsNullOrEmpty(relativePath))
                            {
                                reportLine.Status  = "Fail";
                                reportLine.Message = "Path not found";
                                reportLines.Add(reportLine);
                                totalItemFail++;

                                continue;
                            }

                            if (!relativePath.StartsWith("contents\\") || !reportLine.FileName.Contains("."))
                            {
                                reportLine.Status  = "Fail";
                                reportLine.Message = "The path is not correct";
                                reportLines.Add(reportLine);
                                totalItemFail++;

                                continue;
                            }

                            try
                            {
                                //Data
                                var fileBinary = await GetFileDataById(fileInfo.FileId);

                                byte[] fileThumb12;
                                byte[] fileThumb16;
                                byte[] fileThumb14;
                                byte[] fileThumb18;

                                //Info
                                var fileName          = fileInfo.FileName;
                                var fileNameWithoutEx = Path.GetFileNameWithoutExtension(fileName);
                                var fileEx            = fileInfo.FileExtentions;

                                //Path
                                var pathRoot     = _aqFileProvider.GetAbsolutePath();
                                var saveFilePath = $@"{pathRoot}\{relativePath}";
                                var fullPath     = $@"{saveFilePath}{fileName}";
                                var pathThumb12  = $@"{saveFilePath}{fileNameWithoutEx}_12{fileEx}";
                                var pathThumb14  = $@"{saveFilePath}{fileNameWithoutEx}_14{fileEx}";
                                var pathThumb16  = $@"{saveFilePath}{fileNameWithoutEx}_16{fileEx}";
                                var pathThumb18  = $@"{saveFilePath}{fileNameWithoutEx}_18{fileEx}";

                                var checkDirectoryExists = _aqFileProvider.DirectoryExists(saveFilePath);
                                if (!checkDirectoryExists)
                                {
                                    _aqFileProvider.CreateDirectory(saveFilePath);
                                }

                                var checkFileExist = _aqFileProvider.FileExists(fullPath);

                                var isImageFile = _pictureService.GetImageFormat(fileBinary) != ImageFormatEnum.unknown;

                                if (isImageFile)
                                {
                                    int quality = 100;
                                    //in MB
                                    double fileSize = Convert.ToDouble(fileBinary.Length.ToString()) / 1024 / 1024;
                                    if (fileSize >= 4)
                                    {
                                        quality = 45;
                                    }
                                    else if (fileSize >= 2 && fileSize < 4)
                                    {
                                        quality = 65;
                                    }
                                    else if (fileSize > 0.5 && fileSize < 2)
                                    {
                                        quality = 85;
                                    }

                                    fileBinary = _pictureService.ValidatePicture(fileBinary, 2048, quality);

                                    if (!_aqFileProvider.DirectoryExists(pathThumb12))
                                    {
                                        fileThumb12 = _pictureService.ResizePicture(fileBinary, (int)ThumbRatioEnum.half, quality);
                                        using (Stream f = File.OpenWrite(pathThumb12))
                                        {
                                            await f.WriteAsync(fileThumb12, 0, fileThumb12.Length);
                                        };
                                    }

                                    if (!_aqFileProvider.DirectoryExists(pathThumb14))
                                    {
                                        fileThumb14 = _pictureService.ResizePicture(fileBinary, (int)ThumbRatioEnum.quarter, quality);
                                        using (Stream f = File.OpenWrite(pathThumb14))
                                        {
                                            await f.WriteAsync(fileThumb14, 0, fileThumb14.Length);
                                        };
                                    }

                                    if (!_aqFileProvider.DirectoryExists(pathThumb16))
                                    {
                                        fileThumb16 = _pictureService.ResizePicture(fileBinary, (int)ThumbRatioEnum.oneSixth, quality);
                                        using (Stream f = File.OpenWrite(pathThumb16))
                                        {
                                            await f.WriteAsync(fileThumb16, 0, fileThumb16.Length);
                                        };
                                    }

                                    if (!_aqFileProvider.DirectoryExists(pathThumb18))
                                    {
                                        fileThumb18 = _pictureService.ResizePicture(fileBinary, (int)ThumbRatioEnum.oneEighth, quality);
                                        using (Stream f = File.OpenWrite(pathThumb18))
                                        {
                                            await f.WriteAsync(fileThumb18, 0, fileThumb18.Length);
                                        };
                                    }
                                }

                                if (!_aqFileProvider.DirectoryExists(fullPath))
                                {
                                    using (Stream f = File.OpenWrite(fullPath))
                                    {
                                        await f.WriteAsync(fileBinary, 0, fileBinary.Length);
                                    };
                                }
                                reportLine.Status = "Success";
                                reportLines.Add(reportLine);

                                totalItemSuccess++;
                            }
                            catch
                            {
                                reportLines.Add(reportLine);
                                totalItemFail++;
                                continue;
                            }
                        }
                        else
                        {
                            //File item is null
                            reportLine.Status  = "Fail";
                            reportLine.Message = "File not found";
                            reportLines.Add(reportLine);
                            totalItemFail++;
                        }
                    }

                    skipNumber += getSize;
                    var listFileInfoTemp = _dataContext.FileStreamInfo.Where(x => x.Deleted == false).Skip(skipNumber).Take(getSize).ToList();
                    fileInfoItems.Clear();
                    fileInfoItems = listFileInfoTemp;
                    times--;
                }

                res.TotalItems       = totalItems;
                res.TotalItemFail    = totalItemFail;
                res.TotalItemSuccess = totalItemSuccess;

                report.TotalItems   = totalItems;
                report.TotalSuccess = totalItemSuccess;
                report.TotalFail    = totalItemFail;
                report.DateReport   = DateTime.Now;

                var saveFileReport = absolutePath + $"contents/docs/restorefilereports/";
                if (!_aqFileProvider.DirectoryExists(saveFileReport))
                {
                    _aqFileProvider.CreateDirectory(saveFileReport);
                }
                pathFileReport     = absolutePath + $"contents/docs/restorefilereports/report_{report.DateReport.ToString("dd-MM-yyyy")}_{DateTime.Now.Ticks}.txt";
                report.ReportLines = reportLines;
                var runNo = 1;

                FileStream fs = File.Create(pathFileReport);
                fs.Close();
                using (StreamWriter file = new StreamWriter(pathFileReport))
                {
                    await file.WriteLineAsync($"Date: {report.DateReport}");

                    await file.WriteLineAsync($"TotalItems: {report.TotalItems}");

                    await file.WriteLineAsync($"Total success: {report.TotalSuccess}");

                    await file.WriteLineAsync($"Total fail: {report.TotalFail}");

                    await file.WriteLineAsync("");

                    foreach (var line in report.ReportLines)
                    {
                        await file.WriteLineAsync($"{runNo++} | {line.ReportTime} | ID: {line.FileId} | Name: {line.FileName} | Size: {line.FileSize} | Type: {line.FileType} | Path: {line.Path} | Status: {line.Status} | Message: {line.Message}");
                    }
                }

                var pathReport = $"{baseHost}/{pathFileReport.Replace(absolutePath, "").Replace(@"\", "/")}";
                res.PathReport = pathReport;
                return(res);
            }
            catch
            {
                throw;
            }
        }