fix(archive): Reorganize never plans a move onto a folder of the exact name, keeps long names' extensions, says why a template is refused
Second fix round of owner review 2, phase 4a (planner findings).
- A sequence keeps a folder that differs from its own in case only while no
other folder holds that exact name (RenamePlanner.ExistsExactly, every level
compared exactly). On a case-sensitive file system a stray "Trip (2)" beside
the sequence at "trip (2)" no longer gives a case-only step that MoveFolder
refuses at every archive open: the plan gives "Trip", and a plan whose
target appeared since is refused under the step's leases before anything
moves (or dropped when it resumes). A change of case in an outer level no
longer looks like two folders on Windows.
- A file name longer than 200 characters is shortened before the ".{ext}" the
template ends with, never through it, so a long title never strips the
photo's extension.
- The archive engine's own settings check applies the template rules the
server and the desktop apply (a folder scans skip, a lost extension, names
that repeat), so archive.json can no longer take such a template.
- The server's invalid_template answer names the rule after the field
("fileTemplate:extension") with the desktop's sentence as its message; both
admin panels show it on the field.
- FrameNaming keeps only the naming overloads production uses.
- Comments about Unreadable say the whole sequence stays as it is.
- Tests pin filing against Reorganize: an upload without a capture time, a
card's second session with {session}, a duplicate skipped mid-session, and a
whole folder of two cameras named with the first one's camera.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 50fe59aec1e180daa1733bcb951892a79dceba6c)
This commit is contained in:
1 parent
9e1f109b58
commit
765f0ad36b
20 files changed
+446
-141
No files matched your search
@@ -203,6 +203,8 @@ public sealed class ReorganizeTests(TestContext context)
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -221,6 +223,7 @@ public sealed class ReorganizeTests(TestContext context)
|
||||
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)));
|
||||
}
|
||||
|
||||
@@ -362,6 +365,59 @@ public sealed class ReorganizeTests(TestContext context)
|
||||
}
|
||||
}
|
||||
|
||||
[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 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()
|
||||
{
|
||||
@@ -384,7 +440,8 @@ public sealed class ReorganizeTests(TestContext context)
|
||||
{
|
||||
// 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 = FrameNaming.Unique("a/x.JPG", c => !reference.Contains(c) && companion(c));
|
||||
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}");
|
||||
}
|
||||
|
||||
@@ -68,6 +68,15 @@ public sealed class FrameNamingTests(TestContext context)
|
||||
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]
|
||||
@@ -77,10 +86,11 @@ public sealed class FrameNamingTests(TestContext context)
|
||||
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/"));
|
||||
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", FrameNaming.Unique("a/IMG_5.CR2", f => f != "a/IMG_5.CR2"));
|
||||
Assert.Equal("a/IMG_5_2.CR2", new UniqueNames(new HashSet<string>(["a/IMG_5.CR2"])).Claim("a/IMG_5.CR2"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -92,21 +102,7 @@ public sealed class FrameNamingTests(TestContext context)
|
||||
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 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);
|
||||
@@ -114,6 +110,62 @@ public sealed class FrameNamingTests(TestContext context)
|
||||
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()
|
||||
{
|
||||
|
||||
@@ -89,6 +89,20 @@ public sealed class PathTemplateTests
|
||||
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")]
|
||||
|
||||
@@ -112,8 +112,8 @@ 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", string? lens = null)
|
||||
/// <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);
|
||||
@@ -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", string? lens = null)
|
||||
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);
|
||||
|
||||
@@ -90,6 +90,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);
|
||||
|
||||
@@ -177,6 +177,50 @@ public sealed class ReorganizeTests(TestContext context)
|
||||
Assert.Empty(plan.Steps);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnUploadWithoutACaptureTimeIsFiledAsReorganizeNamesIt()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
const string FolderTemplate = "{year}/{date} {hm}", FileTemplate = "{date}_{time}_{n:0000}";
|
||||
await fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Templates = s.Templates with { Folder = FolderTemplate, File = FileTemplate } }, fx.Ct);
|
||||
// Photos that record no time: the first takes its file's, the second the one its client sent; never the time they are filed.
|
||||
var noon = new DateTime(2026, 9, 28, 12, 0, 0);
|
||||
var first = fx.Stage(null, 60);
|
||||
File.SetLastWriteTime(first.Path, noon);
|
||||
var id = (await fx.Service.Ingest.CommitAsync(Upload(fx, first, "IMG_0001.JPG", "upload-1"), fx.Ct)).SequenceId;
|
||||
var second = fx.Stage(null, 61);
|
||||
await fx.Service.Ingest.CommitAsync(Upload(fx, second, "IMG_0002.JPG", "upload-1") with { ClientCapturedAt = noon.AddSeconds(10) }, fx.Ct);
|
||||
|
||||
Assert.Equal("2026/2026-09-28 12-00", (await fx.Db.Sequences.GetAsync(id))!.Folder);
|
||||
Assert.SequenceEqual(["originals/2026-09-28_12-00-00_0001.JPG", "originals/2026-09-28_12-00-10_0002.JPG"], await FilesAsync(fx, id));
|
||||
Assert.Empty((await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], new RenameTemplates(FolderTemplate, FileTemplate), fx.Ct)).Steps);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task APhotoSkippedMidSessionLeavesNumbersThatReorganizeCloses()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
// The card's second photo is in the archive already (uploaded before): the import skips it.
|
||||
var day = Start.AddDays(1);
|
||||
await fx.Service.Ingest.CommitAsync(Upload(fx, fx.Stage(day.AddSeconds(10), 31), "IMG_0002.JPG", "upload-1"), fx.Ct);
|
||||
var card = context.CreateTempDirectory("card");
|
||||
Photos.WriteSeries(Path.Combine(card, "DCIM", "100CANON"), day, 4, firstSeed: 30);
|
||||
const string FileTemplate = "{date}_{n:0000}";
|
||||
var import = await fx.Service.PlanImportAsync(fx.Archive.Id, card, new ImportOptions { FolderTemplate = "{year}/{date} card", FileTemplate = FileTemplate },
|
||||
null, null, fx.Ct);
|
||||
Assert.SequenceEqual([ImportAction.Copy, ImportAction.SkipInArchive, ImportAction.Copy, ImportAction.Copy], import.Sessions.Single().Items.Select(i => i.Action));
|
||||
var engine = await fx.StartEngineAsync();
|
||||
await fx.WaitForAsync((await engine.EnqueueAsync(ArchiveJobs.Import(fx.Archive, import, null), cancellationToken: fx.Ct)).Id, JobState.Done);
|
||||
|
||||
// Filed with the numbers the import showed, the skipped photo's left out; Reorganize numbers the sequence as it is
|
||||
// now, which its dry run lists (a divergence FrameNaming names).
|
||||
var imported = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Single(l => l.Folder == "2026/2026-09-29 card").Id;
|
||||
Assert.SequenceEqual(["originals/2026-09-29_0001.JPG", "originals/2026-09-29_0003.JPG", "originals/2026-09-29_0004.JPG"], await FilesAsync(fx, imported));
|
||||
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [imported], new RenameTemplates(File: FileTemplate), fx.Ct);
|
||||
Assert.SequenceEqual(["originals/2026-09-29_0003.JPG>originals/2026-09-29_0002.JPG", "originals/2026-09-29_0004.JPG>originals/2026-09-29_0003.JPG"],
|
||||
plan.Steps.Single().FileSamples.Select(s => $"{s.From}>{s.To}"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ASequenceWhoseSidecarCannotBeReadStaysAsItIsAndTheOthersMove()
|
||||
{
|
||||
@@ -730,6 +774,42 @@ public sealed class ReorganizeTests(TestContext context)
|
||||
Assert.Empty(RenameJournal.ListPending(fx.Paths));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AChangeOfCaseOntoAnotherFolderOfThatExactNameIsRefusedBeforeItMoves()
|
||||
{
|
||||
await using var fx = await CreateAsync(context);
|
||||
Directory.CreateDirectory(fx.Paths.FromRelative("probe"));
|
||||
var caseSensitive = !Directory.Exists(fx.Paths.FromRelative("PROBE"));
|
||||
Directory.Delete(fx.Paths.FromRelative("probe"));
|
||||
if (!caseSensitive) TestContext.Skip("needs a case-sensitive file system, where two folders differ only in case");
|
||||
var id = await UploadAsync(fx, 1);
|
||||
await fx.Service.ApplyRenameAsync(await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], new RenameTemplates(Folder: "trip (2)"), fx.Ct), null, fx.Ct);
|
||||
var templates = new RenameTemplates(Folder: "Trip");
|
||||
// Planned while no other folder holds that name: the folder keeps its number, in the template's case.
|
||||
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], templates, fx.Ct);
|
||||
Assert.Equal("Trip (2)", plan.Steps.Single().ToFolder);
|
||||
|
||||
// A folder of exactly that name appears beside it (a copy): refused before anything moves, and dropped when an
|
||||
// interrupted plan resumes, instead of failing at every archive open.
|
||||
var stranger = fx.Paths.FromRelative("Trip (2)/note.txt");
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(stranger)!);
|
||||
File.WriteAllText(stranger, "kept");
|
||||
await Assert.ThrowsAsync<StaleRenamePlanException>(() => fx.Service.ApplyRenameAsync(plan, null, fx.Ct));
|
||||
Assert.Empty(RenameJournal.ListPending(fx.Paths));
|
||||
RenameJournal.Write(fx.Paths, new RenameJournal(plan, []));
|
||||
Assert.Equal(1, await fx.Service.Renamer.ResumePendingAsync(fx.Archive, fx.Ct));
|
||||
Assert.Empty(RenameJournal.ListPending(fx.Paths));
|
||||
Assert.Equal("trip (2)", await FolderAsync(fx, id));
|
||||
|
||||
// Planned now, the sequence takes a folder of its own, and the other folder stays as it was.
|
||||
var again = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], templates, fx.Ct);
|
||||
Assert.Equal("Trip", again.Steps.Single().ToFolder);
|
||||
await fx.Service.ApplyRenameAsync(again, null, fx.Ct);
|
||||
Assert.Equal("Trip", await FolderAsync(fx, id));
|
||||
Assert.Equal("kept", File.ReadAllText(stranger));
|
||||
Assert.SequenceEqual(["note.txt"], Directory.EnumerateFileSystemEntries(Path.GetDirectoryName(stranger)!).Select(Path.GetFileName));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task PhotosHashedAfterThePlanKeepTheNamesItShowed()
|
||||
{
|
||||
|
||||
@@ -175,17 +175,21 @@ 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.
|
||||
foreach (var (refused, field) in new[]
|
||||
// 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"),
|
||||
(archive with { FileTemplate = "{n}{ext}" }, "fileTemplate"),
|
||||
(archive with { FileTemplate = "{date}" }, "fileTemplate"),
|
||||
(archive with { FileTemplate = " " }, "fileTemplate"),
|
||||
(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);
|
||||
Assert.Equal(field, (await response.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_template")).Details);
|
||||
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))
|
||||
{
|
||||
|
||||
@@ -147,17 +147,21 @@ public sealed class ReorganizeTests(TestContext context)
|
||||
}
|
||||
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.
|
||||
foreach (var (bad, field) in new[]
|
||||
// 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"),
|
||||
(valid with { FileTemplate = "{title}" }, "fileTemplate"),
|
||||
(valid with { FolderTemplate = "Exports/{title}" }, "folderTemplate"),
|
||||
(valid with { FolderTemplate = ".hidden/{date}" }, "folderTemplate"),
|
||||
(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);
|
||||
Assert.Equal(field, (await refused.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_template")).Details);
|
||||
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);
|
||||
|
||||
@@ -126,6 +126,13 @@ public sealed partial class AdminReorganizeTests(TestContext context)
|
||||
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);
|
||||
|
||||
Reference in new issue
Block a user