Files
Chronos/tests/Chronos.App.Tests/Archive/ReorganizeDialogTests.cs
T
Alby96 ad72501f11 feat(app): Reorganize existing sequences from the Archive manager, the Library and Settings
Owner review 2, R7 asks to rename and move sequences after import on the desktop too.
The desktop now uses the engine's Reorganize, the same plan and job as the web panel.

- One Reorganize… dialog replaces Rename… and Move… in the Archive manager and Move… in
  the Library. It has three templates: folders, file names and titles. Each one has a
  switch and is checked as it is typed. Folders and file names start on, filled from the
  archive's settings; titles start off as {title}. Renaming only titles is the Titles
  switch alone.
- The dry run stays in the dialog and follows the typing. Each sequence shows its folder,
  title and first file names before and after. Sequences carried along with a folder are
  marked, and photos that keep their names are listed with the reason. A summary counts
  the sequences that change, the files renamed and the names kept.
- Apply no longer changes the archive from the dialog. It queues the engine's move job
  with exactly the plan shown (its fingerprint), so the work can be paused, resumed after
  a restart and followed in Jobs. The job refuses the plan if the archive changed after
  the dry run.
- The Library's Reorganize… works on the selected sequences of one archive. The Archive
  screen reads the archive again when a move job ends.
- After Settings › Archive saves a new folder or file template to an archive that holds
  sequences, a toast offers Reorganize… for every sequence. Its templates are the ones
  changed since; a second change made while the toast is up adds to that toast instead of
  opening another.
- Strings in en and it. The keys of the old Rename and Move were removed and pruned from
  every translation, so the 36 other languages show the new keys as untranslated instead
  of keeping "Move".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 7bbf451f737a71b768dcd70a77b998daaef851f3)
2026-10-27 14:04:37 +01:00

263 lines
15 KiB
C#

