feat(archive): reorganize existing sequences with folder, file and title templates
Owner review 2, R7 asks for renaming and moving after import, on the web panel and the desktop. This is the engine and the server API both UIs build on. - FrameNaming (Core/Naming) is the one naming context and unique-name rule of a frame: imports, uploads and Reorganize now produce identical names (behaviour of the ingest and the import planner unchanged). - RenamePlanner takes a file template: each step counts its renamed frames, shows the first three and the frames version they were planned at, and lists what keeps its name (photos in place outside originals/, never hashed, missing, unreadable sidecar). Names are given in index order with _2, _3 as filing does; XMP companions follow their photo. - MassRenamer renames a step's files under the same leases after its folder moved, checks the frames version, journals .chronos/rename-files.json and moves files in two phases through temporary names so chains and swaps never meet; then sidecar, index (FrameRepository.RenameFilesAsync, both dialects) and journal. A failure puts every file back; a crash is completed by the next writer or the plan's resume, the index following. Plans a paused or cancelled job holds are left to that job. - JobKind.Move gets MoveJobHandler: it plans again and applies only the confirmed plan (fingerprint and frames versions), with progress and checkpoints per sequence. - POST /api/v1/archive/reorganize: dry run with the plan and its fingerprint, otherwise a 202 move job; validated templates, audited, sequenceChanged reorganized events. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit aae1c3eb18ea932b4a6251c5e2a282b9295a5785)
This commit is contained in:
1 parent
81cf58227d
commit
eb2395d9b0
36 files changed
+2238
-164
No files matched your search
@@ -0,0 +1,226 @@
|
||||
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 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 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());
|
||||
Assert.NotEqual(plan.Fingerprint(), Make(manifest with { Versions = new ManifestVersions { Frames = 5 } }).Fingerprint());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TemplatesAreCheckedAsTheArchiveSettingsAre()
|
||||
{
|
||||
Assert.Null(new RenameTemplates("{year}/{title}", "{date}_{n}", "{title} 2026").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());
|
||||
Assert.True(new RenameTemplates().IsEmpty);
|
||||
}
|
||||
|
||||
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))));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
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);
|
||||
}
|
||||
|
||||
[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" };
|
||||
Assert.Equal("originals/2026-09-28_2.JPG", FrameNaming.FileName(template, context, taken, "originals/"));
|
||||
Assert.Equal("originals/2026-09-28_3.JPG", FrameNaming.FileName(template, context, taken, "originals/"));
|
||||
Assert.Contains("originals/2026-09-28_3.JPG", taken);
|
||||
Assert.Equal("a/IMG_5_2.CR2", FrameNaming.Unique("a/IMG_5.CR2", f => f != "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();
|
||||
|
||||
// The sequence the import files: the plan's names, each frame from its photo's metadata, the camera of the first.
|
||||
var frames = session.Items.Select(item =>
|
||||
{
|
||||
var metadata = MetadataReader.Read(Path.Combine(card, item.SourcePath));
|
||||
return SequenceFrames.FromMetadata(Guid.NewGuid(), "originals/" + item.FileName, Path.GetFileName(item.SourcePath), item.Size, new string('b', 64),
|
||||
metadata, item.CapturedAt);
|
||||
}).ToList();
|
||||
var first = MetadataReader.Read(Path.Combine(card, session.Items[0].SourcePath));
|
||||
var manifest = SequenceFrames.Insert(new SequenceManifest
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Camera = new SidecarCamera { Make = first.Make, Model = first.Model },
|
||||
Lens = first.LensModel,
|
||||
}, frames);
|
||||
|
||||
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))));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
using System.Security.Cryptography;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Import;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Naming;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Testing;
|
||||
using static Chronos.Data.Tests.Archiving.ArchiveFixture;
|
||||
|
||||
namespace Chronos.Data.Tests.Archiving;
|
||||
|
||||
/// <summary>
|
||||
/// Reorganize (owner review 2, R7): new folder, file and title templates applied to sequences already in the archive, with a
|
||||
/// dry run, two-phase file renames under a journal, crash recovery, stale plans and the <c>move</c> job.
|
||||
/// </summary>
|
||||
[Category("archive")]
|
||||
public sealed class ReorganizeTests(TestContext context)
|
||||
{
|
||||
private static IngestRequest Upload(ArchiveFixture fx, (string Path, long Size, string Sha256) staged, string name, string key) =>
|
||||
new(fx.Archive.Id, null, null, key, staged.Path, name, staged.Size, staged.Sha256, null, null);
|
||||
|
||||
/// <summary>Uploads photos ten seconds apart (from <paramref name="firstSecond"/>) into the sequence of <paramref name="key"/>; returns its id.</summary>
|
||||
private static async Task<Guid> UploadAsync(ArchiveFixture fx, int count, int firstSeed = 1, int firstSecond = 0, string key = "upload-1")
|
||||
{
|
||||
Guid id = default;
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var staged = fx.Stage(Start.AddSeconds(firstSecond + 10 * i), firstSeed + i);
|
||||
id = (await fx.Service.Ingest.CommitAsync(Upload(fx, staged, $"IMG_{firstSeed + i:0000}.JPG", key), fx.Ct)).SequenceId;
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A sequence whose names follow "{n:0}" no more: two photos filed as 1 and 2, then an earlier one filed before them as 1_2.
|
||||
/// Renamed with "{n:0}" again they chain: 1_2→1, 1→2, 2→3.
|
||||
/// </summary>
|
||||
private static async Task<Guid> ChainAsync(ArchiveFixture fx)
|
||||
{
|
||||
await fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Templates = s.Templates with { File = "{n:0}" } }, fx.Ct);
|
||||
await UploadAsync(fx, 2, firstSeed: 2, firstSecond: 10);
|
||||
var id = await UploadAsync(fx, 1, firstSeed: 1);
|
||||
Assert.SequenceEqual(["originals/1_2.JPG", "originals/1.JPG", "originals/2.JPG"], await FilesAsync(fx, id));
|
||||
return id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The files of a sequence as its sidecar names them, after checking that the index names the same files in the same
|
||||
/// order at the same frames version, that every file holds its frame's photo and that no journal is left.
|
||||
/// </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), rows.Select(r => r.Id));
|
||||
Assert.Equal(sidecar.Versions.Frames, sequence.FramesVersion);
|
||||
Assert.Equal(sidecar.Title, sequence.Title);
|
||||
foreach (var (frame, row) in sidecar.Frames.Zip(rows))
|
||||
{
|
||||
Assert.Equal(folder.ArchiveRelative(frame.File), row.RelativePath);
|
||||
Assert.Equal(Path.GetFileName(frame.File), row.FileName);
|
||||
Assert.Equal(frame.Sha256, Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(folder.File(frame.File)))));
|
||||
}
|
||||
Assert.Null(FileRenameJournal.Read(folder));
|
||||
Assert.Empty(Directory.EnumerateFiles(folder.Originals, ".chronos-rename-*"));
|
||||
return [.. sidecar.Frames.Select(f => f.File)];
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task FilesAreRenamedExactlyAsTheDryRunSaid()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var id = await UploadAsync(fx, 3);
|
||||
var before = await FilesAsync(fx, id);
|
||||
var version = (await fx.Db.Sequences.GetAsync(id))!.FramesVersion;
|
||||
var templates = new RenameTemplates(File: "{title}_{n:000}", Title: "Roof");
|
||||
|
||||
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], templates, fx.Ct);
|
||||
var step = plan.Steps.Single();
|
||||
Assert.Equal((3, version, "Roof"), (step.FileChanges, step.FramesVersion, step.ToTitle));
|
||||
Assert.SequenceEqual(before.Zip(["originals/Roof_001.JPG", "originals/Roof_002.JPG", "originals/Roof_003.JPG"], (f, t) => $"{f}>{t}"),
|
||||
step.FileSamples.Select(s => $"{s.From}>{s.To}"));
|
||||
Assert.SequenceEqual(before, await FilesAsync(fx, id));
|
||||
|
||||
var result = await fx.Service.ApplyRenameAsync(plan, null, fx.Ct);
|
||||
Assert.Equal(3, result.Files);
|
||||
Assert.SequenceEqual([id], result.Changed);
|
||||
Assert.SequenceEqual(["originals/Roof_001.JPG", "originals/Roof_002.JPG", "originals/Roof_003.JPG"], await FilesAsync(fx, id));
|
||||
Assert.Equal(version + 1, (await fx.Db.Sequences.GetAsync(id))!.FramesVersion);
|
||||
Assert.Equal("Roof", (await fx.Db.Sequences.GetAsync(id))!.Title);
|
||||
Assert.Empty(RenameJournal.ListPending(fx.Paths));
|
||||
Assert.Equal(0, (await fx.ScanAsync()).Indexed);
|
||||
// Applied again, the templates change nothing.
|
||||
Assert.False((await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], templates, fx.Ct)).Steps.Any(s => s.Changes));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task UploadsAndImportsAreNamedAsReorganizeNamesThem()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
await UploadAsync(fx, 3);
|
||||
var card = context.CreateTempDirectory("card");
|
||||
Photos.WriteSeries(Path.Combine(card, "DCIM", "100CANON"), Start.AddDays(1), 4, firstSeed: 30);
|
||||
var import = await fx.Service.PlanImportAsync(fx.Archive.Id, card,
|
||||
new ImportOptions { FolderTemplate = fx.Archive.FolderTemplate, FileTemplate = fx.Archive.FileTemplate }, null, null, fx.Ct);
|
||||
var engine = await fx.StartEngineAsync();
|
||||
await fx.WaitForAsync((await engine.EnqueueAsync(ArchiveJobs.Import(fx.Archive, import, null), cancellationToken: fx.Ct)).Id, JobState.Done);
|
||||
Assert.Count(2, await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id));
|
||||
|
||||
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, null, new RenameTemplates(File: fx.Archive.FileTemplate), fx.Ct);
|
||||
Assert.Empty(plan.Steps);
|
||||
Assert.Count(2, plan.Subjects);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AChainOfNewNamesIsRenamedThroughTemporaryNames()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var id = await ChainAsync(fx);
|
||||
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], new RenameTemplates(File: "{n:0}"), fx.Ct);
|
||||
Assert.Equal(3, plan.Steps.Single().FileChanges);
|
||||
await fx.Service.ApplyRenameAsync(plan, null, fx.Ct);
|
||||
Assert.SequenceEqual(["originals/1.JPG", "originals/2.JPG", "originals/3.JPG"], await FilesAsync(fx, id));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case(1)]
|
||||
[Case(2)]
|
||||
public async Task ARenameACrashInterruptedIsCompletedAtTheNextOpen(int phase)
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var id = await ChainAsync(fx);
|
||||
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], new RenameTemplates(File: "{n:0}"), fx.Ct);
|
||||
|
||||
// The process stopped inside the step: the plan's journal and the sequence's, files part-way through their phase.
|
||||
RenameJournal.Write(fx.Paths, new RenameJournal(plan, []));
|
||||
var folder = fx.Paths.Sequence((await fx.Db.Sequences.GetAsync(id))!.Folder);
|
||||
var manifest = ManifestStore.ReadSequence(folder.ManifestPath);
|
||||
var moves = FileRenames.Plan(manifest, null, PathTemplate.Parse("{n:0}"), FileRenames.ListPresent(folder, manifest)).Moves;
|
||||
var journal = FileRenameJournal.Create(manifest.Versions.Frames, moves, "crash") with { Phase = phase };
|
||||
FileRenameJournal.Write(folder, journal);
|
||||
File.Move(folder.File(journal.Files[0].From), folder.File(journal.Files[0].Temp));
|
||||
if (phase == 2)
|
||||
{
|
||||
foreach (var file in journal.Files.Skip(1)) File.Move(folder.File(file.From), folder.File(file.Temp));
|
||||
File.Move(folder.File(journal.Files[0].Temp), folder.File(journal.Files[0].To));
|
||||
}
|
||||
|
||||
await fx.Service.OpenAsync(fx.Archive.RootPath, fx.Ct);
|
||||
Assert.Empty(RenameJournal.ListPending(fx.Paths));
|
||||
Assert.SequenceEqual(["originals/1.JPG", "originals/2.JPG", "originals/3.JPG"], await FilesAsync(fx, id));
|
||||
Assert.Equal(manifest.Versions.Frames + 1, (await fx.Db.Sequences.GetAsync(id))!.FramesVersion);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task APlanWhosePhotosChangedIsRefusedOrResumedWithoutTheirNames()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var id = await UploadAsync(fx, 2);
|
||||
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], new RenameTemplates(File: "{n:000}", Title: "Roof"), fx.Ct);
|
||||
// A photo arrives after the dry run: the names shown are no longer the ones the template gives.
|
||||
await UploadAsync(fx, 1, firstSeed: 9, firstSecond: 5);
|
||||
var before = await FilesAsync(fx, id);
|
||||
|
||||
var stale = await Assert.ThrowsAsync<StaleRenamePlanException>(() => fx.Service.ApplyRenameAsync(plan, null, fx.Ct));
|
||||
Assert.Equal(id, stale.SequenceId);
|
||||
Assert.SequenceEqual(before, await FilesAsync(fx, id));
|
||||
Assert.Null((await fx.Db.Sequences.GetAsync(id))!.Title);
|
||||
Assert.Empty(RenameJournal.ListPending(fx.Paths));
|
||||
|
||||
// Interrupted before its step began, the plan resumes: the title changes, the files keep their names.
|
||||
RenameJournal.Write(fx.Paths, new RenameJournal(plan, []));
|
||||
Assert.Equal(1, await fx.Service.Renamer.ResumePendingAsync(fx.Archive, fx.Ct));
|
||||
Assert.SequenceEqual(before, await FilesAsync(fx, id));
|
||||
Assert.Equal("Roof", (await fx.Db.Sequences.GetAsync(id))!.Title);
|
||||
Assert.Empty(RenameJournal.ListPending(fx.Paths));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CompanionsMoveWithTheirPhoto()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var id = await UploadAsync(fx, 2);
|
||||
var before = await FilesAsync(fx, id);
|
||||
var folder = fx.Paths.Sequence((await fx.Db.Sequences.GetAsync(id))!.Folder);
|
||||
File.WriteAllText(folder.File(Path.ChangeExtension(before[0], ".xmp")), "first");
|
||||
File.WriteAllText(folder.File(before[1] + ".xmp"), "second");
|
||||
await fx.ScanAsync();
|
||||
|
||||
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], new RenameTemplates(File: "{n:000}"), fx.Ct);
|
||||
Assert.Equal(2, plan.Steps.Single().FileChanges);
|
||||
await fx.Service.ApplyRenameAsync(plan, null, fx.Ct);
|
||||
Assert.SequenceEqual(["originals/001.JPG", "originals/002.JPG"], await FilesAsync(fx, id));
|
||||
Assert.Equal("first", File.ReadAllText(folder.File("originals/001.xmp")));
|
||||
Assert.Equal("second", File.ReadAllText(folder.File("originals/002.JPG.xmp")));
|
||||
Assert.SequenceEqual(["001.JPG", "001.xmp", "002.JPG", "002.JPG.xmp"], Directory.EnumerateFiles(folder.Originals).Select(Path.GetFileName).Order(StringComparer.Ordinal));
|
||||
Assert.Equal(0, (await fx.ScanAsync()).Indexed);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task PhotosAdoptedInPlaceKeepTheirNames()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "inbox", "a"), Start, 3);
|
||||
await fx.ScanAsync();
|
||||
var id = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Single().Id;
|
||||
|
||||
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], new RenameTemplates(File: "{n:000}"), fx.Ct);
|
||||
var step = plan.Steps.Single();
|
||||
Assert.False(step.Changes);
|
||||
Assert.Equal((RenameBlock.InPlace, 3), (step.Blocked.Single().Reason, step.Blocked.Single().Frames));
|
||||
var result = await fx.Service.ApplyRenameAsync(plan, null, fx.Ct);
|
||||
Assert.Empty(result.Changed);
|
||||
Assert.SequenceEqual(["IMG_0001.JPG", "IMG_0002.JPG", "IMG_0003.JPG"], ManifestStore.ReadSequence(fx.Paths.Sequence("inbox/a").ManifestPath).Frames.Select(f => f.File));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AMoveJobAppliesTheConfirmedPlanAndRefusesOneTheArchiveOutgrew()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var id = await UploadAsync(fx, 3);
|
||||
var engine = await fx.StartEngineAsync();
|
||||
var templates = new RenameTemplates(Folder: "reorganized/{date}", File: "{n:000}");
|
||||
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], templates, fx.Ct);
|
||||
var job = await engine.EnqueueAsync(ArchiveJobs.Reorganize(fx.Archive, plan, templates), cancellationToken: fx.Ct);
|
||||
Assert.Equal(JobKind.Move, job.Kind);
|
||||
var done = await fx.WaitForAsync(job.Id, JobState.Done);
|
||||
Assert.Equal((1, 1), (done.ProgressDone, done.ProgressTotal));
|
||||
Assert.Contains(Loc.L("Archive.Log.Reorganized", 1, 3), done.LogTail);
|
||||
Assert.Equal("reorganized/2026-09-28", (await fx.Db.Sequences.GetAsync(id))!.Folder);
|
||||
Assert.SequenceEqual(["originals/001.JPG", "originals/002.JPG", "originals/003.JPG"], await FilesAsync(fx, id));
|
||||
|
||||
var back = new RenameTemplates(File: "{date}_{n:0000}");
|
||||
var again = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], back, fx.Ct);
|
||||
await UploadAsync(fx, 1, firstSeed: 9, firstSecond: 5);
|
||||
var before = await FilesAsync(fx, id);
|
||||
var refused = await fx.WaitForAsync((await engine.EnqueueAsync(ArchiveJobs.Reorganize(fx.Archive, again, back), cancellationToken: fx.Ct)).Id, JobState.Failed);
|
||||
Assert.Equal(Loc.L("Archive.Error.StalePlan"), refused.Error);
|
||||
Assert.SequenceEqual(before, await FilesAsync(fx, id));
|
||||
Assert.Empty(RenameJournal.ListPending(fx.Paths));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AHeldPlanWaitsForItsJob()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
var first = await UploadAsync(fx, 2);
|
||||
var second = await UploadAsync(fx, 2, firstSeed: 20, firstSecond: 3600, key: "upload-2");
|
||||
var templates = new RenameTemplates(File: "{n:000}");
|
||||
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [first, second], templates, fx.Ct);
|
||||
Assert.Count(2, plan.Steps);
|
||||
var untouched = await FilesAsync(fx, second);
|
||||
|
||||
// The job stops after the first sequence (paused) and holds its plan: an archive open leaves the rest alone.
|
||||
using var cts = new CancellationTokenSource();
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => fx.Service.Renamer.ApplyAsync(fx.Archive, plan, null, _ =>
|
||||
{
|
||||
cts.Cancel();
|
||||
return ValueTask.CompletedTask;
|
||||
}, cts.Token));
|
||||
Assert.True(MassRenamer.Hold(fx.Archive, plan.Id));
|
||||
Assert.Equal(0, await fx.Service.Renamer.ResumePendingAsync(fx.Archive, fx.Ct));
|
||||
Assert.SequenceEqual(["originals/001.JPG", "originals/002.JPG"], await FilesAsync(fx, first));
|
||||
Assert.SequenceEqual(untouched, await FilesAsync(fx, second));
|
||||
Assert.True(Assert.NotNull(RenameJournal.Read(fx.Paths, plan.Id)).Held);
|
||||
|
||||
// Resumed from its checkpoint, the job completes it; once its journal is gone a run finds the plan complete.
|
||||
var engine = await fx.StartEngineAsync();
|
||||
var request = ArchiveJobs.Reorganize(fx.Archive, plan, templates);
|
||||
var resumed = await fx.WaitForAsync((await fx.EnqueueWithCheckpointAsync(engine, request, "plan:" + plan.Id.ToString("N"))).Id, JobState.Done);
|
||||
Assert.Contains(Loc.L("Archive.Log.Reorganized", 1, 2), resumed.LogTail);
|
||||
Assert.SequenceEqual(["originals/001.JPG", "originals/002.JPG"], await FilesAsync(fx, second));
|
||||
Assert.Null(RenameJournal.Read(fx.Paths, plan.Id));
|
||||
var later = await fx.WaitForAsync((await fx.EnqueueWithCheckpointAsync(engine, request, "plan:" + plan.Id.ToString("N"))).Id, JobState.Done);
|
||||
Assert.Contains(Loc.L("Archive.Log.ReorganizedEarlier"), later.LogTail);
|
||||
}
|
||||
}
|
||||
@@ -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,187 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Chronos.Core.Codecs.Jpeg;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Protocol;
|
||||
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, the <c>move</c> job that
|
||||
/// applies the confirmed plan, 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 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 { 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);
|
||||
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());
|
||||
}
|
||||
Assert.Empty((await server.Database.Jobs.ListAsync(JobState.Queued, JobKind.Move)).Items);
|
||||
}
|
||||
|
||||
[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 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 (job.State == state) 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 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 });
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user