feat: owner review 2 phase 4a: Reorganize sequences after import (#12)
CI / Build and test (push) Successful in 9m15s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 15m35s
CI / PostgreSQL 16 integration (push) Successful in 7m26s
CI / PostgreSQL 17 integration (push) Successful in 6m47s
CI / Docker image (push) Successful in 59s
Release / Server image (push) Successful in 1m24s
CI / Build and test (push) Successful in 9m15s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 15m35s
CI / PostgreSQL 16 integration (push) Successful in 7m26s
CI / PostgreSQL 17 integration (push) Successful in 6m47s
CI / Docker image (push) Successful in 59s
Release / Server image (push) Successful in 1m24s
- Reorganize… on the web panel and the desktop: folder, file and title templates applied to existing sequences, with a dry run and an explicit Apply that runs as a job. - One naming rule (FrameNaming) for import, upload and Reorganize. - Crash-safe plan and file journals, held plans, stale-plan refusal; exports move with their folder. - Writers refuse a folder another program moved or gave to another sequence. - Server: POST /api/v1/archive/reorganize with a bounded plan cache; template rules. - Phase 3 docs and translations merged; strings in all 38 languages. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #12.
This commit is contained in:
1 parent
9aa818ed47
commit
7e4a3b481d
416 files changed
+15304
-1572
No files matched your search
@@ -225,28 +225,23 @@ public sealed class ArchiveLogicTests
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RenameTemplatesAreCheckedAndThePlanListedByMode()
|
||||
public void PlannedTitlesAndFoldersAreListedAsReorganizeRows()
|
||||
{
|
||||
Assert.Null(MassRename.Validate(RenameMode.Titles, "{title} · {camera}"));
|
||||
Assert.NotNull(MassRename.Validate(RenameMode.Titles, "{title"));
|
||||
Assert.NotNull(MassRename.Validate(RenameMode.Titles, " "));
|
||||
Assert.Null(MassRename.Validate(RenameMode.Folders, "{year}/{date} {title}"));
|
||||
Assert.NotNull(MassRename.Validate(RenameMode.Folders, "{nope}"));
|
||||
|
||||
var a = Seq("Harbour", new DateTime(2026, 9, 28));
|
||||
var b = Seq("Comet", new DateTime(2026, 8, 13));
|
||||
var subjects = new[] { a, b }.Select(s => new RenameSubject(s.Id, s.Folder, s.Title, s.FirstCapture, "Canon", "Canon EOS R5", null)).ToList();
|
||||
var titles = RenamePlanner.Plan(Main.Id, subjects, null, "{title} · {camera}", subjects.Select(s => s.Folder), _ => false);
|
||||
var rows = MassRename.Rows(titles, RenameMode.Titles);
|
||||
Assert.Equal("Harbour", rows[0].From);
|
||||
Assert.Equal("Harbour · Canon EOS R5", rows[0].To);
|
||||
Assert.Equal("2 of 5 change", MassRename.Summary(titles, 5));
|
||||
var retitled = ReorganizePlans.Rows(titles).Select(r => r.Lines.Single()).ToList();
|
||||
Assert.SequenceEqual(new[] { "Harbour>Harbour · Canon EOS R5", "Comet>Comet · Canon EOS R5" }, retitled.Select(l => $"{l.From}>{l.To}"));
|
||||
Assert.False(retitled.Any(l => l.IsPath), "titles read in the language's direction");
|
||||
Assert.Equal("2 of 5 change", ReorganizePlans.Summary(titles, 5));
|
||||
|
||||
Assert.Empty(RenamePlanner.Plan(Main.Id, subjects, "{year}/{title}", null, subjects.Select(s => s.Folder), _ => false).Steps);
|
||||
var folders = RenamePlanner.Plan(Main.Id, subjects, "{year}/{date} {title}", null, subjects.Select(s => s.Folder), _ => false);
|
||||
var moves = MassRename.Rows(folders, RenameMode.Folders);
|
||||
Assert.SequenceEqual(new[] { "2026/Harbour", "2026/Comet" }, moves.Select(r => r.From));
|
||||
Assert.SequenceEqual(new[] { "2026/2026-09-28 Harbour", "2026/2026-08-13 Comet" }, moves.Select(r => r.To));
|
||||
var moves = ReorganizePlans.Rows(folders).Select(r => r.Lines.Single()).ToList();
|
||||
Assert.SequenceEqual(new[] { "2026/Harbour", "2026/Comet" }, moves.Select(l => l.From));
|
||||
Assert.SequenceEqual(new[] { "2026/2026-09-28 Harbour", "2026/2026-08-13 Comet" }, moves.Select(l => l.To));
|
||||
Assert.True(moves.All(l => l.IsPath), "folders read left to right");
|
||||
}
|
||||
|
||||
[Test]
|
||||
|
||||
@@ -94,17 +94,18 @@ public sealed class ArchiveScreenSmokeTests
|
||||
Assert.Equal(0, ((SolidColorBrush)frame.Background).Color.A, "the disabled tree keeps its panel's fill instead of the system's white");
|
||||
AssertNoErrorShown(app);
|
||||
|
||||
await ArchiveScenes.ShowAsync(app.Shell, "move");
|
||||
var move = Assert.NotNull(archive.Dialog as RenameDialogViewModel);
|
||||
Assert.NotEmpty(move.Rows, "the dry run lists the folders that change");
|
||||
Assert.Null(move.ErrorText);
|
||||
await app.ExpectAsync<ArchiveView>("archive-move");
|
||||
Assert.True(ButtonFor(app, move.ApplyCommand).IsEnabled, "Apply follows the dry run");
|
||||
Assert.True(ButtonFor(app, move.CloseCommand).IsDefault, "Enter takes the safe way out");
|
||||
await ArchiveScenes.ShowAsync(app.Shell, "reorganize");
|
||||
var reorganize = Assert.NotNull(archive.Dialog as ReorganizeDialogViewModel);
|
||||
Assert.NotEmpty(reorganize.Rows, "the dry run lists the sequences that change");
|
||||
Assert.Null(reorganize.ErrorText);
|
||||
await app.ExpectAsync<ArchiveView>("archive-reorganize");
|
||||
Assert.True(ButtonFor(app, reorganize.ApplyCommand).IsEnabled, "Apply follows the dry run");
|
||||
Assert.True(ButtonFor(app, reorganize.CloseCommand).IsDefault, "Enter takes the safe way out");
|
||||
foreach (var box in app.FindAll<CheckBox>().Where(c => c.IsVisible)) Assert.NotNull(box.ToolTip, "every template switch says what it does");
|
||||
AssertNoErrorShown(app);
|
||||
AssertEveryButtonIsNamed(app);
|
||||
|
||||
move.CloseCommand.Execute(null);
|
||||
reorganize.CloseCommand.Execute(null);
|
||||
archive.RetagSetCommand.Execute(null);
|
||||
var retag = Assert.NotNull(archive.Dialog as RetagDialogViewModel);
|
||||
retag.Add.Text = "sunset";
|
||||
@@ -134,14 +135,15 @@ public sealed class ArchiveScreenSmokeTests
|
||||
await app.ExpectAsync<ArchiveView>("archive-rebuild-ar");
|
||||
Assert.Equal(FlowDirection.LeftToRight, TextFor(app, archive.SelectedArchive!.RootPath).FlowDirection, "the archive folder reads left to right");
|
||||
|
||||
await ArchiveScenes.ShowAsync(app.Shell, "move");
|
||||
var move = Assert.NotNull(archive.Dialog as RenameDialogViewModel);
|
||||
await app.ExpectAsync<ArchiveView>("archive-move-ar");
|
||||
var template = Assert.NotNull(app.FindAll<TextBox>().FirstOrDefault(t => t.IsVisible && EditBehavior.GetField(t) == move.Template));
|
||||
await ArchiveScenes.ShowAsync(app.Shell, "reorganize");
|
||||
var reorganize = Assert.NotNull(archive.Dialog as ReorganizeDialogViewModel);
|
||||
await app.ExpectAsync<ArchiveView>("archive-reorganize-ar");
|
||||
var template = Assert.NotNull(app.FindAll<TextBox>().FirstOrDefault(t => t.IsVisible && EditBehavior.GetField(t) == reorganize.Folders.Field));
|
||||
Assert.Equal(FlowDirection.LeftToRight, template.FlowDirection, "the naming template reads left to right");
|
||||
Assert.Equal(FlowDirection.LeftToRight, TextFor(app, move.Rows[0].From).FlowDirection, "a folder before the move reads left to right");
|
||||
Assert.Equal(FlowDirection.LeftToRight, TextFor(app, move.Rows[0].To).FlowDirection, "a folder after the move reads left to right");
|
||||
move.CloseCommand.Execute(null);
|
||||
var folder = reorganize.Rows.SelectMany(r => r.Lines).First(l => l.IsPath);
|
||||
Assert.Equal(FlowDirection.LeftToRight, TextFor(app, folder.From).FlowDirection, "a folder before the move reads left to right");
|
||||
Assert.Equal(FlowDirection.LeftToRight, TextFor(app, folder.To).FlowDirection, "a folder after the move reads left to right");
|
||||
reorganize.CloseCommand.Execute(null);
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
||||
@@ -0,0 +1,405 @@
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.Json;
|
||||
using Chronos.App.Archiving;
|
||||
using Chronos.App.DesignTime;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Shell;
|
||||
using Chronos.App.Tests.Import;
|
||||
using Chronos.App.Tests.Uploader;
|
||||
using Chronos.App.Tests.Windows;
|
||||
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;
|
||||
using Chronos.Ui.Controls;
|
||||
|
||||
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(main.Id), "both templates, the archive as saved last");
|
||||
Assert.Null(offer.Take(main.Id), "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(other.Id));
|
||||
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");
|
||||
|
||||
// Each toast takes its own archive's offer: the older toast of Main opens Main, not the Other changed since.
|
||||
Assert.Equal((main, ReorganizeParts.Folders), offer.Take(main.Id));
|
||||
Assert.Equal((other, ReorganizeParts.Files | ReorganizeParts.Folders), offer.Take(other.Id), "Other's offer stayed for its own toast");
|
||||
Assert.Null(offer.Take(main.Id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AToastGoneEarlyLetsTheNextChangeRaiseItsOwn()
|
||||
{
|
||||
var main = new Core.Model.Archive { Id = Guid.CreateVersion7(), Name = "Main", RootPath = "/archive" };
|
||||
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));
|
||||
offer.Closed(main.Id, now);
|
||||
Assert.True(offer.Add(main, ReorganizeParts.Files, now.AddSeconds(2)), "dismissed after a second: the next change has a toast of its own");
|
||||
Assert.False(offer.Add(main, ReorganizeParts.Titles, now.AddSeconds(3)), "and joins it while it is up");
|
||||
offer.Closed(main.Id, now);
|
||||
Assert.False(offer.Add(main, ReorganizeParts.Titles, now.AddSeconds(4)), "an older toast leaving changes nothing for the one up");
|
||||
Assert.Equal((main, ReorganizeParts.Folders | ReorganizeParts.Files | ReorganizeParts.Titles), offer.Take(main.Id),
|
||||
"the toast up offers every change since the last one taken");
|
||||
offer.Closed(main.Id, now.AddSeconds(2));
|
||||
Assert.Null(offer.Take(main.Id), "the toast closing after its action finds nothing to keep");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The toasts' host says when a toast leaves the screen, as Settings › Archive needs to know whether its offer is still
|
||||
/// up: dismissed, pushed out by three newer ones, timed out or closed by its action, once each.
|
||||
/// </summary>
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void AToastLeavingTheScreenSaysSoOnce() => WpfApplication.Dispatcher.Invoke(() =>
|
||||
{
|
||||
var host = new ToastHost();
|
||||
var closed = new List<string>();
|
||||
Toast Show(string title)
|
||||
{
|
||||
var toast = new Toast { Title = title };
|
||||
toast.Closed += (_, _) => closed.Add(title);
|
||||
host.Show(toast);
|
||||
return toast;
|
||||
}
|
||||
|
||||
var first = Show("first");
|
||||
var second = Show("second");
|
||||
host.Dismiss(second);
|
||||
host.Dismiss(second);
|
||||
Assert.SequenceEqual(["second"], closed, "dismissed, once");
|
||||
Show("third");
|
||||
Show("fourth");
|
||||
Assert.Empty(closed.Skip(1), "three on screen");
|
||||
Show("fifth");
|
||||
Assert.SequenceEqual(["second", "first"], closed, "the oldest pushed out by a fourth");
|
||||
host.Dismiss(first);
|
||||
Assert.Count(2, closed, "a toast gone already says nothing");
|
||||
foreach (var toast in host.Toasts.ToList()) host.Dismiss(toast);
|
||||
});
|
||||
|
||||
[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; Enter plans it at once.
|
||||
dialog.Folders.Field.Text = "{year}/{date} {title}";
|
||||
Assert.Null(dialog.Plan);
|
||||
Assert.False(dialog.ApplyCommand.CanExecute(null));
|
||||
Assert.True(dialog.Folders.Field.Commit());
|
||||
Assert.Equal(Loc.L("Archive.Reorganize.Planning"), dialog.BusyText, "a template changed since its dry run plans without waiting for the typing to pause");
|
||||
dialog.Folders.Field.Text = "{year}/{date}";
|
||||
await dialog.PlanAsync();
|
||||
plan = Assert.NotNull(dialog.Plan);
|
||||
|
||||
// A click on Apply takes the focus from the field first, which commits it: the dry run on screen is of that text
|
||||
// already, so no other one starts and Apply stays on under the click.
|
||||
Assert.True(dialog.Folders.Field.IsDirty, "typed, not committed");
|
||||
Assert.True(dialog.Folders.Field.Commit());
|
||||
Assert.Same(plan, dialog.Plan);
|
||||
Assert.Null(dialog.BusyText);
|
||||
Assert.True(dialog.ApplyCommand.CanExecute(null));
|
||||
|
||||
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>
|
||||
/// The Settings toast's Reorganize… is reached from another screen while the Archive screen may have a dialog open (a
|
||||
/// Delete moving sequences, the trash): that dialog is neither replaced nor stopped. Reorganize says it waits, and
|
||||
/// opens once that dialog closes, on every sequence with every part the toasts offered meanwhile.
|
||||
/// </summary>
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void TheToastsReorganizeWaitsForTheDialogOpenOnTheArchiveScreen()
|
||||
{
|
||||
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
||||
var environment = AppEnvironment.ForCapture();
|
||||
try
|
||||
{
|
||||
SingleThreadedContext.Run(async () =>
|
||||
{
|
||||
var services = new AppServices(environment, new AppSettings { Language = "en", FirstRunCompleted = true }, () => { }, new NoDialogs());
|
||||
var sample = SampleData.Configure(services);
|
||||
await sample.OpenEmptyAsync();
|
||||
await sample.FillAsync();
|
||||
var shell = new ShellViewModel(services);
|
||||
try
|
||||
{
|
||||
var toasts = new List<Toast>();
|
||||
shell.PendingToasts.CollectionChanged += (_, e) => toasts.AddRange(e.NewItems?.OfType<Toast>() ?? []);
|
||||
var screen = shell.Archive;
|
||||
await screen.LoadAsync();
|
||||
var archive = Assert.NotNull(screen.SelectedArchive);
|
||||
await screen.OpenTrashAsync();
|
||||
var trash = Assert.NotNull(screen.Dialog as TrashDialogViewModel);
|
||||
|
||||
await screen.OpenReorganizeAllAsync(archive with { FileTemplate = "{date}_{n:0000}" }, ReorganizeParts.Files);
|
||||
await screen.OpenReorganizeAllAsync(archive, ReorganizeParts.Folders);
|
||||
Assert.Same(trash, screen.Dialog);
|
||||
Assert.Equal(Loc.L("Archive.Reorganize.Waiting"), toasts[^1].Title);
|
||||
|
||||
trash.CloseCommand.Execute(null);
|
||||
await UntilAsync(() => screen.Dialog is ReorganizeDialogViewModel);
|
||||
var reorganize = (ReorganizeDialogViewModel)screen.Dialog!;
|
||||
await UntilAsync(() => reorganize.BusyText is null);
|
||||
Assert.Null(reorganize.ErrorText);
|
||||
Assert.Equal(Loc.L("Archive.Reorganize.HeadingAll", archive.Name), reorganize.Heading);
|
||||
Assert.True(reorganize.Folders.IsEnabled, "the parts of both toasts");
|
||||
Assert.True(reorganize.Files.IsEnabled);
|
||||
Assert.False(reorganize.Titles.IsEnabled);
|
||||
Assert.Equal(archive.FileTemplate, reorganize.Files.Field.Text, "the archive's templates as the index holds them when it opens");
|
||||
reorganize.CloseCommand.Execute(null);
|
||||
Assert.Null(screen.Dialog);
|
||||
}
|
||||
finally
|
||||
{
|
||||
shell.Dispose();
|
||||
await services.DisposeAsync();
|
||||
}
|
||||
});
|
||||
}
|
||||
finally
|
||||
{
|
||||
environment.DeleteCaptureData();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Dialogs that answer like a user who cancels everything.</summary>
|
||||
private sealed class NoDialogs : IAppDialogs
|
||||
{
|
||||
public string? PickFolder(string title, string? initialFolder = null) => null;
|
||||
public string? PickJsonFile(string title) => null;
|
||||
public bool Confirm(ConfirmRequest request) => false;
|
||||
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
|
||||
}
|
||||
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -330,6 +330,59 @@ public sealed class EditorSmokeTests
|
||||
}
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// A Reorganize of this PC moves the folder of the sequence open in the editor: the editor reads it again where it is
|
||||
/// now as soon as its step is done, so its frames decode and its project goes there.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public Task AnOpenSequenceIsReadAgainWhereAReorganizeMovedIt() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
|
||||
var id = await app.Sample.FillEditorAsync();
|
||||
var db = app.Services.Database!;
|
||||
var archives = app.Services.Archives!;
|
||||
var source = new LocalSequenceSource(db, id, Chronos.Core.Imaging.Decoders.DecoderFactory.CreateClient(null), null);
|
||||
var content = await source.LoadAsync(CancellationToken.None);
|
||||
var editor = new EditorViewModel(app.Shell, new EditorSession(source, content, []), [], EncoderHost.Client);
|
||||
await using (editor)
|
||||
{
|
||||
var archive = (await db.Archives.GetAsync(content.Sequence.ArchiveId))!;
|
||||
var templates = new Chronos.Core.Archiving.RenameTemplates("Moved/{date}");
|
||||
var plan = await archives.PlanReorganizeAsync(archive.Id, [id], templates, CancellationToken.None);
|
||||
var moved = plan.Steps.Single().ToFolder;
|
||||
await using var engine = new Chronos.Data.Jobs.JobEngine(db, archives.CreateJobHandlers(), new Chronos.Data.Jobs.JobEngineOptions
|
||||
{
|
||||
WorkerId = "test",
|
||||
Kinds = [JobKind.Move],
|
||||
PollInterval = TimeSpan.FromMilliseconds(50),
|
||||
});
|
||||
await engine.StartAsync(CancellationToken.None);
|
||||
var job = await Chronos.Data.Archiving.ArchiveJobs.EnqueueAsync(engine, Chronos.Data.Archiving.ArchiveJobs.Reorganize(archive, plan, templates));
|
||||
// The editor reads its photos as it opens; on Windows the folder cannot move while one is open, and the job that
|
||||
// failed holds the plan for its retry.
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
Job? ended = null;
|
||||
for (var i = 0; i < 1200 && ended is null; i++)
|
||||
{
|
||||
await Task.Delay(25);
|
||||
if (await db.Jobs.GetAsync(job.Id) is { State: JobState.Done or JobState.Failed or JobState.Cancelled } now) ended = now;
|
||||
}
|
||||
Assert.NotNull(ended, "the move job ends");
|
||||
if (ended!.State == JobState.Done) break;
|
||||
Assert.True(ended.State == JobState.Failed && attempt < 20, ended.Error);
|
||||
await Task.Delay(250);
|
||||
await engine.ResumeAsync(job.Id, CancellationToken.None);
|
||||
}
|
||||
|
||||
for (var i = 0; i < 400 && editor.Session.Content.Sequence.Folder != moved; i++) await Task.Delay(25);
|
||||
Assert.Equal(moved, editor.Session.Content.Sequence.Folder);
|
||||
Assert.True(await source.FramesCurrentAsync(CancellationToken.None), "the editor holds the frames where they are now");
|
||||
using var frame = await source.DecodeAsync(0, 32, Chronos.Core.Imaging.DecodePurpose.Thumbnail, CancellationToken.None);
|
||||
Assert.NotNull(frame, "its frames decode");
|
||||
}
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// At the 1200 px minimum beside the 200 px rail (owner review 1, R1), the preview's tools stay inside the preview in
|
||||
/// every language, crop mask on (the crop-result tool enabled): they take a second line rather than lose Play and Full screen.
|
||||
|
||||
@@ -215,6 +215,44 @@ public sealed class ProjectStoreTests(TestContext context)
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnEditorOpenWhileAReorganizeMovesItsFolderSavesWhereTheSequenceIsNow()
|
||||
{
|
||||
var (db, sequenceId, root) = await ArchiveAsync(6);
|
||||
await using (db)
|
||||
{
|
||||
var options = new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) };
|
||||
await using var source = new LocalSequenceSource(db, sequenceId, DecoderFactory.CreateClient(null), null, options);
|
||||
var content = await source.LoadAsync(context.Cancellation);
|
||||
var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
|
||||
await using (session)
|
||||
{
|
||||
Assert.True(session.SetHero(2));
|
||||
Assert.True(await session.FlushAsync());
|
||||
|
||||
// Only the folder template changed: the Reorganize moves the folder and keeps the frames version.
|
||||
var service = new ArchiveService(db, options);
|
||||
var plan = await service.PlanRenameAsync(content.Sequence.ArchiveId, [sequenceId], "Moved/{title}", null, context.Cancellation);
|
||||
await service.ApplyRenameAsync(plan, null, context.Cancellation);
|
||||
var moved = new ArchivePaths(root).Sequence(plan.Steps.Single().ToFolder);
|
||||
Assert.Equal(content.Sequence.FramesVersion, (await db.Sequences.GetAsync(sequenceId))!.FramesVersion);
|
||||
Assert.False(await source.FramesCurrentAsync(context.Cancellation), "the files are no longer where the editor read them");
|
||||
|
||||
session.Edit(p => p with { Exposure = p.Exposure with { ExposureOffsetEv = 0.4 } });
|
||||
Assert.True(await session.FlushAsync());
|
||||
|
||||
var row = (await db.Sequences.GetAsync(sequenceId))!;
|
||||
Assert.Equal(0.4, ProjectSettings.FromJson(row.SettingsJson!).Exposure.ExposureOffsetEv);
|
||||
Assert.Equal(row.SettingsJson, File.ReadAllText(moved.ProjectPath), "the moved folder's project has the edit");
|
||||
Assert.False(Directory.Exists(Path.Combine(root, "Synthetic")), "the folder it left is not created again");
|
||||
Assert.True(await source.FramesCurrentAsync(context.Cancellation));
|
||||
Assert.Equal(moved.Exports, session.Content.ExportsFolder);
|
||||
using var frame = await source.DecodeAsync(1, 32, DecodePurpose.Thumbnail, context.Cancellation);
|
||||
Assert.NotNull(frame, "the frames are read where they are now");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ASaveThatDoesNotReachTheIndexThrows()
|
||||
{
|
||||
@@ -230,6 +268,54 @@ public sealed class ProjectStoreTests(TestContext context)
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ASaveAfterAnotherIndexMovedTheFolderWritesNothing()
|
||||
{
|
||||
var (db, sequenceId, root) = await ArchiveAsync(4);
|
||||
await using (db)
|
||||
{
|
||||
await using var source = new LocalSequenceSource(db, sequenceId, DecoderFactory.CreateClient(null), null,
|
||||
new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) });
|
||||
var content = await source.LoadAsync(context.Cancellation);
|
||||
|
||||
// A server sharing the archive moved the folder; this index finds it there at its next scan.
|
||||
var left = Path.Combine(root, "Synthetic");
|
||||
Directory.Move(left, Path.Combine(root, "Moved"));
|
||||
var gone = await Assert.ThrowsAsync<EditorException>(() => source.SaveProjectAsync(content.Project with { HeroFrame = 1 }, content.Project, context.Cancellation));
|
||||
|
||||
Assert.Equal(Loc.L("Editor.Error.Missing"), gone.Message);
|
||||
Assert.False(Directory.Exists(left), "the folder it left is not created again");
|
||||
Assert.Equal(content.Sequence.SettingsVersion, (await db.Sequences.GetAsync(sequenceId))!.SettingsVersion, "nothing recorded");
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ASaveNeverWritesIntoAnotherSequenceMovedIntoTheFolder()
|
||||
{
|
||||
var (db, sequenceId, root) = await ArchiveAsync(4);
|
||||
await using (db)
|
||||
{
|
||||
await using var source = new LocalSequenceSource(db, sequenceId, DecoderFactory.CreateClient(null), null,
|
||||
new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) });
|
||||
var content = await source.LoadAsync(context.Cancellation);
|
||||
|
||||
// A server sharing the archive moved the folder away, then another sequence into the folder it left; this index
|
||||
// finds both at its next scan.
|
||||
var paths = new ArchivePaths(root);
|
||||
Directory.Move(paths.Sequence("Synthetic").Folder, paths.Sequence("Moved").Folder);
|
||||
var stranger = paths.Sequence("Synthetic");
|
||||
Directory.CreateDirectory(stranger.MetaDirectory);
|
||||
ManifestStore.WriteSequence(stranger.ManifestPath, ManifestStore.ReadSequence(paths.Sequence("Moved").ManifestPath) with { Id = Guid.NewGuid() });
|
||||
const string theirs = """{"exposure":{"deflickerWindow":{"isAuto":false,"manual":7}}}""";
|
||||
await File.WriteAllTextAsync(stranger.ProjectPath, theirs, context.Cancellation);
|
||||
var gone = await Assert.ThrowsAsync<EditorException>(() => source.SaveProjectAsync(content.Project with { HeroFrame = 1 }, content.Project, context.Cancellation));
|
||||
|
||||
Assert.Equal(Loc.L("Editor.Error.Missing"), gone.Message);
|
||||
Assert.Equal(theirs, await File.ReadAllTextAsync(stranger.ProjectPath, context.Cancellation), "the other sequence's project is untouched");
|
||||
Assert.Equal(content.Sequence.SettingsVersion, (await db.Sequences.GetAsync(sequenceId))!.SettingsVersion, "nothing recorded");
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task JobsGoToTheEngine()
|
||||
{
|
||||
|
||||
@@ -2,9 +2,11 @@ using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Shell;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Protocol.Client;
|
||||
using Chronos.Testing;
|
||||
@@ -60,4 +62,15 @@ public sealed class ErrorTextTests
|
||||
Assert.Equal("Something went wrong.", ErrorText.For(new IOException(@"Access to the path 'D:\Archive' is denied.")));
|
||||
Assert.Equal(@"The archive D:\Shoots is read-only.", ErrorText.For(new ArchiveOfflineException(@"D:\Shoots", ArchiveAvailability.ReadOnly)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ATemplateAnArchiveRefusesSaysTheRuleItBreaks()
|
||||
{
|
||||
// A new archive with this PC's templates, one saved before the rules existed: the toast says what to change.
|
||||
var refused = new TemplateRuleException("fileTemplate", "NotUnique");
|
||||
const string Sentence = "Names would repeat: add the frame number, the time or the original name.";
|
||||
Assert.Equal(Sentence, ErrorText.For(refused));
|
||||
Assert.Equal(Sentence, ArchiveActions.Cause(refused));
|
||||
Assert.Equal("Something went wrong.", ArchiveActions.Cause(new ArgumentException("The archive setting name is invalid.", "name")));
|
||||
}
|
||||
}
|
||||
@@ -58,7 +58,7 @@ public sealed class LibraryScreenSmokeTests
|
||||
await LibraryScenes.ShowAsync(app.Shell, "mass");
|
||||
Assert.Equal(LibraryScenes.MassSelection, library.SelectionCount);
|
||||
await app.ExpectAsync<LibraryView>("library-mass", waitForThumbnails: true);
|
||||
foreach (var command in new[] { library.AnalyseCommand, library.ProxiesCommand, library.VerifyCommand, library.TagCommand, library.MoveCommand,
|
||||
foreach (var command in new[] { library.AnalyseCommand, library.ProxiesCommand, library.VerifyCommand, library.TagCommand, library.ReorganizeCommand,
|
||||
library.ExportListCommand, library.DeleteCommand })
|
||||
Assert.True(ButtonFor(app, command).IsEnabled, "the bar's archive actions work on sequences of this PC");
|
||||
Assert.True(library.CanRate);
|
||||
|
||||
@@ -65,7 +65,7 @@ public sealed class MassActionsTests
|
||||
var remote = Remote("Sunrise over Superga");
|
||||
SelectedSequence[] mixed = [harbour, remote];
|
||||
|
||||
foreach (var action in new[] { MassAction.Analyse, MassAction.Proxies, MassAction.Verify, MassAction.Tag, MassAction.Rate, MassAction.Move, MassAction.Delete })
|
||||
foreach (var action in new[] { MassAction.Analyse, MassAction.Proxies, MassAction.Verify, MassAction.Tag, MassAction.Rate, MassAction.Reorganize, MassAction.Delete })
|
||||
{
|
||||
Assert.Null(MassActions.Blocker(action, mixed, SignedIn), action.ToString());
|
||||
Assert.SequenceEqual([harbour], MassActions.Targets(action, mixed, SignedIn), action.ToString());
|
||||
@@ -76,11 +76,21 @@ public sealed class MassActionsTests
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void MoveStaysInsideOneArchive()
|
||||
public void ReorganizeStaysInsideOneArchive()
|
||||
{
|
||||
SelectedSequence[] two = [Only("Harbour sunset"), new(Local("Aurora", Guid.CreateVersion7()), null)];
|
||||
Assert.Equal(Loc.L("Library.Blocked.Archives"), MassActions.Blocker(MassAction.Move, two, Offline));
|
||||
Assert.Equal(Loc.L("Library.Blocked.OneArchive"), MassActions.Blocker(MassAction.Reorganize, two, Offline));
|
||||
Assert.Null(MassActions.Blocker(MassAction.Delete, two, Offline), "the trash of each archive takes its own sequences");
|
||||
|
||||
// A server card in the selection is left out: the archive of the sequences here is still one.
|
||||
var remote = Remote("Sunrise over Superga");
|
||||
SelectedSequence[] withCard = [two[0], Only("Comet"), remote];
|
||||
Assert.Null(MassActions.Blocker(MassAction.Reorganize, withCard, SignedIn));
|
||||
Assert.SequenceEqual(withCard[..2], MassActions.Targets(MassAction.Reorganize, withCard, SignedIn));
|
||||
Assert.Equal(Loc.L("Library.Blocked.ServerOnly"), MassActions.Blocker(MassAction.Reorganize, [remote], SignedIn));
|
||||
Assert.Equal(Loc.L("Library.Blocked.NoIndex"), MassActions.Blocker(MassAction.Reorganize, [two[0]], new SelectionContext(HasEngine: false, IsSignedIn: false, default)),
|
||||
"the dry run and the job need the engine");
|
||||
Assert.Equal(Loc.Plural("Tooltips.Library.Mass.Reorganize", 2), MassActions.ToolTip(MassAction.Reorganize, 2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
|
||||
@@ -37,6 +37,8 @@ public sealed class SettingsLogicTests
|
||||
[Case("{date}", "Errors.Template.NotUnique", "", 0)]
|
||||
[Case("{year}/{n}", "Errors.Template.FileSeparator", "", 0)]
|
||||
[Case("{date:%}_{n}", "Errors.Template.Format", "", 0)]
|
||||
[Case("{n}{ext}", "Errors.Template.Extension", "", 0)]
|
||||
[Case("{title}_{ext}", "Errors.Template.Extension", "", 0)]
|
||||
public void InvalidFileTemplatesExplainTheProblem(string template, string key, string token, int position)
|
||||
{
|
||||
var expected = position > 0 ? Loc.L(key, token, position) : Loc.L(key);
|
||||
@@ -56,6 +58,18 @@ public sealed class SettingsLogicTests
|
||||
{
|
||||
Assert.Null(NamingPreview.Validate("{year}/{month}/{camera}", isFolder: true));
|
||||
Assert.Equal("2026/09/Canon EOS R5/IMG_4211.CR2", NamingPreview.FirstNames("{year}/{month}/{camera}", "{name}")[0]);
|
||||
Assert.Null(NamingPreview.Validate("{name}.{ext}", isFolder: false));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case("Originals/{year}")]
|
||||
[Case("{year}/exports")]
|
||||
[Case(".archive/{date}")]
|
||||
[Case("{year}/.chronos")]
|
||||
public void FolderTemplatesScansWouldSkipAreRefused(string template)
|
||||
{
|
||||
Assert.Equal(Loc.L("Errors.Template.ReservedFolder"), NamingPreview.Validate(template, isFolder: true), template);
|
||||
Assert.Empty(NamingPreview.FirstNames(template, TemplateDefaults.File));
|
||||
}
|
||||
|
||||
[Test]
|
||||
|
||||
@@ -70,9 +70,12 @@ public sealed class LeaseFileTests(TestContext context)
|
||||
var duration = TimeSpan.FromSeconds(TestTiming.Budget(0.3));
|
||||
using var lease = LeaseFile.TryAcquire(locks, "seq-1", "server", duration);
|
||||
Assert.NotNull(lease);
|
||||
var first = LeaseFile.Read(lease.Path)!.Expires;
|
||||
await Task.Delay(duration * 3);
|
||||
Assert.True(lease.IsHeld);
|
||||
Assert.Greater((LeaseFile.Read(lease.Path)!.Expires - DateTimeOffset.UtcNow).TotalMilliseconds, 0);
|
||||
// Renewed: the expiry moved on. Whether it is still ahead of the clock at this instant depends on when the last
|
||||
// timer ran, which a busy runner can delay by a few milliseconds past it.
|
||||
Assert.Greater((LeaseFile.Read(lease.Path)!.Expires - first).TotalMilliseconds, duration.TotalMilliseconds);
|
||||
Assert.Null(LeaseFile.TryAcquire(locks, "seq-1", "client", duration));
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,774 @@
|
||||
using System.Text;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Naming;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Core.Tests.Archiving;
|
||||
|
||||
/// <summary>Reorganize (owner review 2, R7): file names planned from a template, and the two-phase renames of a sequence's files.</summary>
|
||||
[Category("archive")]
|
||||
public sealed class ReorganizeTests(TestContext context)
|
||||
{
|
||||
private static readonly DateTime Start = new(2026, 9, 28, 18, 0, 0);
|
||||
|
||||
/// <summary>Frames in index order, every one hashed, ten seconds apart.</summary>
|
||||
private static SequenceManifest Sequence(params string[] files) => new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Camera = new SidecarCamera { Make = "Canon", Model = "Canon EOS R5" },
|
||||
Versions = new ManifestVersions { Frames = 4 },
|
||||
Frames = [.. files.Select((f, i) => new SidecarFrame
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
I = i,
|
||||
File = f,
|
||||
Original = $"IMG_{i + 1:0000}{Path.GetExtension(f)}",
|
||||
Sha256 = new string((char)('a' + i % 6), 64),
|
||||
CapturedAt = Start.AddSeconds(10 * i),
|
||||
})],
|
||||
};
|
||||
|
||||
private static FileRenamePlan Plan(SequenceManifest manifest, string template, string? title = null, IEnumerable<string>? extra = null) =>
|
||||
FileRenames.Plan(manifest, title, PathTemplate.Parse(template), [.. manifest.Frames.Select(f => f.File), .. extra ?? []]);
|
||||
|
||||
[Test]
|
||||
public void FramesAreNamedInIndexOrderAndNamesTakenGetNumbersAsFilingDoes()
|
||||
{
|
||||
var manifest = Sequence("originals/c.JPG", "originals/a.JPG", "originals/b.JPG", "originals/d.JPG");
|
||||
var plan = Plan(manifest, "{date}");
|
||||
Assert.SequenceEqual(["originals/2026-09-28.JPG", "originals/2026-09-28_2.JPG", "originals/2026-09-28_3.JPG", "originals/2026-09-28_4.JPG"],
|
||||
plan.Moves.Select(m => m.To));
|
||||
Assert.SequenceEqual(manifest.Frames.Select(f => f.Id), plan.Moves.Select(m => m.FrameId));
|
||||
Assert.Equal(4, plan.Frames);
|
||||
Assert.SequenceEqual(plan.Moves.Take(FileRenames.SampleCount), plan.Samples);
|
||||
Assert.Empty(plan.Blocked);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AChainOfNamesIsPlannedAndAFileNoFrameListsKeepsItsName()
|
||||
{
|
||||
// Frame 1 now holds the name frame 0 gets, frame 2 the one frame 1 gets: 2→1, 3→2, 4→3. A file no frame lists holds "4".
|
||||
var manifest = Sequence("originals/2.JPG", "originals/3.JPG", "originals/4.JPG");
|
||||
var plan = Plan(manifest, "{n:0}");
|
||||
Assert.SequenceEqual(["originals/2.JPG>originals/1.JPG", "originals/3.JPG>originals/2.JPG", "originals/4.JPG>originals/3.JPG"],
|
||||
plan.Moves.Select(m => $"{m.From}>{m.To}"));
|
||||
|
||||
var stray = Plan(manifest, "{n:0}", extra: ["originals/1.jpg", "originals/notes.txt"]);
|
||||
Assert.Equal("originals/1_2.JPG", stray.Moves[0].To);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PhotosInPlaceUnhashedOrMissingKeepTheirNamesAndHoldThem()
|
||||
{
|
||||
var manifest = Sequence("IMG_0001.JPG", "originals/IMG_0002.JPG", "originals/IMG_0003.JPG", "originals/IMG_0004.JPG");
|
||||
manifest = manifest with { Frames = [manifest.Frames[0], manifest.Frames[1] with { Sha256 = null }, manifest.Frames[2], manifest.Frames[3]] };
|
||||
// The third photo is not on disk; the fourth would take its name.
|
||||
var plan = FileRenames.Plan(manifest, "IMG_0003", PathTemplate.Parse("{title}"), ["IMG_0001.JPG", "originals/IMG_0002.JPG", "originals/IMG_0004.JPG"]);
|
||||
Assert.SequenceEqual([(RenameBlock.InPlace, 1), (RenameBlock.Unhashed, 1), (RenameBlock.Missing, 1)], plan.Blocked.Select(b => (b.Reason, b.Frames)));
|
||||
Assert.Equal("originals/IMG_0004.JPG>originals/IMG_0003_2.JPG", plan.Moves.Select(m => $"{m.From}>{m.To}").Single());
|
||||
Assert.Equal(1, plan.Frames);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CompanionsFollowTheirPhotoAndTheirNamesAreKeptFree()
|
||||
{
|
||||
var manifest = Sequence("originals/A.CR2", "originals/B.CR2");
|
||||
var plan = Plan(manifest, "{n:0000}", extra: ["originals/A.xmp", "originals/B.CR2.xmp", "originals/0001.xmp"]);
|
||||
// "0001.xmp" belongs to no frame: the first photo, whose companion would take it, gets the next free name.
|
||||
Assert.SequenceEqual(["originals/A.CR2>originals/0001_2.CR2", "originals/A.xmp>originals/0001_2.xmp",
|
||||
"originals/B.CR2>originals/0002.CR2", "originals/B.CR2.xmp>originals/0002.CR2.xmp"], plan.Moves.Select(m => $"{m.From}>{m.To}"));
|
||||
Assert.SequenceEqual([false, true, false, true], plan.Moves.Select(m => m.Companion));
|
||||
Assert.Equal(2, plan.Frames);
|
||||
Assert.Count(2, plan.Samples);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheTrashAndReorganizeFindTheSameCompanionsWhateverTheirCase()
|
||||
{
|
||||
var sequence = Folder(out _);
|
||||
var manifest = Sequence("originals/A.CR2", "originals/B.CR2");
|
||||
foreach (var file in new[] { "originals/A.CR2", "originals/B.CR2", "originals/a.XMP", "originals/b.cr2.Xmp", "originals/c.xmp" }) Write(sequence, file, file);
|
||||
var present = FileRenames.ListPresent(sequence, manifest);
|
||||
var plan = FileRenames.Plan(manifest, null, PathTemplate.Parse("{n:0000}"), present);
|
||||
Assert.SequenceEqual(["originals/A.CR2>originals/0001.CR2", "originals/a.XMP>originals/0001.XMP", "originals/B.CR2>originals/0002.CR2",
|
||||
"originals/b.cr2.Xmp>originals/0002.cr2.Xmp"], plan.Moves.Select(m => $"{m.From}>{m.To}"));
|
||||
var index = new FrameCompanions.Index(sequence);
|
||||
Assert.SequenceEqual(["originals/a.XMP"], index.Of("originals/A.CR2"));
|
||||
Assert.SequenceEqual(["originals/b.cr2.Xmp"], index.Of("originals/B.CR2"));
|
||||
Assert.SequenceEqual(plan.Moves.Where(m => m.Companion).Select(m => m.From), manifest.Frames.SelectMany(f => FrameCompanions.Of(sequence, f.File)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void NamesGivenOnceStayAsTheyAre()
|
||||
{
|
||||
var manifest = Sequence("originals/x.JPG", "originals/y.JPG");
|
||||
var plan = Plan(manifest, "{date}_{n:000}");
|
||||
var renamed = FileRenameJournal.Applied(manifest, FileRenameJournal.Create(manifest.Versions.Frames, plan.Moves, "t"))!;
|
||||
Assert.Equal(manifest.Versions.Frames + 1, renamed.Versions.Frames);
|
||||
Assert.SequenceEqual(manifest.Frames.Select(f => f.Id), renamed.Frames.Select(f => f.Id));
|
||||
Assert.Empty(Plan(renamed, "{date}_{n:000}").Moves);
|
||||
Assert.Null(FileRenameJournal.Applied(renamed, FileRenameJournal.Create(manifest.Versions.Frames, plan.Moves, "t")));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void APlanWithAFileTemplateCountsSamplesAndListsWhatKeepsItsName()
|
||||
{
|
||||
var renamed = Sequence("originals/a.JPG", "originals/b.JPG");
|
||||
var adopted = Sequence("a.JPG");
|
||||
var subjects = new[]
|
||||
{
|
||||
new RenameSubject(renamed.Id, "s/one", "Trip", Start, "Canon", "Canon EOS R5", null) { Files = new SequenceFiles(renamed, [.. renamed.Frames.Select(f => f.File)]) },
|
||||
new RenameSubject(adopted.Id, "s/two", "Adopted", Start, "Canon", "Canon EOS R5", null) { Files = new SequenceFiles(adopted, ["a.JPG"]) },
|
||||
new RenameSubject(Guid.NewGuid(), "s/three", null, Start, "Canon", "Canon EOS R5", null),
|
||||
};
|
||||
var plan = RenamePlanner.Plan(Guid.NewGuid(), subjects, null, "{title} 2026", ["s/one", "s/two", "s/three"], _ => false, fileTemplate: "{title}_{n:00}");
|
||||
Assert.Equal("{title}_{n:00}", plan.FileTemplate);
|
||||
Assert.SequenceEqual(subjects.Select(s => s.SequenceId), plan.Subjects);
|
||||
var one = plan.Steps.Single(s => s.SequenceId == renamed.Id);
|
||||
Assert.Equal((2, 4), (one.FileChanges, one.FramesVersion));
|
||||
// The new title names the files.
|
||||
Assert.SequenceEqual(["originals/Trip 2026_01.JPG", "originals/Trip 2026_02.JPG"], one.FileSamples.Select(f => f.To));
|
||||
var two = plan.Steps.Single(s => s.SequenceId == adopted.Id);
|
||||
Assert.Equal((0, 0), (two.FileChanges, two.FramesVersion));
|
||||
Assert.Equal((RenameBlock.InPlace, 1), (two.Blocked.Single().Reason, two.Blocked.Single().Frames));
|
||||
Assert.True(two.Changes, "its title changes");
|
||||
var three = plan.Steps.Single(s => s.SequenceId == subjects[2].SequenceId);
|
||||
Assert.Equal(RenameBlock.Unreadable, three.Blocked.Single().Reason);
|
||||
|
||||
// Nothing but kept names: listed, changes nothing.
|
||||
var keptOnly = RenamePlanner.Plan(Guid.NewGuid(), [subjects[1]], null, null, ["s/two"], _ => false, fileTemplate: "{n}");
|
||||
Assert.False(keptOnly.Steps.Single().Changes);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FoldersTheTemplateGaveAlreadyStayAndASecondRunPlansNothing()
|
||||
{
|
||||
// Two sequences of one day filed by the template, the second beside the first; a third elsewhere, a fourth whose
|
||||
// folder differs only in case, a fifth with a number filing never gives.
|
||||
const string Template = "{year}/{date} {title}";
|
||||
RenameSubject At(string folder) => new(Guid.NewGuid(), folder, "Sunset", Start, null, null, null);
|
||||
RenameSubject[] subjects = [At("2026/2026-09-28 Sunset"), At("2026/2026-09-28 Sunset (2)"), At("inbox/c"), At("2026/2026-09-28 sunset (4)"),
|
||||
At("2026/2026-09-28 Sunset (03)")];
|
||||
var plan = RenamePlanner.Plan(Guid.NewGuid(), subjects, Template, null, subjects.Select(s => s.Folder), _ => false);
|
||||
Assert.SequenceEqual([(subjects[2].SequenceId, "2026/2026-09-28 Sunset (3)"), (subjects[3].SequenceId, "2026/2026-09-28 Sunset (4)"),
|
||||
(subjects[4].SequenceId, "2026/2026-09-28 Sunset (5)")], plan.Steps.Select(s => (s.SequenceId, s.ToFolder)));
|
||||
|
||||
// Where the plan put them, the same template changes nothing.
|
||||
var moved = plan.Steps.ToDictionary(s => s.SequenceId, s => s.ToFolder);
|
||||
RenameSubject[] after = [.. subjects.Select(s => moved.TryGetValue(s.SequenceId, out var to) ? s with { Folder = to } : s)];
|
||||
var onDisk = after.Select(s => s.Folder).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
Assert.Empty(RenamePlanner.Plan(Guid.NewGuid(), after, Template, null, onDisk, onDisk.Contains).Steps);
|
||||
// Nor in another order.
|
||||
Assert.Empty(RenamePlanner.Plan(Guid.NewGuid(), [.. after.Reverse()], Template, null, onDisk, onDisk.Contains).Steps);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheFingerprintFollowsWhatThePlanChanges()
|
||||
{
|
||||
var manifest = Sequence("originals/a.JPG");
|
||||
RenamePlan Make(SequenceManifest m) => RenamePlanner.Plan(Guid.NewGuid(), [new RenameSubject(m.Id, "s", "T", Start, null, null, null)
|
||||
{ Files = new SequenceFiles(m, [.. m.Frames.Select(f => f.File)]) }], null, null, ["s"], _ => false, fileTemplate: "{n:000}");
|
||||
var plan = Make(manifest);
|
||||
Assert.Equal(64, plan.Fingerprint().Length);
|
||||
Assert.Equal(plan.Fingerprint(), Make(manifest).Fingerprint());
|
||||
// A photo received since under the name the plan gives it raises the frames version only: the plan is the one shown.
|
||||
var received = manifest with
|
||||
{
|
||||
Versions = new ManifestVersions { Frames = 5 },
|
||||
Frames = [.. manifest.Frames, manifest.Frames[0] with { Id = Guid.NewGuid(), I = 1, File = "originals/002.JPG", CapturedAt = Start.AddSeconds(10) }],
|
||||
};
|
||||
Assert.Equal(plan.Fingerprint(), Make(received).Fingerprint());
|
||||
// One the plan would rename too, or a file renamed otherwise, is another plan.
|
||||
Assert.NotEqual(plan.Fingerprint(), Make(received with { Frames = [.. received.Frames.SkipLast(1), received.Frames[1] with { File = "originals/b.JPG" }] }).Fingerprint());
|
||||
Assert.NotEqual(plan.Fingerprint(), Make(manifest with { Frames = [manifest.Frames[0] with { File = "originals/c.JPG" }] }).Fingerprint());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AStepNamedAfterTheTitleSaysSo()
|
||||
{
|
||||
var manifest = Sequence("originals/a.JPG");
|
||||
RenameStep Step(string? folder, string? file) => RenamePlanner.Plan(Guid.NewGuid(), [new RenameSubject(manifest.Id, "s", "Roof", Start, null, null, null)
|
||||
{ Files = new SequenceFiles(manifest, [.. manifest.Frames.Select(f => f.File)]) }], folder, null, ["s"], _ => false, fileTemplate: file).Steps.Single();
|
||||
Assert.True(Step("moved/{TITLE}", null) is { MovesFolder: true, NamedByTitle: true, UsesTitle: true, Retitles: false });
|
||||
Assert.True(Step(null, "{title}_{n:000}") is { FileChanges: 1, NamedByTitle: true, UsesTitle: true });
|
||||
Assert.True(Step("moved/{date}", "{n:000}") is { MovesFolder: true, FileChanges: 1, NamedByTitle: false, UsesTitle: false });
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void APlanKeepsItsTemplatesSoTheNamesOfAFirstPhotoNoLongerFirstAreTold()
|
||||
{
|
||||
const string Folder = "moved/{date} {title}", Title = "{title} {time}";
|
||||
var manifest = Sequence("originals/a.JPG", "originals/b.JPG");
|
||||
// Another sequence holds the folder the template gives: this one takes its " (2)".
|
||||
var plan = RenamePlanner.Plan(Guid.NewGuid(), [new RenameSubject(manifest.Id, "s", "Roof", Start, null, null, null)
|
||||
{ Files = new SequenceFiles(manifest, [.. manifest.Frames.Select(f => f.File)]) }], Folder, Title, ["s", "moved/2026-09-28 Roof 18-00-00"], _ => false);
|
||||
Assert.Equal((Folder, Title, (string?)null), (plan.FolderTemplate, plan.TitleTemplate, plan.FileTemplate));
|
||||
var step = plan.Steps.Single();
|
||||
Assert.Equal(("moved/2026-09-28 Roof 18-00-00 (2)", "Roof 18-00-00"), (step.ToFolder, step.ToTitle));
|
||||
|
||||
// From the sidecar as it was, the templates give what the plan gives; with its first photo gone, they name it otherwise.
|
||||
var (title, folder) = RenamePlanner.Names(manifest, "Roof", Folder, Title);
|
||||
Assert.Equal(("Roof 18-00-00", "moved/2026-09-28 Roof 18-00-00"), (title, folder));
|
||||
Assert.True(RenamePlanner.Gives(folder!, step.ToFolder));
|
||||
var (laterTitle, laterFolder) = RenamePlanner.Names(manifest with { Frames = [manifest.Frames[1]] }, "Roof", Folder, Title);
|
||||
Assert.Equal(("Roof 18-00-10", "moved/2026-09-28 Roof 18-00-10"), (laterTitle, laterFolder));
|
||||
Assert.False(RenamePlanner.Gives(laterFolder!, step.ToFolder));
|
||||
// Without templates, the title stays and no folder is given.
|
||||
Assert.Equal(("Roof", (string?)null), RenamePlanner.Names(manifest, "Roof", null, null));
|
||||
|
||||
// Only the folder itself or a number filing gives.
|
||||
Assert.True(RenamePlanner.Gives("a/b", "a/b"));
|
||||
Assert.True(RenamePlanner.Gives("a/b", "a/b (12)"));
|
||||
Assert.False(RenamePlanner.Gives("a/b", "a/b (1)"));
|
||||
Assert.False(RenamePlanner.Gives("a/b", "a/b (02)"));
|
||||
Assert.False(RenamePlanner.Gives("a/b", "A/b"));
|
||||
Assert.False(RenamePlanner.Gives("a/b", "a/b (2) x"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TemplatesAreCheckedAsTheArchiveSettingsAre()
|
||||
{
|
||||
Assert.Null(new RenameTemplates("{year}/{title}", "{date}_{n}", "{title} 2026").Problem());
|
||||
Assert.Null(new RenameTemplates(File: "{name}.{ext}", Title: "Paris: {title}?").Problem());
|
||||
Assert.Equal("folderTemplate", new RenameTemplates(Folder: " ").Problem());
|
||||
Assert.Equal("fileTemplate", new RenameTemplates(File: "{nope}").Problem());
|
||||
Assert.Equal("fileTemplate", new RenameTemplates(File: "{date:%}").Problem());
|
||||
Assert.Equal("titleTemplate", new RenameTemplates(Title: "{title").Problem());
|
||||
// Not valid, blank or written with an unusable format: no rule to name.
|
||||
Assert.Equal(new TemplateProblem("fileTemplate", null), new RenameTemplates(File: "{date:%}").Check());
|
||||
Assert.True(new RenameTemplates().IsEmpty);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case("{n}{ext}", "fileTemplate", "Extension")]
|
||||
[Case("{date}_{n}_{ext}", "fileTemplate", "Extension")]
|
||||
[Case("{title}", "fileTemplate", "NotUnique")]
|
||||
[Case("{date}_{hm}", "fileTemplate", "NotUnique")]
|
||||
[Case("{year}/{n}", "fileTemplate", "FileSeparator")]
|
||||
[Case("Originals/{date:yyyy}/{title}", "folderTemplate", "ReservedFolder")]
|
||||
[Case("{year}/exports", "folderTemplate", "ReservedFolder")]
|
||||
[Case(".archive/{date}", "folderTemplate", "ReservedFolder")]
|
||||
[Case("{date:.yyyy}", "folderTemplate", "ReservedFolder")]
|
||||
public void TemplatesThatWouldLoseOrHidePhotosAreRefused(string template, string field, string rule)
|
||||
{
|
||||
var folder = field == "folderTemplate";
|
||||
var templates = folder ? new RenameTemplates(Folder: template) : new RenameTemplates(File: template);
|
||||
Assert.Equal(field, templates.Problem());
|
||||
Assert.Equal(new TemplateProblem(field, rule), templates.Check());
|
||||
Assert.Equal(rule, folder ? TemplateRules.FolderRule(PathTemplate.Parse(template)) : TemplateRules.FileRule(PathTemplate.Parse(template)));
|
||||
}
|
||||
|
||||
/// <summary>A sidecar of <paramref name="files"/>, each photo's first capture time <paramref name="first"/> (none when null), titled <paramref name="title"/>.</summary>
|
||||
private static RenameSubject Filed(string folder, string? title, DateTime? first, params string[] files)
|
||||
{
|
||||
var manifest = Sequence(files) with { Title = title, Created = new DateTimeOffset(2026, 10, 1, 9, 30, 0, TimeSpan.Zero) };
|
||||
manifest = manifest with { Frames = [.. manifest.Frames.Select(f => f with { CapturedAt = first?.AddSeconds(10 * f.I) })] };
|
||||
return new RenameSubject(manifest.Id, folder, title, first, "Canon", "Canon EOS R5", null)
|
||||
{
|
||||
Files = new SequenceFiles(manifest, [.. manifest.Frames.Select(f => f.File)]),
|
||||
};
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case("{year}/{date} {ext}", "2026/2026-09-28 CR2", "2026/2026-09-28 JPG")]
|
||||
[Case("{date} {name}", "2026-09-28 IMG_0001", "2026-09-28 IMG_0001 (2)")]
|
||||
[Case("{year}/{date} {camera} {iso}", "2026/2026-09-28 Canon EOS R5", "2026/2026-09-28 Canon EOS R5 (2)")]
|
||||
public void FoldersFiledFromTheFirstPhotoStayWhereFilingPutThem(string template, string raw, string jpeg)
|
||||
{
|
||||
// RAW and JPEG of one day, filed by the template from their first photo ({ext}, {name}… are that photo's).
|
||||
RenameSubject[] subjects =
|
||||
[
|
||||
Filed(raw, null, Start, "originals/2026-09-28_0001.CR2", "originals/2026-09-28_0002.CR2"),
|
||||
Filed(jpeg, null, Start, "originals/2026-09-28_0001.JPG", "originals/2026-09-28_0002.JPG"),
|
||||
];
|
||||
var folders = subjects.Select(s => s.Folder).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
Assert.Empty(RenamePlanner.Plan(Guid.NewGuid(), subjects, template, null, folders, folders.Contains).Steps);
|
||||
// The context filing saw: the folder each first frame gives.
|
||||
var context = FrameNaming.Context(subjects[0].Files!.Manifest.Frames[0], subjects[0].Files!.Manifest, null);
|
||||
Assert.Equal(raw.Replace(" (2)", string.Empty, StringComparison.Ordinal), PathTemplate.Parse(template).ExpandFolder(context));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ASequenceWithoutACaptureTimeNeverTakesTodaysDate()
|
||||
{
|
||||
// No time in the sidecar: the day the sequence was made, as its files are named; no sidecar and no time: no move.
|
||||
var timeless = Filed("inbox/a", null, null, "originals/a.JPG");
|
||||
var plan = RenamePlanner.Plan(Guid.NewGuid(), [timeless], "{date}", null, ["inbox/a"], _ => false);
|
||||
Assert.Equal("2026-10-01", plan.Steps.Single().ToFolder);
|
||||
var row = new RenameSubject(Guid.NewGuid(), "inbox/b", "B", null, null, null, null);
|
||||
Assert.Empty(RenamePlanner.Plan(Guid.NewGuid(), [row], "{date}", "{title} {date}", ["inbox/b"], _ => false).Steps);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ASequenceWhoseSidecarCannotBeReadStaysAsItIsAndSoDoesTheFolderAroundIt()
|
||||
{
|
||||
var a = Filed("a", "A", Start, "originals/a.JPG");
|
||||
// Unreadable, titled as D: had it been planned, D would get " (2)".
|
||||
var unreadable = new RenameSubject(Guid.NewGuid(), "u", "D", Start, null, null, null) { Unreadable = true };
|
||||
var carrier = Filed("c", "C", Start, "originals/c.JPG");
|
||||
var inner = new RenameSubject(Guid.NewGuid(), "c/n", "N", Start, null, null, null) { Unreadable = true };
|
||||
var d = Filed("d", "D", Start, "originals/d.JPG");
|
||||
var plan = RenamePlanner.Plan(Guid.NewGuid(), [a, unreadable, carrier, d], "moved/{title}", "{title} 2026", ["a", "u", "c", "c/n", "d"], _ => false,
|
||||
[inner]);
|
||||
var steps = plan.Steps.ToDictionary(s => s.SequenceId);
|
||||
Assert.Equal(("moved/A 2026", "A 2026"), (steps[a.SequenceId].ToFolder, steps[a.SequenceId].ToTitle));
|
||||
Assert.Equal(("moved/D 2026", "D 2026"), (steps[d.SequenceId].ToFolder, steps[d.SequenceId].ToTitle));
|
||||
foreach (var kept in new[] { unreadable, inner })
|
||||
{
|
||||
var step = steps[kept.SequenceId];
|
||||
Assert.Equal((kept.Folder, kept.Title), (step.ToFolder, step.ToTitle));
|
||||
Assert.False(step.Changes);
|
||||
Assert.Equal(RenameBlock.Unreadable, step.Blocked.Single().Reason);
|
||||
}
|
||||
// Its own sidecar reads: the title changes, the folder cannot take the sequence inside along.
|
||||
Assert.Equal(("c", "C 2026"), (steps[carrier.SequenceId].ToFolder, steps[carrier.SequenceId].ToTitle));
|
||||
Assert.False(steps[inner.SequenceId].Carried);
|
||||
|
||||
// With a file template, a sequence without its sidecar's files stays too.
|
||||
var noFiles = new RenameSubject(Guid.NewGuid(), "x", "X", Start, null, null, null);
|
||||
var files = RenamePlanner.Plan(Guid.NewGuid(), [noFiles], "moved/{title}", null, ["x"], _ => false, fileTemplate: "{n}");
|
||||
Assert.Equal(("x", false), (files.Steps.Single().ToFolder, files.Steps.Single().Changes));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AFolderATitleWouldHideFromScansIsEscapedAndFound()
|
||||
{
|
||||
var archive = new ArchivePaths(context.CreateTempDirectory("archive"));
|
||||
var originals = archive.FromRelative("inbox/a/originals");
|
||||
Directory.CreateDirectory(originals);
|
||||
File.WriteAllBytes(Path.Combine(originals, "IMG_0001.JPG"), TestPhotos.Jpeg(Start, 1));
|
||||
var subject = new RenameSubject(Guid.NewGuid(), "inbox/a", "Exports", Start, null, null, null);
|
||||
var step = RenamePlanner.Plan(Guid.NewGuid(), [subject], "{year}/{title}", null, ["inbox/a"], _ => false).Steps.Single();
|
||||
Assert.Equal("2026/_Exports", step.ToFolder);
|
||||
RenamePlanner.MoveFolder(archive, step);
|
||||
Assert.SequenceEqual(["2026/_Exports"], ArchiveScanner.FindSequenceFolders(archive).Select(f => f.RelativeFolder));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TitlesKeepWhatAFileNameCannotHold()
|
||||
{
|
||||
var paris = new RenameSubject(Guid.NewGuid(), "s/paris", "Paris: night", Start, null, null, null);
|
||||
var plan = RenamePlanner.Plan(Guid.NewGuid(), [paris], "{title}", "{title} 2026", ["s/paris"], _ => false);
|
||||
// The title is text; the folder it names is a file name.
|
||||
Assert.Equal(("Paris: night 2026", "Paris_ night 2026"), (plan.Steps.Single().ToTitle, plan.Steps.Single().ToFolder));
|
||||
Assert.Empty(RenamePlanner.Plan(Guid.NewGuid(), [paris with { Folder = "Paris_ night" }], "{title}", "{title}", ["Paris_ night"], _ => false).Steps);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TwoFoldersThatDifferOnlyInCaseAreNeverGivenOneFolder()
|
||||
{
|
||||
// A case-sensitive server: "trip (2)" and "TRIP (2)" are two folders, both of which "Trip (2)" would keep.
|
||||
RenameSubject At(string folder) => new(Guid.NewGuid(), folder, "Trip", Start, null, null, null);
|
||||
RenameSubject[] subjects = [At("trip (2)"), At("TRIP (2)")];
|
||||
var onDisk = new HashSet<string>(["trip (2)", "TRIP (2)"], StringComparer.Ordinal);
|
||||
var plan = RenamePlanner.Plan(Guid.NewGuid(), subjects, "{title}", null, onDisk, onDisk.Contains);
|
||||
var targets = plan.Steps.Select(s => s.ToFolder).ToList();
|
||||
Assert.SequenceEqual(["Trip (2)", "Trip"], targets);
|
||||
|
||||
// Where they went, the same template changes nothing.
|
||||
RenameSubject[] after = [.. subjects.Zip(targets, (s, t) => s with { Folder = t })];
|
||||
var moved = new HashSet<string>(targets, StringComparer.Ordinal);
|
||||
Assert.Empty(RenamePlanner.Plan(Guid.NewGuid(), after, "{title}", null, moved, moved.Contains).Steps);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ACaseOnlyMoveOntoAnotherFolderIsRefused()
|
||||
{
|
||||
var archive = new ArchivePaths(context.CreateTempDirectory("archive"));
|
||||
Directory.CreateDirectory(archive.FromRelative("trip (2)"));
|
||||
File.WriteAllText(Path.Combine(archive.FromRelative("trip (2)"), "a.txt"), "a");
|
||||
var step = new RenameStep(Guid.NewGuid(), "trip (2)", "Trip (2)", "Trip", "Trip");
|
||||
if (Directory.Exists(archive.FromRelative("TRIP (2)")))
|
||||
{
|
||||
// Case-insensitive: the folder takes the new case, and the step repeated finds it done.
|
||||
RenamePlanner.MoveFolder(archive, step);
|
||||
RenamePlanner.MoveFolder(archive, step);
|
||||
Assert.SequenceEqual(["Trip (2)"], Directory.EnumerateDirectories(archive.Root).Select(Path.GetFileName));
|
||||
Assert.Equal("a", File.ReadAllText(Path.Combine(archive.FromRelative("Trip (2)"), "a.txt")));
|
||||
}
|
||||
else
|
||||
{
|
||||
// Case-sensitive: another folder holds the new name exactly; neither moves.
|
||||
Directory.CreateDirectory(archive.FromRelative("Trip (2)"));
|
||||
Assert.Throws<IOException>(() => RenamePlanner.MoveFolder(archive, step));
|
||||
Assert.Equal("a", File.ReadAllText(Path.Combine(archive.FromRelative("trip (2)"), "a.txt")));
|
||||
Assert.Empty(Directory.EnumerateFileSystemEntries(archive.FromRelative("Trip (2)")));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AChangeOfCaseIsNeverPlannedOntoAnotherFolderOfThatExactName()
|
||||
{
|
||||
// A case-sensitive server: "Trip (2)" is a folder of its own beside the sequence at "trip (2)", and no sequence's.
|
||||
var subject = new RenameSubject(Guid.NewGuid(), "trip (2)", "Trip", Start, null, null, null);
|
||||
var onDisk = new HashSet<string>(["trip (2)", "Trip (2)"], StringComparer.Ordinal);
|
||||
var plan = RenamePlanner.Plan(Guid.NewGuid(), [subject], "{title}", null, ["trip (2)"], onDisk.Contains, existsExactly: onDisk.Contains);
|
||||
Assert.Equal("Trip", plan.Steps.Single().ToFolder);
|
||||
|
||||
// Case-insensitive, the only folder of that name is its own: it keeps its number, in the template's case.
|
||||
var own = RenamePlanner.Plan(Guid.NewGuid(), [subject], "{title}", null, ["trip (2)"], f => f.Equals("trip (2)", StringComparison.OrdinalIgnoreCase),
|
||||
existsExactly: f => f == "trip (2)");
|
||||
Assert.Equal("Trip (2)", own.Steps.Single().ToFolder);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AFolderExistsExactlyOnlyInTheCaseOfEveryLevel()
|
||||
{
|
||||
var archive = new ArchivePaths(context.CreateTempDirectory("archive"));
|
||||
Directory.CreateDirectory(archive.FromRelative("trip/day"));
|
||||
File.WriteAllText(Path.Combine(archive.FromRelative("trip/day"), "a.txt"), "a");
|
||||
Assert.True(RenamePlanner.ExistsExactly(archive, "trip/day"));
|
||||
Assert.False(RenamePlanner.ExistsExactly(archive, "Trip/day"));
|
||||
Assert.False(RenamePlanner.ExistsExactly(archive, "trip/Day"));
|
||||
Assert.False(RenamePlanner.ExistsExactly(archive, "trip/night"));
|
||||
|
||||
// An outer level's case alone: the folder moves on any file system (a case-insensitive one keeps the outer name as it was).
|
||||
var step = new RenameStep(Guid.NewGuid(), "trip/day", "Trip/day", "T", "T");
|
||||
RenamePlanner.MoveFolder(archive, step);
|
||||
RenamePlanner.MoveFolder(archive, step);
|
||||
Assert.Equal("a", File.ReadAllText(Path.Combine(archive.FromRelative("Trip/day"), "a.txt")));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AFolderTheDiskSpellsAsTheTemplateDoesIsTheSequencesOwn()
|
||||
{
|
||||
// A case-insensitive file system: the index has "trip (2)" and "Trip/day", the disk spells them "Trip (2)" (renamed in
|
||||
// Explorer since the last scan) and "trip/day" (an outer level a change of case left as it was). The folders found
|
||||
// under the template's exact names are the sequences' own: a change of case is all the plan makes, never " (n)".
|
||||
var disk = new HashSet<string>(["Trip", "Trip (2)", "trip", "trip/day"], StringComparer.Ordinal);
|
||||
bool OnDisk(string f) => disk.Contains(f, StringComparer.OrdinalIgnoreCase);
|
||||
var renamed = new RenameSubject(Guid.NewGuid(), "trip (2)", "Trip", Start, null, null, null);
|
||||
var plan = RenamePlanner.Plan(Guid.NewGuid(), [renamed], "{title}", null, ["trip (2)", "Trip"], OnDisk, existsExactly: disk.Contains);
|
||||
Assert.Equal("Trip (2)", plan.Steps.Single().ToFolder);
|
||||
var outer = new RenameSubject(Guid.NewGuid(), "Trip/day", "day", Start, null, null, null);
|
||||
plan = RenamePlanner.Plan(Guid.NewGuid(), [outer], "trip/day", null, ["Trip/day"], OnDisk, existsExactly: disk.Contains);
|
||||
Assert.Equal("trip/day", plan.Steps.Single().ToFolder);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ACaseOnlyTargetOnDiskIsRefusedOnlyBesideTheSequencesOwnFolder()
|
||||
{
|
||||
var archive = new ArchivePaths(context.CreateTempDirectory("archive"));
|
||||
foreach (var folder in (string[])["Trip", "Trip (2)", "walk/day"])
|
||||
{
|
||||
Directory.CreateDirectory(archive.FromRelative(folder));
|
||||
File.WriteAllText(Path.Combine(archive.FromRelative(folder), "a.txt"), folder);
|
||||
}
|
||||
// The index has "trip (2)" and "Walk/day": on a case-sensitive file system those are folders of their own beside the
|
||||
// ones the template names.
|
||||
var caseSensitive = !Directory.Exists(archive.FromRelative("trip (2)"));
|
||||
if (caseSensitive)
|
||||
{
|
||||
Directory.CreateDirectory(archive.FromRelative("trip (2)"));
|
||||
Directory.CreateDirectory(archive.FromRelative("Walk/day"));
|
||||
}
|
||||
bool OnDisk(string f) => Directory.Exists(archive.FromRelative(f));
|
||||
bool Exactly(string f) => RenamePlanner.ExistsExactly(archive, f);
|
||||
var renamed = new RenameSubject(Guid.NewGuid(), "trip (2)", "Trip", Start, null, null, null);
|
||||
var outer = new RenameSubject(Guid.NewGuid(), "Walk/day", "day", Start, null, null, null);
|
||||
var first = RenamePlanner.Plan(Guid.NewGuid(), [renamed], "{title}", null, ["trip (2)", "Trip", "Walk/day"], OnDisk, existsExactly: Exactly).Steps.Single();
|
||||
var second = RenamePlanner.Plan(Guid.NewGuid(), [outer], "walk/day", null, ["trip (2)", "Trip", "Walk/day"], OnDisk, existsExactly: Exactly).Steps.Single();
|
||||
if (caseSensitive)
|
||||
{
|
||||
Assert.Equal(("Trip (3)", "walk/day (2)"), (first.ToFolder, second.ToFolder));
|
||||
return;
|
||||
}
|
||||
// Case-insensitive: each sequence keeps its own folder, which is already as the template spells it, so applying the
|
||||
// steps (twice, as a resumed plan does) moves nothing and loses nothing.
|
||||
Assert.Equal(("Trip (2)", "walk/day"), (first.ToFolder, second.ToFolder));
|
||||
foreach (var step in (RenameStep[])[first, second, first, second]) RenamePlanner.MoveFolder(archive, step);
|
||||
Assert.SequenceEqual(["Trip", "Trip (2)", "walk"], Directory.EnumerateDirectories(archive.Root).Select(Path.GetFileName).Order(StringComparer.Ordinal));
|
||||
Assert.Equal("Trip (2)", File.ReadAllText(Path.Combine(archive.FromRelative("Trip (2)"), "a.txt")));
|
||||
Assert.Equal("walk/day", File.ReadAllText(Path.Combine(archive.FromRelative("walk/day"), "a.txt")));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PhotosOfALongTitleKeepTheirExtension()
|
||||
{
|
||||
// As long as a title goes, less the room the number and the extension take: the name gives way before ".{ext}".
|
||||
var manifest = Sequence("originals/a.JPG", "originals/b.JPG", "originals/c.JPG");
|
||||
var title = new string('t', 186) + " harbour";
|
||||
const string Template = "{title}_{n:0000}.{ext}";
|
||||
var plan = Plan(manifest, Template, title);
|
||||
Assert.Equal(3, plan.Frames);
|
||||
foreach (var move in plan.Moves)
|
||||
{
|
||||
Assert.True(move.To.EndsWith(".JPG", StringComparison.Ordinal), move.To);
|
||||
Assert.True(Path.GetFileName(move.To).Length <= PathTemplate.MaxSegmentLength + 2, move.To);
|
||||
}
|
||||
Assert.Equal(3, plan.Moves.Select(m => m.To).Distinct(StringComparer.OrdinalIgnoreCase).Count());
|
||||
// Renamed so, the template names them again as they are.
|
||||
var renamed = FileRenameJournal.Applied(manifest, FileRenameJournal.Create(manifest.Versions.Frames, plan.Moves, "t"))!;
|
||||
Assert.Empty(Plan(renamed, Template, title).Moves);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ExtensionsAPhotoLostComeBackFromItsName()
|
||||
{
|
||||
var manifest = Sequence("originals/0001CR3", "originals/0002.CR3");
|
||||
manifest = manifest with { Frames = [.. manifest.Frames.Select(f => f with { Original = $"IMG_{f.I + 1:0000}.CR3" })] };
|
||||
Assert.Equal("CR3", FrameNaming.Context(manifest.Frames[0], manifest, null).Extension);
|
||||
Assert.SequenceEqual(["originals/0001CR3>originals/0001.CR3"], Plan(manifest, "{n:0000}").Moves.Select(m => $"{m.From}>{m.To}"));
|
||||
// A file that has an extension of a photo keeps that one, whatever the card's name said.
|
||||
Assert.Equal("CR3", FrameNaming.Context(manifest.Frames[1] with { Original = "IMG_0002.JPG" }, manifest, null).Extension);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ManyPhotosOfOneNameAreNamedInLinearTimeAsTheSearchFromTwoNamesThem()
|
||||
{
|
||||
// Against the search from _2 it replaces, with names taken by stray files and companions in the way.
|
||||
var taken = new HashSet<string>(["a/x.JPG", "a/x_3.JPG", "a/x_4.xmp"], StringComparer.OrdinalIgnoreCase);
|
||||
var reference = new HashSet<string>(taken, StringComparer.OrdinalIgnoreCase);
|
||||
var names = new UniqueNames(taken);
|
||||
for (var i = 0; i < 12; i++)
|
||||
{
|
||||
// Every third photo has an XMP companion: "x_4" is free for the others, not for it.
|
||||
Func<string, bool> companion = i % 3 == 1 ? c => !reference.Contains(Path.ChangeExtension(c, ".xmp")) : _ => true;
|
||||
var expected = "a/x.JPG";
|
||||
for (var n = 2; reference.Contains(expected) || !companion(expected); n++) expected = FrameNaming.Numbered("a/x.JPG", n);
|
||||
reference.Add(expected);
|
||||
Assert.Equal(expected, names.Claim("a/x.JPG", companion), $"photo {i}");
|
||||
}
|
||||
|
||||
var frames = Enumerable.Range(0, 20_000).Select(i => $"originals/{i:00000}.JPG").ToArray();
|
||||
var manifest = Sequence(frames);
|
||||
var clock = System.Diagnostics.Stopwatch.StartNew();
|
||||
var plan = Plan(manifest, "{title}", title: "Sunset");
|
||||
Assert.True(clock.Elapsed.TotalSeconds < TestTiming.Budget(5), $"{clock.Elapsed.TotalSeconds:0.0} s");
|
||||
Assert.SequenceEqual(["originals/Sunset.JPG", "originals/Sunset_2.JPG", "originals/Sunset_3.JPG"], plan.Samples.Select(s => s.To));
|
||||
Assert.Equal("originals/Sunset_20000.JPG", plan.Moves[^1].To);
|
||||
}
|
||||
|
||||
private SequencePaths Folder(out ArchivePaths archive)
|
||||
{
|
||||
archive = new ArchivePaths(context.CreateTempDirectory("archive"));
|
||||
var sequence = archive.Sequence("s");
|
||||
Directory.CreateDirectory(sequence.Originals);
|
||||
Directory.CreateDirectory(sequence.MetaDirectory);
|
||||
return sequence;
|
||||
}
|
||||
|
||||
private static void Write(SequencePaths sequence, string file, string text) => File.WriteAllText(sequence.File(file), text, Encoding.UTF8);
|
||||
|
||||
private static string Read(SequencePaths sequence, string file) => File.ReadAllText(sequence.File(file), Encoding.UTF8);
|
||||
|
||||
[Test]
|
||||
public void FilesMoveInTwoPhasesSoChainsAndSwapsNeverMeet()
|
||||
{
|
||||
var sequence = Folder(out _);
|
||||
Write(sequence, "originals/a.jpg", "A");
|
||||
Write(sequence, "originals/b.jpg", "B");
|
||||
Write(sequence, "originals/c.jpg", "C");
|
||||
Guid x = Guid.NewGuid(), y = Guid.NewGuid(), z = Guid.NewGuid();
|
||||
// A swap (a↔b) and a chain into a name that frees up (c→a's place is taken by b, so c→d).
|
||||
var journal = FileRenameJournal.Create(7, [new FileRename(x, "originals/a.jpg", "originals/b.jpg"), new FileRename(y, "originals/b.jpg", "originals/a.jpg"),
|
||||
new FileRename(z, "originals/c.jpg", "originals/d.jpg")], "t1");
|
||||
FileRenameJournal.Write(sequence, journal);
|
||||
var done = FileRenameJournal.Run(sequence, journal);
|
||||
Assert.Equal(2, done.Phase);
|
||||
Assert.Equal(("A", "B", "C"), (Read(sequence, "originals/b.jpg"), Read(sequence, "originals/a.jpg"), Read(sequence, "originals/d.jpg")));
|
||||
Assert.FileMissing(sequence.File("originals/c.jpg"));
|
||||
Assert.True(journal.Files.All(f => !File.Exists(sequence.File(f.Temp))));
|
||||
Assert.True(journal.Files.All(f => Path.GetFileName(f.Temp).StartsWith(".chronos-rename-t1-", StringComparison.Ordinal)), "hidden, never a photo");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AFailedMovePutsEveryFileBackAndChangesNothing()
|
||||
{
|
||||
var sequence = Folder(out _);
|
||||
Write(sequence, "originals/a.jpg", "A");
|
||||
Write(sequence, "originals/b.jpg", "B");
|
||||
var journal = FileRenameJournal.Create(1, [new FileRename(Guid.NewGuid(), "originals/a.jpg", "originals/x.jpg"),
|
||||
new FileRename(Guid.NewGuid(), "originals/b.jpg", "originals/y.jpg")], "t2");
|
||||
FileRenameJournal.Write(sequence, journal);
|
||||
// Another file took the second name after the plan: nothing is written over it, and the first file goes back.
|
||||
Write(sequence, "originals/y.jpg", "other");
|
||||
Assert.Throws<IOException>(() => FileRenameJournal.Run(sequence, journal));
|
||||
Assert.Equal(("A", "B", "other"), (Read(sequence, "originals/a.jpg"), Read(sequence, "originals/b.jpg"), Read(sequence, "originals/y.jpg")));
|
||||
Assert.FileMissing(sequence.File("originals/x.jpg"));
|
||||
Assert.Null(FileRenameJournal.Read(sequence));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case(1)]
|
||||
[Case(2)]
|
||||
public void ARenameACrashInterruptedIsCompleted(int phase)
|
||||
{
|
||||
var sequence = Folder(out _);
|
||||
var manifest = Sequence("originals/2.jpg", "originals/3.jpg", "originals/4.jpg");
|
||||
foreach (var f in manifest.Frames) Write(sequence, f.File, f.Id.ToString());
|
||||
var plan = Plan(manifest, "{n:0}");
|
||||
var journal = FileRenameJournal.Create(manifest.Versions.Frames, plan.Moves, "t3") with { Phase = phase };
|
||||
FileRenameJournal.Write(sequence, journal);
|
||||
// Phase 1: the first file reached its temporary name. Phase 2: every file did, and the first its new name.
|
||||
File.Move(sequence.File(journal.Files[0].From), sequence.File(journal.Files[0].Temp));
|
||||
if (phase == 2)
|
||||
{
|
||||
foreach (var f in journal.Files.Skip(1)) File.Move(sequence.File(f.From), sequence.File(f.Temp));
|
||||
File.Move(sequence.File(journal.Files[0].Temp), sequence.File(journal.Files[0].To));
|
||||
}
|
||||
|
||||
var recovered = Assert.NotNull(FileRenameJournal.Recover(sequence, manifest));
|
||||
Assert.SequenceEqual(["originals/1.jpg", "originals/2.jpg", "originals/3.jpg"], recovered.Frames.Select(f => f.File));
|
||||
Assert.Equal(manifest.Versions.Frames + 1, recovered.Versions.Frames);
|
||||
foreach (var f in recovered.Frames) Assert.Equal(f.Id.ToString(), Read(sequence, f.File));
|
||||
Assert.FileMissing(sequence.File("originals/4.jpg"));
|
||||
Assert.True(journal.Files.All(f => !File.Exists(sequence.File(f.Temp))));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A rename of <paramref name="shape"/> (a chain of names that free up, a swap, a cycle of three) a crash interrupted
|
||||
/// in its first phase, once its first file reached its temporary name; each file holds its frame's id.
|
||||
/// </summary>
|
||||
private static (SequenceManifest Manifest, FileRenameJournal Journal) Interrupted(SequencePaths sequence, string shape)
|
||||
{
|
||||
string[][] names = shape switch
|
||||
{
|
||||
"chain" => [["originals/2.jpg", "originals/3.jpg", "originals/4.jpg"], ["originals/1.jpg", "originals/2.jpg", "originals/3.jpg"]],
|
||||
"swap" => [["originals/a.jpg", "originals/b.jpg"], ["originals/b.jpg", "originals/a.jpg"]],
|
||||
_ => [["originals/a.jpg", "originals/b.jpg", "originals/c.jpg"], ["originals/b.jpg", "originals/c.jpg", "originals/a.jpg"]],
|
||||
};
|
||||
var (from, to) = (names[0], names[1]);
|
||||
var manifest = Sequence(from);
|
||||
foreach (var f in manifest.Frames) Write(sequence, f.File, f.Id.ToString());
|
||||
var journal = FileRenameJournal.Create(manifest.Versions.Frames, [.. manifest.Frames.Select((f, i) => new FileRename(f.Id, f.File, to[i]))], "t4");
|
||||
FileRenameJournal.Write(sequence, journal);
|
||||
File.Move(sequence.File(journal.Files[0].From), sequence.File(journal.Files[0].Temp));
|
||||
return (manifest, journal);
|
||||
}
|
||||
|
||||
private static void AssertEveryFrameHoldsItsPhoto(SequencePaths sequence, SequenceManifest recovered)
|
||||
{
|
||||
foreach (var f in recovered.Frames) Assert.Equal(f.Id.ToString(), Read(sequence, f.File));
|
||||
Assert.Empty(Directory.EnumerateFiles(sequence.Originals, ".chronos-rename-*"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case("chain")]
|
||||
[Case("swap")]
|
||||
[Case("cycle")]
|
||||
public void ARecoveryRunAgainLeavesEveryFileWithItsFrame(string shape)
|
||||
{
|
||||
var sequence = Folder(out _);
|
||||
var (manifest, _) = Interrupted(sequence, shape);
|
||||
// Completed, but the sidecar that follows was never written (a full disk, a crash before it): the journal is found again.
|
||||
var first = Assert.NotNull(FileRenameJournal.Recover(sequence, manifest));
|
||||
Assert.Equal(2, Assert.NotNull(FileRenameJournal.Read(sequence)).Phase);
|
||||
var again = Assert.NotNull(FileRenameJournal.Recover(sequence, manifest));
|
||||
Assert.SequenceEqual(first.Frames.Select(f => f.File), again.Frames.Select(f => f.File));
|
||||
Assert.False(manifest.Frames.Select(f => f.File).SequenceEqual(again.Frames.Select(f => f.File)), "every frame has its new name");
|
||||
AssertEveryFrameHoldsItsPhoto(sequence, again);
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void ARecoveryCutShortWhileFilesTakeTheirNewNamesGoesOnFromThere()
|
||||
{
|
||||
var sequence = Folder(out _);
|
||||
var (manifest, journal) = Interrupted(sequence, "chain");
|
||||
// The last file reached its temporary name too, and another program holds it: the recovery stops at it.
|
||||
File.Move(sequence.File(journal.Files[2].From), sequence.File(journal.Files[2].Temp));
|
||||
using (new FileStream(sequence.File(journal.Files[2].Temp), FileMode.Open, FileAccess.Read, FileShare.None))
|
||||
Assert.Throws<IOException>(() => FileRenameJournal.Recover(sequence, manifest));
|
||||
Assert.Equal("originals/1.jpg", journal.Files[0].To);
|
||||
Assert.Equal(manifest.Frames[0].Id.ToString(), Read(sequence, "originals/1.jpg"));
|
||||
|
||||
// Run again, it goes on from there: no file that took its new name moves again.
|
||||
var recovered = Assert.NotNull(FileRenameJournal.Recover(sequence, manifest));
|
||||
Assert.SequenceEqual(["originals/1.jpg", "originals/2.jpg", "originals/3.jpg"], recovered.Frames.Select(f => f.File));
|
||||
AssertEveryFrameHoldsItsPhoto(sequence, recovered);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ANewNameTakenMeanwhileNeverStrandsAPhoto()
|
||||
{
|
||||
var sequence = Folder(out _);
|
||||
var (manifest, journal) = Interrupted(sequence, "chain");
|
||||
// Copied in under the name the second file gets after the crash: never written over. Its own old name is the third
|
||||
// file's new one, so it takes the first free number of that name.
|
||||
Write(sequence, "originals/2.jpg", "other");
|
||||
FileRenameJournal.Delete(sequence);
|
||||
Assert.NotNull(FileRenameJournal.Read(sequence));
|
||||
|
||||
var recovered = Assert.NotNull(FileRenameJournal.Recover(sequence, manifest));
|
||||
Assert.SequenceEqual(["originals/1.jpg", "originals/3_2.jpg", "originals/3.jpg"], recovered.Frames.Select(f => f.File));
|
||||
Assert.Equal("other", Read(sequence, "originals/2.jpg"));
|
||||
AssertEveryFrameHoldsItsPhoto(sequence, recovered);
|
||||
// The new name is in the journal, so a recovery run again finds every file where it is.
|
||||
Assert.Equal("originals/3_2.jpg", Assert.NotNull(FileRenameJournal.Read(sequence)).Files[1].To);
|
||||
Assert.SequenceEqual(recovered.Frames.Select(f => f.File), Assert.NotNull(FileRenameJournal.Recover(sequence, manifest)).Frames.Select(f => f.File));
|
||||
AssertEveryFrameHoldsItsPhoto(sequence, recovered);
|
||||
Assert.Equal(journal.Files.Count, Directory.EnumerateFiles(sequence.Originals).Count() - 1);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void APhotoWhoseCompanionsNewNameIsTakenStaysWithItsCompanion()
|
||||
{
|
||||
var sequence = Folder(out _);
|
||||
var manifest = Sequence("originals/A.CR2");
|
||||
Write(sequence, "originals/A.CR2", "photo");
|
||||
Write(sequence, "originals/A.xmp", "sidecar");
|
||||
var id = manifest.Frames[0].Id;
|
||||
FileRename[] moves = [new(id, "originals/A.CR2", "originals/0001.CR2"), new(id, "originals/A.xmp", "originals/0001.xmp", Companion: true)];
|
||||
var journal = FileRenameJournal.Create(manifest.Versions.Frames, moves, "t5") with { Phase = 2 };
|
||||
FileRenameJournal.Write(sequence, journal);
|
||||
foreach (var f in journal.Files) File.Move(sequence.File(f.From), sequence.File(f.Temp));
|
||||
Write(sequence, "originals/0001.xmp", "other");
|
||||
|
||||
// Both go back to their names, together; the frame keeps its file.
|
||||
Assert.Null(FileRenameJournal.Recover(sequence, manifest));
|
||||
Assert.Equal(("photo", "sidecar", "other"), (Read(sequence, "originals/A.CR2"), Read(sequence, "originals/A.xmp"), Read(sequence, "originals/0001.xmp")));
|
||||
Assert.FileMissing(sequence.File("originals/0001.CR2"));
|
||||
Assert.Empty(Directory.EnumerateFiles(sequence.Originals, ".chronos-rename-*"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void APhotoThatTookItsNewNameGoesBackWithACompanionWhoseNewNameIsTaken()
|
||||
{
|
||||
var sequence = Folder(out _);
|
||||
var manifest = Sequence("originals/A.CR2");
|
||||
Write(sequence, "originals/A.CR2", "photo");
|
||||
Write(sequence, "originals/A.xmp", "sidecar");
|
||||
var id = manifest.Frames[0].Id;
|
||||
FileRename[] moves = [new(id, "originals/A.CR2", "originals/0001.CR2"), new(id, "originals/A.xmp", "originals/0001.xmp", Companion: true)];
|
||||
var journal = FileRenameJournal.Create(manifest.Versions.Frames, moves, "t6") with { Phase = 2 };
|
||||
FileRenameJournal.Write(sequence, journal);
|
||||
foreach (var f in journal.Files) File.Move(sequence.File(f.From), sequence.File(f.Temp));
|
||||
// Stopped once the photo took its new name, before its companion did; then something took the companion's, and the
|
||||
// photo's old name too.
|
||||
File.Move(sequence.File(journal.Files[0].Temp), sequence.File(journal.Files[0].To));
|
||||
Write(sequence, "originals/0001.xmp", "other");
|
||||
Write(sequence, "originals/A.CR2", "another");
|
||||
|
||||
// The photo goes back with its companion, both to the first free number of its old name; the frame names the photo.
|
||||
var recovered = Assert.NotNull(FileRenameJournal.Recover(sequence, manifest));
|
||||
Assert.Equal("originals/A_2.CR2", recovered.Frames.Single().File);
|
||||
Assert.Equal(("photo", "sidecar"), (Read(sequence, "originals/A_2.CR2"), Read(sequence, "originals/A_2.xmp")));
|
||||
Assert.Equal(("other", "another"), (Read(sequence, "originals/0001.xmp"), Read(sequence, "originals/A.CR2")));
|
||||
Assert.FileMissing(sequence.File("originals/0001.CR2"));
|
||||
Assert.Empty(Directory.EnumerateFiles(sequence.Originals, ".chronos-rename-*"));
|
||||
// Run again, every file stays where it is.
|
||||
Assert.Equal("originals/A_2.CR2", Assert.NotNull(FileRenameJournal.Recover(sequence, manifest)).Frames.Single().File);
|
||||
Assert.Equal(("photo", "sidecar"), (Read(sequence, "originals/A_2.CR2"), Read(sequence, "originals/A_2.xmp")));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ADamagedPlanJournalIsSkippedAtOpenAndFailsItsOwnJob()
|
||||
{
|
||||
var archive = new ArchivePaths(context.CreateTempDirectory("archive"));
|
||||
var good = new RenameJournal(new RenamePlan(Guid.NewGuid(), Guid.NewGuid(), []), []);
|
||||
RenameJournal.Write(archive, good);
|
||||
var damaged = Guid.NewGuid();
|
||||
File.WriteAllText(RenameJournal.PathFor(archive, damaged), "{ \"plan\": ");
|
||||
var empty = Guid.NewGuid();
|
||||
File.WriteAllText(RenameJournal.PathFor(archive, empty), "{}");
|
||||
|
||||
// The archive still opens: the readable journal resumes, the others stay where they are.
|
||||
Assert.Equal(good.Plan.Id, RenameJournal.ListPending(archive).Single().Plan.Id);
|
||||
Assert.True(File.Exists(RenameJournal.PathFor(archive, damaged)));
|
||||
// The job of a damaged plan fails with the reason instead of planning again.
|
||||
Assert.Throws<InvalidDataException>(() => RenameJournal.Read(archive, damaged));
|
||||
Assert.Throws<InvalidDataException>(() => RenameJournal.Read(archive, empty));
|
||||
Assert.Null(RenameJournal.Read(archive, Guid.NewGuid()));
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ namespace Chronos.Core.Tests.Archiving;
|
||||
internal static class TestPhotos
|
||||
{
|
||||
public static byte[] Jpeg(DateTime captured, int seed, string make = "Canon", string model = "Canon EOS R5", string? serial = "0431",
|
||||
int width = 48, int height = 32, int orientation = 1)
|
||||
int width = 48, int height = 32, int orientation = 1, string? lens = null)
|
||||
{
|
||||
using var image = new ImageBuffer(width, height);
|
||||
var random = new Random(seed);
|
||||
@@ -28,14 +28,16 @@ internal static class TestPhotos
|
||||
FNumber = 8,
|
||||
Iso = 100,
|
||||
Orientation = orientation,
|
||||
LensModel = lens,
|
||||
});
|
||||
return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 85, App1Segments = [exif[4..]] });
|
||||
}
|
||||
|
||||
public static string Write(string path, DateTime captured, int seed, string make = "Canon", string model = "Canon EOS R5", string? serial = "0431")
|
||||
public static string Write(string path, DateTime captured, int seed, string make = "Canon", string model = "Canon EOS R5", string? serial = "0431",
|
||||
string? lens = null)
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
File.WriteAllBytes(path, Jpeg(captured, seed, make, model, serial));
|
||||
File.WriteAllBytes(path, Jpeg(captured, seed, make, model, serial, lens: lens));
|
||||
return path;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Import;
|
||||
using Chronos.Core.Metadata;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Naming;
|
||||
using Chronos.Core.Tests.Archiving;
|
||||
using Chronos.Testing;
|
||||
using static Chronos.Core.Tests.Import.ImportTestKit;
|
||||
|
||||
namespace Chronos.Core.Tests.Naming;
|
||||
|
||||
/// <summary>Import, upload and Reorganize name a photo alike (owner review 2, R7).</summary>
|
||||
[Category("naming")]
|
||||
public sealed class FrameNamingTests(TestContext context)
|
||||
{
|
||||
private const string EveryToken = "{date}_{time}_{hm}_{sessionstart}_{n:0000}_{nsession}_{camera}_{lens}_{iso}_{shutter}_{aperture}_{name}_{title}";
|
||||
|
||||
private static FrameMetadata Metadata(DateTime captured) => new()
|
||||
{
|
||||
Make = "Canon",
|
||||
Model = "Canon EOS R5",
|
||||
LensModel = "RF15-35mm F2.8 L IS USM",
|
||||
Iso = 400,
|
||||
ExposureTime = 1.0 / 250,
|
||||
FNumber = 8,
|
||||
CapturedAt = captured,
|
||||
TimestampSource = TimestampSource.ExifOriginal,
|
||||
};
|
||||
|
||||
[Test]
|
||||
public void AFrameInItsSequenceIsNamedAsTheUploadOfItsPhotoWas()
|
||||
{
|
||||
var start = new DateTime(2026, 9, 28, 18, 2, 11);
|
||||
var template = PathTemplate.Parse(EveryToken);
|
||||
var frames = Enumerable.Range(0, 3)
|
||||
.Select(i => SequenceFrames.FromMetadata(Guid.NewGuid(), $"originals/x{i}.CR3", $"IMG_{4211 + i}.CR3", 100, new string('a', 64), Metadata(start.AddSeconds(5 * i))))
|
||||
.ToList();
|
||||
var first = Metadata(start);
|
||||
var manifest = SequenceFrames.Insert(new SequenceManifest
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Camera = new SidecarCamera { Make = first.Make, Model = first.Model },
|
||||
Lens = first.LensModel,
|
||||
}, frames);
|
||||
|
||||
for (var i = 0; i < 3; i++)
|
||||
{
|
||||
var filed = template.ExpandFile(FrameNaming.Context(Metadata(start.AddSeconds(5 * i)), $"IMG_{4211 + i}.CR3", start.AddSeconds(5 * i), start, i + 1, "Harbour"));
|
||||
Assert.Equal(filed, template.ExpandFile(FrameNaming.Context(manifest.Frames[i], manifest, "Harbour")));
|
||||
}
|
||||
Assert.Equal("2026-09-28_18-02-16_18-02_2026-09-28 18-02_0002_0002_Canon EOS R5_RF15-35mm F2.8 L IS USM_400_1-250_f8_IMG_4212_Harbour.CR3",
|
||||
template.ExpandFile(FrameNaming.Context(manifest.Frames[1], manifest, "Harbour")));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AFrameWithoutACaptureTimeTakesTheStartOfItsSequence()
|
||||
{
|
||||
var created = new DateTimeOffset(2026, 10, 1, 9, 30, 0, TimeSpan.Zero);
|
||||
var manifest = new SequenceManifest
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Created = created,
|
||||
Frames = [new SidecarFrame { Id = Guid.NewGuid(), File = "originals/a.jpg", Original = "DSC_0001.JPG" }],
|
||||
};
|
||||
var context = FrameNaming.Context(manifest.Frames[0], manifest, null);
|
||||
Assert.Equal(new DateTime(2026, 10, 1, 9, 30, 0), context.CapturedAt);
|
||||
Assert.Equal(context.CapturedAt, context.SessionStart);
|
||||
Assert.Equal("DSC_0001", context.OriginalName);
|
||||
Assert.Equal("jpg", context.Extension);
|
||||
Assert.Equal(1, context.Number);
|
||||
|
||||
// After a first photo that has one, that photo's time.
|
||||
var first = new DateTime(2026, 9, 28, 18, 0, 0);
|
||||
var timed = manifest with
|
||||
{
|
||||
Frames = [manifest.Frames[0] with { CapturedAt = first }, new SidecarFrame { Id = Guid.NewGuid(), I = 1, File = "originals/b.jpg", Original = "DSC_0002.JPG" }],
|
||||
};
|
||||
var second = FrameNaming.Context(timed.Frames[1], timed, null);
|
||||
Assert.Equal((first, first, 2), (second.CapturedAt, second.SessionStart, second.Number));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TakenNamesGetNumbersBeforeTheExtensionAsFilingGivesThem()
|
||||
{
|
||||
var template = PathTemplate.Parse("{date}");
|
||||
var context = FrameNaming.Context(Metadata(new DateTime(2026, 9, 28, 18, 0, 0)), "IMG_1.JPG", new DateTime(2026, 9, 28, 18, 0, 0),
|
||||
new DateTime(2026, 9, 28, 18, 0, 0), 1, null);
|
||||
var taken = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "originals/2026-09-28.jpg" };
|
||||
var names = new UniqueNames(taken);
|
||||
Assert.Equal("originals/2026-09-28_2.JPG", FrameNaming.FileName(template, context, names, "originals/"));
|
||||
Assert.Equal("originals/2026-09-28_3.JPG", FrameNaming.FileName(template, context, names, "originals/"));
|
||||
Assert.Contains("originals/2026-09-28_3.JPG", taken);
|
||||
Assert.Equal("a/IMG_5_2.CR2", new UniqueNames(new HashSet<string>(["a/IMG_5.CR2"])).Claim("a/IMG_5.CR2"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnImportedSessionIsNamedAsReorganizeNamesItsFrames()
|
||||
{
|
||||
var card = context.CreateTempDirectory("card");
|
||||
TestPhotos.WriteSeries(Path.Combine(card, "DCIM", "100CANON"), Start, 4, TimeSpan.FromSeconds(10));
|
||||
const string fileTemplate = "{date}_{time}_{n:0000}_{camera}_{name}";
|
||||
var plan = await PlanAsync(card, context.CreateTempDirectory("archive"), new ImportOptions { FileTemplate = fileTemplate });
|
||||
var session = plan.Sessions.Single();
|
||||
|
||||
var manifest = Filed(card, session);
|
||||
var reorganized = FileRenames.Plan(manifest, session.Title, PathTemplate.Parse(fileTemplate), [.. manifest.Frames.Select(f => f.File)]);
|
||||
Assert.Empty(reorganized.Moves);
|
||||
Assert.Equal(0, reorganized.Frames);
|
||||
Assert.SequenceEqual(session.Items.Select(i => i.FileName),
|
||||
manifest.Frames.Select(f => PathTemplate.Parse(fileTemplate).ExpandFile(FrameNaming.Context(f, manifest, session.Title))));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sequence an import files <paramref name="session"/> of <paramref name="source"/> into: the plan's names, each
|
||||
/// frame from its photo's metadata, the camera and lens of the first.
|
||||
/// </summary>
|
||||
private static SequenceManifest Filed(string source, PlannedSession session)
|
||||
{
|
||||
var frames = session.Items.Select(item => SequenceFrames.FromMetadata(Guid.NewGuid(), "originals/" + item.FileName, Path.GetFileName(item.SourcePath),
|
||||
item.Size, new string('b', 64), MetadataReader.Read(Path.Combine(source, item.SourcePath)), item.CapturedAt)).ToList();
|
||||
var first = MetadataReader.Read(Path.Combine(source, session.Items[0].SourcePath));
|
||||
return SequenceFrames.Insert(new SequenceManifest
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Camera = new SidecarCamera { Make = first.Make, Model = first.Model },
|
||||
Lens = first.LensModel,
|
||||
}, frames);
|
||||
}
|
||||
|
||||
private static List<string> Renames(SequenceManifest manifest, string? title, string template) =>
|
||||
[.. FileRenames.Plan(manifest, title, PathTemplate.Parse(template), [.. manifest.Frames.Select(f => f.File)]).Moves.Select(m => $"{m.From}>{m.To}")];
|
||||
|
||||
[Test]
|
||||
public async Task ASecondSessionOfACardIsNumberedByTheImportAndRenamedByReorganize()
|
||||
{
|
||||
// Two sessions of one card two hours apart: the import numbers them, while each sequence is one session of its own.
|
||||
var card = context.CreateTempDirectory("card");
|
||||
var folder = Path.Combine(card, "DCIM", "100CANON");
|
||||
TestPhotos.WriteSeries(folder, Start, 2, TimeSpan.FromSeconds(10));
|
||||
TestPhotos.WriteSeries(folder, Start.AddHours(2), 2, TimeSpan.FromSeconds(10), firstSeed: 10, firstNumber: 3);
|
||||
const string fileTemplate = "{session}_{n:0000}";
|
||||
var plan = await PlanAsync(card, context.CreateTempDirectory("archive"), new ImportOptions { FileTemplate = fileTemplate, MinimumSessionFrames = 1 });
|
||||
Assert.SequenceEqual(["1_0001.JPG 1_0002.JPG", "2_0001.JPG 2_0002.JPG"], plan.Sessions.Select(s => string.Join(' ', s.Items.Select(i => i.FileName))));
|
||||
|
||||
// A divergence FrameNaming names: Reorganize calls the second sequence's session 1, and its dry run lists the renames.
|
||||
Assert.Empty(Renames(Filed(card, plan.Sessions[0]), plan.Sessions[0].Title, fileTemplate));
|
||||
Assert.SequenceEqual(["originals/2_0001.JPG>originals/1_0001.JPG", "originals/2_0002.JPG>originals/1_0002.JPG"],
|
||||
Renames(Filed(card, plan.Sessions[1]), plan.Sessions[1].Title, fileTemplate));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AWholeFolderOfTwoCamerasNamesEveryPhotoWithTheFirstOnesCamera()
|
||||
{
|
||||
var folder = Path.Combine(context.CreateTempDirectory("source"), "Etna");
|
||||
TestPhotos.WriteSeries(folder, Start, 2, TimeSpan.FromSeconds(10), prefix: "CAN_");
|
||||
TestPhotos.WriteSeries(folder, Start.AddSeconds(5), 2, TimeSpan.FromSeconds(10), firstSeed: 40, prefix: "NIK_", make: "NIKON CORPORATION", model: "NIKON Z 8");
|
||||
const string fileTemplate = "{camera}_{n:0000}";
|
||||
var plan = await PlanAsync(folder, context.CreateTempDirectory("archive"), new ImportOptions { Grouping = ImportGrouping.WholeFolder, FileTemplate = fileTemplate });
|
||||
var session = plan.Sessions.Single();
|
||||
Assert.Equal(2, session.Cameras);
|
||||
Assert.SequenceEqual(["CAN_0001.JPG", "NIK_0001.JPG", "CAN_0002.JPG", "NIK_0002.JPG"], session.Items.Select(i => Path.GetFileName(i.SourcePath)));
|
||||
|
||||
// The sequence carries the first photo's camera, which names every photo of it, the second body's too: Reorganize agrees.
|
||||
Assert.SequenceEqual(["Canon EOS R5_0001.JPG", "Canon EOS R5_0002.JPG", "Canon EOS R5_0003.JPG", "Canon EOS R5_0004.JPG"],
|
||||
session.Items.Select(i => i.FileName));
|
||||
Assert.Empty(Renames(Filed(folder, session), session.Title, fileTemplate));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ALensChangedDuringASessionNamesItsPhotosAsTheirSequenceDoes()
|
||||
{
|
||||
var card = context.CreateTempDirectory("card");
|
||||
var folder = Path.Combine(card, "DCIM", "100CANON");
|
||||
for (var i = 0; i < 4; i++)
|
||||
TestPhotos.Write(Path.Combine(folder, $"IMG_{i + 1:0000}.JPG"), Start.AddSeconds(10 * i), i + 1, lens: i < 2 ? "RF15-35mm" : "RF24-70mm");
|
||||
const string fileTemplate = "{lens}_{n:0000}";
|
||||
var plan = await PlanAsync(card, context.CreateTempDirectory("archive"), new ImportOptions { FileTemplate = fileTemplate });
|
||||
var session = plan.Sessions.Single();
|
||||
// The sequence carries the lens of its first photo, which names every photo of it.
|
||||
Assert.SequenceEqual(["RF15-35mm_0001.JPG", "RF15-35mm_0002.JPG", "RF15-35mm_0003.JPG", "RF15-35mm_0004.JPG"], session.Items.Select(i => i.FileName));
|
||||
|
||||
var frames = session.Items.Select(item => SequenceFrames.FromMetadata(Guid.NewGuid(), "originals/" + item.FileName, Path.GetFileName(item.SourcePath),
|
||||
item.Size, new string('c', 64), MetadataReader.Read(Path.Combine(card, item.SourcePath)), item.CapturedAt)).ToList();
|
||||
var manifest = SequenceFrames.Insert(new SequenceManifest
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Camera = new SidecarCamera { Make = "Canon", Model = "Canon EOS R5" },
|
||||
Lens = "RF15-35mm",
|
||||
}, frames);
|
||||
Assert.Empty(FileRenames.Plan(manifest, session.Title, PathTemplate.Parse(fileTemplate), [.. manifest.Frames.Select(f => f.File)]).Moves);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AnUploadIsNamedWithItsSequencesCameraAsReorganizeNamesIt()
|
||||
{
|
||||
// The creator's hint stands for the camera the photos do not name; a second body's photo takes the sequence's camera.
|
||||
var start = new DateTime(2026, 9, 28, 18, 2, 11);
|
||||
var frames = new[] { Metadata(start), Metadata(start.AddSeconds(5)) with { Make = "GoPro", Model = "HERO12 Black", LensModel = null } }
|
||||
.Select((m, i) => SequenceFrames.FromMetadata(Guid.NewGuid(), $"IMG_{i}.JPG", $"IMG_{i}.JPG", 100, new string('a', 64), m)).ToList();
|
||||
var manifest = SequenceFrames.Insert(new SequenceManifest
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Camera = new SidecarCamera { Model = "Hinted body" },
|
||||
Lens = "RF15-35mm F2.8 L IS USM",
|
||||
}, frames);
|
||||
var template = PathTemplate.Parse("{camera}_{lens}_{n:00}");
|
||||
Assert.SequenceEqual(["Hinted body_RF15-35mm F2.8 L IS USM_01.JPG", "Hinted body_RF15-35mm F2.8 L IS USM_02.JPG"],
|
||||
manifest.Frames.Select(f => template.ExpandFile(FrameNaming.Context(f, manifest, null))));
|
||||
}
|
||||
}
|
||||
@@ -58,6 +58,71 @@ public sealed class PathTemplateTests
|
||||
public void ReservedWindowsNamesAreEscaped() =>
|
||||
Assert.Equal("_CON.CR2", PathTemplate.Parse("{title}").ExpandFile(Frame with { Title = "CON" }));
|
||||
|
||||
[Theory]
|
||||
[Case(".NET Conf", "2026/_.NET Conf")]
|
||||
[Case("Exports", "2026/_Exports")]
|
||||
[Case("originals", "2026/_originals")]
|
||||
[Case("PROXIES", "2026/_PROXIES")]
|
||||
[Case(".chronos", "2026/_.chronos")]
|
||||
[Case("Harbour", "2026/Harbour")]
|
||||
public void FolderLevelsScansNeverEnterAreEscaped(string title, string expected)
|
||||
{
|
||||
var template = PathTemplate.Parse("{year}/{title}");
|
||||
Assert.Equal(expected, template.ExpandFolder(Frame with { Title = title }));
|
||||
Assert.Equal(title != "Harbour", template.WritesHiddenFolder(Frame with { Title = title }));
|
||||
Assert.Equal(title != "Harbour", PathTemplate.IsHiddenFolder(title));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case("{n}", true)]
|
||||
[Case("{name}.{ext}", true)]
|
||||
[Case("{n} .{ext}", true)]
|
||||
[Case("{n}.CR3", true)]
|
||||
[Case("{n}{ext}", false)]
|
||||
[Case("{n}_{ext}", false)]
|
||||
[Case("{n}. {ext}", false)]
|
||||
[Case("{n}.{ext}{ext}", false)]
|
||||
public void AFileTemplateKeepsTheExtensionOnlyWithItsDot(string template, bool keeps)
|
||||
{
|
||||
var parsed = PathTemplate.Parse(template);
|
||||
Assert.Equal(keeps, parsed.KeepsExtension, template);
|
||||
Assert.Equal(keeps, parsed.ExpandFile(Frame).EndsWith(".CR2", StringComparison.Ordinal), parsed.ExpandFile(Frame));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ALongNameIsShortenedBeforeItsExtension()
|
||||
{
|
||||
// A title as long as titles go: the number gives way, the extension never does.
|
||||
var title = new string('a', 195);
|
||||
var name = PathTemplate.Parse("{title}_{n:0000}.{ext}").ExpandFile(Frame with { Title = title });
|
||||
Assert.Equal(title + "_.CR2", name);
|
||||
Assert.Equal(PathTemplate.MaxSegmentLength, name.Length);
|
||||
// Appended, the extension comes after the longest name.
|
||||
Assert.Equal(title + "_0001.CR2", PathTemplate.Parse("{title}_{n:0000}").ExpandFile(Frame with { Title = title }));
|
||||
// Short names are as they were.
|
||||
Assert.Equal("Harbour sunset_0001.CR2", PathTemplate.Parse("{title}_{n:0000}.{ext}").ExpandFile(Frame));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case("{title} 2026", "Paris: night", "Paris: night 2026")]
|
||||
[Case("{title} 2026", "24/7 roof", "24/7 roof 2026")]
|
||||
[Case("{title}", "Aux. trip", "Aux. trip")]
|
||||
[Case("{title}", "What?", "What?")]
|
||||
[Case("{title}", "Sunset...", "Sunset...")]
|
||||
[Case(" {title}\t", "Dawn", "Dawn")]
|
||||
public void TitlesAreTextNotFileNames(string template, string title, string expected) =>
|
||||
Assert.Equal(expected, PathTemplate.Parse(template).ExpandText(Frame with { Title = title }));
|
||||
|
||||
[Test]
|
||||
public void TextKeepsToTheLongestTitle()
|
||||
{
|
||||
var text = PathTemplate.Parse("{title}{title}").ExpandText(Frame with { Title = new string('a', 150) });
|
||||
Assert.Equal(PathTemplate.MaxTextLength, text.Length);
|
||||
// A character outside the basic plane is never cut in two.
|
||||
var emoji = PathTemplate.Parse("{title}").ExpandText(Frame with { Title = new string('a', 199) + "\U0001F305" });
|
||||
Assert.Equal(new string('a', 199), emoji);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ErrorsCarryPositionAndToken()
|
||||
{
|
||||
|
||||
@@ -112,17 +112,24 @@ internal sealed class ArchiveFixture : IAsyncDisposable
|
||||
return job;
|
||||
}
|
||||
|
||||
/// <summary>Stages a verified upload-like file for ingest: returns its path, size and SHA-256.</summary>
|
||||
public (string Path, long Size, string Sha256) Stage(DateTime captured, int seed, string make = "Canon", string model = "Canon EOS R5")
|
||||
/// <summary>Stages a verified upload-like file for ingest (<paramref name="captured"/> null: a photo that records no time): returns its path, size and SHA-256.</summary>
|
||||
public (string Path, long Size, string Sha256) Stage(DateTime? captured, int seed, string? make = "Canon", string? model = "Canon EOS R5", string? lens = null)
|
||||
{
|
||||
var staging = Path.Combine(Paths.StagingDirectory, "uploads");
|
||||
Directory.CreateDirectory(staging);
|
||||
var bytes = Photos.Jpeg(captured, seed, make, model);
|
||||
var bytes = Photos.Jpeg(captured, seed, make, model, lens);
|
||||
var path = Path.Combine(staging, $"{Guid.NewGuid():N}.part");
|
||||
File.WriteAllBytes(path, bytes);
|
||||
return (path, bytes.Length, Convert.ToHexStringLower(SHA256.HashData(bytes)));
|
||||
}
|
||||
|
||||
/// <summary>Every file under <paramref name="folder"/> with the hash of its content, in path order: what a test compares to tell that nothing there changed.</summary>
|
||||
public static List<string> FilesOf(string folder) =>
|
||||
[
|
||||
.. Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories).Order(StringComparer.Ordinal)
|
||||
.Select(p => $"{Path.GetRelativePath(folder, p).Replace('\\', '/')} {Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(p)))}"),
|
||||
];
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
foreach (var owned in _owned) await owned.DisposeAsync();
|
||||
@@ -132,7 +139,7 @@ internal sealed class ArchiveFixture : IAsyncDisposable
|
||||
/// <summary>Small real JPEGs with Exif made by the in-house encoder; each seed gives distinct bytes.</summary>
|
||||
internal static class Photos
|
||||
{
|
||||
public static byte[] Jpeg(DateTime captured, int seed, string make = "Canon", string model = "Canon EOS R5")
|
||||
public static byte[] Jpeg(DateTime? captured, int seed, string? make = "Canon", string? model = "Canon EOS R5", string? lens = null)
|
||||
{
|
||||
using var image = new ImageBuffer(48, 32);
|
||||
var random = new Random(seed);
|
||||
@@ -142,7 +149,7 @@ internal static class Photos
|
||||
var level = (float)random.NextDouble();
|
||||
for (var i = 0; i < plane.Length; i++) plane[i] = level * (0.5f + 0.5f * (i % 48) / 48f);
|
||||
}
|
||||
var exif = ExifWriter.BuildJpegApp1(new FrameMetadata { Make = make, Model = model, BodySerial = "0431", CapturedAt = captured, Iso = 100 });
|
||||
var exif = ExifWriter.BuildJpegApp1(new FrameMetadata { Make = make, Model = model, LensModel = lens, BodySerial = "0431", CapturedAt = captured, Iso = 100 });
|
||||
return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 85, App1Segments = [exif[4..]] });
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ using System.Text.Json.Nodes;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Codecs.Jpeg;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Metadata;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Archiving;
|
||||
@@ -90,6 +91,19 @@ public sealed class ArchiveSettingsTests(TestContext context)
|
||||
var template = await Assert.ThrowsAsync<ArgumentException>(() =>
|
||||
fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Templates = s.Templates with { Folder = "{year/{date" } }, fx.Ct));
|
||||
Assert.Equal("folderTemplate", template.ParamName);
|
||||
// The rules every template is held to wherever it is typed: a folder scans never enter, a lost extension, names that repeat.
|
||||
foreach (var (folder, file, field) in new[]
|
||||
{
|
||||
("exports/{date}", "{n}", "folderTemplate"), ("{date}", "{n}{ext}", "fileTemplate"), ("{date}", "{title}", "fileTemplate"),
|
||||
})
|
||||
{
|
||||
var rule = await Assert.ThrowsAsync<ArgumentException>(() =>
|
||||
fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Templates = s.Templates with { Folder = folder, File = file } }, fx.Ct));
|
||||
Assert.Equal(field, rule.ParamName, $"{folder} · {file}");
|
||||
}
|
||||
var created = await Assert.ThrowsAsync<ArgumentException>(() =>
|
||||
fx.Service.CreateAsync(context.CreateTempDirectory("other"), "Other", new LayoutTemplates { Folder = "{date}", File = "{n}{ext}" }, null, fx.Ct));
|
||||
Assert.Equal("fileTemplate", created.ParamName);
|
||||
var proxies = await Assert.ThrowsAsync<ArgumentException>(() =>
|
||||
fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Proxies = s.Proxies with { LongEdge = 100 } }, fx.Ct));
|
||||
Assert.Equal("proxyLongEdge", proxies.ParamName);
|
||||
@@ -102,6 +116,37 @@ public sealed class ArchiveSettingsTests(TestContext context)
|
||||
Assert.Equal(before, await File.ReadAllTextAsync(fx.Paths.ManifestPath, fx.Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TemplatesSavedBeforeTheRulesNeverFailAnEditOfAnotherSetting()
|
||||
{
|
||||
await using var fx = await ArchiveFixture.CreateAsync(context);
|
||||
// An archive.json of 0.1.0-rc.5 or earlier: both templates break a rule new templates are held to.
|
||||
var manifest = ManifestStore.ReadArchive(fx.Paths.ManifestPath);
|
||||
ManifestStore.WriteArchive(fx.Paths.ManifestPath, manifest with { LayoutTemplates = new LayoutTemplates { Folder = "exports/{date}", File = "{title}" } });
|
||||
|
||||
// The desktop saves one row at a time: each edit keeps the templates it does not change.
|
||||
var proxies = await fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Proxies = s.Proxies with { LongEdge = 2560 } }, fx.Ct);
|
||||
Assert.Equal(("exports/{date}", "{title}", 2560), (proxies.FolderTemplate, proxies.FileTemplate, proxies.ProxyLongEdge));
|
||||
await fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Name = "Studio" }, fx.Ct);
|
||||
var folder = await fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Templates = s.Templates with { Folder = "{year}/{date}" } }, fx.Ct);
|
||||
Assert.Equal(("{year}/{date}", "{title}"), (folder.FolderTemplate, folder.FileTemplate));
|
||||
|
||||
// A template given anew is held to every rule, and the refusal says which.
|
||||
var before = await File.ReadAllTextAsync(fx.Paths.ManifestPath, fx.Ct);
|
||||
var refused = await Assert.ThrowsAsync<TemplateRuleException>(() =>
|
||||
fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Templates = s.Templates with { File = "{n}{ext}" } }, fx.Ct));
|
||||
Assert.Equal(("fileTemplate", "Extension", Loc.L("Errors.Template.Extension")), (refused.ParamName, refused.Rule, refused.Message));
|
||||
Assert.Equal(before, await File.ReadAllTextAsync(fx.Paths.ManifestPath, fx.Ct));
|
||||
|
||||
var file = await fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Templates = s.Templates with { File = "{date}_{n:0000}" } }, fx.Ct);
|
||||
Assert.Equal(("Studio", "{year}/{date}", "{date}_{n:0000}", 2560), (file.Name, file.FolderTemplate, file.FileTemplate, file.ProxyLongEdge));
|
||||
|
||||
// A new archive has nothing to keep: its templates meet every rule.
|
||||
var created = await Assert.ThrowsAsync<TemplateRuleException>(() => fx.Service.CreateAsync(context.CreateTempDirectory("other"), "Other",
|
||||
new LayoutTemplates { Folder = "exports/{date}", File = "{date}_{n:0000}" }, null, fx.Ct));
|
||||
Assert.Equal(("folderTemplate", "ReservedFolder"), (created.ParamName, created.Rule));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnOfflineArchiveIsNotChangedAndItsIndexSettingsAreShown()
|
||||
{
|
||||
|
||||
@@ -1127,6 +1127,90 @@ public abstract class FrameTrashTests(TestContext context) : DatabaseTest(contex
|
||||
Assert.SequenceEqual(frames.Select(f => f.Id), (await fx.Db.Frames.ListBySequenceAsync(sequence.Id)).Select(f => f.Id));
|
||||
}
|
||||
|
||||
/// <summary>The files of a sequence as its sidecar names them, after checking that the index names the same ones and that each holds its photo.</summary>
|
||||
private static async Task<List<string>> FilesAsync(ArchiveFixture fx, Guid id)
|
||||
{
|
||||
var sequence = Assert.NotNull(await fx.Db.Sequences.GetAsync(id));
|
||||
var folder = fx.Paths.Sequence(sequence.Folder);
|
||||
var sidecar = ManifestStore.ReadSequence(folder.ManifestPath);
|
||||
var rows = await fx.Db.Frames.ListBySequenceAsync(id);
|
||||
Assert.SequenceEqual(sidecar.Frames.Select(f => (f.Id, folder.ArchiveRelative(f.File))), rows.Select(r => (r.Id, r.RelativePath)));
|
||||
foreach (var frame in sidecar.Frames) Assert.Equal(frame.Sha256, Sha(folder.File(frame.File)));
|
||||
return [.. sidecar.Frames.Select(f => f.File)];
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task PhotosDeletedBeforeAReorganizeComeBackBesideTheNamesItGave()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var (sequence, frames) = await UploadedAsync(fx, 4);
|
||||
var numbered = new RenameTemplates(File: "{n:000}");
|
||||
await fx.Service.ApplyRenameAsync(await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [sequence.Id], numbered, fx.Ct), null, fx.Ct);
|
||||
var folder = fx.Paths.Sequence(sequence.Folder);
|
||||
File.WriteAllText(folder.File("originals/002.xmp"), "second");
|
||||
await fx.ScanAsync();
|
||||
// The record keeps the names the photo and its companion had: 002.JPG and 002.xmp.
|
||||
var deleted = await DeleteAsync(fx, (await fx.Db.Sequences.GetAsync(sequence.Id))!, frames[1]);
|
||||
Assert.SequenceEqual(["originals/002.JPG", "originals/002.xmp"], FrameTrash.ReadEntry(fx.Paths, deleted.Entry.Name)!.Photos.Single().Files.Select(f => f.From));
|
||||
|
||||
// Moved and renamed since: the photos that stay take 001-003, the deleted photo's name included.
|
||||
var moved = new RenameTemplates(Folder: "moved/{date}", File: "{n:000}");
|
||||
await fx.Service.ApplyRenameAsync(await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [sequence.Id], moved, fx.Ct), null, fx.Ct);
|
||||
Assert.SequenceEqual(["originals/001.JPG", "originals/002.JPG", "originals/003.JPG"], await FilesAsync(fx, sequence.Id));
|
||||
|
||||
// Restored into the sequence where it is now, under its own name made free: its companion follows that name.
|
||||
var restored = await fx.Service.RestoreEntryAsync(fx.Archive.Id, deleted.Entry.Name, null, fx.Ct);
|
||||
Assert.Equal(1, restored.Photos);
|
||||
var row = (await fx.Db.Sequences.GetAsync(sequence.Id))!;
|
||||
Assert.Equal("moved/2026-09-28", row.Folder);
|
||||
Assert.SequenceEqual(["originals/001.JPG", "originals/002_2.JPG", "originals/002.JPG", "originals/003.JPG"], await FilesAsync(fx, sequence.Id));
|
||||
var now = fx.Paths.Sequence(row.Folder);
|
||||
Assert.Equal(frames[1].Sha256, Sha(now.File("originals/002_2.JPG")));
|
||||
Assert.Equal("second", File.ReadAllText(now.File("originals/002_2.xmp")));
|
||||
Assert.SequenceEqual(frames.Select(f => f.Id), (await fx.Db.Frames.ListBySequenceAsync(sequence.Id)).Select(f => f.Id));
|
||||
Assert.DoesNotContain(TrashKind.Photos, (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Select(e => e.Kind));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AReorganizeWaitsForARestoreItsEntryHoldsThenSettlesItFirst()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var (sequence, frames) = await UploadedAsync(fx, 3);
|
||||
var folder = fx.Paths.Sequence(sequence.Folder);
|
||||
var deleted = await DeleteAsync(fx, sequence, frames[1]);
|
||||
// A restore died after moving the original back, before the sidecar; the entry is being emptied meanwhile.
|
||||
var journal = RestoreJournal(fx, deleted.Entry);
|
||||
journal.Write(folder);
|
||||
var back = journal.Photos[0].Moves[0];
|
||||
File.Move(fx.Paths.FromRelative(back.To), folder.File(back.From));
|
||||
var templates = new RenameTemplates(Folder: "moved/{date}", File: "{n:000}");
|
||||
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [sequence.Id], templates, fx.Ct);
|
||||
Assert.Equal(2, plan.Steps.Single().FileChanges);
|
||||
var before = await FilesAsync(fx, sequence.Id);
|
||||
|
||||
using (Assert.NotNull(LeaseFile.TryAcquire(fx.Paths.LocksDirectory, SequenceTrash.EntryLease(deleted.Entry.Name), "other")))
|
||||
{
|
||||
// Neither the folder nor a file name changes under that restore.
|
||||
await Assert.ThrowsAsync<LeaseUnavailableException>(() => fx.Service.ApplyRenameAsync(plan, null, fx.Ct));
|
||||
Assert.Equal(sequence.Folder, (await fx.Db.Sequences.GetAsync(sequence.Id))!.Folder);
|
||||
Assert.SequenceEqual(before, await FilesAsync(fx, sequence.Id));
|
||||
Assert.FileExists(folder.RestoreJournalPath);
|
||||
Assert.FileExists(folder.File(back.From));
|
||||
}
|
||||
|
||||
// Once the entry is free the rename resumes: the restore is settled first (the original goes back into its entry),
|
||||
// then the folder moves and the files are renamed; the photo then comes back beside them.
|
||||
Assert.Equal(1, await fx.Service.Renamer.ResumePendingAsync(fx.Archive, fx.Ct));
|
||||
Assert.Equal(frames[1].Sha256, Sha(fx.Paths.FromRelative(back.To)));
|
||||
var row = (await fx.Db.Sequences.GetAsync(sequence.Id))!;
|
||||
Assert.Equal("moved/2026-09-28", row.Folder);
|
||||
Assert.FileMissing(fx.Paths.Sequence(row.Folder).RestoreJournalPath);
|
||||
Assert.SequenceEqual(["originals/001.JPG", "originals/002.JPG"], await FilesAsync(fx, sequence.Id));
|
||||
Assert.Equal(1, (await fx.Service.RestoreEntryAsync(fx.Archive.Id, deleted.Entry.Name, null, fx.Ct)).Photos);
|
||||
Assert.SequenceEqual(frames.Select(f => f.Id), (await fx.Db.Frames.ListBySequenceAsync(sequence.Id)).Select(f => f.Id));
|
||||
Assert.Count(3, await FilesAsync(fx, sequence.Id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ARestoreIntoANewSequenceStoppedBetweenPhotosKeepsItsRecordTrue()
|
||||
{
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Testing;
|
||||
using static Chronos.Data.Tests.Archiving.ArchiveFixture;
|
||||
|
||||
@@ -233,6 +236,331 @@ public sealed class MassRenameTests(TestContext context)
|
||||
Assert.Equal(0, (await fx.ScanAsync()).Indexed);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ExportsInsideAMovedFolderAreStillReachable()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var ids = await NestedAsync(fx);
|
||||
// Exports of "trips" and of "trips/day2" in their folders, one of "trips/day2/dawn" saved in the exports of "trips"
|
||||
// (the Export tab's folder picker), one of "trips" outside the archive, a row whose path only starts with the same
|
||||
// letters, and one of "trips/day2" in "trips" whose file is gone.
|
||||
var outside = Path.Combine(context.CreateTempDirectory("exports"), "Trips elsewhere.mp4");
|
||||
List<Guid> renders =
|
||||
[
|
||||
await RenderAsync(fx, ids[0], "trips/exports/Trips.mp4"),
|
||||
await RenderAsync(fx, ids[1], "trips/day2/exports/Day 2.mp4"),
|
||||
await RenderAsync(fx, ids[2], "trips/exports/Dawn.mp4"),
|
||||
await RenderAsync(fx, ids[0], outside),
|
||||
await RenderAsync(fx, ids[0], "trips 2/exports/Other.mp4", write: false),
|
||||
await RenderAsync(fx, ids[1], "trips/exports/Gone.mp4", write: false),
|
||||
];
|
||||
var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, [ids[0]], "moved/{date}", null, fx.Ct);
|
||||
Assert.SequenceEqual([false, true, true], plan.Steps.Select(s => s.Carried));
|
||||
|
||||
await fx.Service.ApplyRenameAsync(plan, null, fx.Ct);
|
||||
string[] expected =
|
||||
[
|
||||
"moved/2026-09-28/exports/Trips.mp4", "moved/2026-09-28/day2/exports/Day 2.mp4", "moved/2026-09-28/exports/Dawn.mp4", outside,
|
||||
"trips 2/exports/Other.mp4", "trips/exports/Gone.mp4",
|
||||
];
|
||||
Assert.SequenceEqual(expected, await OutputsAsync(fx, renders));
|
||||
foreach (var path in expected[..4]) Assert.FileExists(Path.IsPathRooted(path) ? path : fx.Paths.FromRelative(path));
|
||||
|
||||
// A crash after the steps were recorded but before the journal said so: completed again, and again, nothing moves twice.
|
||||
RenameJournal.Write(fx.Paths, new RenameJournal(plan, []));
|
||||
Assert.Equal(1, await fx.Service.Renamer.ResumePendingAsync(fx.Archive, fx.Ct));
|
||||
Assert.Equal(0, await fx.Service.Renamer.ResumePendingAsync(fx.Archive, fx.Ct));
|
||||
Assert.SequenceEqual(expected, await OutputsAsync(fx, renders));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnotherIndexFindsTheExportsWhereAReorganizeMovedTheirFolder()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var ids = await PopulateAsync(fx);
|
||||
// This index's exports: of "inbox/a" in its folder, of "inbox/b" saved in the exports of "inbox/a", of "inbox/c" in its own.
|
||||
List<Guid> renders =
|
||||
[
|
||||
await RenderAsync(fx, ids[0], "inbox/a/exports/A.mp4"),
|
||||
await RenderAsync(fx, ids[1], "inbox/a/exports/B.mp4"),
|
||||
await RenderAsync(fx, ids[2], "inbox/c/exports/C.mp4"),
|
||||
];
|
||||
var (server, archive) = await fx.OtherWriterAsync();
|
||||
|
||||
// The other index (a server sharing this desktop's archive) moves "inbox/a", then "inbox/c" into the folder it left.
|
||||
var first = await server.PlanRenameAsync(archive.Id, [ids[0]], "moved/{date}", null, fx.Ct);
|
||||
await server.ApplyRenameAsync(first, null, fx.Ct);
|
||||
var second = await server.PlanRenameAsync(archive.Id, [ids[2]], "inbox/a", null, fx.Ct);
|
||||
Assert.Equal("inbox/a", second.Steps.Single().ToFolder);
|
||||
await server.ApplyRenameAsync(second, null, fx.Ct);
|
||||
|
||||
// A scan here finds both where they are now (the new "inbox/a" first): each export follows the folder its file moved with.
|
||||
await fx.ScanAsync();
|
||||
Assert.Equal("moved/2026-09-28", (await fx.Db.Sequences.GetAsync(ids[0], fx.Ct))!.Folder);
|
||||
Assert.Equal("inbox/a", (await fx.Db.Sequences.GetAsync(ids[2], fx.Ct))!.Folder);
|
||||
string[] expected = ["moved/2026-09-28/exports/A.mp4", "moved/2026-09-28/exports/B.mp4", "inbox/a/exports/C.mp4"];
|
||||
Assert.SequenceEqual(expected, await OutputsAsync(fx, renders));
|
||||
foreach (var path in expected) Assert.FileExists(fx.Paths.FromRelative(path));
|
||||
Assert.Equal(0, (await fx.ScanAsync()).Indexed);
|
||||
Assert.SequenceEqual(expected, await OutputsAsync(fx, renders));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnExportWrittenWhereItsFolderWasStaysWithItsFile()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var ids = await PopulateAsync(fx);
|
||||
List<Guid> renders = [await RenderAsync(fx, ids[0], "inbox/a/exports/A.mp4")];
|
||||
var (server, archive) = await fx.OtherWriterAsync();
|
||||
|
||||
// The other index moves "inbox/a"; a writer here that read the folder before files an export where it was, creating
|
||||
// it again. Another export of the sequence is missing from both places.
|
||||
var plan = await server.PlanRenameAsync(archive.Id, [ids[0]], "moved/{date}", null, fx.Ct);
|
||||
await server.ApplyRenameAsync(plan, null, fx.Ct);
|
||||
renders.Add(await RenderAsync(fx, ids[0], "inbox/a/exports/Late.mp4"));
|
||||
renders.Add(await RenderAsync(fx, ids[0], "inbox/a/exports/Gone.mp4", write: false));
|
||||
|
||||
// The scan here moves the rows whose file went with the folder or is nowhere, and keeps the one whose file stayed.
|
||||
await fx.ScanAsync();
|
||||
Assert.Equal("moved/2026-09-28", (await fx.Db.Sequences.GetAsync(ids[0], fx.Ct))!.Folder);
|
||||
string[] expected = ["moved/2026-09-28/exports/A.mp4", "inbox/a/exports/Late.mp4", "moved/2026-09-28/exports/Gone.mp4"];
|
||||
Assert.SequenceEqual(expected, await OutputsAsync(fx, renders));
|
||||
foreach (var path in expected[..2]) Assert.FileExists(fx.Paths.FromRelative(path));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnImageSequenceExportIsAFolderThatFollowsAsAFileDoes()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var ids = await PopulateAsync(fx);
|
||||
// Image-sequence exports: of "inbox/a" in its folder, and of "inbox/b" saved in the exports of "inbox/a".
|
||||
List<Guid> renders =
|
||||
[
|
||||
await RenderAsync(fx, ids[0], "inbox/a/exports/A frames", frames: true),
|
||||
await RenderAsync(fx, ids[1], "inbox/a/exports/B frames", frames: true),
|
||||
];
|
||||
var (server, archive) = await fx.OtherWriterAsync();
|
||||
|
||||
// The other index moves "inbox/a"; a writer here that read the folder before files one where it was, creating it again.
|
||||
var plan = await server.PlanRenameAsync(archive.Id, [ids[0]], "moved/{date}", null, fx.Ct);
|
||||
await server.ApplyRenameAsync(plan, null, fx.Ct);
|
||||
renders.Add(await RenderAsync(fx, ids[0], "inbox/a/exports/Late frames", frames: true));
|
||||
|
||||
// Each folder follows, or stays, as a file would: both that moved with the folder, not the one written where it was.
|
||||
await fx.ScanAsync();
|
||||
string[] expected = ["moved/2026-09-28/exports/A frames", "moved/2026-09-28/exports/B frames", "inbox/a/exports/Late frames"];
|
||||
Assert.SequenceEqual(expected, await OutputsAsync(fx, renders));
|
||||
foreach (var path in expected) Assert.FileExists(Path.Combine(fx.Paths.FromRelative(path), "000001.png"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnExportNeverNamesTheOneAnotherSequenceBroughtIntoItsOldFolder()
|
||||
{
|
||||
// The new folder is scanned after "inbox/a", then before it. "inbox/a" and "inbox/c" each have an export of the
|
||||
// same name: the one of "inbox/a" gone, both there, or the one of "inbox/c" gone.
|
||||
var cases = from template in new[] { "moved/{date}", "done/{date}" }
|
||||
from files in new[] { (A: false, C: true), (A: true, C: true), (A: true, C: false) }
|
||||
select (template, files.A, files.C);
|
||||
foreach (var (template, a, c) in cases)
|
||||
{
|
||||
var label = $"{template}, a {(a ? "there" : "gone")}, c {(c ? "there" : "gone")}";
|
||||
await using var fx = await CreateAsync(context);
|
||||
var ids = await PopulateAsync(fx);
|
||||
List<Guid> renders =
|
||||
[
|
||||
await RenderAsync(fx, ids[0], "inbox/a/exports/Clip.mp4", write: a),
|
||||
await RenderAsync(fx, ids[2], "inbox/c/exports/Clip.mp4", write: c),
|
||||
];
|
||||
if (a) await File.WriteAllTextAsync(fx.Paths.FromRelative("inbox/a/exports/Clip.mp4"), "a", fx.Ct);
|
||||
if (c) await File.WriteAllTextAsync(fx.Paths.FromRelative("inbox/c/exports/Clip.mp4"), "c", fx.Ct);
|
||||
var (server, archive) = await fx.OtherWriterAsync();
|
||||
|
||||
// The other index moves "inbox/a", then "inbox/c" into the folder it left, their exports along.
|
||||
var first = await server.PlanRenameAsync(archive.Id, [ids[0]], template, null, fx.Ct);
|
||||
await server.ApplyRenameAsync(first, null, fx.Ct);
|
||||
await server.ApplyRenameAsync(await server.PlanRenameAsync(archive.Id, [ids[2]], "inbox/a", null, fx.Ct), null, fx.Ct);
|
||||
|
||||
// Each row follows its own sequence's folder, its file there or missing there too, and never names the other one's.
|
||||
await fx.ScanAsync();
|
||||
string[] expected = [first.Steps.Single().ToFolder + "/exports/Clip.mp4", "inbox/a/exports/Clip.mp4"];
|
||||
Assert.SequenceEqual(expected, await OutputsAsync(fx, renders), label);
|
||||
if (a) Assert.Equal("a", await File.ReadAllTextAsync(fx.Paths.FromRelative(expected[0]), fx.Ct), label);
|
||||
if (c) Assert.Equal("c", await File.ReadAllTextAsync(fx.Paths.FromRelative(expected[1]), fx.Ct), label);
|
||||
Assert.Equal(0, (await fx.ScanAsync()).Indexed);
|
||||
Assert.SequenceEqual(expected, await OutputsAsync(fx, renders), label);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnExportSavedInAnotherSequencesFolderNeverNamesTheOneBroughtIntoIt()
|
||||
{
|
||||
// The new folder is scanned after "inbox/a", then before it.
|
||||
foreach (var template in new[] { "moved/{date}", "done/{date}" })
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var ids = await PopulateAsync(fx);
|
||||
// "inbox/b" saved an export in the exports of "inbox/a" (the Export tab's folder picker); "inbox/c" has one of the same name.
|
||||
List<Guid> renders =
|
||||
[
|
||||
await RenderAsync(fx, ids[1], "inbox/a/exports/Clip.mp4"),
|
||||
await RenderAsync(fx, ids[2], "inbox/c/exports/Clip.mp4"),
|
||||
];
|
||||
await File.WriteAllTextAsync(fx.Paths.FromRelative("inbox/a/exports/Clip.mp4"), "b", fx.Ct);
|
||||
await File.WriteAllTextAsync(fx.Paths.FromRelative("inbox/c/exports/Clip.mp4"), "c", fx.Ct);
|
||||
var (server, archive) = await fx.OtherWriterAsync();
|
||||
|
||||
// The other index moves "inbox/a", the export of "inbox/b" along, then "inbox/c" into the folder it left, its export along.
|
||||
var first = await server.PlanRenameAsync(archive.Id, [ids[0]], template, null, fx.Ct);
|
||||
await server.ApplyRenameAsync(first, null, fx.Ct);
|
||||
await server.ApplyRenameAsync(await server.PlanRenameAsync(archive.Id, [ids[2]], "inbox/a", null, fx.Ct), null, fx.Ct);
|
||||
|
||||
// The export of "inbox/b" follows the folder its file moved with and never names the one of "inbox/c".
|
||||
await fx.ScanAsync();
|
||||
string[] expected = [first.Steps.Single().ToFolder + "/exports/Clip.mp4", "inbox/a/exports/Clip.mp4"];
|
||||
Assert.SequenceEqual(expected, await OutputsAsync(fx, renders), template);
|
||||
Assert.Equal("b", await File.ReadAllTextAsync(fx.Paths.FromRelative(expected[0]), fx.Ct), template);
|
||||
Assert.Equal("c", await File.ReadAllTextAsync(fx.Paths.FromRelative(expected[1]), fx.Ct), template);
|
||||
Assert.Equal(0, (await fx.ScanAsync()).Indexed);
|
||||
Assert.SequenceEqual(expected, await OutputsAsync(fx, renders), template);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task APhotoDeletionWhoseFolderMovedWhileItWaitedForTheLeaseIsRefused()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var ids = await PopulateAsync(fx);
|
||||
var frames = await fx.Db.Frames.ListBySequenceAsync(ids[0], cancellationToken: fx.Ct);
|
||||
var deletion = await fx.Service.FrameTrash.PlanDeleteAsync(ids[0], [frames[1].Id], cancellationToken: fx.Ct);
|
||||
Assert.True(deletion.CanDelete);
|
||||
var pause = TimeSpan.FromSeconds(TestTiming.Budget(0.5));
|
||||
|
||||
// Another process holds the sequence and moves its folder (a Reorganize), while the deletion waits for the lease.
|
||||
Task<FrameDeleteResult> delete;
|
||||
using (await LeaseFile.AcquireAsync(fx.Paths.LocksDirectory, $"seq-{ids[0]:N}", "other", TimeSpan.FromSeconds(5), cancellationToken: fx.Ct))
|
||||
{
|
||||
delete = fx.Service.FrameTrash.DeleteAsync(deletion, cancellationToken: fx.Ct);
|
||||
await Task.Delay(pause, fx.Ct);
|
||||
Assert.False(delete.IsCompleted, "the deletion waits for the other process");
|
||||
Directory.CreateDirectory(fx.Paths.FromRelative("moved"));
|
||||
Directory.Move(fx.Paths.FromRelative("inbox/a"), fx.Paths.FromRelative("moved/a"));
|
||||
await using var tx = await fx.Db.BeginAsync(fx.Ct);
|
||||
await tx.Sequences.RelocateAsync(ids[0], "moved/a", null, fx.Ct);
|
||||
await tx.Frames.RebaseFolderAsync(ids[0], "inbox/a", "moved/a", fx.Ct);
|
||||
await tx.CommitAsync(fx.Ct);
|
||||
}
|
||||
|
||||
await Assert.ThrowsAsync<StaleDeletePlanException>(() => delete);
|
||||
Assert.Count(3, await fx.Db.Frames.ListBySequenceAsync(ids[0], cancellationToken: fx.Ct));
|
||||
Assert.Count(3, ManifestStore.ReadSequence(fx.Paths.Sequence("moved/a").ManifestPath).Frames);
|
||||
foreach (var f in frames) Assert.FileExists(fx.Paths.FromRelative(f.RelativePath.Replace("inbox/a/", "moved/a/", StringComparison.Ordinal)));
|
||||
Assert.Empty(await fx.Service.Trash.ListAsync(fx.Archive, fx.Ct));
|
||||
Assert.False(Directory.Exists(fx.Paths.FromRelative("inbox/a")), "the folder it left is not created again");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnInterruptedMoveTakesTheExportsAlongWhenItResumes()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var ids = await PopulateAsync(fx);
|
||||
List<Guid> renders = [];
|
||||
foreach (var (id, folder) in ids.Zip(["inbox/a", "inbox/b", "inbox/c"])) renders.Add(await RenderAsync(fx, id, $"{folder}/exports/Clip.mp4"));
|
||||
var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, ids, "renamed/{date}", null, fx.Ct);
|
||||
using var cts = new CancellationTokenSource();
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => fx.Service.ApplyRenameAsync(plan, new SyncProgress(_ => cts.Cancel()), cts.Token));
|
||||
Assert.Count(1, RenameJournal.ListPending(fx.Paths).Single().Completed);
|
||||
|
||||
// Crash in the middle of the next step: its folder moved with its export, the index not yet updated.
|
||||
var next = plan.Steps[1];
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(fx.Paths.FromRelative(next.ToFolder))!);
|
||||
Directory.Move(fx.Paths.FromRelative(next.FromFolder), fx.Paths.FromRelative(next.ToFolder));
|
||||
|
||||
await fx.Service.OpenAsync(fx.Archive.RootPath, fx.Ct); // the next start finds the journal
|
||||
Assert.Empty(RenameJournal.ListPending(fx.Paths));
|
||||
Assert.Equal(0, await fx.Service.Renamer.ResumePendingAsync(fx.Archive, fx.Ct));
|
||||
var outputs = await OutputsAsync(fx, renders);
|
||||
Assert.SequenceEqual(ids.Select(id => $"{plan.Steps.Single(s => s.SequenceId == id).ToFolder}/exports/Clip.mp4"), outputs);
|
||||
foreach (var path in outputs) Assert.FileExists(fx.Paths.FromRelative(path));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WritersThatReadTheSequenceBeforeItsFolderMovedWriteWhereItIsNow()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var ids = await PopulateAsync(fx);
|
||||
var stale = (await fx.Db.Sequences.GetAsync(ids[0], fx.Ct))!;
|
||||
var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, [ids[0]], "moved/{date}", null, fx.Ct);
|
||||
await fx.Service.ApplyRenameAsync(plan, null, fx.Ct);
|
||||
var now = fx.Paths.Sequence(plan.Steps.Single().ToFolder);
|
||||
var left = fx.Paths.Sequence(stale.Folder).Folder;
|
||||
Assert.False(Directory.Exists(left));
|
||||
|
||||
// A thumbnail pass and an analysis's project update that read the row before the move take their leases after it.
|
||||
await fx.Service.Images.BuildThumbnailsAsync(fx.Archive, stale, force: false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
|
||||
Assert.FileExists(now.ThumbsPackPath);
|
||||
Assert.True(((await fx.Db.Sequences.GetAsync(ids[0], fx.Ct))!.Status & SequenceStatus.ThumbsBuilt) != 0, "the pass is recorded");
|
||||
var projects = new ProjectStore(fx.Db, new SequenceWriter(new ArchiveServiceOptions { Owner = "analysis" }));
|
||||
Assert.True(await projects.UpdateAsync(fx.Paths, stale, p => p with { HeroFrame = 1 }, fx.Ct));
|
||||
Assert.Equal(1, ProjectSettings.FromJson(await File.ReadAllTextAsync(now.ProjectPath, fx.Ct)).HeroFrame);
|
||||
Assert.False(Directory.Exists(left), "the folder it left is not created again");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task APhotoFiledWhileTheFolderMovesGoesWhereTheSequenceIsNow()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var ids = await PopulateAsync(fx);
|
||||
var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, [ids[0]], "moved/{date}", null, fx.Ct);
|
||||
var staged = fx.Stage(Start.AddMinutes(30), 99);
|
||||
var pause = TimeSpan.FromSeconds(TestTiming.Budget(0.5));
|
||||
|
||||
// Another process writes the sequence: the move waits for it, and an upload that read the row meanwhile waits behind the move.
|
||||
Task apply;
|
||||
Task<IngestResult> upload;
|
||||
using (await LeaseFile.AcquireAsync(fx.Paths.LocksDirectory, $"seq-{ids[0]:N}", "other", TimeSpan.FromSeconds(5), cancellationToken: fx.Ct))
|
||||
{
|
||||
apply = fx.Service.ApplyRenameAsync(plan, null, fx.Ct);
|
||||
await Task.Delay(pause, fx.Ct);
|
||||
upload = fx.Service.Ingest.CommitAsync(new IngestRequest(fx.Archive.Id, ids[0], null, null, staged.Path, "LATE.JPG", staged.Size, staged.Sha256,
|
||||
null, null), fx.Ct);
|
||||
await Task.Delay(pause, fx.Ct);
|
||||
Assert.False(apply.IsCompleted || upload.IsCompleted, "both wait for the other process");
|
||||
}
|
||||
|
||||
await apply;
|
||||
var filed = await upload;
|
||||
var now = plan.Steps.Single().ToFolder;
|
||||
Assert.True(filed.RelativePath.StartsWith(now + "/", StringComparison.Ordinal), filed.RelativePath);
|
||||
Assert.FileExists(fx.Paths.FromRelative(filed.RelativePath));
|
||||
Assert.Count(4, await fx.Db.Frames.ListBySequenceAsync(ids[0], cancellationToken: fx.Ct));
|
||||
Assert.False(Directory.Exists(fx.Paths.FromRelative("inbox/a")), "the folder it left is not created again");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A render row of <paramref name="sequenceId"/> at <paramref name="output"/> (archive-relative or absolute), with its
|
||||
/// file unless told otherwise; with <paramref name="frames"/> an image sequence's export, a folder of frames.
|
||||
/// </summary>
|
||||
private static async Task<Guid> RenderAsync(ArchiveFixture fx, Guid sequenceId, string output, bool write = true, bool frames = false)
|
||||
{
|
||||
if (write)
|
||||
{
|
||||
var file = Path.IsPathRooted(output) ? output : fx.Paths.FromRelative(output);
|
||||
if (frames) file = Path.Combine(file, "000001.png");
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(file)!);
|
||||
await File.WriteAllBytesAsync(file, [1, 2, 3], fx.Ct);
|
||||
}
|
||||
var render = new Render { Id = Guid.CreateVersion7(), SequenceId = sequenceId, PresetName = "1080p", OutputPath = output, Bytes = 3, Created = DateTimeOffset.UtcNow };
|
||||
await fx.Db.Renders.InsertAsync(render, fx.Ct);
|
||||
return render.Id;
|
||||
}
|
||||
|
||||
private static async Task<List<string>> OutputsAsync(ArchiveFixture fx, IEnumerable<Guid> renders)
|
||||
{
|
||||
var outputs = new List<string>();
|
||||
foreach (var id in renders) outputs.Add((await fx.Db.Renders.GetAsync(id, fx.Ct))!.OutputPath);
|
||||
return outputs;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AFolderInsideASequenceFolderIsRefused()
|
||||
{
|
||||
|
||||
@@ -2,9 +2,11 @@ using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Codecs.Jpeg;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Imaging.Decoders;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Metadata;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Tests.Processing;
|
||||
using Chronos.Testing;
|
||||
using static Chronos.Data.Tests.Archiving.ArchiveFixture;
|
||||
|
||||
@@ -37,11 +39,11 @@ public sealed class ProxyTests(TestContext context)
|
||||
var folder = fx.Paths.Sequence(sequence.Folder);
|
||||
var images = fx.Service.Images;
|
||||
|
||||
Assert.Equal(ProxyStoreResult.Invalid, images.StoreProxy(fx.Archive, sequence, frames[0], "not a photo"u8.ToArray()));
|
||||
Assert.Equal(ProxyStoreResult.WrongFrame, images.StoreProxy(fx.Archive, sequence, frames[0], Proxy(frames[1].CapturedAt!.Value, 1)));
|
||||
Assert.Equal(ProxyStoreResult.Invalid, await images.StoreProxyAsync(fx.Archive, sequence, frames[0], "not a photo"u8.ToArray(), fx.Ct));
|
||||
Assert.Equal(ProxyStoreResult.WrongFrame, await images.StoreProxyAsync(fx.Archive, sequence, frames[0], Proxy(frames[1].CapturedAt!.Value, 1), fx.Ct));
|
||||
Assert.FileMissing(folder.Proxy(0));
|
||||
var proxy = Proxy(frames[0].CapturedAt!.Value, 2);
|
||||
Assert.Equal(ProxyStoreResult.Stored, images.StoreProxy(fx.Archive, sequence, frames[0], proxy));
|
||||
Assert.Equal(ProxyStoreResult.Stored, await images.StoreProxyAsync(fx.Archive, sequence, frames[0], proxy, fx.Ct));
|
||||
Assert.SequenceEqual(proxy, await File.ReadAllBytesAsync(folder.Proxy(0), fx.Ct));
|
||||
|
||||
// The proxy pass keeps what was sent and makes none from the originals here, even when forced.
|
||||
@@ -62,6 +64,148 @@ public sealed class ProxyTests(TestContext context)
|
||||
Assert.Equal((0, 1, 1), (again.Built, again.Reused, again.Undecodable));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ProxiesSentOrMadeAfterTheFolderMovedGoWhereTheSequenceIsNow()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var (stale, frames) = await HeifSequenceAsync(fx);
|
||||
var images = fx.Service.Images;
|
||||
var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, [stale.Id], "moved/{date}", null, fx.Ct);
|
||||
await fx.Service.ApplyRenameAsync(plan, null, fx.Ct);
|
||||
var now = fx.Paths.Sequence(plan.Steps.Single().ToFolder);
|
||||
var left = fx.Paths.Sequence(stale.Folder).Folder;
|
||||
Assert.False(Directory.Exists(left));
|
||||
|
||||
// A proxy upload and a proxy pass that read the sequence before the move write once they hold its lease.
|
||||
var proxy = Proxy(frames[0].CapturedAt!.Value, 2);
|
||||
Assert.Equal(ProxyStoreResult.Stored, await images.StoreProxyAsync(fx.Archive, stale, frames[0], proxy, fx.Ct));
|
||||
Assert.SequenceEqual(proxy, await File.ReadAllBytesAsync(now.Proxy(0), fx.Ct));
|
||||
var pass = await images.BuildProxiesAsync(fx.Archive, stale, force: false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
|
||||
Assert.Equal((0, 1, 0, 1), (pass.Built, pass.Reused, pass.Undecodable, pass.Waiting));
|
||||
Assert.False(Directory.Exists(left), "the folder it left is not created again");
|
||||
|
||||
// Deleted since: nothing is written.
|
||||
Assert.True(await fx.Db.Sequences.DeleteAsync(stale.Id, fx.Ct));
|
||||
Assert.Equal(ProxyStoreResult.Gone, await images.StoreProxyAsync(fx.Archive, stale, frames[1], Proxy(frames[1].CapturedAt!.Value, 3), fx.Ct));
|
||||
Assert.FileMissing(now.Proxy(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ProxiesOfAFolderAnotherIndexMovedWaitForThisIndexsScan()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var (sequence, frames) = await HeifSequenceAsync(fx);
|
||||
var images = fx.Service.Images;
|
||||
var left = fx.Paths.Sequence(sequence.Folder).Folder;
|
||||
var (server, archive) = await fx.OtherWriterAsync();
|
||||
var plan = await server.PlanRenameAsync(archive.Id, [sequence.Id], "moved/{date}", null, fx.Ct);
|
||||
await server.ApplyRenameAsync(plan, null, fx.Ct);
|
||||
var moved = fx.Paths.Sequence(plan.Steps.Single().ToFolder);
|
||||
|
||||
// This index still has the folder where it was: a proxy sent and a proxy pass write nothing, anywhere.
|
||||
var proxy = Proxy(frames[0].CapturedAt!.Value, 2);
|
||||
Assert.Equal(ProxyStoreResult.Gone, await images.StoreProxyAsync(fx.Archive, sequence, frames[0], proxy, fx.Ct));
|
||||
var refused = await Assert.ThrowsAsync<InvalidOperationException>(() =>
|
||||
images.BuildProxiesAsync(fx.Archive, sequence, force: false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct));
|
||||
Assert.Equal(Loc.L("Errors.Archive.FolderMoved"), refused.Message);
|
||||
Assert.False(Directory.Exists(left), "the folder it left is not created again");
|
||||
Assert.FileMissing(moved.Proxy(0));
|
||||
|
||||
// Once this index's scan found it there, they go where it is.
|
||||
await fx.ScanAsync();
|
||||
Assert.Equal(ProxyStoreResult.Stored, await images.StoreProxyAsync(fx.Archive, sequence, frames[0], proxy, fx.Ct));
|
||||
Assert.SequenceEqual(proxy, await File.ReadAllBytesAsync(moved.Proxy(0), fx.Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ImagesOfAFolderAnotherSequenceTookAreNotWrittenThere()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var (sequence, frames) = await HeifSequenceAsync(fx);
|
||||
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "inbox", "other"), Start.AddDays(3), 2, firstSeed: 70);
|
||||
await fx.ScanAsync();
|
||||
var stranger = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id, fx.Ct)).Single(l => l.Folder == "inbox/other").Id;
|
||||
var images = fx.Service.Images;
|
||||
var (server, archive) = await fx.OtherWriterAsync();
|
||||
await server.ApplyRenameAsync(await server.PlanRenameAsync(archive.Id, [sequence.Id], "moved/{date}", null, fx.Ct), null, fx.Ct);
|
||||
await server.ApplyRenameAsync(await server.PlanRenameAsync(archive.Id, [stranger], sequence.Folder, null, fx.Ct), null, fx.Ct);
|
||||
var folder = fx.Paths.Sequence(sequence.Folder).Folder;
|
||||
var before = FilesOf(folder);
|
||||
|
||||
// This index still has the sequence in the folder the other sequence holds now: a proxy sent, a proxy pass and a
|
||||
// thumbnail pass write nothing there.
|
||||
Assert.Equal(ProxyStoreResult.Gone, await images.StoreProxyAsync(fx.Archive, sequence, frames[0], Proxy(frames[0].CapturedAt!.Value, 2), fx.Ct));
|
||||
foreach (var pass in new Func<Task<ImagePassResult>>[]
|
||||
{
|
||||
() => images.BuildProxiesAsync(fx.Archive, sequence, force: false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct),
|
||||
() => images.BuildThumbnailsAsync(fx.Archive, sequence, force: true, 0, (_, _) => ValueTask.CompletedTask, fx.Ct),
|
||||
})
|
||||
Assert.Equal(Loc.L("Errors.Archive.FolderMoved"), (await Assert.ThrowsAsync<InvalidOperationException>(pass)).Message);
|
||||
Assert.SequenceEqual(before, FilesOf(folder));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AProxyPassLetsAnotherProcessReorganizeBetweenItsBatches()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
Guid id = default;
|
||||
for (var i = 0; i < 4; i++)
|
||||
{
|
||||
var staged = fx.Stage(Start.AddSeconds(10 * i), 60 + i);
|
||||
id = (await fx.Service.Ingest.CommitAsync(new IngestRequest(fx.Archive.Id, null, null, "batches", staged.Path, $"IMG_{i + 1:0000}.JPG",
|
||||
staged.Size, staged.Sha256, null, null), fx.Ct)).SequenceId;
|
||||
}
|
||||
var sequence = (await fx.Db.Sequences.GetAsync(id, fx.Ct))!;
|
||||
var left = fx.Paths.Sequence(sequence.Folder).Folder;
|
||||
// The second photo is read as a PNG, through the decoders (JPEGs are decoded without them), and slowly.
|
||||
var sidecar = ManifestStore.ReadSequence(fx.Paths.Sequence(sequence.Folder).ManifestPath);
|
||||
ManifestStore.WriteSequence(fx.Paths.Sequence(sequence.Folder).ManifestPath, sidecar with
|
||||
{
|
||||
Frames = [.. sidecar.Frames.Select(f => f.I == 1 ? f with { Format = ImageFileFormat.Png } : f)],
|
||||
});
|
||||
var gate = new GateDecoder { Hold = Path.GetFileName(sidecar.Frames[1].File) };
|
||||
var (server, archive) = await fx.OtherWriterAsync();
|
||||
var plan = await server.PlanRenameAsync(archive.Id, [id], "moved/{date}", null, fx.Ct);
|
||||
var moved = fx.Paths.Sequence(plan.Steps.Single().ToFolder);
|
||||
|
||||
// A proxy pass here, one photo at a time, in batches of a quarter of its lease wait.
|
||||
var batch = TimeSpan.FromSeconds(TestTiming.Budget(2));
|
||||
var here = new ArchiveService(fx.Db, new ArchiveServiceOptions
|
||||
{
|
||||
Owner = "test",
|
||||
LeaseWait = batch * 4,
|
||||
Decoder = new ImageDecoder([gate]),
|
||||
Parallelism = () => 1,
|
||||
});
|
||||
var pass = Task.Run(() => here.Images.BuildProxiesAsync(fx.Archive, sequence, force: false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct));
|
||||
await Task.WhenAny(gate.Holding.Task, pass).WaitAsync(TimeSpan.FromSeconds(60), fx.Ct);
|
||||
if (pass.IsCompleted) Assert.Fail($"The pass ended before the held photo: {await pass}");
|
||||
var held = DateTime.UtcNow;
|
||||
|
||||
// Another process sharing the archive reorganizes the sequence: it holds the sequence, then waits for the thumbnail lease.
|
||||
var move = Task.Run(() => server.ApplyRenameAsync(plan, null, fx.Ct));
|
||||
var until = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(30));
|
||||
while (LeaseFile.Holder(fx.Paths.LocksDirectory, $"seq-{id:N}")?.Owner != "other")
|
||||
{
|
||||
Assert.False(move.IsCompleted, "the Reorganize waits for the pass");
|
||||
Assert.True(DateTime.UtcNow < until, "the Reorganize holds the sequence");
|
||||
await Task.Delay(20, fx.Ct);
|
||||
}
|
||||
var rest = held + batch + TimeSpan.FromSeconds(0.5) - DateTime.UtcNow;
|
||||
if (rest > TimeSpan.Zero) await Task.Delay(rest, fx.Ct);
|
||||
gate.Release();
|
||||
|
||||
// The batch ends with that photo and lets the lease go: the Reorganize moves the folder before the pass ends, and the
|
||||
// pass, finding the folder gone from where this index has it, stops there.
|
||||
await move.WaitAsync(TimeSpan.FromSeconds(TestTiming.Budget(60)), fx.Ct);
|
||||
var stopped = await Assert.ThrowsAsync<InvalidOperationException>(() => pass);
|
||||
Assert.Equal(Loc.L("Errors.Archive.FolderMoved"), stopped.Message);
|
||||
Assert.False(Directory.Exists(left), "the folder it left is not created again");
|
||||
Assert.FileExists(moved.Proxy(0));
|
||||
Assert.FileExists(moved.Proxy(1));
|
||||
Assert.FileMissing(moved.Proxy(2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AProxyLeftByARenumberedFrameIsAskedForAgain()
|
||||
{
|
||||
@@ -99,8 +243,8 @@ public sealed class ProxyTests(TestContext context)
|
||||
|
||||
// A client or render node sending one that small is refused; one of the policy's size (1920 px) is kept.
|
||||
var frame = frames[0] with { Width = 4032, Height = 3024 };
|
||||
Assert.Equal(ProxyStoreResult.TooSmall, images.StoreProxy(fx.Archive, sequence, frame, Proxy(frame.CapturedAt!.Value, 6, 160, 120)));
|
||||
Assert.Equal(ProxyStoreResult.Stored, images.StoreProxy(fx.Archive, sequence, frame, Proxy(frame.CapturedAt!.Value, 7, 1920, 1440)));
|
||||
Assert.Equal(ProxyStoreResult.TooSmall, await images.StoreProxyAsync(fx.Archive, sequence, frame, Proxy(frame.CapturedAt!.Value, 6, 160, 120), fx.Ct));
|
||||
Assert.Equal(ProxyStoreResult.Stored, await images.StoreProxyAsync(fx.Archive, sequence, frame, Proxy(frame.CapturedAt!.Value, 7, 1920, 1440), fx.Ct));
|
||||
var again = await images.BuildProxiesAsync(fx.Archive, sequence, force: false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
|
||||
Assert.Equal((0, 1, 0, 1), (again.Built, again.Reused, again.Undecodable, again.Waiting));
|
||||
Assert.FileExists(folder.Proxy(0));
|
||||
@@ -114,7 +258,7 @@ public sealed class ProxyTests(TestContext context)
|
||||
var manifest = ManifestStore.ReadArchive(fx.Paths.ManifestPath);
|
||||
ManifestStore.WriteArchive(fx.Paths.ManifestPath, manifest with { ProxyPolicy = new ProxyPolicy { LongEdge = ProxyPolicy.Disabled } });
|
||||
|
||||
Assert.Equal(ProxyStoreResult.Disabled, fx.Service.Images.StoreProxy(fx.Archive, sequence, frames[0], Proxy(frames[0].CapturedAt!.Value, 4)));
|
||||
Assert.Equal(ProxyStoreResult.Disabled, await fx.Service.Images.StoreProxyAsync(fx.Archive, sequence, frames[0], Proxy(frames[0].CapturedAt!.Value, 4), fx.Ct));
|
||||
Assert.FileMissing(fx.Paths.Sequence(sequence.Folder).Proxy(0));
|
||||
}
|
||||
|
||||
@@ -170,7 +314,7 @@ public sealed class ProxyTests(TestContext context)
|
||||
|
||||
// A client makes one from the index's time: it is kept, and the next pass reuses it rather than making its own.
|
||||
var sent = Proxy(frame.CapturedAt!.Value, 1);
|
||||
Assert.Equal(ProxyStoreResult.Stored, images.StoreProxy(fx.Archive, sequence, frame, sent));
|
||||
Assert.Equal(ProxyStoreResult.Stored, await images.StoreProxyAsync(fx.Archive, sequence, frame, sent, fx.Ct));
|
||||
var again = await images.BuildProxiesAsync(fx.Archive, sequence, force: false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
|
||||
Assert.Equal((0, 1), (again.Built, again.Reused));
|
||||
Assert.SequenceEqual(sent, await File.ReadAllBytesAsync(folder.Proxy(0), fx.Ct));
|
||||
@@ -264,7 +408,7 @@ public sealed class ProxyTests(TestContext context)
|
||||
await using var fx = await CreateAsync(context);
|
||||
var (sequence, frames) = await HeifSequenceAsync(fx);
|
||||
var images = fx.Service.Images;
|
||||
Assert.Equal(ProxyStoreResult.Stored, images.StoreProxy(fx.Archive, sequence, frames[1], Proxy(frames[1].CapturedAt!.Value, 1)));
|
||||
Assert.Equal(ProxyStoreResult.Stored, await images.StoreProxyAsync(fx.Archive, sequence, frames[1], Proxy(frames[1].CapturedAt!.Value, 1), fx.Ct));
|
||||
|
||||
// A pass resumed at frame 1 (paused, retried or restarted) finds that frame done, but frame 0 still waits: the
|
||||
// status must not tell a server's clients that nothing is wanted.
|
||||
@@ -272,7 +416,7 @@ public sealed class ProxyTests(TestContext context)
|
||||
Assert.Equal((0, 1, 0, 0), (resumed.Built, resumed.Reused, resumed.Undecodable, resumed.Waiting));
|
||||
Assert.False(await ProxiesBuiltAsync(fx, sequence), "frame 0 has no proxy");
|
||||
|
||||
Assert.Equal(ProxyStoreResult.Stored, images.StoreProxy(fx.Archive, sequence, frames[0], Proxy(frames[0].CapturedAt!.Value, 2)));
|
||||
Assert.Equal(ProxyStoreResult.Stored, await images.StoreProxyAsync(fx.Archive, sequence, frames[0], Proxy(frames[0].CapturedAt!.Value, 2), fx.Ct));
|
||||
await images.BuildProxiesAsync(fx.Archive, sequence, force: false, 1, (_, _) => ValueTask.CompletedTask, fx.Ct);
|
||||
Assert.True(await ProxiesBuiltAsync(fx, sequence), "every frame has its proxy");
|
||||
}
|
||||
@@ -290,7 +434,7 @@ public sealed class ProxyTests(TestContext context)
|
||||
{
|
||||
Frames = [.. sidecar.Frames.Select(f => f with { Tier = DecodeTier.EmbeddedPreview, Flags = f.Flags | FrameFlags.PreviewOnly, PreviewW = 160, PreviewH = 120 })],
|
||||
});
|
||||
Assert.Equal(ProxyStoreResult.Stored, images.StoreProxy(fx.Archive, sequence, frames[0], Proxy(frames[0].CapturedAt!.Value, 1)));
|
||||
Assert.Equal(ProxyStoreResult.Stored, await images.StoreProxyAsync(fx.Archive, sequence, frames[0], Proxy(frames[0].CapturedAt!.Value, 1), fx.Ct));
|
||||
|
||||
// Frame 0 now renders from its proxy, not from the thumbnail: it caps nothing. Its tier stays the original's.
|
||||
await images.BuildProxiesAsync(fx.Archive, sequence, force: false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
|
||||
@@ -315,7 +459,7 @@ public sealed class ProxyTests(TestContext context)
|
||||
var (sequence, frames) = await HeifSequenceAsync(fx);
|
||||
var folder = fx.Paths.Sequence(sequence.Folder);
|
||||
var images = fx.Service.Images;
|
||||
Assert.Equal(ProxyStoreResult.Stored, images.StoreProxy(fx.Archive, sequence, frames[0], Proxy(frames[0].CapturedAt!.Value, 1, 640, 480)));
|
||||
Assert.Equal(ProxyStoreResult.Stored, await images.StoreProxyAsync(fx.Archive, sequence, frames[0], Proxy(frames[0].CapturedAt!.Value, 1, 640, 480), fx.Ct));
|
||||
Task<ImagePassResult> ThumbnailsAsync(bool force = false) =>
|
||||
images.BuildThumbnailsAsync(fx.Archive, sequence, force, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
|
||||
(int, int) Entry()
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -455,6 +455,33 @@ public sealed class AnalysisJobTests(TestContext context)
|
||||
Assert.Contains("13", ProjectSettings.FromJson(await ProjectJsonAsync(fx, folder)).Timing.FrameRate.ReasonArgs!);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ADeepAnalysisWhoseFolderAnotherChronosMovedRecordsNothingAndCreatesNoFolder()
|
||||
{
|
||||
// One decode at a time, so the held one is the only photo being read while the folder moves.
|
||||
await using var fx = await ProcessingFixture.CreateAsync(context, o => o with { DeepAnalysis = o.DeepAnalysis with { MaxDegreeOfParallelism = 1 } });
|
||||
var sequence = await fx.AddAsync(Flickering(12));
|
||||
var left = fx.Folder(sequence).Folder;
|
||||
var (server, archive) = await fx.Archive.OtherWriterAsync();
|
||||
await fx.StartEngineAsync();
|
||||
|
||||
// A server sharing this desktop's archive reorganizes the sequence while the deep pass reads its photos.
|
||||
fx.Decoder.HoldFrame(5);
|
||||
var deep = await fx.EnqueueAsync(ProcessingJobs.DeepAnalysis([sequence.Id]));
|
||||
await fx.Decoder.Holding.Task.WaitAsync(TimeSpan.FromSeconds(60), fx.Ct);
|
||||
var plan = await server.PlanRenameAsync(archive.Id, [sequence.Id], "Moved/{date}", null, fx.Ct);
|
||||
await server.ApplyRenameAsync(plan, null, fx.Ct);
|
||||
fx.Decoder.Hold = null;
|
||||
fx.Decoder.Release();
|
||||
var done = await fx.WaitForAsync(deep.Id, JobState.Done);
|
||||
|
||||
Assert.Contains(Loc.L("Advisor.Log.FramesChangedElsewhere", sequence.DisplayTitle), done.LogTail);
|
||||
Assert.False(Directory.Exists(left), "the folder it left is not created again");
|
||||
var moved = fx.Archive.Paths.Sequence(plan.Steps.Single().ToFolder);
|
||||
Assert.FileMissing(moved.AnalysisPath);
|
||||
Assert.False((await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!.Status.HasFlag(SequenceStatus.AnalyzedDeep), "nothing is recorded");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ALightAnalysisOvertakenByAScanMarksNothingAnalysedAndRunsAgain()
|
||||
{
|
||||
|
||||
@@ -9,6 +9,7 @@ using Chronos.Core.Project;
|
||||
using Chronos.Core.Video;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Data.Tests.Archiving;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Processing;
|
||||
@@ -126,6 +127,55 @@ public sealed class RenderJobTests(TestContext context)
|
||||
Assert.Empty(await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ARenderOfAFolderAnotherIndexMovedWaitsForThisIndexsScan()
|
||||
{
|
||||
await using var fx = await ProcessingFixture.CreateAsync(context);
|
||||
var sequence = await fx.AddAsync(Scene());
|
||||
var left = fx.Folder(sequence).Folder;
|
||||
var (server, archive) = await fx.Archive.OtherWriterAsync();
|
||||
var plan = await server.PlanRenameAsync(archive.Id, [sequence.Id], "Moved/{date}", null, fx.Ct);
|
||||
await server.ApplyRenameAsync(plan, null, fx.Ct);
|
||||
await fx.StartEngineAsync();
|
||||
|
||||
// A server sharing the archive moved the folder; this index has not scanned since. Nothing renders, nothing is flagged.
|
||||
var job = await fx.EnqueueAsync(ProcessingJobs.Render(sequence, Mjpeg, 96, 64));
|
||||
var failed = await fx.WaitForAsync(job.Id, JobState.Failed);
|
||||
Assert.Equal(Loc.L("Errors.Archive.FolderMoved"), failed.Error);
|
||||
Assert.False(Directory.Exists(left), "the folder it left is not created again");
|
||||
Assert.Empty(await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct));
|
||||
Assert.True((await fx.Db.Frames.ListBySequenceAsync(sequence.Id, cancellationToken: fx.Ct)).All(f => (f.Flags & (FrameFlags.Missing | FrameFlags.Undecodable)) == 0), "no frame flagged");
|
||||
|
||||
// Once this index's scan found it there, the render goes into its exports.
|
||||
await fx.Archive.ScanAsync();
|
||||
var again = await fx.EnqueueAsync(ProcessingJobs.Render(sequence, Mjpeg, 96, 64));
|
||||
await fx.WaitForAsync(again.Id, JobState.Done);
|
||||
var moved = fx.Archive.Paths.Sequence(plan.Steps.Single().ToFolder);
|
||||
Assert.FileExists(Path.Combine(moved.Exports, "clip-MJPEG.avi"));
|
||||
Assert.False(Directory.Exists(left));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ARenderNeverWritesIntoAnotherSequenceMovedIntoItsFolder()
|
||||
{
|
||||
await using var fx = await ProcessingFixture.CreateAsync(context);
|
||||
var sequence = await fx.AddAsync(Scene());
|
||||
var stranger = await fx.AddAsync(Scene(), "Other");
|
||||
var (server, archive) = await fx.Archive.OtherWriterAsync();
|
||||
await server.ApplyRenameAsync(await server.PlanRenameAsync(archive.Id, [sequence.Id], "Moved/{date}", null, fx.Ct), null, fx.Ct);
|
||||
await server.ApplyRenameAsync(await server.PlanRenameAsync(archive.Id, [stranger.Id], sequence.Folder, null, fx.Ct), null, fx.Ct);
|
||||
var folder = fx.Folder(sequence).Folder;
|
||||
var before = ArchiveFixture.FilesOf(folder);
|
||||
await fx.StartEngineAsync();
|
||||
|
||||
// A server sharing the archive moved the folder away and the other sequence into it; this index has not scanned since.
|
||||
var job = await fx.EnqueueAsync(ProcessingJobs.Render(sequence, Mjpeg, 96, 64));
|
||||
var failed = await fx.WaitForAsync(job.Id, JobState.Failed);
|
||||
Assert.Equal(Loc.L("Errors.Archive.FolderMoved"), failed.Error);
|
||||
Assert.SequenceEqual(before, ArchiveFixture.FilesOf(folder), "the other sequence's files are untouched");
|
||||
Assert.Empty(await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AFrameThatNoLongerDecodesIsReplacedByItsNeighbourAndLeftOutNextTime()
|
||||
{
|
||||
@@ -325,6 +375,50 @@ public sealed class RenderJobTests(TestContext context)
|
||||
Assert.Count(2, await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ARenderResumedAfterItsFolderMovedNeverDeletesWhatAnotherSequenceBroughtIntoIt()
|
||||
{
|
||||
// The crashed attempt's checkpoint names the folder it chose the output in, or (written by an older version) does not.
|
||||
foreach (var named in new[] { true, false })
|
||||
{
|
||||
await using var fx = await ProcessingFixture.CreateAsync(context);
|
||||
var sequence = await fx.AddAsync(Scene());
|
||||
var stranger = await fx.AddAsync(Scene(), "Other");
|
||||
var output = Path.Combine(fx.Folder(sequence).Exports, "clip-MJPEG.avi");
|
||||
// The crashed attempt left its encoder's temporary file and a finished output it never recorded; the other
|
||||
// sequence has an export of that name, and a hidden file that looks like such a leftover.
|
||||
Directory.CreateDirectory(fx.Folder(sequence).Exports);
|
||||
await File.WriteAllBytesAsync(Path.Combine(fx.Folder(sequence).Exports, ".clip-MJPEG.avi.0badf00d.tmp"), new byte[100], fx.Ct);
|
||||
await File.WriteAllBytesAsync(output, new byte[100], fx.Ct);
|
||||
Directory.CreateDirectory(fx.Folder(stranger).Exports);
|
||||
await File.WriteAllBytesAsync(Path.Combine(fx.Folder(stranger).Exports, ".clip-MJPEG.avi.0ddba11.tmp"), new byte[50], fx.Ct);
|
||||
await File.WriteAllBytesAsync(Path.Combine(fx.Folder(stranger).Exports, "clip-MJPEG.avi"), Encoding.ASCII.GetBytes("RIFF theirs"), fx.Ct);
|
||||
|
||||
// Another index moves the folder away, the leftovers along, then the other sequence into the folder it left; this
|
||||
// index's scan finds both before the job resumes.
|
||||
var (server, archive) = await fx.Archive.OtherWriterAsync();
|
||||
var plan = await server.PlanRenameAsync(archive.Id, [sequence.Id], "Moved/{date}", null, fx.Ct);
|
||||
await server.ApplyRenameAsync(plan, null, fx.Ct);
|
||||
await server.ApplyRenameAsync(await server.PlanRenameAsync(archive.Id, [stranger.Id], sequence.Folder, null, fx.Ct), null, fx.Ct);
|
||||
await fx.Archive.ScanAsync();
|
||||
var before = ArchiveFixture.FilesOf(fx.Folder(sequence).Folder);
|
||||
await fx.StartEngineAsync();
|
||||
|
||||
var job = await fx.Archive.EnqueueWithCheckpointAsync(fx.Engine, ProcessingJobs.Render(sequence, Mjpeg, 96, 64),
|
||||
new RenderCheckpoint([], 0, output, named ? sequence.Folder : null).ToJson());
|
||||
await fx.WaitForAsync(job.Id, JobState.Done);
|
||||
|
||||
Assert.SequenceEqual(before, ArchiveFixture.FilesOf(fx.Folder(sequence).Folder), $"{named}: the other sequence's files are untouched");
|
||||
// Its leftovers are removed where the folder took them when the checkpoint says where it chose the output, and
|
||||
// stay otherwise: the render then takes another name.
|
||||
var moved = fx.Archive.Paths.Sequence(plan.Steps.Single().ToFolder).Exports;
|
||||
Assert.SequenceEqual(named ? ["clip-MJPEG.avi"] : [".clip-MJPEG.avi.0badf00d.tmp", "clip-MJPEG (2).avi", "clip-MJPEG.avi"], Entries(moved), named.ToString());
|
||||
var rendered = (await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct)).Single().OutputPath;
|
||||
Assert.Equal(plan.Steps.Single().ToFolder + (named ? "/exports/clip-MJPEG.avi" : "/exports/clip-MJPEG (2).avi"), rendered);
|
||||
Assert.Equal("RIFF", Encoding.ASCII.GetString((await File.ReadAllBytesAsync(fx.Archive.Paths.FromRelative(rendered), fx.Ct))[..4]));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ConcurrentRendersOfOnePresetKeepBothOutputs()
|
||||
{
|
||||
|
||||
@@ -361,6 +361,43 @@ public abstract class CatalogRepositoryTests(TestContext context) : RepositoryTe
|
||||
Assert.True((await Chronos.Data.Processing.SequenceFrames.ListAsync(db, sequence.Id, Ct)).All(f => (f.Flags, f.PreviewWidth, f.PreviewHeight) == (FrameFlags.None, 4, 3)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task FramesTakeTheNamesAReorganizeGaveTheirFiles()
|
||||
{
|
||||
var db = await OpenChronosAsync();
|
||||
var archive = TestData.Archive();
|
||||
await db.Archives.UpsertAsync(archive, Ct);
|
||||
var sequence = TestData.Sequence(archive.Id) with { FramesVersion = 3 };
|
||||
var other = TestData.Sequence(archive.Id);
|
||||
await db.Sequences.UpsertAsync(sequence, Ct);
|
||||
await db.Sequences.UpsertAsync(other, Ct);
|
||||
// More frames than one batched PostgreSQL statement holds, and a frame of another sequence named in the same call.
|
||||
const int count = 1203;
|
||||
var frames = Enumerable.Range(0, count).Select(i => TestData.Frame(sequence.Id, i)).ToList();
|
||||
var foreign = TestData.Frame(other.Id, 0);
|
||||
await db.Frames.BulkInsertAsync([.. frames, foreign], Ct);
|
||||
|
||||
var renamed = frames.Take(count - 1).Select(f => new FrameFileName(f.Id, $"s/originals/{count - f.Index:00000}.cr3", $"{count - f.Index:00000}.cr3")).ToList();
|
||||
Assert.Equal(count - 1, await db.Frames.RenameFilesAsync(sequence.Id, [.. renamed, new FrameFileName(foreign.Id, "x/y.cr3", "y.cr3")], 3, 4, Ct));
|
||||
var read = new List<Frame>();
|
||||
for (var last = -1; ;)
|
||||
{
|
||||
var page = await db.Frames.ListBySequenceAsync(sequence.Id, last, 1000, Ct);
|
||||
read.AddRange(page);
|
||||
if (page.Count < 1000) break;
|
||||
last = page[^1].Index;
|
||||
}
|
||||
Assert.SequenceEqual(frames.Select(f => f.Id), read.Select(f => f.Id));
|
||||
Assert.SequenceEqual([.. renamed.Select(r => (r.RelativePath, r.FileName)), (frames[^1].RelativePath, frames[^1].FileName)],
|
||||
read.Select(f => (f.RelativePath, f.FileName)));
|
||||
Assert.Equal((foreign.RelativePath, foreign.FileName), (await db.Frames.GetAsync(foreign.Id, Ct)) is { } f2 ? (f2.RelativePath, f2.FileName) : default);
|
||||
Assert.Equal(4, (await db.Sequences.GetAsync(sequence.Id, Ct))!.FramesVersion);
|
||||
|
||||
// A row another writer moved past the version the renames started from keeps its own.
|
||||
await db.Frames.RenameFilesAsync(sequence.Id, [], 3, 9, Ct);
|
||||
Assert.Equal(4, (await db.Sequences.GetAsync(sequence.Id, Ct))!.FramesVersion);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task RendersKeepTheSequenceCountInStep()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Repositories;
|
||||
using Chronos.Data.Tests.Infrastructure;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Repositories;
|
||||
|
||||
/// <summary>
|
||||
/// The stamp of what a Reorganize plans from in an archive's index (<see cref="SequenceRepository.GetStampAsync"/>) on both
|
||||
/// dialects: the server makes a kept Reorganize plan again once it is another one, and only then (owner review 2, R7).
|
||||
/// </summary>
|
||||
public abstract class SequenceStampTests(TestContext context) : RepositoryTest(context)
|
||||
{
|
||||
[Test]
|
||||
public async Task TheStampFollowsWhatAReorganizePlansFromAndNothingElse()
|
||||
{
|
||||
var db = await OpenChronosAsync();
|
||||
var archive = TestData.Archive();
|
||||
var other = TestData.Archive("Other");
|
||||
await db.Archives.UpsertAsync(archive, Ct);
|
||||
await db.Archives.UpsertAsync(other, Ct);
|
||||
var roof = TestData.Sequence(archive.Id, new DateTime(2026, 9, 28, 18, 0, 0), "Roof");
|
||||
var inner = TestData.Sequence(archive.Id, null, "Inner") with { Folder = roof.Folder + "/inner" };
|
||||
var ridge = TestData.Sequence(archive.Id, new DateTime(2026, 9, 29, 7, 0, 0), "Ridge");
|
||||
IReadOnlyList<Guid> planned = [roof.Id];
|
||||
var empty = await db.Sequences.GetStampAsync(archive.Id, planned, Ct);
|
||||
foreach (var sequence in new[] { roof, inner, ridge }) await db.Sequences.UpsertAsync(sequence, Ct);
|
||||
var stamp = await db.Sequences.GetStampAsync(archive.Id, planned, Ct);
|
||||
Assert.NotEqual(empty, stamp);
|
||||
Assert.Equal(stamp, await db.Sequences.GetStampAsync(archive.Id, planned, Ct));
|
||||
Assert.NotEqual(stamp, await db.Sequences.GetStampAsync(archive.Id, null, Ct));
|
||||
|
||||
// What the plan does not read: another archive, and the writes of every upload, verify, tag or status change elsewhere.
|
||||
await db.Sequences.UpsertAsync(TestData.Sequence(other.Id), Ct);
|
||||
await VerifyAsync(db, await PhotoAsync(db, ridge, 0, hashed: false));
|
||||
await VerifyAsync(db, await PhotoAsync(db, inner, 0, hashed: false));
|
||||
Assert.Equal(SequenceEditOutcome.Updated, (await db.Sequences.EditAsync(ridge.Id, new SequenceEdit { Title = "Ridge at dawn", Notes = "cold" }, null, Ct)).Outcome);
|
||||
foreach (var id in new[] { roof.Id, ridge.Id })
|
||||
{
|
||||
Assert.True(await db.Sequences.SetTagsAsync(id, ["sky"], Ct));
|
||||
Assert.True(await db.Sequences.UpdateStatusAsync(id, SequenceStatus.ProxiesBuilt, SequenceStatus.None, Ct));
|
||||
Assert.True(await db.Sequences.RecordVerifiedAsync(id, SequenceStatus.None, SequenceStatus.None, TestData.Now, Ct));
|
||||
}
|
||||
Assert.Equal(stamp, await db.Sequences.GetStampAsync(archive.Id, planned, Ct));
|
||||
|
||||
// What it reads gives one never seen before: the sequences planned, the titles inside their folders, every folder.
|
||||
var seen = new HashSet<string>(StringComparer.Ordinal) { empty, stamp };
|
||||
async Task ChangedAsync(string what) => Assert.True(seen.Add(await db.Sequences.GetStampAsync(archive.Id, planned, Ct)), what);
|
||||
Assert.Equal(SequenceEditOutcome.Updated, (await db.Sequences.EditAsync(roof.Id, new SequenceEdit { Title = "Roof at noon" }, null, Ct)).Outcome);
|
||||
await ChangedAsync("title");
|
||||
var scanned = await PhotoAsync(db, roof, 0, hashed: false);
|
||||
await ChangedAsync("photos");
|
||||
await VerifyAsync(db, scanned);
|
||||
await ChangedAsync("photos hashed by a verify, which a file template renames");
|
||||
Assert.Equal(SequenceEditOutcome.Updated, (await db.Sequences.EditAsync(inner.Id, new SequenceEdit { Title = "Inner court" }, null, Ct)).Outcome);
|
||||
await ChangedAsync("title of a sequence a moving folder would carry");
|
||||
Assert.True(await db.Sequences.RelocateAsync(ridge.Id, "2026/ridge", null, Ct));
|
||||
await ChangedAsync("folder of a sequence not planned");
|
||||
Assert.True(await db.Sequences.RelocateAsync(roof.Id, "2026/moved", null, Ct));
|
||||
await ChangedAsync("folder");
|
||||
var added = TestData.Sequence(archive.Id);
|
||||
await db.Sequences.UpsertAsync(added, Ct);
|
||||
await ChangedAsync("a sequence added");
|
||||
Assert.True(await db.Sequences.DeleteAsync(added.Id, Ct));
|
||||
Assert.Contains(await db.Sequences.GetStampAsync(archive.Id, planned, Ct), seen);
|
||||
|
||||
// With every sequence planned, a photo anywhere changes the plan read, and so does a verify that hashes one; a verify
|
||||
// that hashes none still does not.
|
||||
var all = await db.Sequences.GetStampAsync(archive.Id, null, Ct);
|
||||
Assert.True(await db.Sequences.RecordVerifiedAsync(ridge.Id, SequenceStatus.None, SequenceStatus.None, TestData.Now.AddDays(1), Ct));
|
||||
Assert.Equal(all, await db.Sequences.GetStampAsync(archive.Id, null, Ct));
|
||||
var photo = await PhotoAsync(db, ridge, 1, hashed: false);
|
||||
var uploaded = await db.Sequences.GetStampAsync(archive.Id, null, Ct);
|
||||
Assert.NotEqual(all, uploaded);
|
||||
await VerifyAsync(db, photo);
|
||||
var verified = await db.Sequences.GetStampAsync(archive.Id, null, Ct);
|
||||
Assert.False(verified == all || verified == uploaded, "a photo hashed");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A photo indexed into a sequence, as an upload does, or without its hash, as a scan does: the frame, then the row's
|
||||
/// counts and frames version.
|
||||
/// </summary>
|
||||
private async Task<Frame> PhotoAsync(ChronosDatabase db, Sequence sequence, int index, bool hashed = true)
|
||||
{
|
||||
var frame = TestData.Frame(sequence.Id, index);
|
||||
frame = frame with { RelativePath = $"{sequence.Folder}/originals/{frame.FileName}", Sha256 = hashed ? frame.Sha256 : null };
|
||||
await db.Frames.BulkInsertAsync([frame], Ct);
|
||||
Assert.NotNull(await db.Sequences.RefreshStatsAsync(sequence.Id, Ct));
|
||||
return frame;
|
||||
}
|
||||
|
||||
/// <summary>What a verify writes once it hashed a photo never hashed: the hash, then the sequence's verify time, and not another frames version.</summary>
|
||||
private async Task VerifyAsync(ChronosDatabase db, Frame frame)
|
||||
{
|
||||
var version = (await db.Sequences.GetAsync(frame.SequenceId, Ct))!.FramesVersion;
|
||||
var sha256 = TestData.Frame(frame.SequenceId, frame.Index).Sha256;
|
||||
Assert.Equal(1, await db.Frames.UpdateIntegrityAsync([new FrameIntegrity(frame.Id, FrameFlags.None, sha256)], Ct));
|
||||
Assert.True(await db.Sequences.RecordVerifiedAsync(frame.SequenceId, SequenceStatus.Verified, SequenceStatus.None, TestData.Now, Ct));
|
||||
Assert.Equal(version, (await db.Sequences.GetAsync(frame.SequenceId, Ct))!.FramesVersion);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class SqliteSequenceStampTests(TestContext context) : SequenceStampTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.SqliteMemory;
|
||||
}
|
||||
|
||||
[RequiresEnvironment(PgTestServer.Variable)]
|
||||
public sealed class PostgresSequenceStampTests(TestContext context) : SequenceStampTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.Postgres;
|
||||
}
|
||||
@@ -103,22 +103,38 @@ internal sealed class FakeSyncRemote : ISyncRemote
|
||||
}
|
||||
}
|
||||
|
||||
public Task<SequenceManifest> GetManifestAsync(Guid id, CancellationToken cancellationToken)
|
||||
/// <summary>Runs once, before the next manifest is answered: the archive on this PC changing while the sync compares.</summary>
|
||||
public Func<Task>? OnceBeforeManifest { get; set; }
|
||||
|
||||
public async Task<SequenceManifest> GetManifestAsync(Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
if (OnceBeforeManifest is { } before)
|
||||
{
|
||||
OnceBeforeManifest = null;
|
||||
await before();
|
||||
}
|
||||
lock (_gate)
|
||||
{
|
||||
ManifestCalls++;
|
||||
if (Refused.Contains(id)) throw new ChronosApiException(HttpStatusCode.Forbidden, new ApiError("forbidden", "refused"));
|
||||
return Task.FromResult(Find(id).Manifest(SentProxies.ContainsKey));
|
||||
return Find(id).Manifest(SentProxies.ContainsKey);
|
||||
}
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<FrameDto>> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken)
|
||||
/// <summary>Runs once, before the next frame listing is answered (frame positions translated against the server's frames).</summary>
|
||||
public Func<Task>? OnceBeforeFrames { get; set; }
|
||||
|
||||
public async Task<IReadOnlyList<FrameDto>> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken)
|
||||
{
|
||||
if (OnceBeforeFrames is { } before)
|
||||
{
|
||||
OnceBeforeFrames = null;
|
||||
await before();
|
||||
}
|
||||
lock (_gate)
|
||||
{
|
||||
var sequence = Find(sequenceId);
|
||||
return Task.FromResult<IReadOnlyList<FrameDto>>([.. sequence.Frames.Select(sequence.FrameDto)]);
|
||||
return [.. sequence.Frames.Select(sequence.FrameDto)];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Archiving;
|
||||
@@ -97,6 +98,35 @@ public sealed class SyncServiceTests(TestContext context)
|
||||
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SettingsTakenWhileAReorganizeMovesTheFolderGoWhereTheSequenceIsNow()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(2);
|
||||
var local = await f.LocalAsync("Harbour", photos);
|
||||
var remote = f.Remote.Add("Harbour", photos);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
await f.RefreshAsync();
|
||||
var left = f.Archive.Paths.Sequence((await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.Folder).Folder;
|
||||
|
||||
// The server's edit is taken after a Reorganize moved the folder of the copy the comparison had read.
|
||||
f.Remote.EditSettings(remote.Id, SyncFixture.Window33);
|
||||
f.Remote.OnceBeforeManifest = async () =>
|
||||
{
|
||||
var plan = await f.Archive.Service.PlanRenameAsync(f.Archive.Archive.Id, [local.Id], "moved/{title}", null, f.Ct);
|
||||
await f.Archive.Service.ApplyRenameAsync(plan, null, f.Ct);
|
||||
};
|
||||
await f.RefreshAsync();
|
||||
Assert.Null(f.Remote.OnceBeforeManifest, "the folder moved during the comparison");
|
||||
|
||||
var taken = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!;
|
||||
Assert.Equal("moved/Harbour", taken.Folder);
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, taken.SettingsJson), "the server's edit reached this PC");
|
||||
var project = await File.ReadAllTextAsync(f.Archive.Paths.Sequence(taken.Folder).ProjectPath, f.Ct);
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, project), "project.json in the moved folder follows the index");
|
||||
Assert.False(Directory.Exists(left), "the folder it left is not created again");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task PositionsSentToTheServerNameItsFramesAndWaitForPhotosItLacks()
|
||||
{
|
||||
@@ -403,6 +433,144 @@ public sealed class SyncServiceTests(TestContext context)
|
||||
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Holy grail")).Status);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SaveBothWhileAReorganizeMovesTheFolderKeepsTheCopyWhereTheSequenceIsNow()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var (local, remote) = await ConflictAsync(f);
|
||||
var left = f.Archive.Paths.Sequence(local.Folder).Folder;
|
||||
|
||||
// A Reorganize moves the folder while the server's version is read.
|
||||
f.Remote.OnceBeforeManifest = async () =>
|
||||
{
|
||||
var plan = await f.Archive.Service.PlanRenameAsync(f.Archive.Archive.Id, [local.Id], "moved/{title}", null, f.Ct);
|
||||
await f.Archive.Service.ApplyRenameAsync(plan, null, f.Ct);
|
||||
};
|
||||
var copy = await f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.SaveBoth, f.Ct);
|
||||
Assert.Null(f.Remote.OnceBeforeManifest, "the folder moved during the resolution");
|
||||
|
||||
var taken = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!;
|
||||
Assert.Equal("moved/Holy grail", taken.Folder);
|
||||
Assert.Equal(copy, Assert.Contains(Directory.GetFiles(f.Archive.Paths.Sequence(taken.Folder).MetaDirectory, "project.this-pc-*.json"), _ => true));
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, await File.ReadAllTextAsync(copy!, f.Ct)), "this PC's version is kept");
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, taken.SettingsJson));
|
||||
Assert.False(Directory.Exists(left), "the folder it left is not created again");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SaveBothThatCannotKeepThisPcsVersionTakesNothing()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
// The server holds a photo this PC does not have yet, and its settings name a frame: taking them reads the server's
|
||||
// frames, after this PC's copy was kept and before the server's version is written.
|
||||
var photos = f.NewPhotos(3);
|
||||
var local = await f.LocalAsync("Holy grail", photos[..2]);
|
||||
var remote = f.Remote.Add("Holy grail", photos);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
await f.RefreshAsync();
|
||||
local = await f.EditLocalSettingsAsync(local.Id, SyncFixture.Window41);
|
||||
var theirs = """{"heroFrame":1,"exposure":{"deflickerWindow":{"isAuto":false,"manual":33}}}""";
|
||||
f.Remote.EditSettings(remote.Id, theirs);
|
||||
await f.RefreshAsync();
|
||||
Assert.NotNull((await f.EntryAsync("Holy grail")).Link!.ConflictRemote);
|
||||
var left = f.Archive.Paths.Sequence(local.Folder).Folder;
|
||||
|
||||
// Another index moves the folder while the server's version is read, so this PC's version cannot be kept there; this
|
||||
// index's scan finds the folder before the server's version would be written.
|
||||
var (other, archive) = await f.Archive.OtherWriterAsync();
|
||||
string? moved = null;
|
||||
f.Remote.OnceBeforeManifest = async () =>
|
||||
{
|
||||
var plan = await other.PlanRenameAsync(archive.Id, [local.Id], "moved/{title}", null, f.Ct);
|
||||
await other.ApplyRenameAsync(plan, null, f.Ct);
|
||||
moved = plan.Steps.Single().ToFolder;
|
||||
};
|
||||
f.Remote.OnceBeforeFrames = () => f.Archive.ScanAsync();
|
||||
var refused = await Assert.ThrowsAsync<SyncConflictChangedException>(() => f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.SaveBoth, f.Ct));
|
||||
Assert.Equal(Loc.L("Errors.Archive.FolderMoved"), refused.Message, "the user hears to try again after the next scan");
|
||||
// The server's frames were not read for a version that is not taken: the scan comes now.
|
||||
f.Remote.OnceBeforeFrames = null;
|
||||
await f.Archive.ScanAsync();
|
||||
|
||||
var kept = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!;
|
||||
Assert.Equal(moved, kept.Folder, "the scan found the folder");
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, kept.SettingsJson), "this PC's version is not replaced without its copy");
|
||||
var meta = f.Archive.Paths.Sequence(kept.Folder).MetaDirectory;
|
||||
Assert.Empty(Directory.GetFiles(meta, SyncService.SavedCopyPattern));
|
||||
Assert.False(Directory.Exists(left), "the folder it left is not created again");
|
||||
Assert.NotNull((await f.EntryAsync("Holy grail")).Link!.ConflictRemote, "still a conflict");
|
||||
|
||||
// Asked again where the sequence is now, both versions are kept.
|
||||
var copy = await f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.SaveBoth, f.Ct);
|
||||
Assert.Equal(copy, Assert.Contains(Directory.GetFiles(meta, SyncService.SavedCopyPattern), _ => true));
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, await File.ReadAllTextAsync(copy!, f.Ct)), "this PC's version is kept");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TakeServerWhereAnotherIndexMovedTheFolderWritesNothing()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var (local, remote) = await ConflictAsync(f);
|
||||
var left = f.Archive.Paths.Sequence(local.Folder).Folder;
|
||||
|
||||
// Another index moves the folder while the server's version is read; this index has not scanned it since.
|
||||
var (other, archive) = await f.Archive.OtherWriterAsync();
|
||||
f.Remote.OnceBeforeManifest = async () =>
|
||||
{
|
||||
var plan = await other.PlanRenameAsync(archive.Id, [local.Id], "moved/{title}", null, f.Ct);
|
||||
await other.ApplyRenameAsync(plan, null, f.Ct);
|
||||
};
|
||||
var refused = await Assert.ThrowsAsync<SyncConflictChangedException>(() => f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.TakeServer, f.Ct));
|
||||
Assert.Null(f.Remote.OnceBeforeManifest, "the folder moved during the resolution");
|
||||
Assert.Equal(Loc.L("Errors.Archive.FolderMoved"), refused.Message, "the user hears to try again after the next scan");
|
||||
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson), "nothing applied");
|
||||
Assert.False(Directory.Exists(left), "the folder it left is not created again");
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, await File.ReadAllTextAsync(f.Archive.Paths.Sequence("moved/Holy grail").ProjectPath, f.Ct)),
|
||||
"the moved project is this PC's version");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TakeServerAndSaveBothWriteNothingIntoAnotherSequenceMovedIntoTheFolder()
|
||||
{
|
||||
const string strangers = """{"exposure":{"deflickerWindow":{"isAuto":false,"manual":7}}}""";
|
||||
foreach (var resolution in new[] { SyncResolution.TakeServer, SyncResolution.SaveBoth })
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var (local, remote) = await ConflictAsync(f);
|
||||
var stranger = await f.LocalAsync("Stranger", f.NewPhotos(2), strangers);
|
||||
var folder = f.Archive.Paths.Sequence(local.Folder);
|
||||
|
||||
// Another index moves the folder away while the server's version is read, then another sequence (first parked
|
||||
// elsewhere: its folder is the same name with a number) into the folder it left; this index has scanned neither.
|
||||
var (other, archive) = await f.Archive.OtherWriterAsync();
|
||||
List<string>? before = null;
|
||||
f.Remote.OnceBeforeManifest = async () =>
|
||||
{
|
||||
foreach (var (id, template) in new[] { (local.Id, "moved/{title}"), (stranger.Id, "parked/{title}"), (stranger.Id, local.Folder) })
|
||||
await other.ApplyRenameAsync(await other.PlanRenameAsync(archive.Id, [id], template, null, f.Ct), null, f.Ct);
|
||||
before = ArchiveFixture.FilesOf(folder.Folder);
|
||||
};
|
||||
var refused = await Assert.ThrowsAsync<SyncConflictChangedException>(() => f.Sync.ResolveAsync(f.Remote, remote.Id, resolution, f.Ct));
|
||||
Assert.Equal(Loc.L("Errors.Archive.FolderMoved"), refused.Message, $"{resolution}: the user hears to try again after the next scan");
|
||||
|
||||
// Neither version went into the other sequence's folder, nor replaced this PC's where the sequence is.
|
||||
Assert.Equal(stranger.Id, SequenceTrash.SidecarId(folder.ManifestPath), "the other sequence holds the folder");
|
||||
Assert.SequenceEqual(before!, ArchiveFixture.FilesOf(folder.Folder), $"{resolution}: the other sequence's files are untouched");
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson), "nothing applied");
|
||||
var moved = f.Archive.Paths.Sequence("moved/Holy grail");
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, await File.ReadAllTextAsync(moved.ProjectPath, f.Ct)), "the moved project is this PC's version");
|
||||
Assert.Empty(Directory.GetFiles(moved.MetaDirectory, SyncService.SavedCopyPattern));
|
||||
|
||||
// Chosen again once this index's scan found both, it is done where the sequence is now.
|
||||
await f.Archive.ScanAsync();
|
||||
var copy = await f.Sync.ResolveAsync(f.Remote, remote.Id, resolution, f.Ct);
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, await File.ReadAllTextAsync(moved.ProjectPath, f.Ct)), resolution.ToString());
|
||||
Assert.Equal(resolution == SyncResolution.SaveBoth, copy is not null && Path.GetDirectoryName(copy) == moved.MetaDirectory);
|
||||
Assert.True(SyncRules.SameSettings(strangers, await File.ReadAllTextAsync(folder.ProjectPath, f.Ct)), "the other sequence keeps its own");
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task KeepMineRefusesWhenTheServerChangedAfterTheConflictWasShown()
|
||||
{
|
||||
@@ -441,7 +609,8 @@ public sealed class SyncServiceTests(TestContext context)
|
||||
var later = SyncFixture.Window41.Replace("41", "45", StringComparison.Ordinal);
|
||||
await f.EditLocalSettingsAsync(local.Id, later);
|
||||
|
||||
await Assert.ThrowsAsync<SyncConflictChangedException>(() => f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.TakeServer, f.Ct));
|
||||
var refused = await Assert.ThrowsAsync<SyncConflictChangedException>(() => f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.TakeServer, f.Ct));
|
||||
Assert.Equal(Loc.L("Errors.Sync.ChangedAgain"), refused.Message);
|
||||
|
||||
Assert.True(SyncRules.SameSettings(later, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson), "this PC's later edit is kept");
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, remote.SettingsJson));
|
||||
|
||||
@@ -6,6 +6,7 @@ using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Render;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Data.Tests.Archiving;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Testing;
|
||||
|
||||
@@ -384,6 +385,54 @@ public sealed class SyncTransferTests(TestContext context)
|
||||
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnOriginalIsRestoredOnlyWhereTheSequenceIsNow()
|
||||
{
|
||||
// The folder the sequence left holds another sequence now, or nothing.
|
||||
foreach (var taken in new[] { true, false })
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(3);
|
||||
var local = await f.LocalAsync("Harbour", photos);
|
||||
var stranger = taken ? await f.LocalAsync("Stranger", f.NewPhotos(2)) : null;
|
||||
var lost = (await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct))[1];
|
||||
File.Delete(f.Archive.Paths.FromRelative(lost.RelativePath));
|
||||
await f.Archive.Service.Verifier.VerifyAsync(f.Archive.Archive, [local.Id], default, (_, _, _) => ValueTask.CompletedTask, cancellationToken: f.Ct);
|
||||
var remote = f.Remote.Add("Harbour", photos);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
await f.RefreshAsync();
|
||||
var engine = await f.StartEngineAsync();
|
||||
|
||||
// Another index moves the folder away, then the other sequence (first parked elsewhere: its folder is the same
|
||||
// name with a number) into the folder it left; this index has scanned neither.
|
||||
var folder = f.Archive.Paths.Sequence(local.Folder).Folder;
|
||||
var (other, archive) = await f.Archive.OtherWriterAsync();
|
||||
var moves = stranger is null ? [(local.Id, "moved/{title}")] : new[] { (local.Id, "moved/{title}"), (stranger.Id, "parked/{title}"), (stranger.Id, local.Folder) };
|
||||
foreach (var (id, template) in moves)
|
||||
await other.ApplyRenameAsync(await other.PlanRenameAsync(archive.Id, [id], template, null, f.Ct), null, f.Ct);
|
||||
var before = taken ? ArchiveFixture.FilesOf(folder) : null;
|
||||
|
||||
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Harbour", SyncDownloadMode.Originals, null);
|
||||
var failed = await f.Archive.WaitForAsync(job.Id, JobState.Failed);
|
||||
Assert.Equal(Loc.L("Errors.Archive.FolderMoved"), failed.Error, taken.ToString());
|
||||
if (taken) Assert.SequenceEqual(before!, ArchiveFixture.FilesOf(folder), "the other sequence's files are untouched");
|
||||
else Assert.False(Directory.Exists(folder), "the folder it left is not created again");
|
||||
|
||||
// Once this index's scan found it there, the original goes back into the folder the sequence is in now.
|
||||
await f.Archive.ScanAsync();
|
||||
job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Harbour", SyncDownloadMode.Originals, null);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
var moved = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.Folder;
|
||||
Assert.Equal("moved/Harbour", moved);
|
||||
var restored = (await f.Db.Frames.GetAsync(lost.Id, f.Ct))!;
|
||||
Assert.Equal(moved + lost.RelativePath[local.Folder.Length..], restored.RelativePath);
|
||||
Assert.Equal(lost.Sha256, Sha(await File.ReadAllBytesAsync(f.Archive.Paths.FromRelative(restored.RelativePath), f.Ct)));
|
||||
Assert.True((await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct)).All(fr => (fr.Flags & FrameFlags.Missing) == 0), "nothing missing");
|
||||
if (taken) Assert.SequenceEqual(before!, ArchiveFixture.FilesOf(folder), "the other sequence's files are still untouched");
|
||||
else Assert.False(Directory.Exists(folder));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task OriginalsTheServerHasNotHashedAreDownloadedAndHashedHere()
|
||||
{
|
||||
@@ -600,6 +649,55 @@ public sealed class SyncTransferTests(TestContext context)
|
||||
Assert.Equal(0, (await f.EntryAsync("Star trails")).Link!.ExportsToGet);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheServersRendersGoWhereTheSequenceIsNow()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(2);
|
||||
var local = await f.LocalAsync("Star trails", photos);
|
||||
var remote = f.Remote.Add("Star trails", photos);
|
||||
var first = new FakeRender(Guid.CreateVersion7(), "Star trails 4K.mp4", "4K HEVC", [.. Enumerable.Range(0, 3000).Select(i => (byte)i)]);
|
||||
remote.Renders.Add(first);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
await f.RefreshAsync();
|
||||
var engine = await f.StartEngineAsync();
|
||||
var left = f.Archive.Paths.Sequence(local.Folder).Folder;
|
||||
|
||||
// A Reorganize here moves the folder while the server's renders are listed: the render goes where the sequence is.
|
||||
string? moved = null;
|
||||
f.Remote.OnceBeforeManifest = async () =>
|
||||
{
|
||||
var plan = await f.Archive.Service.PlanRenameAsync(f.Archive.Archive.Id, [local.Id], "moved/{title}", null, f.Ct);
|
||||
await f.Archive.Service.ApplyRenameAsync(plan, null, f.Ct);
|
||||
moved = plan.Steps.Single().ToFolder;
|
||||
};
|
||||
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Star trails", SyncDownloadMode.Exports, null);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
Assert.Equal($"{moved}/exports/Star trails 4K.mp4", (await f.Db.Renders.GetAsync(first.Id, f.Ct))!.OutputPath);
|
||||
Assert.FileExists(f.Archive.Paths.FromRelative($"{moved}/exports/Star trails 4K.mp4"));
|
||||
Assert.False(Directory.Exists(left), "the folder it left is not created again");
|
||||
|
||||
// Another index moves it: nothing is filed until this index's scan finds it there.
|
||||
var second = new FakeRender(Guid.CreateVersion7(), "Star trails 1080p.mp4", "1080p", [.. Enumerable.Range(0, 2000).Select(i => (byte)(i * 3))]);
|
||||
remote.Renders.Add(second);
|
||||
remote.UpdatedAt = DateTimeOffset.UtcNow.AddSeconds(1);
|
||||
var (other, archive) = await f.Archive.OtherWriterAsync();
|
||||
var away = await other.PlanRenameAsync(archive.Id, [local.Id], "elsewhere/{title}", null, f.Ct);
|
||||
await other.ApplyRenameAsync(away, null, f.Ct);
|
||||
job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Star trails", SyncDownloadMode.Exports, null);
|
||||
var failed = await f.Archive.WaitForAsync(job.Id, JobState.Failed);
|
||||
Assert.Equal(Loc.L("Errors.Archive.FolderMoved"), failed.Error);
|
||||
Assert.False(Directory.Exists(f.Archive.Paths.Sequence(moved!).Folder), "the folder it left is not created again");
|
||||
Assert.Null(await f.Db.Renders.GetAsync(second.Id, f.Ct));
|
||||
|
||||
await f.Archive.ScanAsync();
|
||||
job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Star trails", SyncDownloadMode.Exports, null);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
var fetched = (await f.Db.Renders.GetAsync(second.Id, f.Ct))!;
|
||||
Assert.Equal("elsewhere/Star trails/exports/Star trails 1080p.mp4", fetched.OutputPath);
|
||||
Assert.SequenceEqual(second.Bytes, await File.ReadAllBytesAsync(f.Archive.Paths.FromRelative(fetched.OutputPath), f.Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task RendersMadeHereAreSentOnRequestAndAGoneFileIsReported()
|
||||
{
|
||||
|
||||
@@ -175,6 +175,22 @@ public sealed class AdminTests(TestContext context)
|
||||
|
||||
using (var bad = await admin.PutAsJsonAsync("/api/v1/archive/settings", archive with { FolderTemplate = "{year/{date" }, ProtocolJson.Default.ArchiveSettingsDto))
|
||||
Assert.Equal("folderTemplate", (await bad.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_template")).Details);
|
||||
// Templates that would hide sequences from scans, drop extensions or repeat names: refused as Reorganize refuses them,
|
||||
// with the rule after the field and the message saying why, as the desktop does.
|
||||
foreach (var (refused, details, rule) in new[]
|
||||
{
|
||||
(archive with { FolderTemplate = "Originals/{year}" }, "folderTemplate:reserved_folder", "ReservedFolder"),
|
||||
(archive with { FileTemplate = "{n}{ext}" }, "fileTemplate:extension", "Extension"),
|
||||
(archive with { FileTemplate = "{date}" }, "fileTemplate:not_unique", "NotUnique"),
|
||||
(archive with { FileTemplate = " " }, "fileTemplate", (string?)null),
|
||||
})
|
||||
{
|
||||
using var response = await admin.PutAsJsonAsync("/api/v1/archive/settings", refused, ProtocolJson.Default.ArchiveSettingsDto);
|
||||
var error = await response.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_template");
|
||||
Assert.Equal(details, error.Details);
|
||||
Assert.Equal(Chronos.Core.Localization.Loc.Get(rule is null ? "Server.Error.InvalidTemplate" : "Errors.Template." + rule,
|
||||
System.Globalization.CultureInfo.GetCultureInfo("en")), error.Message);
|
||||
}
|
||||
using (var good = await admin.PutAsJsonAsync("/api/v1/archive/settings", archive with { Name = "Studio", ProxyLongEdge = 2560 }, ProtocolJson.Default.ArchiveSettingsDto))
|
||||
{
|
||||
var saved = await good.ReadAsync(ProtocolJson.Default.ArchiveSettingsDto);
|
||||
@@ -250,4 +266,54 @@ public sealed class AdminTests(TestContext context)
|
||||
}
|
||||
await File.WriteAllBytesAsync(path, saved, context.Cancellation);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TemplatesSavedBeforeTheRulesNeverFailASaveOfTheOtherFields()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: Chronos.Server.Storage.ArchiveModule.Register);
|
||||
var admin = await server.AdminAsync();
|
||||
// An archive.json of 0.1.0-rc.5 or earlier: both templates break a rule new templates are held to.
|
||||
var path = new Chronos.Core.Archiving.ArchivePaths(server.Options.ArchivePath).ManifestPath;
|
||||
var manifest = Chronos.Core.Archiving.ManifestStore.ReadArchive(path);
|
||||
Chronos.Core.Archiving.ManifestStore.WriteArchive(path, manifest with
|
||||
{
|
||||
LayoutTemplates = new Chronos.Core.Archiving.LayoutTemplates { Folder = "exports/{date}", File = "{date}" },
|
||||
});
|
||||
using var read = await admin.GetAsync("/api/v1/archive/settings");
|
||||
var archive = await read.ReadAsync(ProtocolJson.Default.ArchiveSettingsDto);
|
||||
Assert.Equal(("exports/{date}", "{date}"), (archive.FolderTemplate, archive.FileTemplate));
|
||||
|
||||
// The form sends every field with each save: the name and the proxies change, the templates stay as they are.
|
||||
using (var put = await admin.PutAsJsonAsync("/api/v1/archive/settings", archive with { Name = "Studio", ProxyLongEdge = 2560 }, ProtocolJson.Default.ArchiveSettingsDto))
|
||||
{
|
||||
var saved = await put.ReadAsync(ProtocolJson.Default.ArchiveSettingsDto);
|
||||
Assert.Equal(("Studio", "exports/{date}", "{date}", 2560), (saved.Name, saved.FolderTemplate, saved.FileTemplate, saved.ProxyLongEdge));
|
||||
}
|
||||
archive = archive with { Name = "Studio", ProxyLongEdge = 2560 };
|
||||
|
||||
// A template given anew is held to every rule; each one is fixed alone.
|
||||
using (var refused = await admin.PutAsJsonAsync("/api/v1/archive/settings", archive with { FileTemplate = "{n}{ext}" }, ProtocolJson.Default.ArchiveSettingsDto))
|
||||
Assert.Equal("fileTemplate:extension", (await refused.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_template")).Details);
|
||||
using (var folder = await admin.PutAsJsonAsync("/api/v1/archive/settings", archive with { FolderTemplate = "{year}/{date}" }, ProtocolJson.Default.ArchiveSettingsDto))
|
||||
{
|
||||
var saved = await folder.ReadAsync(ProtocolJson.Default.ArchiveSettingsDto);
|
||||
Assert.Equal(("{year}/{date}", "{date}"), (saved.FolderTemplate, saved.FileTemplate));
|
||||
}
|
||||
archive = archive with { FolderTemplate = "{year}/{date}" };
|
||||
|
||||
// A desktop fixed the file template in archive.json since the form was read: the old one the form still sends is no
|
||||
// longer the file's, so it is held to the rules and the save says which one it breaks.
|
||||
Chronos.Core.Archiving.ManifestStore.WriteArchive(path, Chronos.Core.Archiving.ManifestStore.ReadArchive(path) with
|
||||
{
|
||||
LayoutTemplates = new Chronos.Core.Archiving.LayoutTemplates { Folder = "{year}/{date}", File = "{date}_{n:0000}" },
|
||||
});
|
||||
var before = await File.ReadAllBytesAsync(path, context.Cancellation);
|
||||
using (var stale = await admin.PutAsJsonAsync("/api/v1/archive/settings", archive with { ProxyLongEdge = 1280 }, ProtocolJson.Default.ArchiveSettingsDto))
|
||||
{
|
||||
var error = await stale.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_template");
|
||||
Assert.Equal(("fileTemplate:not_unique", Chronos.Core.Localization.Loc.Get("Errors.Template.NotUnique", System.Globalization.CultureInfo.GetCultureInfo("en"))),
|
||||
(error.Details, error.Message));
|
||||
}
|
||||
Assert.SequenceEqual(before, await File.ReadAllBytesAsync(path, context.Cancellation));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,892 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Codecs.Jpeg;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Api;
|
||||
using Chronos.Server.Events;
|
||||
using Chronos.Server.Storage;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Server.Tests.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Reorganize on the server (owner review 2, R7): <c>POST /api/v1/archive/reorganize</c>, its dry run and the plan kept from it
|
||||
/// for the confirmation (<see cref="ReorganizePlanCache"/>), the <c>move</c> job that applies the confirmed plan (paused and
|
||||
/// resumed too), and what the request may not do, against the real archive engine.
|
||||
/// </summary>
|
||||
[Category("server")]
|
||||
public sealed class ReorganizeTests(TestContext context)
|
||||
{
|
||||
private const string Url = "/api/v1/archive/reorganize";
|
||||
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(TestTiming.Budget(30));
|
||||
|
||||
[Test]
|
||||
public async Task AReorganizeIsDryRunThenAppliedByAJob()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var admin = await server.AdminAsync();
|
||||
Guid id = default;
|
||||
for (var i = 0; i < 3; i++) id = (await Uploads.UploadAsync(editor, Photo(i), $"IMG_{i + 1:0000}.JPG", sessionKey: "roof")).SequenceId;
|
||||
await UntilIdleAsync(server);
|
||||
var before = await server.Database.Frames.ListBySequenceAsync(id);
|
||||
|
||||
var request = new ReorganizeRequest([id], false, "reorganized/{title}", "{title}_{n:000}", "Roof", DryRun: true);
|
||||
ReorganizePlanDto plan;
|
||||
using (var dry = await admin.PostAsJsonAsync(Url, request, ProtocolJson.Default.ReorganizeRequest))
|
||||
plan = await dry.ReadAsync(ProtocolJson.Default.ReorganizePlanDto);
|
||||
Assert.Equal((1, 3, 0), (plan.Sequences, plan.Files, plan.Kept));
|
||||
var step = plan.Steps.Single();
|
||||
Assert.Equal((id, "reorganized/Roof", "Roof", 3), (step.SequenceId, step.ToFolder, step.ToTitle, step.FileChanges));
|
||||
Assert.SequenceEqual(["originals/Roof_001.JPG", "originals/Roof_002.JPG", "originals/Roof_003.JPG"], step.FileSamples.Select(f => f.To));
|
||||
Assert.Equal(64, plan.Fingerprint.Length);
|
||||
Assert.SequenceEqual(before.Select(f => f.RelativePath), (await server.Database.Frames.ListBySequenceAsync(id)).Select(f => f.RelativePath));
|
||||
|
||||
using (var missing = await admin.PostAsJsonAsync(Url, request with { DryRun = false }, ProtocolJson.Default.ReorganizeRequest))
|
||||
Assert.Equal("fingerprint", (await missing.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request")).Details);
|
||||
using (var wrong = await admin.PostAsJsonAsync(Url, request with { DryRun = false, Fingerprint = "0123" }, ProtocolJson.Default.ReorganizeRequest))
|
||||
Assert.Equal(plan.Fingerprint, (await wrong.ExpectErrorAsync(HttpStatusCode.Conflict, "plan_changed")).Details);
|
||||
|
||||
using var events = server.Services.GetRequiredService<EventHub>().Subscribe();
|
||||
JobDto job;
|
||||
using (var applied = await admin.PostAsJsonAsync(Url, request with { DryRun = false, Fingerprint = plan.Fingerprint }, ProtocolJson.Default.ReorganizeRequest))
|
||||
{
|
||||
await applied.ExpectAsync(HttpStatusCode.Accepted);
|
||||
job = await applied.ReadAsync(ProtocolJson.Default.JobDto);
|
||||
}
|
||||
Assert.Equal("move", job.Kind);
|
||||
await UntilJobAsync(admin, job.Id, "done");
|
||||
|
||||
var sequence = (await server.Database.Sequences.GetAsync(id))!;
|
||||
Assert.Equal(("reorganized/Roof", "Roof"), (sequence.Folder, sequence.Title));
|
||||
var after = await server.Database.Frames.ListBySequenceAsync(id);
|
||||
Assert.SequenceEqual(before.Select(f => f.Id), after.Select(f => f.Id));
|
||||
Assert.SequenceEqual(["reorganized/Roof/originals/Roof_001.JPG", "reorganized/Roof/originals/Roof_002.JPG", "reorganized/Roof/originals/Roof_003.JPG"],
|
||||
after.Select(f => f.RelativePath));
|
||||
foreach (var (was, now) in before.Zip(after))
|
||||
Assert.Equal(was.Sha256, Uploads.Sha(File.ReadAllBytes(Path.Combine(server.Options.ArchivePath, now.RelativePath))));
|
||||
Assert.NotEmpty((await server.Database.Audit.ListAsync(null, "archive_reorganized", 10, null)).Items);
|
||||
|
||||
var until = DateTime.UtcNow + Wait;
|
||||
while (true)
|
||||
{
|
||||
using var timeout = new CancellationTokenSource(until - DateTime.UtcNow);
|
||||
var e = await events.Reader.ReadAsync(timeout.Token);
|
||||
if (e is SequenceChangedEvent { Change: "reorganized" } changed && changed.SequenceId == id)
|
||||
{
|
||||
Assert.Equal(sequence.FramesVersion, changed.FramesVersion);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnExportMovesWithItsFolderAndStaysDownloadable()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var admin = await server.AdminAsync();
|
||||
var id = (await Uploads.UploadAsync(editor, Photo(1), "IMG_0001.JPG", sessionKey: "roof")).SequenceId;
|
||||
await UntilIdleAsync(server);
|
||||
var folder = (await server.Database.Sequences.GetAsync(id))!.Folder;
|
||||
var video = Uploads.Photo(4096, 28);
|
||||
var relative = $"{folder}/exports/Roof - 4K.mp4";
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(Path.Combine(server.Options.ArchivePath, relative))!);
|
||||
await File.WriteAllBytesAsync(Path.Combine(server.Options.ArchivePath, relative), video);
|
||||
var render = new Render { Id = Guid.CreateVersion7(), SequenceId = id, PresetName = "4K HEVC", OutputPath = relative, Bytes = video.Length, Created = DateTimeOffset.UtcNow };
|
||||
await server.Database.Renders.InsertAsync(render);
|
||||
|
||||
// A new folder and title, the files keep their names: the folder moves with its exports.
|
||||
var request = new ReorganizeRequest([id], false, "reorganized/{title}", null, "Roof", DryRun: true);
|
||||
ReorganizePlanDto plan;
|
||||
using (var dry = await admin.PostAsJsonAsync(Url, request, ProtocolJson.Default.ReorganizeRequest))
|
||||
plan = await dry.ReadAsync(ProtocolJson.Default.ReorganizePlanDto);
|
||||
JobDto job;
|
||||
using (var applied = await admin.PostAsJsonAsync(Url, request with { DryRun = false, Fingerprint = plan.Fingerprint }, ProtocolJson.Default.ReorganizeRequest))
|
||||
{
|
||||
await applied.ExpectAsync(HttpStatusCode.Accepted);
|
||||
job = await applied.ReadAsync(ProtocolJson.Default.JobDto);
|
||||
}
|
||||
await UntilJobAsync(admin, job.Id, "done");
|
||||
|
||||
Assert.Equal("reorganized/Roof", (await server.Database.Sequences.GetAsync(id))!.Folder);
|
||||
Assert.Equal("reorganized/Roof/exports/Roof - 4K.mp4", (await server.Database.Renders.GetAsync(render.Id))!.OutputPath);
|
||||
using var response = await editor.GetAsync($"/api/v1/renders/{render.Id}/file");
|
||||
await response.ExpectAsync(HttpStatusCode.OK);
|
||||
await Http.BytesEqualAsync(video, response.Content.ReadAsByteArrayAsync());
|
||||
Assert.False(Directory.Exists(Path.Combine(server.Options.ArchivePath, folder)), "nothing is left at the old place");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnExportFiledAfterItsFolderMovedGoesWhereTheSequenceIsNow()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var id = (await Uploads.UploadAsync(editor, Photo(1), "IMG_0001.JPG", sessionKey: "roof")).SequenceId;
|
||||
await UntilIdleAsync(server);
|
||||
var stale = (await server.Database.Sequences.GetAsync(id))!;
|
||||
|
||||
// A render node's output read the sequence before a Reorganize moved its folder, and is filed after it.
|
||||
var archives = server.Services.GetRequiredService<ArchiveService>();
|
||||
var plan = await archives.PlanRenameAsync(stale.ArchiveId, [id], "reorganized/{date}", null, CancellationToken.None);
|
||||
await archives.ApplyRenameAsync(plan, null, CancellationToken.None);
|
||||
var folder = plan.Steps.Single().ToFolder;
|
||||
var video = Uploads.Photo(4096, 29);
|
||||
var staged = Path.Combine(context.CreateTempDirectory("staged"), "render.mp4");
|
||||
await File.WriteAllBytesAsync(staged, video);
|
||||
var render = Assert.NotNull(await server.Services.GetRequiredService<RenderStore>().CommitAsync(stale, staged,
|
||||
new RenderResultRequest("Roof - 4K.mp4", video.Length, Uploads.Sha(video), "4K HEVC", "hevc", 3840, 2160, 25, 4), "studio-pc", CancellationToken.None));
|
||||
|
||||
Assert.Equal($"{folder}/exports/Roof - 4K.mp4", render.OutputPath);
|
||||
await Http.BytesEqualAsync(video, File.ReadAllBytesAsync(Path.Combine(server.Options.ArchivePath, render.OutputPath)));
|
||||
Assert.False(Directory.Exists(Path.Combine(server.Options.ArchivePath, stale.Folder)), "the folder it left is not created again");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnExportOfAFolderAnotherIndexMovedIsNotFiled()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var id = (await Uploads.UploadAsync(editor, Photo(1), "IMG_0001.JPG", sessionKey: "roof")).SequenceId;
|
||||
await UntilIdleAsync(server);
|
||||
var sequence = (await server.Database.Sequences.GetAsync(id))!;
|
||||
|
||||
// A desktop sharing the archive moved the folder; this server's index still has it at the old place.
|
||||
var left = Path.Combine(server.Options.ArchivePath, sequence.Folder);
|
||||
Directory.Move(left, Path.Combine(server.Options.ArchivePath, "elsewhere"));
|
||||
var video = Uploads.Photo(4096, 30);
|
||||
var staged = Path.Combine(context.CreateTempDirectory("staged"), "render.mp4");
|
||||
await File.WriteAllBytesAsync(staged, video);
|
||||
await Assert.ThrowsAsync<FolderMovedException>(() => server.Services.GetRequiredService<RenderStore>().CommitAsync(sequence, staged,
|
||||
new RenderResultRequest("Roof - 4K.mp4", video.Length, Uploads.Sha(video), "4K HEVC", "hevc", 3840, 2160, 25, 4), "studio-pc", CancellationToken.None));
|
||||
|
||||
Assert.FileExists(staged);
|
||||
Assert.False(Directory.Exists(left), "the folder it left is not created again");
|
||||
Assert.Empty(await server.Database.Renders.ListBySequenceAsync(id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnExportIsNeverFiledAmongThoseOfAnotherSequenceMovedIntoItsFolder()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var id = (await Uploads.UploadAsync(editor, Photo(1), "IMG_0001.JPG", sessionKey: "roof")).SequenceId;
|
||||
var other = (await Uploads.UploadAsync(editor, Photo(2), "IMG_0002.JPG", sessionKey: "cam")).SequenceId;
|
||||
await UntilIdleAsync(server);
|
||||
var sequence = (await server.Database.Sequences.GetAsync(id))!;
|
||||
var stranger = (await server.Database.Sequences.GetAsync(other))!;
|
||||
|
||||
// A desktop sharing the archive moved the folder away, then the other sequence into the folder it left; this server's
|
||||
// index still has both where they were.
|
||||
var folder = Path.Combine(server.Options.ArchivePath, sequence.Folder);
|
||||
Directory.Move(folder, Path.Combine(server.Options.ArchivePath, "elsewhere"));
|
||||
Directory.Move(Path.Combine(server.Options.ArchivePath, stranger.Folder), folder);
|
||||
var before = Files(folder);
|
||||
var video = Uploads.Photo(4096, 31);
|
||||
var staged = Path.Combine(context.CreateTempDirectory("staged"), "render.mp4");
|
||||
await File.WriteAllBytesAsync(staged, video);
|
||||
await Assert.ThrowsAsync<FolderMovedException>(() => server.Services.GetRequiredService<RenderStore>().CommitAsync(sequence, staged,
|
||||
new RenderResultRequest("Roof - 4K.mp4", video.Length, Uploads.Sha(video), "4K HEVC", "hevc", 3840, 2160, 25, 4), "studio-pc", CancellationToken.None));
|
||||
|
||||
Assert.FileExists(staged);
|
||||
Assert.SequenceEqual(before, Files(folder), "the other sequence's files are untouched");
|
||||
Assert.Empty(await server.Database.Renders.ListBySequenceAsync(id));
|
||||
}
|
||||
|
||||
/// <summary>Every file under <paramref name="folder"/> with the hash of its content, in path order.</summary>
|
||||
private static List<string> Files(string folder) =>
|
||||
[
|
||||
.. Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories).Order(StringComparer.Ordinal)
|
||||
.Select(p => $"{Path.GetRelativePath(folder, p).Replace('\\', '/')} {Uploads.Sha(File.ReadAllBytes(p))}"),
|
||||
];
|
||||
|
||||
[Test]
|
||||
public async Task AReorganizeAsksForTheArchiveAndAValidRequest()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var admin = await server.AdminAsync();
|
||||
var a = (await Uploads.UploadAsync(editor, Photo(1), "a.jpg", sessionKey: "a")).SequenceId;
|
||||
var b = (await Uploads.UploadAsync(editor, Photo(2), "b.jpg", sessionKey: "b")).SequenceId;
|
||||
await UntilIdleAsync(server);
|
||||
var valid = new ReorganizeRequest([a], false, null, "{n:000}", null, DryRun: true);
|
||||
|
||||
using (var forbidden = await editor.PostAsJsonAsync(Url, valid, ProtocolJson.Default.ReorganizeRequest))
|
||||
await forbidden.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
|
||||
foreach (var (bad, details) in new[]
|
||||
{
|
||||
(valid with { All = true }, "sequenceIds"),
|
||||
(valid with { SequenceIds = null }, "sequenceIds"),
|
||||
(valid with { SequenceIds = [] }, "sequenceIds"),
|
||||
(valid with { SequenceIds = [.. Enumerable.Range(0, LibraryEndpoints.MaxBulkIds + 1).Select(_ => Guid.NewGuid())] }, "sequenceIds"),
|
||||
(valid with { FileTemplate = null }, "templates"),
|
||||
})
|
||||
{
|
||||
using var response = await admin.PostAsJsonAsync(Url, bad, ProtocolJson.Default.ReorganizeRequest);
|
||||
Assert.Equal(details, (await response.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request")).Details);
|
||||
}
|
||||
using (var template = await admin.PostAsJsonAsync(Url, valid with { FileTemplate = "{nope}" }, ProtocolJson.Default.ReorganizeRequest))
|
||||
Assert.Equal("fileTemplate", (await template.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_template")).Details);
|
||||
// The desktop's rules: no lost extension, names that tell the photos apart, no folder scans skip; each named after the
|
||||
// field, with the desktop's sentence.
|
||||
foreach (var (bad, details, rule) in new[]
|
||||
{
|
||||
(valid with { FileTemplate = "{n}{ext}" }, "fileTemplate:extension", "Extension"),
|
||||
(valid with { FileTemplate = "{title}" }, "fileTemplate:not_unique", "NotUnique"),
|
||||
(valid with { FileTemplate = "{year}/{n}" }, "fileTemplate:file_separator", "FileSeparator"),
|
||||
(valid with { FolderTemplate = "Exports/{title}" }, "folderTemplate:reserved_folder", "ReservedFolder"),
|
||||
(valid with { FolderTemplate = ".hidden/{date}" }, "folderTemplate:reserved_folder", "ReservedFolder"),
|
||||
})
|
||||
{
|
||||
using var refused = await admin.PostAsJsonAsync(Url, bad, ProtocolJson.Default.ReorganizeRequest);
|
||||
var error = await refused.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_template");
|
||||
Assert.Equal(details, error.Details);
|
||||
Assert.Equal(Chronos.Core.Localization.Loc.Get("Errors.Template." + rule, System.Globalization.CultureInfo.GetCultureInfo("en")), error.Message);
|
||||
}
|
||||
using (var blank = await admin.PostAsJsonAsync(Url, valid with { FolderTemplate = " " }, ProtocolJson.Default.ReorganizeRequest))
|
||||
Assert.Equal("folderTemplate", (await blank.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_template")).Details);
|
||||
using (var unknown = await admin.PostAsJsonAsync(Url, valid with { SequenceIds = [Guid.NewGuid()] }, ProtocolJson.Default.ReorganizeRequest))
|
||||
await unknown.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
|
||||
|
||||
// One sequence's new folder inside the other's: refused, nothing planned.
|
||||
var host = (await server.Database.Sequences.GetAsync(a))!.Folder;
|
||||
using (var nested = await admin.PostAsJsonAsync(Url, new ReorganizeRequest([b], false, host + "/inside", null, null, DryRun: true),
|
||||
ProtocolJson.Default.ReorganizeRequest))
|
||||
Assert.Equal(host + "/inside", (await nested.ExpectErrorAsync(HttpStatusCode.Conflict, "nested_target")).Details);
|
||||
|
||||
using (var all = await admin.PostAsJsonAsync(Url, valid with { SequenceIds = null, All = true }, ProtocolJson.Default.ReorganizeRequest))
|
||||
{
|
||||
var plan = await all.ReadAsync(ProtocolJson.Default.ReorganizePlanDto);
|
||||
Assert.Equal((2, 2), (plan.Sequences, plan.Files));
|
||||
Assert.SequenceEqual(new[] { a, b }.Order(), plan.Steps.Select(s => s.SequenceId).Order());
|
||||
}
|
||||
|
||||
// The archive drive is gone: neither a dry run nor a plan kept from one is answered.
|
||||
var manifest = new ArchivePaths(server.Options.ArchivePath).ManifestPath;
|
||||
File.Move(manifest, manifest + ".away");
|
||||
try
|
||||
{
|
||||
foreach (var request in new[] { valid, valid with { SequenceIds = null, All = true }, valid with { DryRun = false, Fingerprint = new string('0', 64) } })
|
||||
{
|
||||
using var offline = await admin.PostAsJsonAsync(Url, request, ProtocolJson.Default.ReorganizeRequest);
|
||||
await offline.ExpectErrorAsync(HttpStatusCode.ServiceUnavailable, "archive_offline");
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Move(manifest + ".away", manifest);
|
||||
}
|
||||
Assert.Empty((await server.Database.Jobs.ListAsync(JobState.Queued, JobKind.Move)).Items);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AReorganizeIsRefusedWhereNoJobCanApplyIt()
|
||||
{
|
||||
// Without the archive module the server plans, but no handler of move jobs runs here.
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var admin = await server.AdminAsync();
|
||||
var id = (await Uploads.UploadAsync(editor, Photo(1), "a.jpg", sessionKey: "a")).SequenceId;
|
||||
var request = new ReorganizeRequest([id], false, "moved/{date}", null, null, DryRun: true);
|
||||
string fingerprint;
|
||||
using (var dry = await admin.PostAsJsonAsync(Url, request, ProtocolJson.Default.ReorganizeRequest))
|
||||
{
|
||||
// No archive engine wrote the sequence's sidecar here: it stays as it is, and says why.
|
||||
var plan = await dry.ReadAsync(ProtocolJson.Default.ReorganizePlanDto);
|
||||
Assert.Equal("unreadable", plan.Steps.Single().Blocked.Single().Reason);
|
||||
fingerprint = plan.Fingerprint;
|
||||
}
|
||||
using (var unavailable = await admin.PostAsJsonAsync(Url, request with { DryRun = false, Fingerprint = fingerprint }, ProtocolJson.Default.ReorganizeRequest))
|
||||
Assert.Equal("move", (await unavailable.ExpectErrorAsync(HttpStatusCode.Conflict, "job_unavailable")).Details);
|
||||
Assert.Empty((await server.Database.Jobs.ListAsync(null, JobKind.Move)).Items);
|
||||
Assert.Empty((await server.Database.Audit.ListAsync(null, "archive_reorganized", 10, null)).Items);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task EverySequenceIsReorganizedByAJobAroundThoseAlreadyInPlace()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var admin = await server.AdminAsync();
|
||||
var days = new ReorganizeRequest(null, true, "days/{date}", null, null, DryRun: true);
|
||||
// A sequence already where the template puts it: the others of that day go beside it.
|
||||
var placed = (await Uploads.UploadAsync(editor, Photo(0), "IMG_0001.JPG", sessionKey: "placed")).SequenceId;
|
||||
await UntilIdleAsync(server);
|
||||
await UntilJobAsync(admin, await ConfirmAsync(admin, days with { All = false, SequenceIds = [placed] }), "done");
|
||||
Assert.Equal("days/2026-09-28", (await server.Database.Sequences.GetAsync(placed))!.Folder);
|
||||
var a = (await Uploads.UploadAsync(editor, Photo(1), "IMG_0002.JPG", sessionKey: "a")).SequenceId;
|
||||
var b = (await Uploads.UploadAsync(editor, Photo(2), "IMG_0003.JPG", sessionKey: "b")).SequenceId;
|
||||
await UntilIdleAsync(server);
|
||||
|
||||
ReorganizePlanDto plan;
|
||||
using (var dry = await admin.PostAsJsonAsync(Url, days, ProtocolJson.Default.ReorganizeRequest))
|
||||
plan = await dry.ReadAsync(ProtocolJson.Default.ReorganizePlanDto);
|
||||
Assert.Equal((2, 0, 0), (plan.Sequences, plan.Files, plan.Kept));
|
||||
Assert.SequenceEqual(new[] { a, b }.Order(), plan.Steps.Select(s => s.SequenceId).Order());
|
||||
Assert.SequenceEqual(["days/2026-09-28 (2)", "days/2026-09-28 (3)"], plan.Steps.Select(s => s.ToFolder).Order(StringComparer.Ordinal));
|
||||
|
||||
// The job plans again over the sequences with a step only: the one left where it is still decides the " (n)".
|
||||
using var events = server.Services.GetRequiredService<EventHub>().Subscribe();
|
||||
var job = await ConfirmAsync(admin, days with { DryRun = false, Fingerprint = plan.Fingerprint });
|
||||
await UntilJobAsync(admin, job, "done");
|
||||
var folders = new Dictionary<Guid, string>();
|
||||
foreach (var id in new[] { placed, a, b }) folders[id] = (await server.Database.Sequences.GetAsync(id))!.Folder;
|
||||
Assert.Equal("days/2026-09-28", folders[placed]);
|
||||
Assert.SequenceEqual(plan.Steps.Select(s => s.ToFolder), plan.Steps.Select(s => folders[s.SequenceId]));
|
||||
foreach (var id in new[] { a, b })
|
||||
Assert.True(Directory.Exists(Path.Combine(server.Options.ArchivePath, folders[id])), folders[id]);
|
||||
Assert.SequenceEqual(new[] { a, b }.Order(), (await ReorganizedAsync(events, 2)).Order());
|
||||
|
||||
using var again = await admin.PostAsJsonAsync(Url, days, ProtocolJson.Default.ReorganizeRequest);
|
||||
Assert.Equal(0, (await again.ReadAsync(ProtocolJson.Default.ReorganizePlanDto)).Sequences);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task EverySequenceIsReorganizedByAJobWithTheOnesItCarriesAndTheOnesWhosePhotosStay()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var admin = await server.AdminAsync();
|
||||
var roof = Guid.Empty;
|
||||
for (var i = 0; i < 2; i++) roof = (await Uploads.UploadAsync(editor, Photo(i), $"IMG_{i + 1:0000}.JPG", sessionKey: "roof")).SequenceId;
|
||||
await UntilIdleAsync(server);
|
||||
await UntilJobAsync(admin, await ConfirmAsync(admin, new ReorganizeRequest([roof], false, null, null, "Roof", DryRun: true)), "done");
|
||||
var folder = (await server.Database.Sequences.GetAsync(roof))!.Folder;
|
||||
// Photos copied in by hand and found by a scan: in the layout inside the roof's folder (a sequence without a title),
|
||||
// and in place in a folder of their own (titled by it).
|
||||
var root = server.Options.ArchivePath;
|
||||
Directory.CreateDirectory(Path.Combine(root, folder, "inner", "originals"));
|
||||
await File.WriteAllBytesAsync(Path.Combine(root, folder, "inner", "originals", "IMG_0100.JPG"), Photo(3));
|
||||
Directory.CreateDirectory(Path.Combine(root, "trips"));
|
||||
for (var i = 0; i < 2; i++) await File.WriteAllBytesAsync(Path.Combine(root, "trips", $"IMG_{i + 200:0000}.JPG"), Photo(4 + i));
|
||||
using (var scan = await admin.PostAsync("/api/v1/archive/scan", null)) await scan.ExpectAsync(HttpStatusCode.Accepted);
|
||||
await UntilIdleAsync(server);
|
||||
var locations = await server.Database.Sequences.ListLocationsAsync((await server.Database.Archives.ListAsync()).Single().Id);
|
||||
var inner = locations.Single(l => l.Folder == folder + "/inner").Id;
|
||||
var trips = locations.Single(l => l.Folder == "trips").Id;
|
||||
var tripFiles = Directory.GetFiles(Path.Combine(root, "trips")).Order(StringComparer.Ordinal).ToList();
|
||||
|
||||
// The roof moves to its title with its photos renamed and carries the sequence inside it, whose title gives no
|
||||
// folder; the trips keep their folder, and their photos their names, which the plan says why.
|
||||
var every = new ReorganizeRequest(null, true, "{title}", "{n:000}", null, DryRun: true);
|
||||
var plan = await DryRunAsync(admin, every);
|
||||
Assert.SequenceEqual([roof, trips, inner], plan.Steps.Select(s => s.SequenceId));
|
||||
Assert.Equal(("Roof", false, 2), (plan.Steps[0].ToFolder, plan.Steps[0].Carried, plan.Steps[0].FileChanges));
|
||||
Assert.Equal(("trips", 0), (plan.Steps[1].ToFolder, plan.Steps[1].FileChanges));
|
||||
Assert.Equal(("in_place", 2), (plan.Steps[1].Blocked.Single().Reason, plan.Steps[1].Blocked.Single().Photos));
|
||||
Assert.Equal(("Roof/inner", true, 0), (plan.Steps[2].ToFolder, plan.Steps[2].Carried, plan.Steps[2].FileChanges));
|
||||
Assert.Equal((2, 2), (plan.Sequences, plan.Files));
|
||||
|
||||
// The job plans again over the sequences with a step, the carried and the kept ones among them, and ends done.
|
||||
using var events = server.Services.GetRequiredService<EventHub>().Subscribe();
|
||||
await UntilJobAsync(admin, await ConfirmAsync(admin, every with { DryRun = false, Fingerprint = plan.Fingerprint }), "done");
|
||||
Assert.Equal(("Roof", "Roof"), ((await server.Database.Sequences.GetAsync(roof))!.Folder, (await server.Database.Sequences.GetAsync(roof))!.Title));
|
||||
Assert.SequenceEqual(["Roof/originals/001.JPG", "Roof/originals/002.JPG"], (await server.Database.Frames.ListBySequenceAsync(roof)).Select(f => f.RelativePath));
|
||||
Assert.Equal("Roof/inner", (await server.Database.Sequences.GetAsync(inner))!.Folder);
|
||||
Assert.SequenceEqual(["Roof/inner/originals/IMG_0100.JPG"], (await server.Database.Frames.ListBySequenceAsync(inner)).Select(f => f.RelativePath));
|
||||
Assert.True(File.Exists(Path.Combine(root, "Roof", "inner", "originals", "IMG_0100.JPG")), "the carried photo moved with its folder");
|
||||
Assert.Equal("trips", (await server.Database.Sequences.GetAsync(trips))!.Folder);
|
||||
Assert.SequenceEqual(tripFiles, Directory.GetFiles(Path.Combine(root, "trips")).Order(StringComparer.Ordinal));
|
||||
Assert.False(Directory.Exists(Path.Combine(root, folder)), "nothing is left at the old place");
|
||||
Assert.SequenceEqual(new[] { roof, inner }.Order(), (await ReorganizedAsync(events, 2)).Order());
|
||||
|
||||
// Done: the next dry run plans no change, only the photos that keep their names.
|
||||
var after = await DryRunAsync(admin, every);
|
||||
Assert.Equal(0, after.Sequences);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnUploadAfterTheDryRunChangesThePlanToConfirm()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var admin = await server.AdminAsync();
|
||||
Guid id = default;
|
||||
for (var i = 0; i < 2; i++) id = (await Uploads.UploadAsync(editor, Photo(i), $"IMG_{i + 1:0000}.JPG", sessionKey: "roof")).SequenceId;
|
||||
await UntilIdleAsync(server);
|
||||
var request = new ReorganizeRequest([id], false, null, "{n:000}", null, DryRun: true);
|
||||
var shown = await DryRunAsync(admin, request);
|
||||
Assert.Equal(2, shown.Files);
|
||||
|
||||
// A photo arrives before Apply: the plan confirmed is not the one now, which the answer carries.
|
||||
await Uploads.UploadAsync(editor, Photo(2), "IMG_0003.JPG", sessionKey: "roof");
|
||||
await UntilIdleAsync(server);
|
||||
string now;
|
||||
using (var changed = await admin.PostAsJsonAsync(Url, request with { DryRun = false, Fingerprint = shown.Fingerprint }, ProtocolJson.Default.ReorganizeRequest))
|
||||
now = Assert.NotNull((await changed.ExpectErrorAsync(HttpStatusCode.Conflict, "plan_changed")).Details);
|
||||
Assert.NotEqual(shown.Fingerprint, now);
|
||||
Assert.Empty((await server.Database.Jobs.ListAsync(null, JobKind.Move)).Items);
|
||||
var replanned = await DryRunAsync(admin, request);
|
||||
Assert.Equal((now, 3), (replanned.Fingerprint, replanned.Files));
|
||||
|
||||
await UntilJobAsync(admin, await ConfirmAsync(admin, request with { DryRun = false, Fingerprint = now }), "done");
|
||||
Assert.SequenceEqual(["001.JPG", "002.JPG", "003.JPG"], (await server.Database.Frames.ListBySequenceAsync(id)).Select(f => f.FileName));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnUploadFiledUnderTheNameThePlanGivesLeavesThePlanToConfirm()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var admin = await server.AdminAsync();
|
||||
Guid id = default;
|
||||
for (var i = 0; i < 2; i++) id = (await Uploads.UploadAsync(editor, Photo(i), $"IMG_{i + 1:0000}.JPG", sessionKey: "roof")).SequenceId;
|
||||
await UntilIdleAsync(server);
|
||||
// The archive files new photos as the Reorganize names them; the two filed before do not follow it yet.
|
||||
using (var read = await admin.GetAsync("/api/v1/archive/settings"))
|
||||
{
|
||||
var settings = await read.ReadAsync(ProtocolJson.Default.ArchiveSettingsDto);
|
||||
using var put = await admin.PutAsJsonAsync("/api/v1/archive/settings", settings with { FileTemplate = "{n:000}" }, ProtocolJson.Default.ArchiveSettingsDto);
|
||||
await put.ExpectAsync(HttpStatusCode.OK);
|
||||
}
|
||||
var request = new ReorganizeRequest([id], false, null, "{n:000}", null, DryRun: true);
|
||||
var shown = await DryRunAsync(admin, request);
|
||||
Assert.Equal(2, shown.Files);
|
||||
|
||||
// The camera still uploads before Apply, a photo after the others: it takes the name the plan leaves it, so the plan
|
||||
// confirmed is the one now.
|
||||
await Uploads.UploadAsync(editor, Photo(2), "IMG_0003.JPG", sessionKey: "roof", capturedAt: new DateTime(2026, 9, 28, 18, 3, 0));
|
||||
await UntilIdleAsync(server);
|
||||
Assert.Equal("003.JPG", (await server.Database.Frames.ListBySequenceAsync(id))[^1].FileName);
|
||||
await UntilJobAsync(admin, await ConfirmAsync(admin, request with { DryRun = false, Fingerprint = shown.Fingerprint }), "done");
|
||||
Assert.SequenceEqual(["001.JPG", "002.JPG", "003.JPG"], (await server.Database.Frames.ListBySequenceAsync(id)).Select(f => f.FileName));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AMoveJobPausedBetweenTwoSequencesCompletesTheRestWhenResumed()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var admin = await server.AdminAsync();
|
||||
var first = (await Uploads.UploadAsync(editor, Photo(0), "IMG_0001.JPG", sessionKey: "first")).SequenceId;
|
||||
var second = (await Uploads.UploadAsync(editor, Photo(1), "IMG_0002.JPG", sessionKey: "second")).SequenceId;
|
||||
await UntilIdleAsync(server);
|
||||
var request = new ReorganizeRequest([first, second], false, "moved/{date}", null, null, DryRun: true);
|
||||
var plan = await DryRunAsync(admin, request);
|
||||
Assert.SequenceEqual([first, second], plan.Steps.Select(s => s.SequenceId));
|
||||
var was = (await server.Database.Sequences.GetAsync(second))!.Folder;
|
||||
|
||||
// The second sequence is busy (an editor saving it): the job moves the first, then waits for it and is paused there.
|
||||
var paths = new ArchivePaths(server.Options.ArchivePath);
|
||||
var busy = Assert.NotNull(LeaseFile.TryAcquire(paths.LocksDirectory, $"seq-{second:N}", "tests"));
|
||||
using var events = server.Services.GetRequiredService<EventHub>().Subscribe();
|
||||
Guid job;
|
||||
try
|
||||
{
|
||||
job = await ConfirmAsync(admin, request with { DryRun = false, Fingerprint = plan.Fingerprint });
|
||||
await UntilAsync(admin, job, j => j is { State: "running", ProgressDone: 1 });
|
||||
using (var pause = await admin.PostAsync($"/api/v1/jobs/{job}/pause", null)) await pause.ExpectAsync(HttpStatusCode.OK);
|
||||
await UntilJobAsync(admin, job, "paused");
|
||||
// The job is paused before its run stops: once stopped, the plan waits for it.
|
||||
var until = DateTime.UtcNow + Wait;
|
||||
while (!RenameJournal.ListPending(paths).Single().Held)
|
||||
{
|
||||
Assert.True(DateTime.UtcNow < until, "the plan is held");
|
||||
await Task.Delay(50);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
busy.Dispose();
|
||||
}
|
||||
Assert.Equal(plan.Steps[0].ToFolder, (await server.Database.Sequences.GetAsync(first))!.Folder);
|
||||
Assert.Equal(was, (await server.Database.Sequences.GetAsync(second))!.Folder);
|
||||
// The first sequence was told as soon as its step was done, before the pause.
|
||||
Assert.SequenceEqual([first], await ReorganizedAsync(events, 1));
|
||||
|
||||
// Resumed, it completes the plan it held and tells the sequence it changed then, and that one only.
|
||||
using (var resume = await admin.PostAsync($"/api/v1/jobs/{job}/resume", null)) await resume.ExpectAsync(HttpStatusCode.OK);
|
||||
await UntilJobAsync(admin, job, "done");
|
||||
Assert.Equal(plan.Steps[1].ToFolder, (await server.Database.Sequences.GetAsync(second))!.Folder);
|
||||
Assert.Empty(RenameJournal.ListPending(paths));
|
||||
Assert.SequenceEqual([second], await ReorganizedAsync(events, 1, second));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ADryRunIsKeptForTheConfirmWhileTheIndexStaysAsItWas()
|
||||
{
|
||||
var clock = new ManualTimeProvider();
|
||||
await using var server = await TestServer.StartAsync(context, services: s =>
|
||||
{
|
||||
ArchiveModule.Register(s);
|
||||
s.AddSingleton<TimeProvider>(clock);
|
||||
});
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var admin = await server.AdminAsync();
|
||||
Guid id = default;
|
||||
for (var i = 0; i < 2; i++) id = (await Uploads.UploadAsync(editor, Photo(i), $"IMG_{i + 1:0000}.JPG", sessionKey: "roof")).SequenceId;
|
||||
var other = (await Uploads.UploadAsync(editor, Photo(5), "IMG_0100.JPG", sessionKey: "other")).SequenceId;
|
||||
await UntilIdleAsync(server);
|
||||
var request = new ReorganizeRequest([id], false, "moved/{date}", "{n:000}", null, DryRun: true);
|
||||
var target = Path.Combine(server.Options.ArchivePath, "moved", "2026-09-28");
|
||||
var before = (await server.Database.Sequences.GetAsync(id))!.Folder;
|
||||
|
||||
// A folder made on disk alone is not in the index: the same dry run again is the plan made before.
|
||||
var shown = await DryRunAsync(admin, request);
|
||||
Assert.Equal(("moved/2026-09-28", 2), (shown.Steps.Single().ToFolder, shown.Files));
|
||||
Directory.CreateDirectory(target);
|
||||
Assert.Equal(shown.Fingerprint, (await DryRunAsync(admin, request)).Fingerprint);
|
||||
|
||||
// Neither are what the plan does not read: a photo uploaded into another sequence (and the jobs it queues), a verify
|
||||
// of photos an upload hashed already.
|
||||
var versions = (await server.Database.Sequences.GetAsync(other))!.FramesVersion;
|
||||
await Uploads.UploadAsync(editor, Photo(6), "IMG_0101.JPG", sessionKey: "other");
|
||||
using (var verify = await admin.PostAsync("/api/v1/archive/verify", null)) await verify.ExpectAsync(HttpStatusCode.Accepted);
|
||||
await UntilIdleAsync(server);
|
||||
Assert.NotEqual(versions, (await server.Database.Sequences.GetAsync(other))!.FramesVersion);
|
||||
Assert.NotNull((await server.Database.Sequences.GetAsync(id))!.VerifiedAt);
|
||||
Assert.Equal(shown.Fingerprint, (await DryRunAsync(admin, request)).Fingerprint);
|
||||
|
||||
// A change of what it reads plans again at once.
|
||||
await Uploads.UploadAsync(editor, Photo(2), "IMG_0003.JPG", sessionKey: "roof");
|
||||
await UntilIdleAsync(server);
|
||||
var beside = await DryRunAsync(admin, request);
|
||||
Assert.Equal(("moved/2026-09-28 (2)", 3), (beside.Steps.Single().ToFolder, beside.Files));
|
||||
|
||||
// The confirmation takes the plan kept; the job plans again and refuses what the kept plan could not see.
|
||||
Directory.Delete(target);
|
||||
Assert.Equal(beside.Fingerprint, (await DryRunAsync(admin, request)).Fingerprint);
|
||||
Assert.Equal("failed", (await FinishedAsync(admin, await ConfirmAsync(admin, request with { DryRun = false, Fingerprint = beside.Fingerprint }))).State);
|
||||
Assert.Equal(before, (await server.Database.Sequences.GetAsync(id))!.Folder);
|
||||
Assert.False(Directory.Exists(target), "nothing moved");
|
||||
Assert.Empty(RenameJournal.ListPending(new ArchivePaths(server.Options.ArchivePath)));
|
||||
|
||||
// A queued plan is no longer kept; a kept one lasts its lifetime.
|
||||
var free = await DryRunAsync(admin, request);
|
||||
Assert.Equal(("moved/2026-09-28", 3), (free.Steps.Single().ToFolder, free.Files));
|
||||
Directory.CreateDirectory(target);
|
||||
Assert.Equal(free.Fingerprint, (await DryRunAsync(admin, request)).Fingerprint);
|
||||
await UntilIdleAsync(server);
|
||||
clock.Advance(ReorganizePlanCache.Lifetime);
|
||||
var later = await DryRunAsync(admin, request);
|
||||
Assert.Equal("moved/2026-09-28 (2)", later.Steps.Single().ToFolder);
|
||||
using (var changed = await admin.PostAsJsonAsync(Url, request with { DryRun = false, Fingerprint = free.Fingerprint }, ProtocolJson.Default.ReorganizeRequest))
|
||||
Assert.Equal(later.Fingerprint, (await changed.ExpectErrorAsync(HttpStatusCode.Conflict, "plan_changed")).Details);
|
||||
await UntilJobAsync(admin, await ConfirmAsync(admin, request with { DryRun = false, Fingerprint = later.Fingerprint }), "done");
|
||||
Assert.Equal("moved/2026-09-28 (2)", (await server.Database.Sequences.GetAsync(id))!.Folder);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ADryRunPlansAgainOnceAVerifyHashedItsPhotos()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var admin = await server.AdminAsync();
|
||||
// Photos copied into the archive's layout by hand and found by a scan: never hashed, they keep their names.
|
||||
var originals = Path.Combine(server.Options.ArchivePath, "trips", "originals");
|
||||
Directory.CreateDirectory(originals);
|
||||
for (var i = 0; i < 2; i++) await File.WriteAllBytesAsync(Path.Combine(originals, $"IMG_{i:0000}.JPG"), Photo(i));
|
||||
using (var scan = await admin.PostAsync("/api/v1/archive/scan", null)) await scan.ExpectAsync(HttpStatusCode.Accepted);
|
||||
await UntilIdleAsync(server);
|
||||
var id = (await server.Database.Sequences.ListLocationsAsync((await server.Database.Archives.ListAsync()).Single().Id)).Single().Id;
|
||||
var request = new ReorganizeRequest([id], false, null, "{n:000}", null, DryRun: true);
|
||||
var unhashed = await DryRunAsync(admin, request);
|
||||
Assert.Equal((0, 2), (unhashed.Files, unhashed.Kept));
|
||||
Assert.Equal("unhashed", unhashed.Steps.Single().Blocked.Single().Reason);
|
||||
|
||||
// A verify hashes them and leaves the sequence's frames version as it was: the same dry run plans again, and renames them.
|
||||
var versions = (await server.Database.Sequences.GetAsync(id))!.FramesVersion;
|
||||
using (var verify = await admin.PostAsync("/api/v1/archive/verify", null)) await verify.ExpectAsync(HttpStatusCode.Accepted);
|
||||
await UntilIdleAsync(server);
|
||||
Assert.Equal(versions, (await server.Database.Sequences.GetAsync(id))!.FramesVersion);
|
||||
var hashed = await DryRunAsync(admin, request);
|
||||
Assert.Equal((2, 0), (hashed.Files, hashed.Kept));
|
||||
await UntilJobAsync(admin, await ConfirmAsync(admin, request with { DryRun = false, Fingerprint = hashed.Fingerprint }), "done");
|
||||
Assert.SequenceEqual(["trips/originals/001.JPG", "trips/originals/002.JPG"], (await server.Database.Frames.ListBySequenceAsync(id)).Select(f => f.RelativePath));
|
||||
Assert.True(File.Exists(Path.Combine(originals, "001.JPG")), "renamed on disk");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task KeptPlansAreTheNewestFewWithinTheirLifetime()
|
||||
{
|
||||
var clock = new ManualTimeProvider();
|
||||
using var plans = new ReorganizePlanCache(clock);
|
||||
var archive = Guid.NewGuid();
|
||||
var templates = new RenameTemplates(Folder: "moved/{date}");
|
||||
var made = 0;
|
||||
Task<RenamePlan> Plan(CancellationToken stop)
|
||||
{
|
||||
made++;
|
||||
return Task.FromResult(new RenamePlan(Guid.NewGuid(), archive, []));
|
||||
}
|
||||
ReorganizePlanCache.Key Key(int i) => ReorganizePlanCache.Key.Of(archive, "stamp", [new Guid(i, 0, 0, new byte[8])], templates);
|
||||
|
||||
var kept = await plans.GetOrPlanAsync(Key(0), Plan);
|
||||
Assert.True(ReferenceEquals(kept, await plans.GetOrPlanAsync(Key(0), Plan)), "kept");
|
||||
Assert.Equal(1, made);
|
||||
// Another order of the sequences, every sequence, another stamp or other templates is another plan.
|
||||
var (x, y) = (Guid.NewGuid(), Guid.NewGuid());
|
||||
Assert.NotEqual(ReorganizePlanCache.Key.Of(archive, "stamp", [x, y], templates), ReorganizePlanCache.Key.Of(archive, "stamp", [y, x], templates));
|
||||
Assert.Equal(ReorganizePlanCache.Key.Of(archive, "stamp", [x, y], templates), ReorganizePlanCache.Key.Of(archive, "stamp", [x, y], templates with { }));
|
||||
Assert.NotEqual(ReorganizePlanCache.Key.Of(archive, "stamp", null, templates), ReorganizePlanCache.Key.Of(archive, "stamp", [x], templates));
|
||||
Assert.NotEqual(Key(0), ReorganizePlanCache.Key.Of(archive, "other", [new Guid(0, 0, 0, new byte[8])], templates));
|
||||
Assert.NotEqual(Key(0), ReorganizePlanCache.Key.Of(archive, "stamp", [new Guid(0, 0, 0, new byte[8])], templates with { File = "{n}" }));
|
||||
|
||||
// At most Capacity plans: the oldest goes first.
|
||||
for (var i = 1; i <= ReorganizePlanCache.Capacity; i++)
|
||||
{
|
||||
clock.Advance(TimeSpan.FromSeconds(1));
|
||||
await plans.GetOrPlanAsync(Key(i), Plan);
|
||||
}
|
||||
Assert.Equal(1 + ReorganizePlanCache.Capacity, made);
|
||||
await plans.GetOrPlanAsync(Key(ReorganizePlanCache.Capacity), Plan);
|
||||
Assert.Equal(1 + ReorganizePlanCache.Capacity, made);
|
||||
await plans.GetOrPlanAsync(Key(0), Plan);
|
||||
Assert.Equal(2 + ReorganizePlanCache.Capacity, made);
|
||||
|
||||
// A plan is kept for its lifetime, from when it was made, even before its timer lets it go.
|
||||
clock.Advance(ReorganizePlanCache.Lifetime - TimeSpan.FromSeconds(1));
|
||||
await plans.GetOrPlanAsync(Key(0), Plan);
|
||||
Assert.Equal(2 + ReorganizePlanCache.Capacity, made);
|
||||
clock.Advance(TimeSpan.FromSeconds(1));
|
||||
await plans.GetOrPlanAsync(Key(0), Plan);
|
||||
Assert.Equal(3 + ReorganizePlanCache.Capacity, made);
|
||||
|
||||
// A refusal follows from the same reads, and is kept as a plan is: a folder inside a sequence's, a sequence not in the
|
||||
// archive. A failure is not kept, and neither is a plan or refusal forgotten.
|
||||
await Assert.ThrowsAsync<NestedRenameException>(() => plans.GetOrPlanAsync(Key(99), _ => throw new NestedRenameException("a/b", "a")));
|
||||
await Assert.ThrowsAsync<NestedRenameException>(() => plans.GetOrPlanAsync(Key(99), Plan));
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => plans.GetOrPlanAsync(Key(98), _ => throw new ArgumentException("Not in the archive.")));
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => plans.GetOrPlanAsync(Key(98), Plan));
|
||||
Assert.Equal(3 + ReorganizePlanCache.Capacity, made);
|
||||
await Assert.ThrowsAsync<IOException>(() => plans.GetOrPlanAsync(Key(97), _ => throw new IOException("The sidecar cannot be read.")));
|
||||
await plans.GetOrPlanAsync(Key(97), Plan);
|
||||
Assert.Equal(4 + ReorganizePlanCache.Capacity, made);
|
||||
plans.Forget(Key(99));
|
||||
await plans.GetOrPlanAsync(Key(99), Plan);
|
||||
Assert.Equal(5 + ReorganizePlanCache.Capacity, made);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task APlanIsMadeOnceForEveryRequestAndOutlivesOneCutOff()
|
||||
{
|
||||
var clock = new SteppedTimeProvider();
|
||||
using var plans = new ReorganizePlanCache(clock);
|
||||
var templates = new RenameTemplates(Folder: "moved/{date}");
|
||||
var key = ReorganizePlanCache.Key.Of(Guid.NewGuid(), "stamp", null, templates);
|
||||
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var made = 0;
|
||||
async Task<RenamePlan> SlowPlan(CancellationToken stop)
|
||||
{
|
||||
Interlocked.Increment(ref made);
|
||||
await release.Task;
|
||||
return new RenamePlan(Guid.NewGuid(), key.ArchiveId, []);
|
||||
}
|
||||
|
||||
// A request cut off while its plan is made (a proxy's timeout) leaves it to be made; asked again, it is waited for.
|
||||
using (var cutOff = new CancellationTokenSource())
|
||||
{
|
||||
var first = plans.GetOrPlanAsync(key, SlowPlan, cutOff.Token);
|
||||
await cutOff.CancelAsync();
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => first);
|
||||
}
|
||||
var again = plans.GetOrPlanAsync(key, SlowPlan);
|
||||
var meanwhile = plans.GetOrPlanAsync(key, SlowPlan);
|
||||
// Being made, it is not the one let go for other plans.
|
||||
for (var i = 0; i < ReorganizePlanCache.Capacity; i++)
|
||||
await plans.GetOrPlanAsync(ReorganizePlanCache.Key.Of(key.ArchiveId, "stamp", [new Guid(i, 0, 0, new byte[8])], templates), PlanAtOnce);
|
||||
release.SetResult();
|
||||
var plan = await again;
|
||||
Assert.True(ReferenceEquals(plan, await meanwhile), "one plan for both");
|
||||
Assert.True(ReferenceEquals(plan, await plans.GetOrPlanAsync(key, SlowPlan)), "kept");
|
||||
Assert.Equal(1 + ReorganizePlanCache.Capacity, made);
|
||||
Assert.Equal(ReorganizePlanCache.Capacity, plans.Count);
|
||||
|
||||
// Its timer lets it go at the end of its lifetime, with no request asking.
|
||||
clock.Advance(ReorganizePlanCache.Lifetime - TimeSpan.FromSeconds(1));
|
||||
Assert.Equal(ReorganizePlanCache.Capacity, plans.Count);
|
||||
clock.Advance(TimeSpan.FromSeconds(1));
|
||||
Assert.Equal(0, plans.Count);
|
||||
await plans.GetOrPlanAsync(key, SlowPlan);
|
||||
Assert.Equal(2 + ReorganizePlanCache.Capacity, made);
|
||||
|
||||
Task<RenamePlan> PlanAtOnce(CancellationToken stop)
|
||||
{
|
||||
Interlocked.Increment(ref made);
|
||||
return Task.FromResult(new RenamePlan(Guid.NewGuid(), key.ArchiveId, []));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task PlansAreMadeAFewAtOnceAndStopWhenLetGoOrPastTheirTime()
|
||||
{
|
||||
var clock = new SteppedTimeProvider();
|
||||
using var plans = new ReorganizePlanCache(clock);
|
||||
var archive = Guid.NewGuid();
|
||||
var templates = new RenameTemplates(Folder: "moved/{date}");
|
||||
ReorganizePlanCache.Key Key(int i) => ReorganizePlanCache.Key.Of(archive, "stamp", [new Guid(i, 0, 0, new byte[8])], templates);
|
||||
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var started = new ConcurrentDictionary<int, bool>();
|
||||
var stopped = new ConcurrentDictionary<int, bool>();
|
||||
// A plan made once released, which tells when it starts and when it is stopped.
|
||||
Func<CancellationToken, Task<RenamePlan>> Plan(int i) => async stop =>
|
||||
{
|
||||
started[i] = true;
|
||||
try
|
||||
{
|
||||
await release.Task.WaitAsync(stop);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
stopped[i] = true;
|
||||
throw;
|
||||
}
|
||||
return new RenamePlan(Guid.NewGuid(), archive, []);
|
||||
};
|
||||
|
||||
// A few are made at once; the others wait for their turn.
|
||||
var asked = Enumerable.Range(0, ReorganizePlanCache.Capacity).Select(i => plans.GetOrPlanAsync(Key(i), Plan(i))).ToList();
|
||||
await EventuallyAsync(() => started.Count == ReorganizePlanCache.Concurrency);
|
||||
await Task.Delay(200);
|
||||
Assert.SequenceEqual(Enumerable.Range(0, ReorganizePlanCache.Concurrency), started.Keys.Order());
|
||||
|
||||
// One more lets go the plan asked first, being made with none kept: it stops, its waiter is told, the next one starts.
|
||||
var newest = plans.GetOrPlanAsync(Key(ReorganizePlanCache.Capacity), Plan(ReorganizePlanCache.Capacity));
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => asked[0]);
|
||||
await EventuallyAsync(() => stopped.ContainsKey(0) && started.ContainsKey(ReorganizePlanCache.Concurrency));
|
||||
Assert.Equal(ReorganizePlanCache.Capacity, plans.Count);
|
||||
release.SetResult();
|
||||
foreach (var plan in asked.Skip(1).Append(newest)) await plan;
|
||||
Assert.SequenceEqual([0], stopped.Keys);
|
||||
|
||||
// A plan still being made at its time stops, also when its work never ends (a read that hangs), and so does one still
|
||||
// waiting for its turn, which never starts.
|
||||
var hang = new TaskCompletionSource<RenamePlan>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
Func<CancellationToken, Task<RenamePlan>> Hanging(int i) => _ =>
|
||||
{
|
||||
started[i] = true;
|
||||
return hang.Task;
|
||||
};
|
||||
var hung = plans.GetOrPlanAsync(Key(20), Hanging(20));
|
||||
var stuck = plans.GetOrPlanAsync(Key(21), Hanging(21));
|
||||
await EventuallyAsync(() => started.ContainsKey(20) && started.ContainsKey(21));
|
||||
var waiting = plans.GetOrPlanAsync(Key(22), Plan(22));
|
||||
clock.Advance(ReorganizePlanCache.PlanTimeout - TimeSpan.FromSeconds(1));
|
||||
Assert.False(hung.IsCompleted, "still in time");
|
||||
clock.Advance(TimeSpan.FromSeconds(1));
|
||||
foreach (var plan in new[] { hung, stuck, waiting }) await Assert.ThrowsAsync<OperationCanceledException>(() => plan);
|
||||
Assert.False(started.ContainsKey(22), "stopped before its turn");
|
||||
Assert.Equal(0, plans.Count);
|
||||
|
||||
// Asked again, it is made once a turn is free: the work that hangs holds its turn until it ends, and what it makes
|
||||
// then is not kept.
|
||||
var again = plans.GetOrPlanAsync(Key(20), Plan(30));
|
||||
await Task.Delay(200);
|
||||
Assert.False(started.ContainsKey(30), "no turn while two works hang");
|
||||
hang.SetResult(new RenamePlan(Guid.NewGuid(), archive, []));
|
||||
var made = await again;
|
||||
Assert.True(ReferenceEquals(made, await plans.GetOrPlanAsync(Key(20), Plan(31))), "kept");
|
||||
Assert.False(started.ContainsKey(31), "kept, not made again");
|
||||
Assert.Equal(1, plans.Count);
|
||||
}
|
||||
|
||||
/// <summary>Waits until <paramref name="condition"/> holds.</summary>
|
||||
private static async Task EventuallyAsync(Func<bool> condition, [System.Runtime.CompilerServices.CallerArgumentExpression(nameof(condition))] string? expression = null)
|
||||
{
|
||||
var until = DateTime.UtcNow + Wait;
|
||||
while (!condition())
|
||||
{
|
||||
Assert.True(DateTime.UtcNow < until, expression);
|
||||
await Task.Delay(10);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<ReorganizePlanDto> DryRunAsync(HttpClient client, ReorganizeRequest request)
|
||||
{
|
||||
using var response = await client.PostAsJsonAsync(Url, request with { DryRun = true }, ProtocolJson.Default.ReorganizeRequest);
|
||||
return await response.ReadAsync(ProtocolJson.Default.ReorganizePlanDto);
|
||||
}
|
||||
|
||||
/// <summary>Confirms a plan; returns the move job queued.</summary>
|
||||
private static async Task<Guid> ConfirmAsync(HttpClient client, ReorganizeRequest request)
|
||||
{
|
||||
if (request.DryRun) request = request with { DryRun = false, Fingerprint = (await DryRunAsync(client, request)).Fingerprint };
|
||||
using var response = await client.PostAsJsonAsync(Url, request, ProtocolJson.Default.ReorganizeRequest);
|
||||
await response.ExpectAsync(HttpStatusCode.Accepted);
|
||||
return (await response.ReadAsync(ProtocolJson.Default.JobDto)).Id;
|
||||
}
|
||||
|
||||
/// <summary>The sequences told reorganized, until <paramref name="count"/> were (or <paramref name="awaited"/> was).</summary>
|
||||
private static async Task<List<Guid>> ReorganizedAsync(EventHub.Subscription events, int count, Guid? awaited = null)
|
||||
{
|
||||
var told = new List<Guid>();
|
||||
var until = DateTime.UtcNow + Wait;
|
||||
while (awaited is { } id ? !told.Contains(id) : told.Count < count)
|
||||
{
|
||||
using var timeout = new CancellationTokenSource(until - DateTime.UtcNow);
|
||||
if (await events.Reader.ReadAsync(timeout.Token) is SequenceChangedEvent { Change: "reorganized" } changed) told.Add(changed.SequenceId);
|
||||
}
|
||||
return told;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task PhotosThatKeepTheirNamesAreToldWhy()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var admin = await server.AdminAsync();
|
||||
// Photos copied into the archive by hand and found by a scan stay where they are.
|
||||
var folder = Path.Combine(server.Options.ArchivePath, "trips");
|
||||
Directory.CreateDirectory(folder);
|
||||
for (var i = 0; i < 2; i++) await File.WriteAllBytesAsync(Path.Combine(folder, $"IMG_{i:0000}.JPG"), Photo(i));
|
||||
using (var scan = await admin.PostAsync("/api/v1/archive/scan", null)) await scan.ExpectAsync(HttpStatusCode.Accepted);
|
||||
await UntilIdleAsync(server);
|
||||
var id = (await server.Database.Sequences.ListLocationsAsync((await server.Database.Archives.ListAsync()).Single().Id)).Single().Id;
|
||||
|
||||
var request = new ReorganizeRequest([id], false, null, "{n:000}", null, DryRun: true);
|
||||
admin.DefaultRequestHeaders.AcceptLanguage.ParseAdd("it");
|
||||
using var dry = await admin.PostAsJsonAsync(Url, request, ProtocolJson.Default.ReorganizeRequest);
|
||||
var plan = await dry.ReadAsync(ProtocolJson.Default.ReorganizePlanDto);
|
||||
Assert.Equal((0, 0, 2), (plan.Sequences, plan.Files, plan.Kept));
|
||||
var blocked = plan.Steps.Single().Blocked.Single();
|
||||
Assert.Equal(("in_place", 2), (blocked.Reason, blocked.Photos));
|
||||
Assert.Equal(Chronos.Core.Localization.Loc.Get("Archive.Reorganize.Blocked.InPlace", System.Globalization.CultureInfo.GetCultureInfo("it")), blocked.Message);
|
||||
}
|
||||
|
||||
private static async Task UntilJobAsync(HttpClient client, Guid id, string state)
|
||||
{
|
||||
var job = await UntilAsync(client, id, j => j.State == state || j.State is "failed" or "cancelled");
|
||||
if (job.State != state) Assert.Fail($"job {job.Kind} {job.State}: {job.Error}\n{job.LogTail}");
|
||||
}
|
||||
|
||||
/// <summary>The job once it ended: done, failed or cancelled.</summary>
|
||||
private static Task<JobDto> FinishedAsync(HttpClient client, Guid id) => UntilAsync(client, id, j => j.State is "done" or "failed" or "cancelled");
|
||||
|
||||
private static async Task<JobDto> UntilAsync(HttpClient client, Guid id, Func<JobDto, bool> reached)
|
||||
{
|
||||
var until = DateTime.UtcNow + Wait;
|
||||
while (true)
|
||||
{
|
||||
using var response = await client.GetAsync($"/api/v1/jobs/{id}");
|
||||
var job = await response.ReadAsync(ProtocolJson.Default.JobDto);
|
||||
if (reached(job)) return job;
|
||||
Assert.True(DateTime.UtcNow < until, $"job {job.Kind} still {job.State} ({job.ProgressDone}/{job.ProgressTotal})");
|
||||
await Task.Delay(50);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Waits until no job is queued or running (the thumbnails, proxies and analyses uploads queue).</summary>
|
||||
private static async Task UntilIdleAsync(TestServer server)
|
||||
{
|
||||
var until = DateTime.UtcNow + Wait;
|
||||
foreach (var state in new[] { JobState.Queued, JobState.Running, JobState.Queued, JobState.Running })
|
||||
{
|
||||
while ((await server.Database.Jobs.ListAsync(state)).Items.Count > 0)
|
||||
{
|
||||
Assert.True(DateTime.UtcNow < until, $"jobs still {state}");
|
||||
await Task.Delay(50);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] Photo(int seed)
|
||||
{
|
||||
const int width = 96, height = 64;
|
||||
var pixels = new byte[width * height * 3];
|
||||
for (var i = 0; i < pixels.Length; i++) pixels[i] = (byte)((i * 7 + seed * 31) % 251);
|
||||
return JpegEncoder.Encode(pixels, width, height, 3, new JpegEncodeOptions { Quality = 90 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Chronos.Core.Codecs.Jpeg;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Storage;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Server.Tests.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// Reorganize on the admin panel (owner review 2, R7; <c>Admin/web/reorganize.js</c>): where the panel offers it (the
|
||||
/// Library's mass bar, the Archive page's save toast), the dialog module and its strings, and the requests the dialog
|
||||
/// writes, sent through the cookie session as <c>api.js</c> sends them and read back by the names the dialog reads.
|
||||
/// </summary>
|
||||
[Category("server")]
|
||||
public sealed partial class AdminReorganizeTests(TestContext context)
|
||||
{
|
||||
private const string Url = "/api/v1/archive/reorganize";
|
||||
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(TestTiming.Budget(30));
|
||||
|
||||
[Test]
|
||||
public async Task TheLibraryAndTheArchivePageOpenTheReorganizeDialog()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
var library = await server.Client.GetStringAsync("/admin/pages/library.js");
|
||||
Assert.Contains(@"from ""../reorganize.js""", library);
|
||||
Assert.Contains(@"data-mass=""reorganize"" data-i18n=""Admin.Reorganize.Action"" data-i18n-title=""Admin.Reorganize.Action.Tip""", library);
|
||||
Assert.Contains(@"if (action === ""reorganize"") return reorganize();", library);
|
||||
// The selection: its ids up to a thousand (one request); beyond, every sequence only while the selection is exactly
|
||||
// what Select all fetched without a filter, the archive no larger since; a sequence unticked or added is never in it.
|
||||
Assert.Contains("openReorganize({ api, target: everything ? { all: true } : { sequenceIds: ids }", library);
|
||||
Assert.Contains("const everything = ids.length > BULK_LIMIT && matching !== null && !isFiltered() && total === matching.length &&", library);
|
||||
Assert.Contains("ids.length === matching.length && matching.every((s) => selection.has(s.id));", library);
|
||||
Assert.Contains("if (!everything && ids.length > BULK_LIMIT) {", library);
|
||||
var archive = await server.Client.GetStringAsync("/admin/pages/archive.js");
|
||||
Assert.Contains(@"from ""../reorganize.js""", archive);
|
||||
Assert.Contains("target: { all: true }", archive);
|
||||
|
||||
using var response = await server.Client.GetAsync("/admin/reorganize.js");
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/javascript", response.Content.Headers.ContentType?.MediaType);
|
||||
var dialog = await response.Content.ReadAsStringAsync();
|
||||
Assert.True(Regex.IsMatch(dialog, @"export function openReorganize\(\{ api, target, "), "reorganize.js exports openReorganize({ api, target, … })");
|
||||
var imports = StaticImport().Matches(dialog).Select(m => m.Groups[1].Value).ToList();
|
||||
Assert.SequenceEqual(["./i18n.js", "./ui.js"], imports);
|
||||
foreach (var module in imports)
|
||||
{
|
||||
using var imported = await server.Client.GetAsync("/admin/" + module[2..]);
|
||||
Assert.Equal(HttpStatusCode.OK, imported.StatusCode, module);
|
||||
}
|
||||
// A dry run at every change; Apply sends that plan's fingerprint back and links the job it queued.
|
||||
Assert.Contains("api.post(ENDPOINT, { ...body, dryRun: true })", dialog);
|
||||
Assert.Contains("api.post(ENDPOINT, { ...JSON.parse(chosen.key), dryRun: false, fingerprint: chosen.fingerprint })", dialog);
|
||||
Assert.Contains("#/jobs?job=", dialog);
|
||||
Assert.True(!Regex.IsMatch(dialog, @"\son[a-z]+="""), "inline handler");
|
||||
// Enter in a template plans at once: a form of three fields and no submit button never submits on Enter.
|
||||
Assert.Contains(@"form.addEventListener(""keydown"", (e) => {", dialog);
|
||||
Assert.Contains(@"if (e.key !== ""Enter"" || e.isComposing || !(e.target instanceof HTMLInputElement) || e.target.type === ""checkbox"") return;", dialog);
|
||||
// An untitled sequence that gets a title reads by its old name before, never by the new title twice.
|
||||
Assert.Contains("const before = fromTitle ?? names.get(s.sequenceId) ?? folderName(s.fromFolder);", dialog);
|
||||
Assert.Contains(@"change(before, toTitle ?? before, ""auto"")", dialog);
|
||||
// A dry run answering during the confirmation: the same plan is applied, a different one is shown and said.
|
||||
Assert.Contains("if (plan !== chosen && (plan?.key !== chosen.key || plan.fingerprint !== chosen.fingerprint)) {", dialog);
|
||||
Assert.Contains(@"showError(t(""Admin.Reorganize.PlanChanged""))", dialog);
|
||||
Assert.True(!dialog.Contains("plan !== chosen) return;", StringComparison.Ordinal), "a confirmed apply is dropped when the same plan is answered again");
|
||||
|
||||
var en = Assert.NotNull(await server.Client.GetFromJsonAsync("/api/v1/i18n/en", ProtocolJson.Default.DictionaryStringString));
|
||||
var it = Assert.NotNull(await server.Client.GetFromJsonAsync("/api/v1/i18n/it", ProtocolJson.Default.DictionaryStringString));
|
||||
foreach (var key in Regex.Matches(dialog + library + archive, @"""(Admin\.Reorganize\.[A-Za-z.]+)""").Select(m => m.Groups[1].Value).Distinct())
|
||||
{
|
||||
var name = en.ContainsKey(key) ? key : key + ".other";
|
||||
Assert.True(en.ContainsKey(name) && it.ContainsKey(name), key);
|
||||
}
|
||||
Assert.Equal("Riorganizza…", it["Admin.Reorganize.Action"]);
|
||||
// The job renames and moves; nothing in it hashes a file again, so nothing says it verifies them.
|
||||
Assert.False(en["Admin.Reorganize.Confirm.Tip"].Contains("verif", StringComparison.OrdinalIgnoreCase), en["Admin.Reorganize.Confirm.Tip"]);
|
||||
Assert.False(it["Admin.Reorganize.Confirm.Tip"].Contains("verific", StringComparison.OrdinalIgnoreCase), it["Admin.Reorganize.Confirm.Tip"]);
|
||||
Assert.False(Regex.IsMatch(dialog, @"^//.*\bverified\b", RegexOptions.Multiline), "the header says the moves are verified");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheDialogsRequestsPlanAndQueueAReorganize()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
Guid id = default;
|
||||
for (var i = 0; i < 2; i++) id = (await Uploads.UploadAsync(editor, Photo(i), $"IMG_{i + 1:0000}.JPG", sessionKey: "roof")).SequenceId;
|
||||
await UntilIdleAsync(server);
|
||||
var browser = await Browser.SignInAsync(server);
|
||||
|
||||
// The body the dialog writes: the selection's ids and the parts switched on, then dryRun.
|
||||
StringContent Body(string tail) =>
|
||||
Json($$"""{"all":false,"sequenceIds":["{{id}}"],"folderTemplate":"reorganized/{title}","fileTemplate":"{title}_{n:000}","titleTemplate":"Roof",{{tail}}}""");
|
||||
string fingerprint;
|
||||
using (var dry = await browser.SendAsync(HttpMethod.Post, Url, Body("\"dryRun\":true")))
|
||||
{
|
||||
await dry.ExpectAsync(HttpStatusCode.OK);
|
||||
using var plan = JsonDocument.Parse(await dry.Content.ReadAsStringAsync());
|
||||
var root = plan.RootElement;
|
||||
Assert.Equal((1, 2, 0), (root.GetProperty("sequences").GetInt32(), root.GetProperty("files").GetInt32(), root.GetProperty("kept").GetInt32()));
|
||||
fingerprint = root.GetProperty("fingerprint").GetString()!;
|
||||
Assert.Equal(64, fingerprint.Length);
|
||||
var step = root.GetProperty("steps").EnumerateArray().Single();
|
||||
Assert.Equal(id, step.GetProperty("sequenceId").GetGuid());
|
||||
Assert.True(step.GetProperty("fromFolder").GetString()!.Length > 0, "fromFolder");
|
||||
Assert.Equal("reorganized/Roof", step.GetProperty("toFolder").GetString());
|
||||
Assert.Equal("Roof", step.GetProperty("toTitle").GetString());
|
||||
Assert.False(step.GetProperty("carried").GetBoolean());
|
||||
Assert.Equal(2, step.GetProperty("fileChanges").GetInt32());
|
||||
var sample = step.GetProperty("fileSamples").EnumerateArray().First();
|
||||
Assert.True(sample.GetProperty("from").GetString()!.StartsWith("originals/", StringComparison.Ordinal), "from");
|
||||
Assert.Equal("originals/Roof_001.JPG", sample.GetProperty("to").GetString());
|
||||
Assert.Equal(0, step.GetProperty("blocked").GetArrayLength());
|
||||
}
|
||||
|
||||
// A template the server refuses names its field, in the page's language: the dialog marks that field.
|
||||
using (var bad = await browser.SendAsync(HttpMethod.Post, Url, Json("""{"all":true,"fileTemplate":"{nope}","dryRun":true}""")))
|
||||
{
|
||||
var error = await bad.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_template");
|
||||
Assert.Equal("fileTemplate", error.Details);
|
||||
Assert.Equal(Loc.Get("Server.Error.InvalidTemplate", CultureInfo.GetCultureInfo("it")), error.Message);
|
||||
}
|
||||
// One that breaks a rule says why: the dialog shows the sentence on that field.
|
||||
using (var lost = await browser.SendAsync(HttpMethod.Post, Url, Json("""{"all":true,"fileTemplate":"{n}{ext}","dryRun":true}""")))
|
||||
{
|
||||
var error = await lost.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_template");
|
||||
Assert.Equal("fileTemplate:extension", error.Details);
|
||||
Assert.Equal(Loc.Get("Errors.Template.Extension", CultureInfo.GetCultureInfo("it")), error.Message);
|
||||
}
|
||||
// A plan that no longer matches is refused with the one there is now: the dialog plans again.
|
||||
using (var stale = await browser.SendAsync(HttpMethod.Post, Url, Body($"\"dryRun\":false,\"fingerprint\":\"{new string('0', 64)}\"")))
|
||||
Assert.Equal(fingerprint, (await stale.ExpectErrorAsync(HttpStatusCode.Conflict, "plan_changed")).Details);
|
||||
|
||||
Guid job;
|
||||
using (var applied = await browser.SendAsync(HttpMethod.Post, Url, Body($"\"dryRun\":false,\"fingerprint\":\"{fingerprint}\"")))
|
||||
{
|
||||
await applied.ExpectAsync(HttpStatusCode.Accepted);
|
||||
using var queued = JsonDocument.Parse(await applied.Content.ReadAsStringAsync());
|
||||
Assert.Equal("move", queued.RootElement.GetProperty("kind").GetString());
|
||||
job = queued.RootElement.GetProperty("id").GetGuid();
|
||||
}
|
||||
await UntilJobAsync(browser, job);
|
||||
var sequence = Assert.NotNull(await server.Database.Sequences.GetAsync(id));
|
||||
Assert.Equal(("reorganized/Roof", "Roof"), (sequence.Folder, sequence.Title));
|
||||
|
||||
// Every sequence (Select all without a filter) with the same templates: nothing is left to change.
|
||||
using var again = await browser.SendAsync(HttpMethod.Post, Url,
|
||||
Json("""{"all":true,"folderTemplate":"reorganized/{title}","fileTemplate":"{title}_{n:000}","dryRun":true}"""));
|
||||
await again.ExpectAsync(HttpStatusCode.OK);
|
||||
using var none = JsonDocument.Parse(await again.Content.ReadAsStringAsync());
|
||||
Assert.Equal(0, none.RootElement.GetProperty("sequences").GetInt32());
|
||||
Assert.Equal(0, none.RootElement.GetProperty("steps").GetArrayLength());
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"from ""(\.{1,2}/[^""]+)""")]
|
||||
private static partial Regex StaticImport();
|
||||
|
||||
private static async Task UntilJobAsync(Browser browser, Guid id)
|
||||
{
|
||||
var until = DateTime.UtcNow + Wait;
|
||||
while (true)
|
||||
{
|
||||
using var response = await browser.SendAsync(HttpMethod.Get, $"/api/v1/jobs/{id}");
|
||||
var job = await response.ReadAsync(ProtocolJson.Default.JobDto);
|
||||
if (job.State == "done") return;
|
||||
if (job.State is "failed" or "cancelled") Assert.Fail($"job {job.Kind} {job.State}: {job.Error}\n{job.LogTail}");
|
||||
Assert.True(DateTime.UtcNow < until, $"job {job.Kind} still {job.State}");
|
||||
await Task.Delay(50);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Waits until no job is queued or running (the thumbnails, proxies and analyses uploads queue).</summary>
|
||||
private static async Task UntilIdleAsync(TestServer server)
|
||||
{
|
||||
var until = DateTime.UtcNow + Wait;
|
||||
foreach (var state in new[] { JobState.Queued, JobState.Running, JobState.Queued, JobState.Running })
|
||||
{
|
||||
while ((await server.Database.Jobs.ListAsync(state)).Items.Count > 0)
|
||||
{
|
||||
Assert.True(DateTime.UtcNow < until, $"jobs still {state}");
|
||||
await Task.Delay(50);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static StringContent Json(string json) => new(json, Encoding.UTF8, "application/json");
|
||||
|
||||
private static byte[] Photo(int seed)
|
||||
{
|
||||
const int width = 96, height = 64;
|
||||
var pixels = new byte[width * height * 3];
|
||||
for (var i = 0; i < pixels.Length; i++) pixels[i] = (byte)((i * 7 + seed * 31) % 251);
|
||||
return JpegEncoder.Encode(pixels, width, height, 3, new JpegEncodeOptions { Quality = 90 });
|
||||
}
|
||||
|
||||
/// <summary>The bootstrap administrator signed in to the panel (a cookie session over HTTPS), calling as <c>api.js</c> does.</summary>
|
||||
private sealed class Browser(HttpClient client, string csrfToken)
|
||||
{
|
||||
public static async Task<Browser> SignInAsync(TestServer server)
|
||||
{
|
||||
await server.AdminAsync();
|
||||
var cookies = new CookieContainer();
|
||||
var client = server.NewCookieClient(cookies);
|
||||
using var login = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("admin", TestServer.Password, "admin-web", Cookie: true),
|
||||
ProtocolJson.Default.LoginRequest);
|
||||
await login.ExpectAsync(HttpStatusCode.OK);
|
||||
return new Browser(client, Assert.NotNull(cookies.GetCookies(Assert.NotNull(server.HttpsBase))["chronos_csrf"]).Value);
|
||||
}
|
||||
|
||||
/// <summary>JSON accepted, the page's language (Italian here), and the CSRF header on every call but a GET.</summary>
|
||||
public async Task<HttpResponseMessage> SendAsync(HttpMethod method, string url, HttpContent? content = null)
|
||||
{
|
||||
using var request = new HttpRequestMessage(method, url) { Content = content };
|
||||
request.Headers.Accept.ParseAdd("application/json");
|
||||
request.Headers.AcceptLanguage.ParseAdd("it");
|
||||
if (method != HttpMethod.Get) request.Headers.Add("X-CSRF-Token", csrfToken);
|
||||
return await client.SendAsync(request);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -184,8 +184,9 @@ public sealed partial class SystemEndpointTests(TestContext context)
|
||||
var seen = await ModulesAsync(server);
|
||||
Assert.True(seen.Count >= 20, string.Join(", ", seen.Keys));
|
||||
// The Library's views (owner review 2, R6) are modules of their own under pages/library; the web upload (R3) is the
|
||||
// dialog, its hash worker and the in-house SHA-256 the worker imports.
|
||||
foreach (var module in new[] { "pages/library.js", "pages/library/sequence.js", "pages/library/trash.js", "pages/library/shared.js", "upload.js", "hash-worker.js", "sha256.js" })
|
||||
// dialog, its hash worker and the in-house SHA-256 the worker imports; Reorganize (R7) is the dialog the Library and
|
||||
// the Archive page import.
|
||||
foreach (var module in new[] { "pages/library.js", "pages/library/sequence.js", "pages/library/trash.js", "pages/library/shared.js", "upload.js", "hash-worker.js", "sha256.js", "reorganize.js" })
|
||||
Assert.True(seen.ContainsKey(module), module);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,9 +2,13 @@ using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Protocol.Client;
|
||||
using Chronos.Server.Jobs;
|
||||
using Chronos.Server.Storage;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Server.Tests.Jobs;
|
||||
@@ -120,6 +124,99 @@ public sealed class RenderNodeTests(TestContext context)
|
||||
Assert.Equal(render.Id, (await renders.ReadAsync(ProtocolJson.Default.ListRenderDto)).Single().Id);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ARenderThatCannotBeFiledForNowIsCompletedAgain()
|
||||
{
|
||||
// The archive engine with a short lease wait: a sequence another writer holds refuses the filing at once.
|
||||
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = 64 * 1024, s => s.AddSingleton(sp =>
|
||||
new ArchiveService(sp.GetRequiredService<ChronosDatabase>(), new ArchiveServiceOptions { Owner = ArchiveModule.Owner, LeaseWait = TimeSpan.FromMilliseconds(200) })));
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor", renderNode: true);
|
||||
var frame = await Uploads.UploadAsync(editor, Uploads.Photo(5000, 54), "IMG_0001.CR3");
|
||||
var job = await JobApiTests.CreateAsync(editor, "render", frame.SequenceId, HevcJob);
|
||||
var node = await RegisterAsync(editor, "studio-pc", "hevc", 8192);
|
||||
using (var claim = await editor.PostAsync($"/api/v1/nodes/{node.Id}/claim", null)) await claim.ExpectAsync(HttpStatusCode.OK);
|
||||
|
||||
// A render node's output, and a render a client sends of the same sequence, both fully received.
|
||||
var output = Uploads.Photo(3000, 55);
|
||||
var result = new RenderResultRequest("Roof - 4K HEVC.mp4", output.Length, Uploads.Sha(output), "4K HEVC", "hevc", 3840, 2160, 25, 120);
|
||||
Guid fromNode;
|
||||
using (var started = await editor.PostAsJsonAsync($"/api/v1/nodes/{node.Id}/jobs/{job.Id}/result", result, ProtocolJson.Default.RenderResultRequest))
|
||||
{
|
||||
await started.ExpectAsync(HttpStatusCode.Created);
|
||||
fromNode = Assert.NotNull((await started.ReadAsync(ProtocolJson.Default.StartUploadResponse)).UploadId);
|
||||
}
|
||||
using (var put = await Uploads.PutChunkAsync(editor, fromNode, 0, output)) await put.ExpectAsync(HttpStatusCode.OK);
|
||||
var sent = Uploads.Photo(2000, 56);
|
||||
var offered = new RenderUploadRequest(Guid.CreateVersion7(), "Roof.mp4", sent.Length, Uploads.Sha(sent), "1080p", "h264", 1920, 1080, 30, 10, null);
|
||||
Guid fromClient;
|
||||
using (var started = await editor.PostAsJsonAsync($"/api/v1/sequences/{frame.SequenceId}/renders", offered, ProtocolJson.Default.RenderUploadRequest))
|
||||
{
|
||||
await started.ExpectAsync(HttpStatusCode.Created);
|
||||
fromClient = Assert.NotNull((await started.ReadAsync(ProtocolJson.Default.StartUploadResponse)).UploadId);
|
||||
}
|
||||
using (var put = await Uploads.PutChunkAsync(editor, fromClient, 0, sent)) await put.ExpectAsync(HttpStatusCode.OK);
|
||||
|
||||
var completions = new[] { $"/api/v1/nodes/{node.Id}/jobs/{job.Id}/result/complete", $"/api/v1/sequences/{frame.SequenceId}/renders/{fromClient}/complete" };
|
||||
var paths = new ArchivePaths(server.Options.ArchivePath);
|
||||
async Task RefusedAsync(string code)
|
||||
{
|
||||
foreach (var complete in completions)
|
||||
{
|
||||
using var refused = await editor.PostAsync(complete, null);
|
||||
await refused.ExpectErrorAsync(HttpStatusCode.ServiceUnavailable, code);
|
||||
}
|
||||
// Nothing filed, nothing staged: both uploads receive again with their chunks, and the node keeps its job.
|
||||
foreach (var upload in new[] { fromNode, fromClient })
|
||||
{
|
||||
Assert.Equal(Chronos.Data.Repositories.UploadState.Receiving, (await server.Database.Uploads.GetAsync(upload))!.State);
|
||||
Assert.True(server.Services.GetRequiredService<UploadStore>().Exists(upload));
|
||||
}
|
||||
Assert.False(Directory.Exists(server.Options.StagingPath) && Directory.EnumerateFiles(server.Options.StagingPath).Any());
|
||||
Assert.Equal(0, (await server.Database.Sequences.GetAsync(frame.SequenceId))!.RenderedCount);
|
||||
var waiting = await JobApiTests.GetAsync(editor, job.Id);
|
||||
Assert.Equal(("running", node.Id.ToString()), (waiting.State, waiting.NodeId));
|
||||
}
|
||||
|
||||
// Another writer holds the sequence past the lease wait (a Reorganize step, a photo deletion).
|
||||
using (Assert.NotNull(LeaseFile.TryAcquire(paths.LocksDirectory, $"seq-{frame.SequenceId:N}", "tests")))
|
||||
await RefusedAsync("sequence_busy");
|
||||
// The archive drive is gone.
|
||||
File.Move(paths.ManifestPath, paths.ManifestPath + ".away");
|
||||
try
|
||||
{
|
||||
await RefusedAsync("archive_offline");
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Move(paths.ManifestPath + ".away", paths.ManifestPath);
|
||||
}
|
||||
// A desktop sharing the archive moved the sequence's folder: this server's index has it at the old place until its
|
||||
// next scan, and nothing is filed there meanwhile.
|
||||
var folder = (await server.Database.Sequences.GetAsync(frame.SequenceId))!.Folder;
|
||||
var left = paths.FromRelative(folder);
|
||||
Directory.Move(left, paths.FromRelative(folder + " moved"));
|
||||
await RefusedAsync("folder_moved");
|
||||
Assert.False(Directory.Exists(left), "the folder it left is not created again");
|
||||
// The next scan finds it where it is now (moved here as a scan moves it: this composition writes no sidecars), and the
|
||||
// renders are filed there.
|
||||
await using (var tx = await server.Database.BeginAsync(context.Cancellation))
|
||||
{
|
||||
await tx.Sequences.RelocateAsync(frame.SequenceId, folder + " moved", null, context.Cancellation);
|
||||
await tx.CommitAsync(context.Cancellation);
|
||||
}
|
||||
|
||||
foreach (var complete in completions)
|
||||
{
|
||||
using var filed = await editor.PostAsync(complete, null);
|
||||
await filed.ExpectAsync(HttpStatusCode.OK);
|
||||
}
|
||||
Assert.Equal("done", (await JobApiTests.GetAsync(editor, job.Id)).State);
|
||||
var sequence = (await server.Database.Sequences.GetAsync(frame.SequenceId))!;
|
||||
Assert.Equal(2, sequence.RenderedCount);
|
||||
await Http.BytesEqualAsync(output, File.ReadAllBytesAsync(Path.Combine(server.Options.ArchivePath, sequence.Folder, "exports", "Roof - 4K HEVC.mp4")));
|
||||
await Http.BytesEqualAsync(sent, File.ReadAllBytesAsync(Path.Combine(server.Options.ArchivePath, sequence.Folder, "exports", "Roof.mp4")));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task NodesReportFailuresAndNeedTheRight()
|
||||
{
|
||||
|
||||
@@ -19,11 +19,13 @@ internal static class Uploads
|
||||
|
||||
public static string Sha(byte[] data) => Convert.ToHexStringLower(SHA256.HashData(data));
|
||||
|
||||
/// <param name="capturedAt">The capture time the client sends; null: 2026-09-28 18:02:11.</param>
|
||||
public static async Task<StartUploadResponse> StartAsync(HttpClient client, byte[] data, string fileName = "IMG_0001.CR3", Guid? sequenceId = null,
|
||||
string? sessionKey = null, HttpStatusCode expected = HttpStatusCode.Created)
|
||||
string? sessionKey = null, HttpStatusCode expected = HttpStatusCode.Created, DateTime? capturedAt = null)
|
||||
{
|
||||
using var response = await client.PostAsJsonAsync("/api/v1/uploads",
|
||||
new StartUploadRequest(sequenceId, fileName, data.Length, Sha(data), new DateTime(2026, 9, 28, 18, 2, 11), sessionKey), ProtocolJson.Default.StartUploadRequest);
|
||||
new StartUploadRequest(sequenceId, fileName, data.Length, Sha(data), capturedAt ?? new DateTime(2026, 9, 28, 18, 2, 11), sessionKey),
|
||||
ProtocolJson.Default.StartUploadRequest);
|
||||
await response.ExpectAsync(expected);
|
||||
return await response.ReadAsync(ProtocolJson.Default.StartUploadResponse);
|
||||
}
|
||||
@@ -40,9 +42,9 @@ internal static class Uploads
|
||||
|
||||
/// <summary>Start, every chunk, complete; returns the committed frame.</summary>
|
||||
public static async Task<CompleteUploadResponse> UploadAsync(HttpClient client, byte[] data, string fileName = "IMG_0001.CR3", Guid? sequenceId = null,
|
||||
string? sessionKey = null)
|
||||
string? sessionKey = null, DateTime? capturedAt = null)
|
||||
{
|
||||
var start = await StartAsync(client, data, fileName, sequenceId, sessionKey);
|
||||
var start = await StartAsync(client, data, fileName, sequenceId, sessionKey, capturedAt: capturedAt);
|
||||
var id = Assert.NotNull(start.UploadId);
|
||||
var chunks = (data.Length + start.ChunkSize - 1) / start.ChunkSize;
|
||||
for (var i = 0; i < chunks; i++)
|
||||
|
||||
Reference in new issue
Block a user