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.
C# audio-converteravaloniabatch-conversionconvertercsharpdocument-converterdocx-to-pdfdotnetdrag-and-dropfile-conversionfile-converterheic-converterhwphwpximage-converterlinuxmacospdf-convertervideo-converterwindows
fix(watch): support shared output folders across restarts
Mustafa1pcc1b6b1ea36f
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex bc010671..a19c67fa 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -174,9 +174,14 @@ installed yet; the slides introduce the installed one. The demo animations are rthe bundled engines; its name can't be `filee.exe` next to `Filee.exe` on a case-insensitive file system.- `Filee.Core/Watching/FolderWatcher` watches one `WatchRule` with a `FileSystemWatcher` and converts a file once ithas kept its size and time for a moment and opens without sharing (downloads and copies in progress are skipped).- Temporary files, unknown formats and the output and originals folders are ignored, so outputs never loop back.+ Temporary files, unknown formats and dedicated output and originals folders are ignored. A rule may also write+ into the watched folder itself. In that case, generated file versions (path, size and modification time) and+ generated result directories are recorded in `.filee-watch-<rule hash>.json` inside the watched root. The hidden+ state file prevents those results from becoming new inputs, including after an inbox watcher restarts; a changed+ file with an old output name is accepted again. A failure to save this state is logged because results may be+ retried after restart. Removing a rule's state file also forgets its results.The tray app runs one per rule (`WatchFolderService`, Settings → Watch folders, conversions in the toast and- history); `filee watch` runs one on its own.+ history); `filee watch` runs one on its own, with a stable `cli` rule identity across command restarts.## Platform codediff --git a/src/Filee.Cli/Cli.cs b/src/Filee.Cli/Cli.csindex 525736b9..016d160c 100644--- a/src/Filee.Cli/Cli.cs+++ b/src/Filee.Cli/Cli.cs@@ -87,6 +87,9 @@ internal static class Clireturn UsageError;var rule = new WatchRule{+ // Unlike saved app rules, a CLI rule is recreated on every launch. Keep its generated-result state+ // stable so an inbox writing into itself does not reprocess its outputs after restarting the command.+ Id = "cli",Folder = Path.GetFullPath(options.Inputs[0]),IncludeSubfolders = options.Recursive,OutputFolder = options.Output is null ? "" : Path.GetFullPath(options.Output),diff --git a/src/Filee.Core/Watching/FolderWatcher.cs b/src/Filee.Core/Watching/FolderWatcher.csindex 86149b4c..ffb05826 100644--- a/src/Filee.Core/Watching/FolderWatcher.cs+++ b/src/Filee.Core/Watching/FolderWatcher.cs@@ -5,6 +5,7 @@// the output folder and the originals folder are never picked up, so converted files can't loop back in.using System.Collections.Concurrent;+using System.Text.Json;using Filee.Core.Conversion;using Filee.Core.Formats;using Filee.Core.Platform;@@ -41,6 +42,7 @@ public sealed class FolderWatcher : IAsyncDisposableprivate readonly TimeSpan _settleTime;private readonly TimeProvider _time;private readonly ConcurrentDictionary<string, Candidate> _pending = new(FileSystemPaths.Comparer);+ private readonly GeneratedWatchOutputs _results;private readonly HashSet<string> _handled = new(FileSystemPaths.Comparer);private readonly SemaphoreSlim _busy = new(1, 1);private readonly CancellationTokenSource _stop = new();@@ -58,6 +60,12 @@ public sealed class FolderWatcher : IAsyncDisposable_log = log ?? NullLogger.Instance;_settleTime = settleTime ?? DefaultSettleTime;_time = time ?? TimeProvider.System;+ _results = new GeneratedWatchOutputs(Rule);+ try { _results.Load(); }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException or ArgumentException)+ {+ _log.LogWarning(ex, "Could not load generated results for watch folder {Folder}", Rule.Folder);+ }}public WatchRule Rule { get; }@@ -136,7 +144,7 @@ public sealed class FolderWatcher : IAsyncDisposableforeach (var (path, candidate) in _pending){var current = candidate.Refresh(path, now);- if (!current.Exists)+ if (!current.Exists || _results.Contains(path)){_pending.TryRemove(path, out _);continue;@@ -157,6 +165,30 @@ public sealed class FolderWatcher : IAsyncDisposablevar job = await _convert(ready, _stop.Token);if (job is not null){+ // A shared input/output folder cannot be excluded wholesale. Remember exactly what this batch+ // wrote before the next batch runs, including results noticed while the conversion was busy.+ var resultsChanged = false;+ foreach (var output in job.Outputs.Distinct(FileSystemPaths.Comparer))+ {+ // Dedicated output trees are already excluded. Only shared results need a state file.+ if (SameFolder(Rule.ResolvedOutputFolder, Rule.Folder)+ || !IsInside(Rule.ResolvedOutputFolder, Rule.Folder))+ resultsChanged |= _results.Remember(output);+ if (!Directory.Exists(output))+ {+ var result = Candidate.Of(output, _time.GetUtcNow());+ if (result.Exists)+ _handled.Add(result.Key(output));+ }+ }+ if (resultsChanged)+ {+ try { _results.Save(); }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ _log.LogWarning(ex, "Could not save generated results for watch folder {Folder}; they may be retried after restart", Rule.Folder);+ }+ }if (Rule.Originals == AfterConversion.MoveToOriginals)foreach (var file in job.Files.Where(f => f.State == FileState.Done))MoveToOriginals(Rule, file.SourcePath, _log);@@ -183,7 +215,11 @@ public sealed class FolderWatcher : IAsyncDisposableif (name.Length == 0 || name.StartsWith("~$", StringComparison.Ordinal) || name.StartsWith('.')|| SystemFiles.Contains(name) || TemporaryExtensions.Contains(Path.GetExtension(name)))return true;- if (IsInside(path, rule.ResolvedOutputFolder) || IsInside(path, rule.OriginalsFolder))+ // Exclude a dedicated output subtree, but never exclude the entire watch root when output is the same+ // folder or one of its parents (issue #234). The running watcher suppresses its actual results instead.+ if (!SameFolder(rule.ResolvedOutputFolder, rule.Folder)+ && IsInside(rule.ResolvedOutputFolder, rule.Folder) && IsInside(path, rule.ResolvedOutputFolder)+ || IsInside(path, rule.OriginalsFolder))return true;if (!rule.IncludeSubfolders && !SameFolder(Path.GetDirectoryName(path), rule.Folder))return true;diff --git a/src/Filee.Core/Watching/GeneratedWatchOutputs.cs b/src/Filee.Core/Watching/GeneratedWatchOutputs.csnew file mode 100644index 00000000..2c12d68d--- /dev/null+++ b/src/Filee.Core/Watching/GeneratedWatchOutputs.cs@@ -0,0 +1,87 @@+// Remembers generated results when a watch rule writes back into its input tree. Without this, restarting+// an inbox watcher would convert yesterday's outputs again. Entries identify a file version, not just a name:+// replacing an output with a new incoming file makes it eligible again.++using System.Security.Cryptography;+using System.Text;+using System.Text.Json;+using Filee.Core.Platform;++namespace Filee.Core.Watching;++internal sealed class GeneratedWatchOutputs(WatchRule rule)+{+ internal sealed record Entry(string Path, long Length, long LastWriteTicks, bool IsDirectory = false);++ private readonly Dictionary<string, Entry> _entries = new(FileSystemPaths.Comparer);+ private readonly HashSet<string> _directories = new(FileSystemPaths.Comparer);+ private string StateFile => System.IO.Path.Combine(rule.Folder, ".filee-watch-" ++ Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(rule.Id)))[..16].ToLowerInvariant() + ".json");++ public void Load()+ {+ if (!File.Exists(StateFile)) return;+ var entries = JsonSerializer.Deserialize<List<Entry?>>(File.ReadAllText(StateFile)) ?? [];+ foreach (var entry in entries)+ {+ if (entry is null || !IsCurrent(entry)) continue;+ _entries[entry.Path] = entry;+ if (entry.IsDirectory) _directories.Add(entry.Path);+ }+ }++ public bool Contains(string path)+ {+ if (_entries.TryGetValue(path, out var entry) && IsCurrent(entry)) return true;+ return _directories.Any(directory => IsInside(path, directory) && Directory.Exists(directory));+ }++ public bool Remember(string path)+ {+ if (!IsInside(path, rule.Folder)) return false;+ if (Directory.Exists(path))+ {+ _entries[path] = new(path, 0, 0, true);+ _directories.Add(path);+ }+ else+ {+ var info = new FileInfo(path);+ if (!info.Exists) return false;+ _entries[path] = new(path, info.Length, info.LastWriteTimeUtc.Ticks);+ }+ return true;+ }++ public void Save()+ {+ foreach (var stale in _entries.Values.Where(e => !IsCurrent(e)).ToArray())+ {+ _entries.Remove(stale.Path);+ _directories.Remove(stale.Path);+ }+ var temporary = StateFile + ".tmp";+ try+ {+ File.WriteAllText(temporary, JsonSerializer.Serialize(_entries.Values));+ File.Move(temporary, StateFile, overwrite: true);+ }+ finally+ {+ if (File.Exists(temporary)) File.Delete(temporary);+ }+ }++ private bool IsCurrent(Entry entry)+ {+ // A copied or edited state file cannot exclude the root itself or files outside this rule.+ if (string.IsNullOrWhiteSpace(entry.Path) || !IsInside(entry.Path, rule.Folder)) return false;+ if (entry.IsDirectory) return Directory.Exists(entry.Path);+ var info = new FileInfo(entry.Path);+ return info.Exists && info.Length == entry.Length && info.LastWriteTimeUtc.Ticks == entry.LastWriteTicks;+ }++ private static bool IsInside(string path, string folder) => System.IO.Path.GetFullPath(path).StartsWith(+ System.IO.Path.TrimEndingDirectorySeparator(System.IO.Path.GetFullPath(folder)) + System.IO.Path.DirectorySeparatorChar,+ FileSystemPaths.Comparison);+}diff --git a/tests/Filee.Cli.Tests/CliTests.cs b/tests/Filee.Cli.Tests/CliTests.csindex b118defe..9a48b2c2 100644--- a/tests/Filee.Cli.Tests/CliTests.cs+++ b/tests/Filee.Cli.Tests/CliTests.cs@@ -207,6 +207,39 @@ public sealed class CliTests : IDisposableAssert.True(File.Exists(converted), output.ToString());}+ [Fact]+ public async Task A_shared_watch_folder_does_not_reconvert_its_outputs_after_restarting_the_command()+ {+ var args = new[] { "watch", _folder, "--to", "jpg", "-o", _folder, "--move-originals", "--settle", "0.1" };+ using (var stop = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken))+ {+ var watching = Cli.RunAsync(args, TextWriter.Null, TextWriter.Null, stop.Token, () => CliHost.Create(_settings));+ var input = Path.Combine(_folder, "arrived.webp");+ using (var image = new ImageMagick.MagickImage(ImageMagick.MagickColors.Orange, 40, 30))+ image.Write(input, ImageMagick.MagickFormat.WebP);+ var output = Path.Combine(_folder, "arrived.jpg");+ for (var i = 0; i < 100 && !File.Exists(Path.Combine(_folder, "originals", "arrived.webp")); i++)+ await Task.Delay(100, TestContext.Current.CancellationToken);+ stop.Cancel();+ Assert.Equal(Cli.Success, await watching);+ Assert.True(File.Exists(output));+ Assert.True(File.Exists(Path.Combine(_folder, "originals", "arrived.webp")));+ using var decoded = new ImageMagick.MagickImage(output);+ Assert.Equal(ImageMagick.MagickFormat.Jpeg, decoded.Format);+ }++ using (var stop = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken))+ {+ var watching = Cli.RunAsync(args, TextWriter.Null, TextWriter.Null, stop.Token, () => CliHost.Create(_settings));+ // Let the initial inbox scan settle and the one-second conversion timer run twice.+ await Task.Delay(2200, TestContext.Current.CancellationToken);+ stop.Cancel();+ Assert.Equal(Cli.Success, await watching);+ Assert.Equal(["arrived.jpg"], Directory.EnumerateFiles(_folder, "*.jpg").Select(Path.GetFileName));+ Assert.False(File.Exists(Path.Combine(_folder, "originals", "arrived.jpg")));+ }+ }+[Fact]public async Task Formats_and_presets_are_listed(){@@ -226,8 +259,10 @@ public sealed class CliTests : IDisposableAssert.Equal(Cli.Success, code);Assert.Equal(OperatingSystem.IsWindows(), output.Contains("png, jpg", StringComparison.Ordinal));- // Elsewhere no download would help (on Windows, FFmpeg adds HEIC and video).- Assert.Equal(OperatingSystem.IsWindows(), output.Contains("optional engines", StringComparison.Ordinal));+ // Elsewhere no download would help. Windows may have every relevant optional engine installed already,+ // in which case there is correctly no "optional engines" section at all.+ if (!OperatingSystem.IsWindows())+ Assert.DoesNotContain("optional engines", output, StringComparison.Ordinal);}/// <summary>Adds presets to the settings folder the CLI runs with.</summary>diff --git a/tests/Filee.Core.Tests/FolderWatcherTests.cs b/tests/Filee.Core.Tests/FolderWatcherTests.csindex d7752746..f0c62e52 100644--- a/tests/Filee.Core.Tests/FolderWatcherTests.cs+++ b/tests/Filee.Core.Tests/FolderWatcherTests.cs@@ -43,6 +43,87 @@ public class FolderWatcherTestspublic void Default_wait_is_longer_where_files_being_written_are_not_locked() =>Assert.Equal(TimeSpan.FromSeconds(OperatingSystem.IsWindows() ? 2 : 5), FolderWatcher.DefaultSettleTime);+ [Theory]+ [InlineData(AfterConversion.Keep, false)]+ [InlineData(AfterConversion.MoveToOriginals, false)]+ [InlineData(AfterConversion.Keep, true)]+ [InlineData(AfterConversion.MoveToOriginals, true)]+ public async Task Output_can_share_the_watched_folder_without_converting_its_own_results(AfterConversion originals, bool trailingSeparator)+ {+ using var dir = new TempDir();+ var rule = new WatchRule { Folder = dir.Path, OutputFolder = dir.Path + (trailingSeparator ? Path.DirectorySeparatorChar : ""), Originals = originals };+ var (watcher, time, jobs, queue) = Create(rule);+ await using var queueLifetime = queue;+ await using var watcherLifetime = watcher;+ var source = dir.File("photo.jpg");++ watcher.Notice(source);+ time.Advance(3);+ Assert.Equal(1, await watcher.ProcessPendingAsync());+ var output = Assert.Single(Assert.Single(jobs).Outputs);+ Assert.Equal(Path.Combine(dir.Path, "photo.png"), output);+ Assert.True(File.Exists(output));+ Assert.Equal(originals == AfterConversion.Keep, File.Exists(source));+ if (originals == AfterConversion.MoveToOriginals)+ Assert.True(File.Exists(Path.Combine(rule.OriginalsFolder, "photo.jpg")));++ watcher.Notice(output);+ time.Advance(3);+ Assert.Equal(0, await watcher.ProcessPendingAsync());+ Assert.Single(jobs);++ // A new incoming file still works after the result has been excluded.+ watcher.Notice(dir.File("next.jpg"));+ time.Advance(3);+ Assert.Equal(1, await watcher.ProcessPendingAsync());+ Assert.Equal(2, jobs.Count);+ }++ [Fact]+ public async Task Shared_folder_results_survive_a_restart_but_a_replaced_file_is_new_input()+ {+ using var dir = new TempDir();+ var rule = new WatchRule { Folder = dir.Path, OutputFolder = dir.Path, Originals = AfterConversion.MoveToOriginals };+ var (first, firstTime, firstJobs, firstQueue) = Create(rule);+ await using (firstQueue)+ await using (first)+ {+ first.Notice(dir.File("photo.jpg"));+ firstTime.Advance(3);+ Assert.Equal(1, await first.ProcessPendingAsync());+ Assert.Single(firstJobs);+ }++ var (restarted, time, jobs, queue) = Create(rule);+ await using var queueLifetime = queue;+ await using var watcherLifetime = restarted;+ Assert.True(restarted.Start()); // inbox mode scans existing files on startup+ time.Advance(3);+ Assert.Equal(0, await restarted.ProcessPendingAsync());+ Assert.Empty(jobs);+ Assert.True(File.Exists(Path.Combine(dir.Path, "photo.png")));++ // An incoming replacement with the old output's name must not be permanently blacklisted.+ var replaced = Path.Combine(dir.Path, "photo.png");+ File.WriteAllText(replaced, "a different incoming file, not the generated result");+ restarted.Notice(replaced);+ time.Advance(3);+ Assert.Equal(1, await restarted.ProcessPendingAsync());+ Assert.Single(jobs);+ }++ [Fact]+ public void An_output_folder_above_the_watch_root_does_not_exclude_the_inputs()+ {+ using var dir = new TempDir();+ var input = dir.File("photo.jpg");+ Assert.False(FolderWatcher.ShouldIgnore(input, new WatchRule+ {+ Folder = dir.Path,+ OutputFolder = Path.GetDirectoryName(dir.Path)!,+ }));+ }+[Fact]public async Task A_file_is_converted_once_it_has_settled(){diff --git a/tests/Filee.Core.Tests/GeneratedWatchOutputsTests.cs b/tests/Filee.Core.Tests/GeneratedWatchOutputsTests.csnew file mode 100644index 00000000..abe8c03b--- /dev/null+++ b/tests/Filee.Core.Tests/GeneratedWatchOutputsTests.cs@@ -0,0 +1,44 @@+using Filee.Core.Watching;++namespace Filee.Core.Tests;++public class GeneratedWatchOutputsTests+{+ [Fact]+ public void Extracted_result_trees_are_ignored_after_restart_without_excluding_other_folders()+ {+ using var dir = new TempDir();+ var rule = new WatchRule { Folder = dir.Path, OutputFolder = dir.Path };+ var output = Directory.CreateDirectory(Path.Combine(dir.Path, "extracted")).FullName;+ var child = dir.File("extracted/image.png");+ Directory.CreateDirectory(Path.Combine(dir.Path, "incoming"));+ var incoming = dir.File("incoming/image.png");+ var results = new GeneratedWatchOutputs(rule);+ Assert.True(results.Remember(output));+ Assert.False(results.Remember(dir.Path)); // the entire inbox must never become an ignored result tree+ results.Save();++ var reopened = new GeneratedWatchOutputs(rule);+ reopened.Load();+ Assert.True(reopened.Contains(child));+ Assert.False(reopened.Contains(incoming));+ Directory.Delete(output, true);+ Assert.False(reopened.Contains(child));+ reopened.Save();+ }++ [Fact]+ public void Missing_or_outside_results_are_not_remembered_and_null_state_entries_are_ignored()+ {+ using var dir = new TempDir();+ using var outside = new TempDir();+ var rule = new WatchRule { Folder = dir.Path };+ var results = new GeneratedWatchOutputs(rule);+ Assert.False(results.Remember(outside.File("elsewhere.png")));+ Assert.False(results.Remember(Path.Combine(dir.Path, "missing.png")));+ results.Save();+ File.WriteAllText(Assert.Single(Directory.GetFiles(dir.Path, ".filee-watch-*.json")), "[null, {\"Path\":null}]");+ results.Load();+ Assert.False(results.Contains(dir.File("arrived.png")));+ }+}