Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

Subfolder only when a file becomes several (#259)

flexeykinDev03e579a7ad8f
diff --git a/src/Filee.App/Assets/i18n/ar.json b/src/Filee.App/Assets/i18n/ar.json
index 106fa958..f812e2e5 100644
--- a/src/Filee.App/Assets/i18n/ar.json
+++ b/src/Filee.App/Assets/i18n/ar.json
@@ -576,6 +576,8 @@
"presets.location.Subfolder": "مجلد فرعي",
"presets.location.CustomFolder": "مجلد ثابت",
"presets.subfolder": "اسم المجلد الفرعي",
+ "presets.subfolder_only_several": "فقط عندما ينتج أكثر من ملف",
+ "presets.subfolder_only_several_hint": "إذا نتج عن التحويل ملف واحد فإنه يُحفظ بجانب الأصل؛ ولا يُنشأ المجلد الفرعي إلا عندما ينتج عدة ملفات (مثل تقسيم PDF إلى صفحات).",
"presets.custom_folder": "المجلد",
"presets.browse": "استعراض…",
"presets.pattern": "اسم الملف",
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index 89c97d52..b6af9522 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -591,6 +591,8 @@
"presets.location.Subfolder": "A subfolder",
"presets.location.CustomFolder": "A fixed folder",
"presets.subfolder": "Subfolder name",
+ "presets.subfolder_only_several": "Only when a file becomes several",
+ "presets.subfolder_only_several_hint": "A file converted to one file is saved next to the original; only one that becomes several files (a PDF split into pages) gets the subfolder.",
"presets.custom_folder": "Folder",
"presets.browse": "Browse…",
"presets.pattern": "File name",
diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.json
index 8d9a057b..2fe255e4 100644
--- a/src/Filee.App/Assets/i18n/es.json
+++ b/src/Filee.App/Assets/i18n/es.json
@@ -576,6 +576,8 @@
"presets.location.Subfolder": "Una subcarpeta",
"presets.location.CustomFolder": "Una carpeta fija",
"presets.subfolder": "Nombre de la subcarpeta",
+ "presets.subfolder_only_several": "Solo si salen varios archivos",
+ "presets.subfolder_only_several_hint": "Si un archivo se convierte en uno solo, se guarda junto al original; la subcarpeta solo se crea cuando salen varios archivos (un PDF dividido en páginas).",
"presets.custom_folder": "Carpeta",
"presets.browse": "Examinar…",
"presets.pattern": "Nombre del archivo",
diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.json
index e219eb65..055e126b 100644
--- a/src/Filee.App/Assets/i18n/hi.json
+++ b/src/Filee.App/Assets/i18n/hi.json
@@ -576,6 +576,8 @@
"presets.location.Subfolder": "एक सबफ़ोल्डर",
"presets.location.CustomFolder": "एक तय फ़ोल्डर",
"presets.subfolder": "सबफ़ोल्डर का नाम",
+ "presets.subfolder_only_several": "सिर्फ़ तब, जब कई फ़ाइलें बनें",
+ "presets.subfolder_only_several_hint": "एक फ़ाइल बनने पर वह मूल फ़ाइल के पास सेव होती है; सबफ़ोल्डर सिर्फ़ तब बनता है जब कई फ़ाइलें बनें (जैसे PDF को पेजों में बाँटने पर)।",
"presets.custom_folder": "फ़ोल्डर",
"presets.browse": "ब्राउज़ करें…",
"presets.pattern": "फ़ाइल का नाम",
diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.json
index d5c6b067..1af80166 100644
--- a/src/Filee.App/Assets/i18n/ja.json
+++ b/src/Filee.App/Assets/i18n/ja.json
@@ -576,6 +576,8 @@
"presets.location.Subfolder": "サブフォルダー",
"presets.location.CustomFolder": "指定したフォルダー",
"presets.subfolder": "サブフォルダー名",
+ "presets.subfolder_only_several": "複数のファイルになるときだけ",
+ "presets.subfolder_only_several_hint": "1つのファイルに変換されたときは元のファイルの隣に保存し、複数のファイルになるとき(PDFをページごとに分けるときなど)だけサブフォルダーを作ります。",
"presets.custom_folder": "フォルダー",
"presets.browse": "参照…",
"presets.pattern": "ファイル名",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index d3e05b1a..20f306d4 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -591,6 +591,8 @@
"presets.location.Subfolder": "하위 폴더",
"presets.location.CustomFolder": "지정한 폴더",
"presets.subfolder": "하위 폴더 이름",
+ "presets.subfolder_only_several": "여러 파일이 될 때만",
+ "presets.subfolder_only_several_hint": "한 파일로 변환되면 원본 옆에 저장하고, 여러 파일이 될 때(PDF를 페이지별로 나눌 때 등)만 하위 폴더를 만듭니다.",
"presets.custom_folder": "폴더",
"presets.browse": "찾아보기…",
"presets.pattern": "파일 이름",
diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json
index 82559afb..be25a532 100644
--- a/src/Filee.App/Assets/i18n/pl.json
+++ b/src/Filee.App/Assets/i18n/pl.json
@@ -591,6 +591,8 @@
"presets.location.Subfolder": "Podfolder",
"presets.location.CustomFolder": "Stały folder",
"presets.subfolder": "Nazwa podfolderu",
+ "presets.subfolder_only_several": "Tylko gdy powstaje kilka plików",
+ "presets.subfolder_only_several_hint": "Plik przekonwertowany na jeden plik zostaje zapisany obok oryginału; podfolder powstaje tylko wtedy, gdy powstaje kilka plików (PDF podzielony na strony).",
"presets.custom_folder": "Folder",
"presets.browse": "Przeglądaj…",
"presets.pattern": "Nazwa pliku",
diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.json
index ab823de2..85fee0ec 100644
--- a/src/Filee.App/Assets/i18n/ru.json
+++ b/src/Filee.App/Assets/i18n/ru.json
@@ -591,6 +591,8 @@
"presets.location.Subfolder": "Во вложенную папку",
"presets.location.CustomFolder": "В заданную папку",
"presets.subfolder": "Имя вложенной папки",
+ "presets.subfolder_only_several": "Только если файлов получается несколько",
+ "presets.subfolder_only_several_hint": "Если из файла получается один файл, он сохраняется рядом с оригиналом; вложенная папка создаётся, только когда файлов несколько (например, PDF разбит на страницы).",
"presets.custom_folder": "Папка",
"presets.browse": "Обзор…",
"presets.pattern": "Имя файла",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index fdc7be5c..d3ea8fa0 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -591,6 +591,8 @@
"presets.location.Subfolder": "子文件夹",
"presets.location.CustomFolder": "指定文件夹",
"presets.subfolder": "子文件夹名称",
+ "presets.subfolder_only_several": "仅在生成多个文件时",
+ "presets.subfolder_only_several_hint": "只生成一个文件时保存在原文件旁边;生成多个文件时(例如 PDF 拆分成页面)才新建子文件夹。",
"presets.custom_folder": "文件夹",
"presets.browse": "浏览…",
"presets.pattern": "文件名",
diff --git a/src/Filee.App/ViewModels/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
index 6ddb748a..73b0cb24 100644
--- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs
+++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
@@ -158,6 +158,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject
_pdfA = _edit.Document.PdfA;
_leaveOutPictures = _edit.Document.LeaveOutPictures;
_subfolderName = _edit.Output.SubfolderName;
+ _subfolderOnlyForSeveralFiles = _edit.Output.SubfolderOnlyForSeveralFiles;
_customFolder = _edit.Output.CustomFolder;
_pattern = _edit.Output.FileNamePattern;
_keepDates = _edit.Output.KeepDates;
@@ -393,6 +394,8 @@ public sealed partial class PresetEditorViewModel : ObservableObject
/// <summary>Markdown: the text only, no picture folder next to it (DocumentOptions.LeaveOutPictures).</summary>
[ObservableProperty] private bool _leaveOutPictures;
[ObservableProperty] private string _subfolderName;
+ /// <summary>The subfolder only for a file that becomes several (OutputRule.SubfolderOnlyForSeveralFiles).</summary>
+ [ObservableProperty] private bool _subfolderOnlyForSeveralFiles;
[ObservableProperty] private string _customFolder;
[ObservableProperty] private string _pattern;
[ObservableProperty] private bool _keepDates;
@@ -629,6 +632,8 @@ public sealed partial class PresetEditorViewModel : ObservableObject
var output = _original.Output;
output.Location = Location.Value;
output.SubfolderName = string.IsNullOrWhiteSpace(SubfolderName) ? "converted" : SubfolderName.Trim();
+ // Only with a subfolder, where it is offered: a box ticked there must not stay on hidden behind another location.
+ output.SubfolderOnlyForSeveralFiles = ShowSubfolder && SubfolderOnlyForSeveralFiles;
output.CustomFolder = CustomFolder.Trim();
output.FileNamePattern = string.IsNullOrWhiteSpace(Pattern) ? "{name}" : Pattern.Trim();
output.Conflict = Conflict.Value;
diff --git a/src/Filee.App/Views/PresetEditorView.axaml b/src/Filee.App/Views/PresetEditorView.axaml
index 4468623d..8c81df87 100644
--- a/src/Filee.App/Views/PresetEditorView.axaml
+++ b/src/Filee.App/Views/PresetEditorView.axaml
@@ -378,6 +378,8 @@
<StackPanel IsVisible="{Binding ShowSubfolder}">
<TextBlock Classes="label" Text="{DynamicResource presets.subfolder}" />
<TextBox Text="{Binding SubfolderName}" PlaceholderText="converted" />
+ <CheckBox Content="{DynamicResource presets.subfolder_only_several}" IsChecked="{Binding SubfolderOnlyForSeveralFiles}"
+ ToolTip.Tip="{DynamicResource presets.subfolder_only_several_hint}" Margin="0,6,0,0" />
</StackPanel>
<StackPanel IsVisible="{Binding ShowCustomFolder}">
<TextBlock Classes="label" Text="{DynamicResource presets.custom_folder}" />
diff --git a/src/Filee.Core/Conversion/JobQueue.cs b/src/Filee.Core/Conversion/JobQueue.cs
index 228e0703..e45210d8 100644
--- a/src/Filee.Core/Conversion/JobQueue.cs
+++ b/src/Filee.Core/Conversion/JobQueue.cs
@@ -245,7 +245,7 @@ public sealed class JobQueue : IAsyncDisposable
return;
var first = job.Files[0];
- var allocator = CreateFinalAllocator(job, first.SourcePath, 1);
+ var allocator = CreateFinalAllocator(job, first.SourcePath, 1, oneFile: true);
var output = allocator.Allocate("pdf");
if (output is null)
{
@@ -289,7 +289,7 @@ public sealed class JobQueue : IAsyncDisposable
return;
var first = job.Files[0];
- var output = CreateFinalAllocator(job, first.SourcePath, 1).Allocate("tiff");
+ var output = CreateFinalAllocator(job, first.SourcePath, 1, oneFile: true).Allocate("tiff");
if (output is null)
{
foreach (var f in job.Files) f.State = FileState.Skipped;
@@ -335,7 +335,7 @@ public sealed class JobQueue : IAsyncDisposable
return;
}
- var output = CreateFinalAllocator(job, inputs[0].SourcePath, 1).Allocate(format.PrimaryExtension);
+ var output = CreateFinalAllocator(job, inputs[0].SourcePath, 1, oneFile: true).Allocate(format.PrimaryExtension);
if (output is null)
{
foreach (var f in inputs)
@@ -548,6 +548,8 @@ public sealed class JobQueue : IAsyncDisposable
if (zipResult && inputs.Count > 0)
inputs = PackZip(job, file, index, inputs, ct);
+ else if (finalOutput && inputs.Count == 1)
+ inputs = [NextToSource(job, file, index, inputs[0])];
if (finalOutput)
{
@@ -610,7 +612,7 @@ public sealed class JobQueue : IAsyncDisposable
/// </summary>
private IReadOnlyList<string> PackZip(ConversionJob job, FileResult file, int index, IReadOnlyList<string> files, CancellationToken ct)
{
- if (CreateFinalAllocator(job, file.SourcePath, index).Allocate("zip") is not { } zipPath)
+ if (CreateFinalAllocator(job, file.SourcePath, index, oneFile: true).Allocate("zip") is not { } zipPath)
return [];
try
{
@@ -661,8 +663,75 @@ public sealed class JobQueue : IAsyncDisposable
return new SemaphoreSlim(max, max);
});
- private FinalAllocator CreateFinalAllocator(ConversionJob job, string sourcePath, int index) =>
- new(this, job.Preset.Output, new OutputPathResolver.Tokens(sourcePath, job.PresetDisplayName, index, job.CreatedAt));
+ /// <param name="oneFile">The output is one file whatever happens (a merged PDF, a multi-page TIFF, an archive).</param>
+ private FinalAllocator CreateFinalAllocator(ConversionJob job, string sourcePath, int index, bool oneFile = false) =>
+ new(this, oneFile ? ForOneFile(job.Preset.Output) : job.Preset.Output,
+ new OutputPathResolver.Tokens(sourcePath, job.PresetDisplayName, index, job.CreatedAt));
+
+ /// <summary>
+ /// The rule for a single output file: with <see cref="OutputRule.SubfolderOnlyForSeveralFiles"/> it is saved next to
+ /// the source instead of in the subfolder.
+ /// </summary>
+ private static OutputRule ForOneFile(OutputRule rule)
+ {
+ if (!rule.SubfolderOnlyForSeveralFiles || rule.Location != OutputLocation.Subfolder)
+ return rule;
+ var single = rule.Clone();
+ single.Location = OutputLocation.SameFolder;
+ return single;
+ }
+
+ /// <summary>
+ /// With <see cref="OutputRule.SubfolderOnlyForSeveralFiles"/>: moves the one file a source became out of the
+ /// subfolder to the folder next to the source, keeping its name (the conflict policy applies there), and removes
+ /// the subfolder if that left it empty. A file that can't be moved (the policy skips an existing file, or the file
+ /// is in use) stays in the subfolder.
+ /// </summary>
+ private string NextToSource(ConversionJob job, FileResult file, int index, string output)
+ {
+ var rule = ForOneFile(job.Preset.Output);
+ if (ReferenceEquals(rule, job.Preset.Output) || !File.Exists(output))
+ return output;
+ // The name was already made from the pattern and renames: it is kept as it is.
+ rule.FileNamePattern = Path.GetFileNameWithoutExtension(output);
+ rule.Renames = [];
+
+ lock (_reservedOutputs)
+ {
+ var tokens = new OutputPathResolver.Tokens(file.SourcePath, job.PresetDisplayName, index, job.CreatedAt);
+ var target = OutputPathResolver.Resolve(rule, tokens, Path.GetExtension(output),
+ p => !PathsEqual(p, output) && (File.Exists(p) || Directory.Exists(p) || _reservedOutputs.Contains(p)));
+ if (target is null || PathsEqual(target, output))
+ return output;
+ try
+ {
+ File.Move(output, target, overwrite: true);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ _log.LogWarning(ex, "Could not move {Output} next to its source", output);
+ return output;
+ }
+ _reservedOutputs.Remove(output);
+ _reservedOutputs.Add(target);
+
+ // Another file of this or a running job may still be written into the same subfolder.
+ var subfolder = Path.GetDirectoryName(output)!;
+ if (!_reservedOutputs.Any(p => PathsEqual(Path.GetDirectoryName(p) ?? "", subfolder)))
+ {
+ try
+ {
+ if (!Directory.EnumerateFileSystemEntries(subfolder).Any())
+ Directory.Delete(subfolder);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { }
+ }
+ return target;
+ }
+
+ static bool PathsEqual(string a, string b) =>
+ string.Equals(Path.GetFullPath(a), Path.GetFullPath(b), StringComparison.OrdinalIgnoreCase);
+ }
private void Notify(ConversionJob job)
{
diff --git a/src/Filee.Core/Presets/OutputRule.cs b/src/Filee.Core/Presets/OutputRule.cs
index f4c5e491..157df1ed 100644
--- a/src/Filee.Core/Presets/OutputRule.cs
+++ b/src/Filee.Core/Presets/OutputRule.cs
@@ -36,6 +36,13 @@ public sealed class OutputRule
public string SubfolderName { get; set; } = "converted";
+ /// <summary>
+ /// With <see cref="OutputLocation.Subfolder"/>: only a source that becomes several files (a PDF split into pages)
+ /// gets the subfolder; one that becomes a single file is saved next to the source, so a one-page PDF doesn't end up
+ /// alone in a folder of its own.
+ /// </summary>
+ public bool SubfolderOnlyForSeveralFiles { get; set; }
+
public string CustomFolder { get; set; } = "";
/// <summary>
diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.cs
index 0e147dd2..4f488dcb 100644
--- a/src/Filee.Core/Settings/AppSettings.cs
+++ b/src/Filee.Core/Settings/AppSettings.cs
@@ -259,6 +259,7 @@ public sealed class AppSettings
{
copy.Output.Location = DefaultOutput.Location == OutputLocation.Default ? OutputLocation.SameFolder : DefaultOutput.Location;
copy.Output.SubfolderName = DefaultOutput.SubfolderName;
+ copy.Output.SubfolderOnlyForSeveralFiles = false;
copy.Output.CustomFolder = DefaultOutput.CustomFolder;
}
if (dates)
diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.cs
index 9a4ee3d6..ae6a4253 100644
--- a/tests/Filee.App.Tests/RenderTests.cs
+++ b/tests/Filee.App.Tests/RenderTests.cs
@@ -1067,6 +1067,35 @@ public class RenderTests
Assert.Equal("jpg", preset.TargetFormat);
}
+ [AvaloniaFact]
+ public void Preset_editor_offers_the_subfolder_only_for_several_files_with_a_subfolder()
+ {
+ TestServices.EnsureInitialized("en");
+ var loc = AppHost.Get<Filee.Core.Localization.ILocalizer>();
+ // PDF → page images saves into a folder per document.
+ var preset = Filee.Core.Presets.BuiltInData.CreatePresets().Single(p => p.Id == "pdf-split");
+ var vm = new PresetEditorViewModel(preset, loc);
+ Assert.True(vm.ShowSubfolder);
+ Assert.False(vm.SubfolderOnlyForSeveralFiles);
+
+ vm.SubfolderOnlyForSeveralFiles = true;
+ var window = new PresetEditorWindow { DataContext = vm, Height = 1400 };
+ window.Show();
+ Pump();
+ Save(window, "preset-subfolder-en.png");
+ window.Close();
+ Assert.True(vm.Apply());
+ Assert.True(preset.Output.SubfolderOnlyForSeveralFiles);
+
+ // Hidden with another location, and not kept on behind it.
+ vm = new PresetEditorViewModel(preset, loc);
+ Assert.True(vm.SubfolderOnlyForSeveralFiles);
+ vm.Location = vm.Locations.Single(l => l.Value == Filee.Core.Presets.OutputLocation.SameFolder);
+ Assert.False(vm.ShowSubfolder);
+ Assert.True(vm.Apply());
+ Assert.False(preset.Output.SubfolderOnlyForSeveralFiles);
+ }
+
[AvaloniaFact]
public void Preset_editor_keeps_rotation_visible_for_pdf_and_drops_it_for_targets_that_cannot_turn()
{
diff --git a/tests/Filee.Core.Tests/DefaultOutputTests.cs b/tests/Filee.Core.Tests/DefaultOutputTests.cs
index b0f9268e..2b1b17af 100644
--- a/tests/Filee.Core.Tests/DefaultOutputTests.cs
+++ b/tests/Filee.Core.Tests/DefaultOutputTests.cs
@@ -28,6 +28,19 @@ public class DefaultOutputTests
Assert.Equal(OutputLocation.Default, preset.Output.Location); // the saved preset is not changed
}
+ [Fact]
+ public void A_preset_on_default_uses_the_default_subfolder_for_every_file()
+ {
+ var settings = new AppSettings { DefaultOutput = { Location = OutputLocation.Subfolder, SubfolderName = "converted" } };
+ // Left over from when the preset had its own subfolder: the default location doesn't offer it.
+ var preset = new Preset { TargetFormat = "png", Output = { SubfolderOnlyForSeveralFiles = true } };
+
+ var used = settings.WithDefaultOutput(preset);
+
+ Assert.Equal(OutputLocation.Subfolder, used.Output.Location);
+ Assert.False(used.Output.SubfolderOnlyForSeveralFiles);
+ }
+
[Fact]
public void Presets_on_default_save_to_the_folder_from_settings()
{
diff --git a/tests/Filee.Core.Tests/JobQueueTests.cs b/tests/Filee.Core.Tests/JobQueueTests.cs
index 546258df..6744d417 100644
--- a/tests/Filee.Core.Tests/JobQueueTests.cs
+++ b/tests/Filee.Core.Tests/JobQueueTests.cs
@@ -537,6 +537,108 @@ public class JobQueueTests
Assert.Equal(2, job.Outputs.Distinct().Count());
}
+ [Fact]
+ public async Task Subfolder_only_for_several_files_keeps_a_single_output_next_to_its_source()
+ {
+ using var dir = new TempDir();
+ var photo = dir.File("photo.jpg");
+ var report = dir.File("report.pdf");
+ var catalog = new ConverterCatalog([
+ new FakeConverter("magick", new ConversionEdge("jpg", "png")),
+ new FakeConverter("pdfium", new ConversionEdge("pdf", "png")) { OutputsPerInput = 3 },
+ ]);
+ await using var queue = new JobQueue(catalog);
+ var preset = new Preset
+ {
+ TargetFormat = "png",
+ Output = { Location = OutputLocation.Subfolder, SubfolderName = "{name}", SubfolderOnlyForSeveralFiles = true },
+ };
+
+ var job = await Run(queue, [photo, report], preset);
+
+ Assert.Equal(JobState.Completed, job.State);
+ Assert.Equal([Path.Combine(dir.Path, "photo.png")], job.Files[0].Outputs);
+ Assert.False(Directory.Exists(Path.Combine(dir.Path, "photo")));
+ Assert.Equal(3, job.Files[1].Outputs.Count);
+ Assert.All(job.Files[1].Outputs, o => Assert.Equal(Path.Combine(dir.Path, "report"), Path.GetDirectoryName(o)));
+ Assert.All(job.Outputs, o => Assert.True(File.Exists(o)));
+ }
+
+ [Fact]
+ public async Task Subfolder_only_for_several_files_leaves_a_shared_subfolder_to_the_files_still_in_it()
+ {
+ using var dir = new TempDir();
+ var catalog = new ConverterCatalog([
+ new FakeConverter("magick", new ConversionEdge("jpg", "png")),
+ new FakeConverter("pdfium", new ConversionEdge("pdf", "png")) { OutputsPerInput = 2 },
+ ]);
+ await using var queue = new JobQueue(catalog);
+ var preset = new Preset
+ {
+ TargetFormat = "png",
+ Output = { Location = OutputLocation.Subfolder, SubfolderName = "converted", SubfolderOnlyForSeveralFiles = true },
+ };
+
+ var job = await Run(queue, [dir.File("a.jpg"), dir.File("b.pdf"), dir.File("c.jpg")], preset);
+
+ Assert.Equal(JobState.Completed, job.State);
+ Assert.True(File.Exists(Path.Combine(dir.Path, "a.png")));
+ Assert.True(File.Exists(Path.Combine(dir.Path, "c.png")));
+ Assert.True(File.Exists(Path.Combine(dir.Path, "converted", "b_p1.png")));
+ Assert.True(File.Exists(Path.Combine(dir.Path, "converted", "b_p2.png")));
+ }
+
+ [Fact]
+ public async Task Subfolder_only_for_several_files_applies_the_conflict_policy_next_to_the_source()
+ {
+ using var dir = new TempDir();
+ var photo = dir.File("photo.jpg");
+ dir.File("photo.png", "older");
+ await using var queue = new JobQueue(new ConverterCatalog([new FakeConverter("magick", new ConversionEdge("jpg", "png"))]));
+ var preset = new Preset
+ {
+ TargetFormat = "png",
+ Output = { Location = OutputLocation.Subfolder, SubfolderName = "{name}", SubfolderOnlyForSeveralFiles = true },
+ };
+
+ var job = await Run(queue, [photo], preset);
+
+ Assert.Equal([Path.Combine(dir.Path, "photo (2).png")], job.Outputs);
+ Assert.Equal("older", File.ReadAllText(Path.Combine(dir.Path, "photo.png")));
+ Assert.False(Directory.Exists(Path.Combine(dir.Path, "photo")));
+ }
+
+ [Fact]
+ public async Task Subfolder_only_for_several_files_saves_a_merged_pdf_next_to_the_first_file()
+ {
+ using var dir = new TempDir();
+ var catalog = new ConverterCatalog([new FakeConverter("magick", new ConversionEdge("jpg", "pdf"))]);
+ await using var queue = new JobQueue(catalog, pdfMerger: new FakeMerger());
+ var preset = new Preset
+ {
+ TargetFormat = "pdf",
+ Pdf = { MergeIntoSingle = true },
+ Output = { Location = OutputLocation.Subfolder, SubfolderName = "{name}", SubfolderOnlyForSeveralFiles = true },
+ };
+
+ var job = await Run(queue, [dir.File("a.jpg"), dir.File("b.jpg")], preset);
+
+ Assert.Equal([Path.Combine(dir.Path, "a.pdf")], job.Outputs);
+ Assert.False(Directory.Exists(Path.Combine(dir.Path, "a")));
+ }
+
+ [Fact]
+ public async Task Without_subfolder_only_for_several_files_a_single_output_stays_in_the_subfolder()
+ {
+ using var dir = new TempDir();
+ await using var queue = new JobQueue(new ConverterCatalog([new FakeConverter("magick", new ConversionEdge("jpg", "png"))]));
+ var preset = new Preset { TargetFormat = "png", Output = { Location = OutputLocation.Subfolder, SubfolderName = "{name}" } };
+
+ var job = await Run(queue, [dir.File("photo.jpg")], preset);
+
+ Assert.Equal([Path.Combine(dir.Path, "photo", "photo.png")], job.Outputs);
+ }
+
[Fact]
public async Task Enqueue_runs_in_background_and_raises_finished()
{