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.

Watch folders: recent results on the card, retries move originals

KnifeLemonfe738d82152c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7e03cbcf..8cc12942 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,8 +14,8 @@ find it, what it does and doesn't do.
lists them with the reason (click "2 failed" to open the list; names and reasons can be selected and copied).
**Retry** converts the files that failed again with the same settings and save location, even after the preset
was changed or deleted. Files that are no longer there are left out. The progress card that pops up after a
- conversion has the same **Retry** button. Conversions from watch folders are listed and retried the same way;
- a retried file stays in the watched folder, also when the folder moves originals to "originals".
+ conversion has the same **Retry** button. A retried file from a watch folder is handled like the folder handles
+ its files: when the folder moves originals to "originals", the original moves once it converts.
- **Watch folders: choose files and name them** (Settings → Watch folders → *More options*, all optional; empty
fields change nothing):
- *Files to convert*: patterns entered as tags. Typing `heic` adds `*.heic`, other text picks names that contain
@@ -32,6 +32,8 @@ find it, what it does and doesn't do.
- A **preview** on every watch folder shows a converted file as it will be saved (`IMG_0412.jpg →
converted\Photo_0412.pdf`, using a file already in the folder when there is one), what happens when the name is
taken and what happens to the original.
+ - **Recent results** on every watch folder: how many files it converted and which failed, with the reason, and
+ **Retry** right there. A file that converts on a retry or a later copy no longer counts as failed.
### Documentation
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index ece2e5f8..3d54c92d 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -538,6 +538,9 @@
"watch.recipe.suffix": "Add text at the end",
"watch.invalid_regex": "Not a valid regular expression: {0}",
"watch.preview": "Preview",
+ "watch.results": "Recent results",
+ "watch.results_ok": "{0} file(s) converted, none failed",
+ "watch.results_failed": "{0} file(s) converted · {1} failed",
"watch.sample_file": "photo.jpg",
"watch.preview_keep": "The original stays where it is",
"watch.preview_move": "The original moves to \"originals\"",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index f49021d8..9ddc1180 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -538,6 +538,9 @@
"watch.recipe.suffix": "뒤에 글자 붙이기",
"watch.invalid_regex": "올바른 정규식이 아니에요: {0}",
"watch.preview": "미리보기",
+ "watch.results": "최근 결과",
+ "watch.results_ok": "{0}개 변환, 실패 없음",
+ "watch.results_failed": "{0}개 변환 · {1}개 실패",
"watch.sample_file": "사진.jpg",
"watch.preview_keep": "원본은 그대로 둬요",
"watch.preview_move": "원본은 \"originals\" 폴더로 옮겨요",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index 07628995..0fd9a441 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -538,6 +538,9 @@
"watch.recipe.suffix": "在末尾加文字",
"watch.invalid_regex": "不是有效的正则表达式:{0}",
"watch.preview": "预览",
+ "watch.results": "最近结果",
+ "watch.results_ok": "已转换 {0} 个,没有失败",
+ "watch.results_failed": "已转换 {0} 个 · {1} 个失败",
"watch.sample_file": "照片.jpg",
"watch.preview_keep": "原文件保留在原处",
"watch.preview_move": "原文件移到 \"originals\" 文件夹",
diff --git a/src/Filee.App/Services/ConversionService.cs b/src/Filee.App/Services/ConversionService.cs
index 328715c1..0cb8c244 100644
--- a/src/Filee.App/Services/ConversionService.cs
+++ b/src/Filee.App/Services/ConversionService.cs
@@ -29,6 +29,9 @@ public sealed class ConversionService
private readonly System.Collections.Concurrent.ConcurrentDictionary<string, JobViewModel> _byId = new();
private readonly System.Collections.Concurrent.ConcurrentDictionary<string, TaskCompletionSource<ConversionJob>> _waiting = new();
+ /// <summary>Jobs that came from a watch folder: job id → rule id (for the history and for retrying).</summary>
+ private readonly System.Collections.Concurrent.ConcurrentDictionary<string, string> _watchJobs = new();
+
public ConversionService(JobQueue queue, UserDataStore store, ILocalizer loc, IPlatformServices platform)
{
_queue = queue;
@@ -71,30 +74,55 @@ public sealed class ConversionService
return vm;
}
+ /// <summary>
+ /// Converts a watch folder's files again (rule id, files, preset as the job ran it): WatchFolderService sets it, so
+ /// a retry also does what the folder does afterwards (moving originals).
+ /// </summary>
+ public Func<string, IReadOnlyList<string>, Preset, Task>? WatchRetry { get; set; }
+
/// <summary>
/// Converts files that failed again with the preset their job ran with (shown in the toast). Files that are no
- /// longer there are left out.
+ /// longer there are left out. Files of a watch folder go through <see cref="WatchRetry"/>.
/// </summary>
- /// <returns>The new job, or null when none of the files is left.</returns>
- public JobViewModel? Retry(IEnumerable<string> sources, Preset preset) =>
- Start(sources.Where(Exists).Distinct(StringComparer.Ordinal).ToList(), preset);
+ /// <returns>The new job, or null when none of the files is left or the watch folder converts them.</returns>
+ public JobViewModel? Retry(IEnumerable<string> sources, Preset preset, string? watchRuleId = null)
+ {
+ var files = sources.Where(Exists).Distinct(StringComparer.Ordinal).ToList();
+ if (files.Count == 0)
+ return null;
+ if (watchRuleId is not null && WatchRetry is { } watchRetry)
+ {
+ _ = watchRetry(watchRuleId, files, preset);
+ return null;
+ }
+ return Start(files, preset);
+ }
/// <summary>True when a source file (or folder) is still where it was.</summary>
public static bool Exists(string path) => File.Exists(path) || Directory.Exists(path);
private void RetryFailed(JobViewModel vm)
{
+ var watchRuleId = _watchJobs.GetValueOrDefault(vm.Job.Id);
+ var failed = vm.FailedSources.ToList();
Remove(vm);
- Retry(vm.FailedSources, vm.Job.Preset);
+ Retry(failed, vm.Job.Preset, watchRuleId);
}
/// <summary>
/// Converts like <see cref="Start"/> (shown in the toast and history) and completes when the job has finished.
/// Callable from any thread; used by watch folders.
/// </summary>
- public async Task<ConversionJob?> RunAsync(IReadOnlyList<string> files, Preset preset)
+ /// <param name="watchRuleId">The watch folder the files come from; recorded in the history.</param>
+ public async Task<ConversionJob?> RunAsync(IReadOnlyList<string> files, Preset preset, string? watchRuleId = null)
{
- var vm = await Dispatcher.UIThread.InvokeAsync(() => Start(files, preset));
+ var vm = await Dispatcher.UIThread.InvokeAsync(() =>
+ {
+ var started = Start(files, preset);
+ if (started is not null && watchRuleId is not null)
+ _watchJobs[started.Job.Id] = watchRuleId;
+ return started;
+ });
if (vm is null)
return null;
var finished = _waiting.GetOrAdd(vm.Job.Id, _ => new TaskCompletionSource<ConversionJob>(TaskCreationOptions.RunContinuationsAsynchronously));
@@ -122,7 +150,9 @@ public sealed class ConversionService
private void OnJobFinished(object? sender, ConversionJob job)
{
- _store.AddHistory(HistoryEntry.From(job));
+ var entry = HistoryEntry.From(job);
+ entry.WatchRuleId = _watchJobs.GetValueOrDefault(job.Id);
+ _store.AddHistory(entry);
if (_waiting.TryGetValue(job.Id, out var waiting))
waiting.TrySetResult(job);
Dispatcher.UIThread.Post(() =>
@@ -154,5 +184,6 @@ public sealed class ConversionService
Jobs.Remove(vm);
ToastJobs.Remove(vm);
_byId.TryRemove(vm.Job.Id, out _);
+ _watchJobs.TryRemove(vm.Job.Id, out _);
}
}
diff --git a/src/Filee.App/Services/WatchFolderService.cs b/src/Filee.App/Services/WatchFolderService.cs
index e3b86588..378927f5 100644
--- a/src/Filee.App/Services/WatchFolderService.cs
+++ b/src/Filee.App/Services/WatchFolderService.cs
@@ -24,6 +24,7 @@ public sealed class WatchFolderService(UserDataStore store, ConversionService co
public void Start()
{
+ conversions.WatchRetry = RetryAsync;
_ = ApplyAsync();
store.SettingsChanged += (_, _) =>
{
@@ -80,7 +81,20 @@ public sealed class WatchFolderService(UserDataStore store, ConversionService co
log.LogWarning("Watch folder {Folder}: preset {Preset} no longer exists", rule.Folder, rule.PresetId);
return null;
}
- return await conversions.RunAsync(files, rule.Apply(preset));
+ return await conversions.RunAsync(files, rule.Apply(preset), rule.Id);
+ }
+
+ /// <summary>
+ /// Converts files of a watch folder again (a retry from the toast or the history) with the preset as it ran, then
+ /// moves the originals that converted when the folder does that.
+ /// </summary>
+ internal async Task RetryAsync(string ruleId, IReadOnlyList<string> files, Core.Presets.Preset preset)
+ {
+ var job = await conversions.RunAsync(files, preset, ruleId);
+ if (job is null || store.Settings.WatchFolders.FirstOrDefault(r => r.Id == ruleId) is not { Originals: AfterConversion.MoveToOriginals } rule)
+ return;
+ foreach (var file in job.Files.Where(f => f.State == Core.Conversion.FileState.Done))
+ FolderWatcher.MoveToOriginals(rule, file.SourcePath, log);
}
/// <summary>Everything that needs a new watcher when it changes.</summary>
diff --git a/src/Filee.App/ViewModels/Pages/HomePageViewModel.cs b/src/Filee.App/ViewModels/Pages/HomePageViewModel.cs
index e1308ffc..274e7c6d 100644
--- a/src/Filee.App/ViewModels/Pages/HomePageViewModel.cs
+++ b/src/Filee.App/ViewModels/Pages/HomePageViewModel.cs
@@ -63,7 +63,7 @@ public sealed partial class HistoryItemViewModel : ObservableObject
private void Retry()
{
if (_conversions is not null && _entry.Preset is not null)
- _conversions.Retry(_entry.Failures.Select(f => f.Source), _entry.Preset);
+ _conversions.Retry(_entry.Failures.Select(f => f.Source), _entry.Preset, _entry.WatchRuleId);
}
[RelayCommand]
diff --git a/src/Filee.App/ViewModels/Pages/WatchFoldersPageViewModel.cs b/src/Filee.App/ViewModels/Pages/WatchFoldersPageViewModel.cs
index 0cf71957..7980803b 100644
--- a/src/Filee.App/ViewModels/Pages/WatchFoldersPageViewModel.cs
+++ b/src/Filee.App/ViewModels/Pages/WatchFoldersPageViewModel.cs
@@ -2,11 +2,13 @@
// saved at once; the service applies it after a short pause.
using System.Collections.ObjectModel;
+using Avalonia.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Filee.App.Controls;
using Filee.App.Services;
using Filee.Core.Formats;
+using Filee.Core.History;
using Filee.Core.Localization;
using Filee.Core.Presets;
using Filee.Core.Settings;
@@ -19,12 +21,14 @@ public sealed partial class WatchFoldersPageViewModel : ObservableObject, IDispo
private readonly UserDataStore _store;
private readonly WatchFolderService _service;
private readonly ILocalizer _loc;
+ private readonly ConversionService? _conversions;
- public WatchFoldersPageViewModel(UserDataStore store, WatchFolderService service, ILocalizer loc)
+ public WatchFoldersPageViewModel(UserDataStore store, WatchFolderService service, ILocalizer loc, ConversionService? conversions = null)
{
_store = store;
_service = service;
_loc = loc;
+ _conversions = conversions;
Presets = store.Presets.Select(p => new Choice<string>(p.Id, loc.DisplayName(p), FormatLabels.NameOf(loc, p.TargetFormat))).ToList();
OriginalsChoices =
[
@@ -34,6 +38,7 @@ public sealed partial class WatchFoldersPageViewModel : ObservableObject, IDispo
foreach (var rule in store.Settings.WatchFolders)
Rules.Add(new WatchRuleViewModel(rule, this));
service.StatusChanged += OnStatusChanged;
+ store.HistoryChanged += OnHistoryChanged;
}
public ObservableCollection<WatchRuleViewModel> Rules { get; } = [];
@@ -193,7 +198,30 @@ public sealed partial class WatchFoldersPageViewModel : ObservableObject, IDispo
rule.RefreshStatus();
}
- public void Dispose() => _service.StatusChanged -= OnStatusChanged;
+ /// <summary>A conversion finished (a watch folder's, perhaps): the cards' recent results follow.</summary>
+ private void OnHistoryChanged(object? sender, EventArgs e) => Dispatcher.UIThread.Post(() =>
+ {
+ foreach (var rule in Rules)
+ rule.RefreshResults();
+ });
+
+ /// <summary>What the rule's folder converted lately, from the history.</summary>
+ internal WatchResults ResultsOf(WatchRule rule) => WatchResults.Of(_store.History, rule.Id);
+
+ /// <summary>Converts the folder's failed files again, each with the preset its job ran with.</summary>
+ internal void RetryFailures(WatchRule rule, IEnumerable<WatchFailure> failures)
+ {
+ if (_conversions is null)
+ return;
+ foreach (var group in failures.Where(f => f.Preset is not null).GroupBy(f => f.Preset!))
+ _conversions.Retry(group.Select(f => f.Failure.Source), group.Key, rule.Id);
+ }
+
+ public void Dispose()
+ {
+ _service.StatusChanged -= OnStatusChanged;
+ _store.HistoryChanged -= OnHistoryChanged;
+ }
}
/// <summary>One watch folder on the page; edits go straight into the settings' <see cref="WatchRule"/>.</summary>
@@ -216,6 +244,7 @@ public sealed partial class WatchRuleViewModel : ObservableObject
_showOptions = rule.Include.Count > 0 || rule.FileNamePattern.Length > 0 || rule.Renames.Count > 0;
RefreshIncludeTags();
RefreshPreview();
+ RefreshResults();
}
public WatchRule Rule { get; }
@@ -261,6 +290,47 @@ public sealed partial class WatchRuleViewModel : ObservableObject
public bool HasPreview => PreviewExample is not null;
+ // Recent results of the folder, from the history.
+ private WatchResults _results = new(0, []);
+
+ /// <summary>"12 converted · 2 failed", or null before the folder converted anything.</summary>
+ [ObservableProperty] private string? _resultsSummary;
+
+ /// <summary>The files whose last conversion failed, and why.</summary>
+ [ObservableProperty] private IReadOnlyList<FailureItem> _resultFailures = [];
+
+ [ObservableProperty] private bool _showResultFailures;
+
+ public bool HasResults => ResultsSummary is not null;
+ public bool HasResultFailures => ResultFailures.Count > 0;
+
+ /// <summary>"2 failed": the button that shows the list.</summary>
+ public string ResultFailuresLabel => _page.Format("home.failed_files", ResultFailures.Count);
+
+ /// <summary>A failed file is still there and its preset is known.</summary>
+ public bool CanRetryResults => _results.Failures.Any(f => f.Preset is not null && ConversionService.Exists(f.Failure.Source));
+
+ [RelayCommand]
+ private void ToggleResultFailures() => ShowResultFailures = !ShowResultFailures;
+
+ [RelayCommand]
+ private void RetryResults() => _page.RetryFailures(Rule, _results.Failures);
+
+ internal void RefreshResults()
+ {
+ _results = _page.ResultsOf(Rule);
+ ResultsSummary = _results.IsEmpty ? null
+ : _results.Failures.Count == 0 ? _page.Format("watch.results_ok", _results.Converted)
+ : _page.Format("watch.results_failed", _results.Converted, _results.Failures.Count);
+ ResultFailures = _results.Failures
+ .Select(f => new FailureItem(Path.GetFileName(f.Failure.Source), FailureText.Reason(_page.Localizer, f.Failure.ErrorKey, f.Failure.ErrorDetail)))
+ .ToList();
+ OnPropertyChanged(nameof(HasResults));
+ OnPropertyChanged(nameof(HasResultFailures));
+ OnPropertyChanged(nameof(ResultFailuresLabel));
+ OnPropertyChanged(nameof(CanRetryResults));
+ }
+
partial void OnEnabledChanged(bool value) => Change(r => r.Enabled = value);
partial void OnFolderChanged(string value) => Change(r => r.Folder = value.Trim());
partial void OnPresetChanged(Choice<string>? value) => Change(r => r.PresetId = value?.Value ?? "");
diff --git a/src/Filee.App/Views/Pages/WatchFoldersPage.axaml b/src/Filee.App/Views/Pages/WatchFoldersPage.axaml
index aa0c31fd..3ed77f68 100644
--- a/src/Filee.App/Views/Pages/WatchFoldersPage.axaml
+++ b/src/Filee.App/Views/Pages/WatchFoldersPage.axaml
@@ -2,6 +2,7 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:Filee.App.ViewModels.Pages"
xmlns:c="using:Filee.App.Controls"
+ xmlns:app="using:Filee.App.ViewModels"
x:Class="Filee.App.Views.Pages.WatchFoldersPage"
x:DataType="vm:WatchFoldersPageViewModel">
<UserControl.Styles>
@@ -119,6 +120,45 @@
<TextBlock Classes="caption" Text="{Binding PreviewDetails}" TextWrapping="Wrap" />
</StackPanel>
</Border>
+
+ <!-- What the folder converted lately; failed files with the reason, and converting them again -->
+ <Border BorderBrush="{DynamicResource SubtleBorderBrush}" BorderThickness="1" CornerRadius="8" Padding="12,10" IsVisible="{Binding HasResults}">
+ <StackPanel Spacing="6">
+ <DockPanel>
+ <Button DockPanel.Dock="Right" Command="{Binding RetryResultsCommand}" IsVisible="{Binding CanRetryResults}" Padding="10,5">
+ <StackPanel Orientation="Horizontal" Spacing="6">
+ <PathIcon Width="13" Height="13" Data="{StaticResource Icon.Refresh}" />
+ <TextBlock Text="{DynamicResource common.retry}" />
+ </StackPanel>
+ </Button>
+ <StackPanel VerticalAlignment="Center" Spacing="2">
+ <TextBlock Classes="label" Text="{DynamicResource watch.results}" />
+ <TextBlock Text="{Binding ResultsSummary}" TextWrapping="Wrap" />
+ </StackPanel>
+ </DockPanel>
+ <Button Classes="ghost" Command="{Binding ToggleResultFailuresCommand}" Padding="6,4" HorizontalAlignment="Left" IsVisible="{Binding HasResultFailures}">
+ <StackPanel Orientation="Horizontal" Spacing="6">
+ <PathIcon Classes="chevron" Classes.open="{Binding ShowResultFailures}" Width="12" Height="12" Data="{StaticResource Icon.ChevronRight}" />
+ <TextBlock Classes="caption danger" Text="{Binding ResultFailuresLabel}" />
+ </StackPanel>
+ </Button>
+ <ItemsControl ItemsSource="{Binding ResultFailures}" IsVisible="{Binding ShowResultFailures}" Margin="24,0,0,0">
+ <ItemsControl.ItemsPanel>
+ <ItemsPanelTemplate>
+ <StackPanel Spacing="4" />
+ </ItemsPanelTemplate>
+ </ItemsControl.ItemsPanel>
+ <ItemsControl.ItemTemplate>
+ <DataTemplate x:DataType="app:FailureItem">
+ <StackPanel>
+ <SelectableTextBlock Classes="caption" FontWeight="SemiBold" Text="{Binding Name}" TextWrapping="Wrap" />
+ <SelectableTextBlock Classes="caption" Text="{Binding Reason}" TextWrapping="Wrap" />
+ </StackPanel>
+ </DataTemplate>
+ </ItemsControl.ItemTemplate>
+ </ItemsControl>
+ </StackPanel>
+ </Border>
</StackPanel>
</Border>
</DataTemplate>
diff --git a/src/Filee.Core/History/HistoryEntry.cs b/src/Filee.Core/History/HistoryEntry.cs
index a05063c9..6718a9b8 100644
--- a/src/Filee.Core/History/HistoryEntry.cs
+++ b/src/Filee.Core/History/HistoryEntry.cs
@@ -16,6 +16,9 @@ public sealed class HistoryEntry
public List<string> Sources { get; set; } = [];
public List<string> Outputs { get; set; } = [];
+ /// <summary>The watch folder (<see cref="Watching.WatchRule.Id"/>) the job came from, or null.</summary>
+ public string? WatchRuleId { get; set; }
+
/// <summary>Files that failed, with the reason.</summary>
public List<HistoryFailure> Failures { get; set; } = [];
diff --git a/src/Filee.Core/History/WatchResults.cs b/src/Filee.Core/History/WatchResults.cs
new file mode 100644
index 00000000..7a9e1213
--- /dev/null
+++ b/src/Filee.Core/History/WatchResults.cs
@@ -0,0 +1,38 @@
+// What a watch folder converted lately, from the history: how many files went through and which failed (a file that
+// failed and then converted on a retry or a later copy counts as converted).
+
+using Filee.Core.Platform;
+using Filee.Core.Presets;
+
+namespace Filee.Core.History;
+
+/// <summary>A file of a watch folder whose last conversion failed, with the preset that job ran with.</summary>
+public sealed record WatchFailure(HistoryFailure Failure, Preset? Preset);
+
+/// <summary>Recent results of one watch folder.</summary>
+public sealed record WatchResults(int Converted, IReadOnlyList<WatchFailure> Failures)
+{
+ /// <summary>Results of the watch folder <paramref name="ruleId"/> in <paramref name="history"/> (newest first).</summary>
+ public static WatchResults Of(IEnumerable<HistoryEntry> history, string ruleId)
+ {
+ var seen = new HashSet<string>(FileSystemPaths.Comparer);
+ var converted = 0;
+ var failures = new List<WatchFailure>();
+ foreach (var entry in history.Where(e => e.WatchRuleId == ruleId))
+ {
+ foreach (var source in entry.Sources)
+ {
+ if (!seen.Add(source))
+ continue; // a newer job already decided this file
+ var failure = entry.Failures.FirstOrDefault(f => FileSystemPaths.Comparer.Equals(f.Source, source));
+ if (failure is null)
+ converted++;
+ else
+ failures.Add(new WatchFailure(failure, entry.Preset));
+ }
+ }
+ return new WatchResults(converted, failures);
+ }
+
+ public bool IsEmpty => Converted == 0 && Failures.Count == 0;
+}
diff --git a/src/Filee.Core/Watching/FolderWatcher.cs b/src/Filee.Core/Watching/FolderWatcher.cs
index 20de9630..86149b4c 100644
--- a/src/Filee.Core/Watching/FolderWatcher.cs
+++ b/src/Filee.Core/Watching/FolderWatcher.cs
@@ -159,7 +159,7 @@ public sealed class FolderWatcher : IAsyncDisposable
{
if (Rule.Originals == AfterConversion.MoveToOriginals)
foreach (var file in job.Files.Where(f => f.State == FileState.Done))
- MoveToOriginals(file.SourcePath);
+ MoveToOriginals(Rule, file.SourcePath, _log);
Converted?.Invoke(this, job);
}
return ready.Count;
@@ -216,11 +216,17 @@ public sealed class FolderWatcher : IAsyncDisposable
}
}
- private void MoveToOriginals(string source)
+ /// <summary>
+ /// Moves a converted source into the rule's originals folder (keeping its subfolder), numbering it when the name is
+ /// taken. A file outside the watched folder stays where it is.
+ /// </summary>
+ public static void MoveToOriginals(WatchRule rule, string source, ILogger log)
{
+ if (!IsInside(source, rule.Folder) || IsInside(source, rule.OriginalsFolder))
+ return;
try
{
- var target = Path.Combine(Rule.OriginalsFolder, Path.GetRelativePath(Rule.Folder, source));
+ var target = Path.Combine(rule.OriginalsFolder, Path.GetRelativePath(rule.Folder, source));
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
var name = Path.GetFileNameWithoutExtension(target);
var extension = Path.GetExtension(target);
@@ -230,7 +236,7 @@ public sealed class FolderWatcher : IAsyncDisposable
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
- _log.LogWarning(ex, "Could not move {File} to the originals folder", source);
+ log.LogWarning(ex, "Could not move {File} to the originals folder", source);
}
}
diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.cs
index 11253aca..1e0fa24b 100644
--- a/tests/Filee.App.Tests/RenderTests.cs
+++ b/tests/Filee.App.Tests/RenderTests.cs
@@ -77,6 +77,67 @@ public class RenderTests
}
}
+ [AvaloniaTheory]
+ [InlineData("en")]
+ [InlineData("ko")]
+ public void Watch_folder_card_shows_recent_results_and_retries_in_the_folder(string language)
+ {
+ TestServices.EnsureInitialized(language);
+ var store = AppHost.Get<Filee.Core.Settings.UserDataStore>();
+ var conversions = AppHost.Get<ConversionService>();
+ var folder = Directory.CreateTempSubdirectory("filee-watch-").FullName;
+ var broken = Path.Combine(folder, "scan-0412.heic");
+ File.WriteAllBytes(broken, [0]);
+ var rule = new Filee.Core.Watching.WatchRule { Folder = folder, PresetId = "to-pdf", Enabled = false };
+ store.Settings.WatchFolders.Add(rule);
+ store.AddHistory(new Filee.Core.History.HistoryEntry
+ {
+ WatchRuleId = rule.Id,
+ FinishedAt = DateTime.Now,
+ Sources = [Path.Combine(folder, "a.jpg"), Path.Combine(folder, "b.jpg"), broken],
+ Failures = [new() { Source = broken, ErrorKey = "error.conversion_failed", ErrorDetail = "HEIC decoder: unexpected end of file" }],
+ Preset = new Filee.Core.Presets.Preset { TargetFormat = "pdf" },
+ });
+ var retried = new List<(string Rule, IReadOnlyList<string> Files)>();
+ var previousRetry = conversions.WatchRetry;
+ conversions.WatchRetry = (id, files, _) =>
+ {
+ retried.Add((id, files));
+ return Task.CompletedTask;
+ };
+ try
+ {
+ var vm = new MainWindowViewModel(AppHost.Services, AppHost.Get<Filee.Core.Localization.ILocalizer>(), AppHost.Get<UpdateService>());
+ vm.Navigate("watch");
+ var window = new MainWindow { DataContext = vm, Width = 1080, Height = 1000 };
+ window.Show();
+ Pump();
+
+ var item = Assert.Single(((Filee.App.ViewModels.Pages.WatchFoldersPageViewModel)vm.CurrentPage).Rules);
+ Assert.True(item.HasResults);
+ Assert.Equal("scan-0412.heic", Assert.Single(item.ResultFailures).Name);
+ Assert.True(item.CanRetryResults);
+ item.ToggleResultFailuresCommand.Execute(null);
+ Pump();
+ Save(window, $"page-watch-results-{language}.png");
+
+ // Retrying goes through the watch folder (which then moves originals when it does that).
+ item.RetryResultsCommand.Execute(null);
+ var (ruleId, files) = Assert.Single(retried);
+ Assert.Equal(rule.Id, ruleId);
+ Assert.Equal([broken], files);
+ window.Close();
+ }
+ finally
+ {
+ conversions.WatchRetry = previousRetry;
+ store.Settings.WatchFolders.Remove(rule);
+ store.SaveSettings();
+ store.ClearHistory();
+ try { Directory.Delete(folder, true); } catch (IOException) { }
+ }
+ }
+
[AvaloniaTheory]
[InlineData("en")]
[InlineData("ko")]
diff --git a/tests/Filee.Core.Tests/WatchResultsTests.cs b/tests/Filee.Core.Tests/WatchResultsTests.cs
new file mode 100644
index 00000000..415aff3e
--- /dev/null
+++ b/tests/Filee.Core.Tests/WatchResultsTests.cs
@@ -0,0 +1,56 @@
+// A watch folder's recent results: converted and failed files from the history, and moving originals after a retry.
+
+using Filee.Core.History;
+using Filee.Core.Presets;
+using Filee.Core.Watching;
+using Microsoft.Extensions.Logging.Abstractions;
+
+namespace Filee.Core.Tests;
+
+public class WatchResultsTests
+{
+ [Fact]
+ public void A_file_that_converted_after_failing_no_longer_counts_as_failed()
+ {
+ var preset = new Preset { TargetFormat = "pdf" };
+ var history = new List<HistoryEntry> // newest first, as the history keeps them
+ {
+ new() { WatchRuleId = "inbox", Sources = ["a.jpg"] }, // the retry of a.jpg worked
+ new() { WatchRuleId = "other", Sources = ["x.jpg"], Failures = [new() { Source = "x.jpg" }] },
+ new()
+ {
+ WatchRuleId = "inbox",
+ Sources = ["a.jpg", "b.jpg", "c.jpg"],
+ Failures = [new() { Source = "a.jpg" }, new() { Source = "b.jpg", ErrorKey = "error.conversion_failed" }],
+ Preset = preset,
+ },
+ };
+
+ var results = WatchResults.Of(history, "inbox");
+
+ Assert.Equal(2, results.Converted); // a.jpg (retried) and c.jpg
+ var failure = Assert.Single(results.Failures);
+ Assert.Equal("b.jpg", failure.Failure.Source);
+ Assert.Same(preset, failure.Preset);
+ Assert.True(WatchResults.Of(history, "nothing").IsEmpty);
+ }
+
+ [Fact]
+ public void Originals_move_into_the_originals_folder_only_from_the_watched_folder()
+ {
+ using var dir = new TempDir();
+ var inbox = Path.Combine(dir.Path, "Inbox");
+ Directory.CreateDirectory(inbox);
+ var inside = Path.Combine(inbox, "scan.jpg");
+ File.WriteAllText(inside, "x");
+ var outside = dir.File("elsewhere.jpg");
+ var rule = new WatchRule { Folder = inbox, Originals = AfterConversion.MoveToOriginals };
+
+ FolderWatcher.MoveToOriginals(rule, inside, NullLogger.Instance);
+ FolderWatcher.MoveToOriginals(rule, outside, NullLogger.Instance);
+
+ Assert.False(File.Exists(inside));
+ Assert.True(File.Exists(Path.Combine(inbox, "originals", "scan.jpg")));
+ Assert.True(File.Exists(outside));
+ }
+}