-типы методов класса конвертации изменены на статические

-удаляются только преобразованные файлы
This commit is contained in:
eugeniy_ivanov 2023-01-20 08:31:38 +05:00
parent 219fe450a1
commit 350759f1c6
4 changed files with 32 additions and 12 deletions

View File

@ -10,9 +10,9 @@ using System.Threading;
namespace AsbCloudInfrastructure.Services.DrillingProgram.Convert
{
#nullable enable
internal class ConvertToPdf
sealed internal class ConvertToPdf
{
private readonly string[] filesExtensions = { ".xlsx", ".xls", ".ods", ".odt", ".doc", ".docx", ".pdf" };
private static readonly string[] filesExtensions = { ".xlsx", ".xls", ".ods", ".odt", ".doc", ".docx", ".pdf" };
private static void MergeFiles(IEnumerable<string> inputFiles, string outFile)
{
@ -35,12 +35,14 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram.Convert
private static async Task StartConvertProcessAsync(string inputFileName, string outFileName, CancellationToken token)
{
var result = Cli.Wrap("/usr/bin/soffice")
.WithArguments($"--headless --convert-to pdf {inputFileName} --outdir {outFileName}");
//var result = Cli.Wrap("/usr/bin/soffice")
// .WithArguments($"--headless --convert-to pdf {inputFileName} --outdir {outFileName}");
var result = Cli.Wrap("C:\\Program Files\\LibreOffice\\program\\soffice.exe")
.WithArguments($"-headless -convert-to pdf {inputFileName} --outdir {outFileName}");
await result.ExecuteAsync(token);
}
public async Task GetConverteAndMergedFileAsync(IEnumerable<string> filesNames, string resultPath, CancellationToken token)
public static async Task GetConverteAndMergedFileAsync(IEnumerable<string> filesNames, string resultPath, CancellationToken token)
{
var badFiles = filesNames.Where(f => !filesExtensions.Contains(Path.GetExtension(f)));
if (badFiles.Any())
@ -55,15 +57,21 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram.Convert
convertedFile = Path.ChangeExtension(f, ".pdf")
})
.ToList();
var listFilesToDelete = new List<string>();
foreach (var fileName in listFileNames)
{
var fileExt = Path.GetExtension(fileName.inputFile);
if (fileExt != ".pdf")
{
await StartConvertProcessAsync(fileName.inputFile, fileName.convertedFile, token);
listFilesToDelete.Add(fileName.convertedFile);
}
}
MergeFiles(listFileNames.Select(c => c.convertedFile), resultPath);
foreach (var file in listFilesToDelete)
{
File.Delete(file);
}
}
}
#nullable disable

View File

@ -12,6 +12,12 @@ Windows - C:\Program Files\LibreOffice\program\soffice.exe
изначально обозначенные в задаче.
При необходимости список можно расширить.
4. Если для тестирования исходники необходимо запустить на машине под управлением Windows
необходимо поменять содержание переменной result в методе StartConvertProcessAsync на :
var result = Cli.Wrap("C:\\Program Files\\LibreOffice\\program\\soffice.exe")
.WithArguments($"-headless -convert-to pdf {inputFileName} --outdir {outFileName}");

View File

@ -30,6 +30,7 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
private readonly IConfiguration configuration;
private readonly BackgroundWorker backgroundWorker;
private readonly IEmailService emailService;
private readonly IServiceProvider serviceProvider;
private const int idFileCategoryDrillingProgram = 1000;
private const int idFileCategoryDrillingProgramPartsStart = 1001;
@ -58,7 +59,8 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
IWellService wellService,
IConfiguration configuration,
BackgroundWorker backgroundWorker,
IEmailService emailService)
IEmailService emailService,
IServiceProvider serviceProvider)
{
this.context = context;
this.fileService = fileService;
@ -67,6 +69,8 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
this.configuration = configuration;
this.backgroundWorker = backgroundWorker;
this.emailService = emailService;
this.serviceProvider = serviceProvider;
}
public async Task<IEnumerable<UserDto>> GetAvailableUsers(int idWell, CancellationToken token = default)
@ -474,14 +478,13 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
{
var well = (await wellService.GetOrDefaultAsync(idWell, token))!;
var resultFileName = $"Программа бурения {well.Cluster} {well.Caption}.xlsx";
var tempResultFilePath = Path.Combine(Path.GetTempPath(), "drillingProgram", resultFileName);
var converter = new ConvertToPdf();
var tempResultFilePath = Path.Combine(Path.GetTempPath(), "drillingProgram", resultFileName);
var workAction = async (string workId, IServiceProvider serviceProvider, CancellationToken token) =>
{
var context = serviceProvider.GetRequiredService<IAsbCloudDbContext>();
var fileService = serviceProvider.GetRequiredService<FileService>();
var files = state.Parts.Select(p => fileService.GetUrl(p.File));
await converter.GetConverteAndMergedFileAsync(files, tempResultFilePath, token);
await ConvertToPdf.GetConverteAndMergedFileAsync(files, tempResultFilePath, token);
await fileService.MoveAsync(idWell, null, idFileCategoryDrillingProgram, resultFileName, tempResultFilePath, token);
};

View File

@ -126,8 +126,11 @@ namespace AsbCloudWebApi.Controllers
var fileName = files[0].FileName;
if (!fileName.EndsWith(".xlsx"))
return BadRequest(ArgumentInvalidException.MakeValidationError("file", "Файл должен быть xlsx"));
// TODO: в текущем контексте доработки по ковертации
// данная проверка будет некорректна, т.к. планируется загружать
// файлы разных форматов
//if (!fileName.EndsWith(".xlsx"))
// return BadRequest(ArgumentInvalidException.MakeValidationError("file", "Файл должен быть xlsx"));
var fileStream = files[0].OpenReadStream();
var result = await drillingProgramService.AddFile(idWell, idFileCategory, (int)idUser, fileName, fileStream, token);