-refact path convert file

This commit is contained in:
eugeniy_ivanov 2023-01-25 05:32:32 +05:00
parent be9168b4bf
commit 907fcc88e8
3 changed files with 19 additions and 29 deletions

View File

@ -33,45 +33,40 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram.Convert
};
}
private static async Task StartConvertProcessAsync(string inputFileName, string outFileName, CancellationToken token)
private static async Task StartConvertProcessAsync(string inputFileName, string resultFileDir,CancellationToken token)
{
//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);
var command = Cli.Wrap("C:\\Program Files\\LibreOffice\\program\\soffice.exe")
.WithArguments($"-headless -convert-to pdf {inputFileName} --outdir {resultFileDir}");
await command.ExecuteAsync(token);
}
public static async Task GetConverteAndMergedFileAsync(IEnumerable<string> filesNames, string resultPath, CancellationToken token)
public static async Task GetConverteAndMergedFileAsync(IEnumerable<string> files, string resultPath, string convertedFilesDir,CancellationToken token)
{
var badFiles = filesNames.Where(f => !filesExtensions.Contains(Path.GetExtension(f)));
var badFiles = files.Where(f => !filesExtensions.Contains(Path.GetExtension(f)));
if (badFiles.Any())
{
throw new FileFormatException($"Файлы: {string.Join(", ", badFiles)} - неподдерживаемого формата. " +
$"Они не могут быть добавлены в список файлов для конвертации и слияния в общий файл программы бурения.");
}
var listFileNames = filesNames
var listFiles = files
.Distinct()
.Select(f => new {
inputFile = f,
convertedFile = Path.ChangeExtension(f, ".pdf")
convertedFile = Path.Combine(convertedFilesDir,"pdf",Path.ChangeExtension(Path.GetFileName(f), ".pdf"))
})
.ToList();
var listFilesToDelete = new List<string>();
foreach (var fileName in listFileNames)
{
var fileExt = Path.GetExtension(fileName.inputFile);
foreach (var file in listFiles)
{
var fileExt = Path.GetExtension(file.inputFile);
if (fileExt != ".pdf")
{
await StartConvertProcessAsync(fileName.inputFile, fileName.convertedFile, token);
listFilesToDelete.Add(fileName.convertedFile);
await StartConvertProcessAsync(file.inputFile, Path.GetDirectoryName(file.convertedFile)!,token);
}
}
MergeFiles(listFileNames.Select(c => c.convertedFile), resultPath);
foreach (var file in listFilesToDelete)
{
File.Delete(file);
}
MergeFiles(listFiles.Select(c => c.convertedFile), resultPath);
Directory.Delete(Path.Combine(convertedFilesDir,"pdf"),true);
}
}
#nullable disable

View File

@ -477,14 +477,15 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
if (!backgroundWorker.Contains(workId))
{
var well = (await wellService.GetOrDefaultAsync(idWell, token))!;
var resultFileName = $"Программа бурения {well.Cluster} {well.Caption}.xlsx";
var tempResultFilePath = Path.Combine(Path.GetTempPath(), "drillingProgram", resultFileName);
var resultFileName = $"Программа бурения {well.Cluster} {well.Caption}.pdf";
var convertedFilesDir = Path.Combine(Path.GetTempPath(), "drillingProgram", $"{well.Cluster}_{well.Caption}");
var tempResultFilePath = Path.Combine(convertedFilesDir, 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 ConvertToPdf.GetConverteAndMergedFileAsync(files, tempResultFilePath, token);
await ConvertToPdf.GetConverteAndMergedFileAsync(files, tempResultFilePath, convertedFilesDir, token);
await fileService.MoveAsync(idWell, null, idFileCategoryDrillingProgram, resultFileName, tempResultFilePath, token);
};

View File

@ -125,13 +125,7 @@ namespace AsbCloudWebApi.Controllers
return BadRequest(ArgumentInvalidException.MakeValidationError(nameof(files), "at list 1 file should be uploaded"));
var fileName = files[0].FileName;
// 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);