fix(archive): Reorganize names as filing does and refuses templates that lose or hide photos

Reorganize with the archive's own templates planned renames and moves for
photos just filed, and some templates could strip extensions, hide sequences
from scans or stall a dry run. Owner review 2, phase 4a findings.

- Filing and Reorganize share one context: uploads and imports name every
  photo with the sequence's camera and lens (its first photo's, or the
  creator's hint), an upload's folder from its first frame in the new
  sequence, and a missing capture time from the sequence start instead of
  the current time. The planner expands folder and title templates from the
  first frame in the sidecar ({name}, {ext}, {iso}...), never today's date.
- Titles expand as text (ExpandText): "Paris: night" stays as typed.
- A sequence whose sidecar cannot be read (torn, another sequence's) keeps
  its folder, title and names, listed with why, and so does every folder
  around it; the dry run reads every sidecar, nested ones included.
- Kept never gives one folder to two sequences of a plan whatever the case,
  and a case-only move onto another folder is refused instead of taken as
  done.
- Shared template rules (TemplateRules) for the server's Reorganize and
  archive settings and the desktop's fields: a file template must keep the
  photo's extension ("{n}{ext}" refused) and tell a session's photos apart;
  a folder template may not write a level scans skip (a leading dot,
  originals, proxies, exports). Levels a title gives are escaped with "_".
- {ext} comes from the file, or from the original name when the file lost
  a photo's extension, so a Reorganize can put it back.
- Unique names cost linear time (UniqueNames) with the same names as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 6c734777e01476881a3f34b3188571cc3f7150ab)
This commit is contained in:
Alby96 committed 2026-10-27 16:29:31 +01:00
1 parent 13c2ac321c
commit b253cac8d4
25 files changed
+777 -173

No files matched your search

@@ -113,11 +113,11 @@ internal sealed class ArchiveFixture : IAsyncDisposable
}
/// <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")
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)));
@@ -132,7 +132,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 +142,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..]] });
}
@@ -132,11 +132,85 @@ public sealed class ReorganizeTests(TestContext context)
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);
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, null, new RenameTemplates(fx.Archive.FolderTemplate, fx.Archive.FileTemplate), fx.Ct);
Assert.Empty(plan.Steps);
Assert.Count(2, plan.Subjects);
}
[Test]
public async Task UploadsAreFiledWithTheirSequencesCameraAndLensAsReorganizeNamesThem()
{
await using var fx = await CreateAsync(context);
const string FolderTemplate = "{year}/{date} {camera} {ext}", FileTemplate = "{camera}_{lens}_{n:0000}";
await fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Templates = s.Templates with { Folder = FolderTemplate, File = FileTemplate } }, fx.Ct);
// A sequence created with the camera it is for, whose photos name none: the hint names them.
var hinted = new Sequence
{
Id = Guid.CreateVersion7(),
ArchiveId = fx.Archive.Id,
Title = "Roof",
Folder = string.Empty,
CameraModel = "GoPro HERO12 Black",
Origin = SequenceOrigin.Server,
UpdatedAt = DateTimeOffset.UtcNow,
};
await fx.Db.Sequences.UpsertAsync(hinted, fx.Ct);
for (var i = 0; i < 2; i++)
{
var staged = fx.Stage(Start.AddSeconds(10 * i), 40 + i, make: null, model: null);
await fx.Service.Ingest.CommitAsync(new IngestRequest(fx.Archive.Id, hinted.Id, null, null, staged.Path, $"GOPR{i:0000}.JPG", staged.Size,
staged.Sha256, null, null), fx.Ct);
}
// A lens changed during a session: its photos take the first one's, as the sequence does.
Guid lensed = default;
foreach (var (lens, i) in new[] { "RF15-35mm", "RF24-70mm" }.Select((l, i) => (l, i)))
{
var staged = fx.Stage(Start.AddHours(2).AddSeconds(10 * i), 50 + i, lens: lens);
lensed = (await fx.Service.Ingest.CommitAsync(Upload(fx, staged, $"IMG_{i:0000}.JPG", "upload-2"), fx.Ct)).SequenceId;
}
Assert.SequenceEqual(["originals/GoPro HERO12 Black__0001.JPG", "originals/GoPro HERO12 Black__0002.JPG"], await FilesAsync(fx, hinted.Id));
Assert.Equal("2026/2026-09-28 GoPro HERO12 Black JPG", (await fx.Db.Sequences.GetAsync(hinted.Id))!.Folder);
Assert.SequenceEqual(["originals/Canon EOS R5_RF15-35mm_0001.JPG", "originals/Canon EOS R5_RF15-35mm_0002.JPG"], await FilesAsync(fx, lensed));
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, null, new RenameTemplates(FolderTemplate, FileTemplate), fx.Ct);
Assert.Count(2, plan.Subjects);
Assert.Empty(plan.Steps);
}
[Test]
public async Task ASequenceWhoseSidecarCannotBeReadStaysAsItIsAndTheOthersMove()
{
await using var fx = await CreateAsync(context);
var good = await UploadAsync(fx, 2);
var torn = await UploadAsync(fx, 2, firstSeed: 20, firstSecond: 3600, key: "upload-2");
var foreign = await UploadAsync(fx, 2, firstSeed: 30, firstSecond: 7200, key: "upload-3");
var last = await UploadAsync(fx, 2, firstSeed: 40, firstSecond: 10800, key: "upload-4");
async Task<SequencePaths> FolderOf(Guid id) => fx.Paths.Sequence((await fx.Db.Sequences.GetAsync(id))!.Folder);
File.WriteAllText((await FolderOf(torn)).ManifestPath, "{ \"schemaVersion\": 1, \"id\": ");
File.Copy((await FolderOf(good)).ManifestPath, (await FolderOf(foreign)).ManifestPath, overwrite: true);
var kept = new Dictionary<Guid, string>();
foreach (var id in new[] { torn, foreign }) kept[id] = (await fx.Db.Sequences.GetAsync(id))!.Folder;
var templates = new RenameTemplates(Folder: "moved/{date}", Title: "{title} {hm}");
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, null, templates, fx.Ct);
foreach (var id in kept.Keys)
{
var step = plan.Steps.Single(s => s.SequenceId == id);
Assert.Equal((kept[id], step.FromTitle), (step.ToFolder, step.ToTitle));
Assert.False(step.Changes);
Assert.Equal(RenameBlock.Unreadable, step.Blocked.Single().Reason);
}
// The one after them gets the " (2)" they never take.
Assert.Equal(("moved/2026-09-28 (2)", "21-00"), (plan.Steps.Single(s => s.SequenceId == last).ToFolder, plan.Steps.Single(s => s.SequenceId == last).ToTitle));
var result = await fx.Service.ApplyRenameAsync(plan, null, fx.Ct);
Assert.SequenceEqual([good, last], result.Changed);
Assert.Equal("moved/2026-09-28", (await fx.Db.Sequences.GetAsync(good))!.Folder);
foreach (var id in kept.Keys) Assert.Equal(kept[id], (await fx.Db.Sequences.GetAsync(id))!.Folder);
Assert.Empty(RenameJournal.ListPending(fx.Paths));
Assert.Equal(0, await fx.Service.Renamer.ResumePendingAsync(fx.Archive, fx.Ct));
}
[Test]
public async Task AChainOfNewNamesIsRenamedThroughTemporaryNames()
{