using System.Globalization;
using System.IO;
using System.Security.Cryptography;
using System.Text.Json;
using Chronos.App.Archiving;
using Chronos.App.Tests.Import;
using Chronos.Core.Archiving;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Testing;
namespace Chronos.App.Tests.Archiving;
/// <summary>
/// Reorganize… (owner review 2, R7): each template with its switch, the dry run listed sequence by sequence, and Apply
/// queuing the job of exactly the plan on screen, which the job then applies.
/// </summary>
public sealed class ReorganizeDialogTests(TestContext context)
{
private static readonly DateTime Start = new(2026, 9, 28, 18, 0, 0);
[Test]
public void EachTemplateIsCheckedAsItsPartIsNamed()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
Assert.Null(ReorganizePlans.Validate(ReorganizeParts.Folders, "{year}/{date} {title}"));
Assert.NotNull(ReorganizePlans.Validate(ReorganizeParts.Folders, "{nope}"));
Assert.Null(ReorganizePlans.Validate(ReorganizeParts.Files, "{date}_{n:000}"));
Assert.Equal(Loc.L("Errors.Template.FileSeparator"), ReorganizePlans.Validate(ReorganizeParts.Files, "{year}/{n}"), "a file name has no folder");
Assert.Equal(Loc.L("Errors.Template.NotUnique"), ReorganizePlans.Validate(ReorganizeParts.Files, "{date}"), "file names tell the photos apart");
Assert.Null(ReorganizePlans.Validate(ReorganizeParts.Titles, "{title} · {camera}"));
Assert.Null(ReorganizePlans.Validate(ReorganizeParts.Titles, "{date}"), "every photo of a sequence shares its title");
Assert.NotNull(ReorganizePlans.Validate(ReorganizeParts.Titles, "{title"));
foreach (var part in new[] { ReorganizeParts.Folders, ReorganizeParts.Files, ReorganizeParts.Titles })
Assert.Equal(Loc.L("Errors.Template.Empty", string.Empty, 1), ReorganizePlans.Validate(part, " "), part.ToString());
}
[Test]
public void TheDryRunIsListedSequenceBySequence()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var moved = new RenameStep(Guid.CreateVersion7(), "2026/Harbour", "2026/2026-09-28 Harbour", "Harbour", "Harbour sunset")
{
FramesVersion = 3,
FileChanges = 120,
FileSamples =
[
new FileRename(Guid.CreateVersion7(), "originals/IMG_0001.JPG", "originals/Harbour sunset_001.JPG"),
new FileRename(Guid.CreateVersion7(), "originals/IMG_0002.JPG", "originals/Harbour sunset_002.JPG"),
],
Blocked = [new RenameBlocked(RenameBlock.Unhashed, 12)],
};
var carried = new RenameStep(Guid.CreateVersion7(), "2026/Harbour/Night", "2026/2026-09-28 Harbour/Night", null, null, Carried: true);
var kept = new RenameStep(Guid.CreateVersion7(), "2025/Comet", "2025/Comet", "Comet", "Comet") { Blocked = [new RenameBlocked(RenameBlock.Unreadable, 0)] };
var plan = new RenamePlan(Guid.CreateVersion7(), Guid.CreateVersion7(), [moved, kept, carried])
{
FileTemplate = "{title}_{n:000}",
Subjects = [moved.SequenceId, kept.SequenceId],
};
var rows = ReorganizePlans.Rows(plan);
Assert.Count(3, rows);
var first = rows[0];
Assert.Equal("Harbour sunset", first.Name);
Assert.False(first.IsNamePath, "a title reads in the language's direction");
Assert.Equal(Loc.Plural("Archive.Reorganize.Renamed", 120), first.Note);
Assert.SequenceEqual(
[
$"{Loc.L("Archive.Reorganize.Folder")}|2026/Harbour|2026/2026-09-28 Harbour|True",
$"{Loc.L("Archive.Reorganize.Title")}|Harbour|Harbour sunset|False",
$"{Loc.L("Archive.Reorganize.File")}|originals/IMG_0001.JPG|originals/Harbour sunset_001.JPG|True",
$"{Loc.L("Archive.Reorganize.File")}|originals/IMG_0002.JPG|originals/Harbour sunset_002.JPG|True",
],
first.Lines.Select(l => $"{l.Label}|{l.From}|{l.To}|{l.IsPath}"));
Assert.SequenceEqual([Loc.L("Archive.Reorganize.Blocked.Unhashed") + Loc.Separator + Loc.Plural("Shell.Status.Photos", 12)], first.Kept);
Assert.Contains(Loc.L("Archive.Reorganize.Change", Loc.L("Archive.Reorganize.Folder"), "2026/Harbour", "2026/2026-09-28 Harbour"), first.Description);
Assert.Contains(first.Kept[0], first.Description);
var comet = rows[1];
Assert.Empty(comet.Lines, "nothing of it changes");
Assert.SequenceEqual([Loc.L("Archive.Reorganize.Blocked.Unreadable")], comet.Kept, "an unreadable sidecar has no photo count");
Assert.False(comet.HasNote);
var night = rows[2];
Assert.Equal("2026/2026-09-28 Harbour/Night", night.Name, "without a title, the row is named by its folder");
Assert.True(night.IsNamePath);
Assert.Equal(Loc.L("Archive.Reorganize.Carried"), night.Note);
// A sequence carried along is listed, not counted; the names kept are the photos', not the sequences'.
Assert.Equal(1, ReorganizePlans.Changed(plan));
Assert.Equal(string.Join(Loc.Separator, Loc.Plural("Archive.Rename.Summary", 1, 2), Loc.Plural("Archive.Reorganize.Renamed", 120),
Loc.Plural("Archive.Reorganize.Kept", 12)), ReorganizePlans.Summary(plan, 2));
Assert.Equal(Loc.Plural("Archive.Rename.Summary", 1, 2), ReorganizePlans.Summary(plan with { FileTemplate = null, Steps = [moved with { Blocked = [] }] }, 2),
"no file template, no file count; nothing kept, nothing said");
}
[Test]
public void TemplatesChangedWhileTheToastIsUpJoinItsOffer()
{
var main = new Core.Model.Archive { Id = Guid.CreateVersion7(), Name = "Main", RootPath = "/archive" };
var other = new Core.Model.Archive { Id = Guid.CreateVersion7(), Name = "Other", RootPath = "/other" };
var offer = new ReorganizeOffer(TimeSpan.FromSeconds(8));
var now = new DateTime(2026, 10, 27, 9, 0, 0, DateTimeKind.Utc);
Assert.True(offer.Add(main, ReorganizeParts.Folders, now), "the first change raises the toast");
var saved = main with { FileTemplate = "{date}_{n:000}" };
Assert.False(offer.Add(saved, ReorganizeParts.Files, now.AddSeconds(5)), "a change while it is up joins it");
Assert.Equal((saved, ReorganizeParts.Folders | ReorganizeParts.Files), offer.Take(), "both templates, the archive as saved last");
Assert.Null(offer.Take(), "a second toast of the same offer finds it taken");
Assert.True(offer.Add(main, ReorganizeParts.Folders, now.AddSeconds(6)), "once taken, the next change raises a toast again");
Assert.True(offer.Add(other, ReorganizeParts.Files, now.AddSeconds(7)), "another archive has its own toast");
Assert.Equal((other, ReorganizeParts.Files), offer.Take());
Assert.True(offer.Add(other, ReorganizeParts.Files, now.AddSeconds(8)));
Assert.True(offer.Add(other, ReorganizeParts.Folders, now.AddSeconds(17)), "the toast is gone: a new one");
}
[Test]
public async Task SwitchesChooseTheTemplatesAndApplyQueuesExactlyThatPlan()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var directory = context.CreateTempDirectory("reorganize-dialog");
await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(directory, "index.db")), context.Cancellation);
var archives = new ArchiveService(db, new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(TestTiming.Budget(20)) });
var archive = await archives.CreateAsync(Path.Combine(directory, "archive"), "Main", cancellationToken: context.Cancellation);
var harbour = await UploadAsync(archives, archive, "harbour", Start, 1);
var comet = await UploadAsync(archives, archive, "comet", Start.AddDays(1), 11);
var (before, title) = (await db.Sequences.GetAsync(harbour)) is { } filed ? (filed.Folder, filed.Title ?? string.Empty) : default;
var queued = new TaskCompletionSource<ArchiveJobRequest>(TaskCreationOptions.RunContinuationsAsynchronously);
var closed = false;
using var dialog = new ReorganizeDialogViewModel(archives, archive, [harbour, comet], ReorganizePlans.Layout, request =>
{
queued.TrySetResult(request);
return Task.CompletedTask;
}, _ => closed = true);
// From the mass bar: the archive's layout, folders and file names, prefilled from its settings.
Assert.True(dialog.Folders.IsEnabled);
Assert.True(dialog.Files.IsEnabled);
Assert.False(dialog.Titles.IsEnabled);
Assert.Equal(new RenameTemplates(archive.FolderTemplate, archive.FileTemplate), dialog.Current());
Assert.Equal(Loc.Plural("Archive.Reorganize.Heading", 2), dialog.Heading);
await dialog.PlanAsync();
Assert.Empty(dialog.Rows, "photos filed with the archive's templates already follow them");
Assert.Equal(Loc.L("Archive.Blocked.NoChanges"), dialog.ApplyToolTip);
Assert.False(dialog.ApplyCommand.CanExecute(null));
// A template switched off neither counts nor blocks with its errors; switched on, its error does.
dialog.Titles.Field.Text = "{title";
Assert.Null(dialog.Titles.Error);
Assert.Null(dialog.Current()!.Title);
dialog.Titles.IsEnabled = true;
Assert.NotNull(dialog.Titles.Error);
Assert.Null(dialog.Current());
Assert.Equal(dialog.Titles.Error, dialog.ApplyToolTip);
dialog.Titles.IsEnabled = false;
dialog.Folders.IsEnabled = false;
dialog.Files.IsEnabled = false;
Assert.Null(dialog.Current());
Assert.Equal(Loc.L("Archive.Blocked.NoTemplate"), dialog.ApplyToolTip);
Assert.False(dialog.ApplyCommand.CanExecute(null));
dialog.Folders.IsEnabled = true;
dialog.Folders.Field.Text = "{year}/{date}";
dialog.Titles.Field.Text = "Shoot {date}";
dialog.Titles.IsEnabled = true;
Assert.Equal(Loc.L("Archive.Blocked.Planning"), dialog.ApplyToolTip, "the dry run on screen is not the one of the templates typed");
await dialog.PlanAsync();
var plan = Assert.NotNull(dialog.Plan);
Assert.Count(2, dialog.Rows);
var row = dialog.Rows.Single(r => r.SequenceId == harbour);
Assert.Equal("Shoot 2026-09-28", row.Name);
Assert.SequenceEqual([$"{before}>2026/2026-09-28", $"{title}>Shoot 2026-09-28"], row.Lines.Select(l => $"{l.From}>{l.To}"), "folders and titles, no file names");
Assert.Equal(Loc.Plural("Archive.Rename.Summary", 2, 2), dialog.SummaryText);
Assert.Null(plan.FileTemplate);
Assert.True(dialog.ApplyCommand.CanExecute(null));
// Typing again: Apply waits for the dry run of what is on screen.
dialog.Folders.Field.Text = "{year}/{date} {title}";
Assert.Null(dialog.Plan);
Assert.False(dialog.ApplyCommand.CanExecute(null));
dialog.Folders.Field.Text = "{year}/{date}";
await dialog.PlanAsync();
plan = Assert.NotNull(dialog.Plan);
dialog.ApplyCommand.Execute(null);
var request = await queued.Task.WaitAsync(TimeSpan.FromSeconds(TestTiming.Budget(20)));
await UntilAsync(() => closed);
Assert.Equal(JobKind.Move, request.Kind);
Assert.SequenceEqual([archive.Id], request.Targets);
Assert.Equal(archive.Name, request.Label);
Assert.Equal(JobPriority.User, request.Priority);
using (var parameters = JsonDocument.Parse(request.ParametersJson!))
{
var json = parameters.RootElement;
Assert.Equal("{year}/{date}", json.GetProperty("folderTemplate").GetString());
Assert.Equal("Shoot {date}", json.GetProperty("titleTemplate").GetString());
Assert.False(json.TryGetProperty("fileTemplate", out var file) && file.ValueKind != JsonValueKind.Null, "the file names were switched off");
Assert.Equal(plan.Fingerprint(), json.GetProperty("fingerprint").GetString());
}
Assert.Equal(before, (await db.Sequences.GetAsync(harbour))!.Folder, "the job reorganizes, not the dialog");
// The job applies the plan the dialog showed.
await using var engine = new JobEngine(db, archives.CreateJobHandlers(),
new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
await engine.StartAsync(context.Cancellation);
var job = await engine.EnqueueAsync(request, cancellationToken: context.Cancellation);
await WaitForAsync(db, job.Id);
var after = (await db.Sequences.GetAsync(harbour))!;
Assert.Equal(("2026/2026-09-28", "Shoot 2026-09-28"), (after.Folder, after.Title));
Assert.True(Directory.Exists(Path.Combine(archive.RootPath, "2026", "2026-09-28")));
}
/// <summary>Uploads two photos ten seconds apart into a new sequence filed with the archive's templates; returns its id.</summary>
private async Task<Guid> UploadAsync(ArchiveService archives, Core.Model.Archive archive, string key, DateTime start, int seed)
{
Guid id = default;
var staging = Path.Combine(new ArchivePaths(archive.RootPath).StagingDirectory, "uploads");
Directory.CreateDirectory(staging);
for (var i = 0; i < 2; i++)
{
var bytes = ImportTestData.Jpeg(start.AddSeconds(10 * i), seed + i);
var path = Path.Combine(staging, $"{Guid.NewGuid():N}.part");
await File.WriteAllBytesAsync(path, bytes, context.Cancellation);
var request = new IngestRequest(archive.Id, null, null, key, path, $"IMG_{seed + i:0000}.JPG", bytes.Length, Convert.ToHexStringLower(SHA256.HashData(bytes)),
null, null);
id = (await archives.Ingest.CommitAsync(request, context.Cancellation)).SequenceId;
}
return id;
}
private async Task WaitForAsync(ChronosDatabase db, Guid jobId)
{
var until = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(30));
Job? job = null;
while (DateTime.UtcNow < until)
{
job = await db.Jobs.GetAsync(jobId, context.Cancellation);
if (job?.State == JobState.Done) return;
if (job?.State is JobState.Failed or JobState.Cancelled) Assert.Fail($"The reorganize job ended {job.State}: {job.Error}\n{job.LogTail}");
await Task.Delay(20, context.Cancellation);
}
Assert.Fail($"The reorganize job did not finish (now {job?.State}).");
}
private static async Task UntilAsync(Func<bool> condition)
{
var until = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(20));
while (!condition())
{
Assert.True(DateTime.UtcNow < until, "timed out");
await Task.Delay(20);
}
}
}