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:
Alby96 committed 2026-10-27 18:08:08 +01:00
1 parent 9e1f109b58
commit 765f0ad36b
20 files changed
+446 -141

No files matched your search

+1 -1
View File
@@ -42,7 +42,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S
| `Video` (+ `Mp4`, `Avi`, `Bitstream`, `Yuv`, `Managed`) | `IVideoEncoderProvider`, MP4 muxer and inspector, AVI-MJPEG, NV12/P010, managed encoders (MJPEG-AVI, GIF, APNG, image sequences) | | `Video` (+ `Mp4`, `Avi`, `Bitstream`, `Yuv`, `Managed`) | `IVideoEncoderProvider`, MP4 muxer and inspector, AVI-MJPEG, NV12/P010, managed encoders (MJPEG-AVI, GIF, APNG, image sequences) |
| `Archiving` | Archive layout and paths, sidecars (`sequence.json`, `project.json`), scanner, index snapshot, leases, thumbnail packs, verify, adopt, rename plans (`RenamePlanner`: folder, title and file templates, `RenameTemplates`, the plan's fingerprint, which pins every file rename by its digest and not the frames version; `FileRenames`: a sequence's new file names; `FileRenameJournal`: two-phase renames through temporary names, `.chronos/rename-files.json`, a recovery safe to run again from wherever it stopped, a new name taken meanwhile sending that photo and its companions back together to their old names or a free `_2`, those that took their new names already with them; `FrameCompanions`: the XMP files that follow a photo, one rule for the trash and Reorganize, matched whatever their case and each folder listed once by `FrameCompanions.Index`) | | `Archiving` | Archive layout and paths, sidecars (`sequence.json`, `project.json`), scanner, index snapshot, leases, thumbnail packs, verify, adopt, rename plans (`RenamePlanner`: folder, title and file templates, `RenameTemplates`, the plan's fingerprint, which pins every file rename by its digest and not the frames version; `FileRenames`: a sequence's new file names; `FileRenameJournal`: two-phase renames through temporary names, `.chronos/rename-files.json`, a recovery safe to run again from wherever it stopped, a new name taken meanwhile sending that photo and its companions back together to their old names or a free `_2`, those that took their new names already with them; `FrameCompanions`: the XMP files that follow a photo, one rule for the trash and Reorganize, matched whatever their case and each folder listed once by `FrameCompanions.Index`) |
| `Import` | Card scan, session detection, import plan, hash-verified copy, card eraser (re-hash before delete) | | `Import` | Card scan, session detection, import plan, hash-verified copy, card eraser (re-hash before delete) |
| `Naming` | Folder/file templates and tokens (folder levels scans skip escaped with `_`; `ExpandText` for titles); `FrameNaming` (the naming context and unique file name of a frame, shared by import, upload and Reorganize: the sequence's camera and lens, the first frame for folders; `UniqueNames`: `_2`, `_3`… in linear time); `TemplateRules` (what every place a template is typed or sent refuses: a folder scans skip, a lost extension, names that repeat) | | `Naming` | Folder/file templates and tokens (folder levels scans skip escaped with `_`; `ExpandText` for titles); `FrameNaming` (the naming context and unique file name of a frame, shared by import, upload and Reorganize: the sequence's camera and lens, the first frame for folders; `UniqueNames`: `_2`, `_3`… in linear time); `TemplateRules` (what every place a template is typed or sent refuses, the archive engine's settings included: a folder scans skip, a lost extension, names that repeat; a long file name is shortened before its `.{ext}`) |
| `Model` | Domain entities and enums (§5) shared by Data, Server and clients | | `Model` | Domain entities and enums (§5) shared by Data, Server and clients |
| `Packaging` | TPK1 installer payload writer/reader, staged install transaction | | `Packaging` | TPK1 installer payload writer/reader, staged install transaction |
| `Diagnostics` | `Log` (never throws: a line its sink cannot write is dropped), `FileLogSink` with `LogFileOptions` (level, daily or hourly files, numbered parts past a size, pruning by age and by the total size, never the file being written), synthetic sequences, `SecretScrubber`, `DiagnosticsArchive` (scrubbed diagnostics zip) | | `Diagnostics` | `Log` (never throws: a line its sink cannot write is dropped), `FileLogSink` with `LogFileOptions` (level, daily or hourly files, numbered parts past a size, pruning by age and by the total size, never the file being written), synthetic sequences, `SecretScrubber`, `DiagnosticsArchive` (scrubbed diagnostics zip) |
+8 -2
View File
@@ -5,7 +5,10 @@ using Chronos.Core.Naming;
namespace Chronos.Core.Archiving; namespace Chronos.Core.Archiving;
/// <summary>Why frames of a sequence keep their file names in a Reorganize (owner review 2, R7); nothing of them is touched.</summary> /// <summary>
/// Why frames of a sequence keep their file names in a Reorganize (owner review 2, R7), nothing of them touched; or, for
/// <see cref="Unreadable"/>, why the whole sequence stays as it is.
/// </summary>
public enum RenameBlock public enum RenameBlock
{ {
/// <summary>Photos adopted in place, outside <c>originals/</c>: they belong to a tree someone else keeps.</summary> /// <summary>Photos adopted in place, outside <c>originals/</c>: they belong to a tree someone else keeps.</summary>
@@ -17,7 +20,10 @@ public enum RenameBlock
/// <summary>Photos whose file is not there.</summary> /// <summary>Photos whose file is not there.</summary>
Missing, Missing,
/// <summary>The sequence's sidecar cannot be read, is of a newer format this build does not rewrite, or belongs to another sequence.</summary> /// <summary>
/// The sequence's sidecar cannot be read, is of a newer format this build does not rewrite, or belongs to another
/// sequence: the sequence keeps its folder, title and file names, and so does every folder it is inside (0 frames).
/// </summary>
Unreadable, Unreadable,
} }
+73 -29
View File
@@ -32,7 +32,8 @@ public sealed record SequenceFiles(SequenceManifest Manifest, IReadOnlyCollectio
/// <summary> /// <summary>
/// One sequence's change: its folder, its title, the names of its files (Reorganize, owner review 2, R7), or several of /// One sequence's change: its folder, its title, the names of its files (Reorganize, owner review 2, R7), or several of
/// them. A step that changes nothing lists only why files keep their names (<see cref="Blocked"/>). /// them. A step that changes nothing lists only why: frames that keep their file names, or a sequence that stays as it is
/// because its sidecar cannot be read (<see cref="Blocked"/>).
/// </summary> /// </summary>
/// <param name="Carried">The folder moves only because a folder it is inside moves (a sequence nested in another).</param> /// <param name="Carried">The folder moves only because a folder it is inside moves (a sequence nested in another).</param>
public sealed record RenameStep(Guid SequenceId, string FromFolder, string ToFolder, string? FromTitle, string? ToTitle, bool Carried = false) public sealed record RenameStep(Guid SequenceId, string FromFolder, string ToFolder, string? FromTitle, string? ToTitle, bool Carried = false)
@@ -71,7 +72,7 @@ public sealed record RenameStep(Guid SequenceId, string FromFolder, string ToFol
/// </summary> /// </summary>
public string? FileDigest { get; init; } public string? FileDigest { get; init; }
/// <summary>Frames that keep their file names, and why.</summary> /// <summary>Frames that keep their file names, and why; <see cref="RenameBlock.Unreadable"/> (0 frames) when the whole sequence stays as it is.</summary>
public IReadOnlyList<RenameBlocked> Blocked { get; init; } = []; public IReadOnlyList<RenameBlocked> Blocked { get; init; } = [];
} }
@@ -90,33 +91,45 @@ public sealed record RenameTemplates(string? Folder = null, string? File = null,
/// <c>titleTemplate</c>): blank, not valid (<see cref="PathTemplate.IsValid"/>), with a format a sample cannot be written /// <c>titleTemplate</c>): blank, not valid (<see cref="PathTemplate.IsValid"/>), with a format a sample cannot be written
/// with (<c>{date:%}</c>), expanding to nothing, or, for a folder or file template, breaking a rule of the archive's /// with (<c>{date:%}</c>), expanding to nothing, or, for a folder or file template, breaking a rule of the archive's
/// templates (<see cref="TemplateRules"/>: a folder scans never enter; a slash, a lost extension or names that would /// templates (<see cref="TemplateRules"/>: a folder scans never enter; a slash, a lost extension or names that would
/// repeat); null when every one given can. The archive settings' templates are checked alike. /// repeat); null when every one given can. The archive settings' templates are checked alike
/// (<c>ArchiveSettings.Problem</c>).
/// </summary> /// </summary>
public string? Problem() public string? Problem() => Check()?.Field;
{
if (Unusable(Folder, t => t.ExpandFolder(Sample), TemplateRules.FolderRule)) return "folderTemplate";
if (Unusable(File, t => t.ExpandFile(Sample), TemplateRules.FileRule)) return "fileTemplate";
if (Unusable(Title, t => t.ExpandText(Sample))) return "titleTemplate";
return null;
}
private static bool Unusable(string? template, Func<PathTemplate, string> expand, Func<PathTemplate, string?>? rule = null) /// <summary>
/// The first template that cannot be used (<see cref="Problem"/>), with the rule of <see cref="TemplateRules"/> it breaks
/// when it parses and expands (<see cref="TemplateProblem.Rule"/>); null when every one given can.
/// </summary>
public TemplateProblem? Check() =>
Unusable("folderTemplate", Folder, t => t.ExpandFolder(Sample), TemplateRules.FolderRule)
?? Unusable("fileTemplate", File, t => t.ExpandFile(Sample), TemplateRules.FileRule)
?? Unusable("titleTemplate", Title, t => t.ExpandText(Sample));
private static TemplateProblem? Unusable(string field, string? template, Func<PathTemplate, string> expand, Func<PathTemplate, string?>? rule = null)
{ {
if (template is null) return false; if (template is null) return null;
if (string.IsNullOrWhiteSpace(template)) return true; if (string.IsNullOrWhiteSpace(template)) return new TemplateProblem(field, null);
var parsed = PathTemplate.Parse(template); var parsed = PathTemplate.Parse(template);
if (!parsed.IsValid) return true; if (!parsed.IsValid) return new TemplateProblem(field, null);
try try
{ {
return expand(parsed).Length == 0 || rule?.Invoke(parsed) is not null; if (expand(parsed).Length == 0) return new TemplateProblem(field, null);
return rule?.Invoke(parsed) is { } broken ? new TemplateProblem(field, broken) : null;
} }
catch (FormatException) catch (FormatException)
{ {
return true; return new TemplateProblem(field, null);
} }
} }
} }
/// <summary>
/// A template that cannot be used: its API name (<c>folderTemplate</c>, <c>fileTemplate</c>, <c>titleTemplate</c>) and the
/// rule of <see cref="TemplateRules"/> it breaks (<c>ReservedFolder</c>, <c>FileSeparator</c>, <c>Extension</c>,
/// <c>NotUnique</c>, each explained by <c>Errors.Template.&lt;Rule&gt;</c>); no rule when it is blank, not valid or expands to nothing.
/// </summary>
public sealed record TemplateProblem(string Field, string? Rule);
/// <summary>A planned folder would lie inside a sequence's folder (nesting one sequence in another); nothing is planned.</summary> /// <summary>A planned folder would lie inside a sequence's folder (nesting one sequence in another); nothing is planned.</summary>
public sealed class NestedRenameException(string target, string folder) public sealed class NestedRenameException(string target, string folder)
: ArgumentException(Loc.L("Archive.Error.NestedTarget", target, folder)) : ArgumentException(Loc.L("Archive.Error.NestedTarget", target, folder))
@@ -219,7 +232,8 @@ public static class RenamePlanner
/// <paramref name="folderTemplate"/> (where <c>{title}</c> is the new title) for every subject, from its first frame as /// <paramref name="folderTemplate"/> (where <c>{title}</c> is the new title) for every subject, from its first frame as
/// filing saw it (<see cref="FrameNaming.Context(SidecarFrame, SequenceManifest, string?)"/>); a title is text, not a file /// filing saw it (<see cref="FrameNaming.Context(SidecarFrame, SequenceManifest, string?)"/>); a title is text, not a file
/// name (<see cref="PathTemplate.ExpandText"/>). A target folder that is any current sequence folder, exists on disk or /// name (<see cref="PathTemplate.ExpandText"/>). A target folder that is any current sequence folder, exists on disk or
/// was given to an earlier subject (whatever its case) gets " (2)", " (3)"…. With <paramref name="fileTemplate"/> every /// was given to an earlier subject (whatever its case) gets " (2)", " (3)"…; a sequence keeps its own folder in the
/// template's case only while no other folder holds that exact name. With <paramref name="fileTemplate"/> every
/// subject's frames get their names from it as filing names them (<see cref="FileRenames.Plan"/>, with the new title), /// subject's frames get their names from it as filing names them (<see cref="FileRenames.Plan"/>, with the new title),
/// counted and sampled in its step, and the frames that keep their names are listed there with the reason; a step whose /// counted and sampled in its step, and the frames that keep their names are listed there with the reason; a step whose
/// new folder or file names come from <c>{title}</c> says so (<see cref="RenameStep.NamedByTitle"/>). A subject /// new folder or file names come from <c>{title}</c> says so (<see cref="RenameStep.NamedByTitle"/>). A subject
@@ -231,10 +245,15 @@ public static class RenamePlanner
/// </summary> /// </summary>
/// <param name="occupied">Every sequence folder of the archive (renamed or not).</param> /// <param name="occupied">Every sequence folder of the archive (renamed or not).</param>
/// <param name="nested">The archive's other sequences inside a subject's folder, with their titles.</param> /// <param name="nested">The archive's other sequences inside a subject's folder, with their titles.</param>
/// <param name="existsExactly">Whether a folder of exactly that name, in every level's case, is on disk
/// (<see cref="ExistsExactly"/>): on a case-sensitive file system <c>Trip (2)</c> beside a sequence at <c>trip (2)</c> is
/// another folder, which a change of case could never move onto. Null when no folder but the sequences' own counts.</param>
/// <exception cref="NestedRenameException">A target lies inside a sequence's folder, or inside another target.</exception> /// <exception cref="NestedRenameException">A target lies inside a sequence's folder, or inside another target.</exception>
public static RenamePlan Plan(Guid archiveId, IReadOnlyList<RenameSubject> subjects, string? folderTemplate, string? titleTemplate, public static RenamePlan Plan(Guid archiveId, IReadOnlyList<RenameSubject> subjects, string? folderTemplate, string? titleTemplate,
IEnumerable<string> occupied, Func<string, bool> existsOnDisk, IReadOnlyList<RenameSubject>? nested = null, string? fileTemplate = null) IEnumerable<string> occupied, Func<string, bool> existsOnDisk, IReadOnlyList<RenameSubject>? nested = null, string? fileTemplate = null,
Func<string, bool>? existsExactly = null)
{ {
existsExactly ??= _ => false;
var folder = folderTemplate is null ? null : PathTemplate.Parse(folderTemplate); var folder = folderTemplate is null ? null : PathTemplate.Parse(folderTemplate);
var title = titleTemplate is null ? null : PathTemplate.Parse(titleTemplate); var title = titleTemplate is null ? null : PathTemplate.Parse(titleTemplate);
var file = fileTemplate is null ? null : PathTemplate.Parse(fileTemplate); var file = fileTemplate is null ? null : PathTemplate.Parse(fileTemplate);
@@ -269,7 +288,7 @@ public static class RenamePlanner
} }
else else
{ {
newFolder = Kept(s.Folder, expanded, taken, given) ?? Unique(expanded, claimed, existsOnDisk); newFolder = Kept(s.Folder, expanded, taken, given, existsExactly) ?? Unique(expanded, claimed, existsOnDisk);
claimed.Add(newFolder); claimed.Add(newFolder);
given.Add(newFolder); given.Add(newFolder);
} }
@@ -367,17 +386,17 @@ public static class RenamePlanner
/// a case-only change goes through a temporary name (case-insensitive file systems). /// a case-only change goes through a temporary name (case-insensitive file systems).
/// </summary> /// </summary>
/// <exception cref="IOException">The target is occupied by something else (for a case-only change, a folder of its own /// <exception cref="IOException">The target is occupied by something else (for a case-only change, a folder of its own
/// on a case-sensitive file system), or neither folder exists.</exception> /// on a case-sensitive file system, which the plan and the apply refuse first), or neither folder exists.</exception>
public static void MoveFolder(ArchivePaths archive, RenameStep step) public static void MoveFolder(ArchivePaths archive, RenameStep step)
{ {
if (!step.MovesFolder) return; if (!step.MovesFolder) return;
var from = archive.FromRelative(step.FromFolder); var from = archive.FromRelative(step.FromFolder);
var to = archive.FromRelative(step.ToFolder); var to = archive.FromRelative(step.ToFolder);
var caseOnly = step.FromFolder.Equals(step.ToFolder, StringComparison.OrdinalIgnoreCase); var caseOnly = step.FromFolder.Equals(step.ToFolder, StringComparison.OrdinalIgnoreCase);
if (Directory.Exists(to) && (!caseOnly || HasExactName(to))) if (Directory.Exists(to) && (!caseOnly || ExistsExactly(archive, step.ToFolder)))
{ {
// Both names there: the target is another folder (for a case-only change, on a case-sensitive file system). // Both names there: the target is another folder (for a case-only change, on a case-sensitive file system).
if (Directory.Exists(from) && (!caseOnly || HasExactName(from))) throw new IOException($"Rename target {step.ToFolder} already exists."); if (Directory.Exists(from) && (!caseOnly || ExistsExactly(archive, step.FromFolder))) throw new IOException($"Rename target {step.ToFolder} already exists.");
return; return;
} }
if (!Directory.Exists(from)) throw new DirectoryNotFoundException($"Sequence folder {step.FromFolder} is missing."); if (!Directory.Exists(from)) throw new DirectoryNotFoundException($"Sequence folder {step.FromFolder} is missing.");
@@ -394,21 +413,45 @@ public static class RenamePlanner
} }
} }
private static bool HasExactName(string path) => /// <summary>
Directory.EnumerateDirectories(Path.GetDirectoryName(path)!, Path.GetFileName(path)) /// Whether the folder <paramref name="folder"/> (archive-relative, forward slashes) is on disk with exactly that name at
.Any(d => Path.GetFileName(d).Equals(Path.GetFileName(path), StringComparison.Ordinal)); /// every level. On a case-insensitive file system a folder whose name differs in case only does not count, so a change
/// of case only finds its own folder under its old name alone; on a case-sensitive one this is any folder of that name.
/// </summary>
public static bool ExistsExactly(ArchivePaths archive, string folder)
{
ArgumentNullException.ThrowIfNull(archive);
ArgumentNullException.ThrowIfNull(folder);
var path = archive.Root;
var options = new EnumerationOptions { MatchType = MatchType.Simple, AttributesToSkip = 0, IgnoreInaccessible = true };
foreach (var name in folder.Split('/', StringSplitOptions.RemoveEmptyEntries))
{
try
{
// The name as a pattern finds it whatever its case on Windows; only the exact one counts.
if (!Directory.EnumerateDirectories(path, name, options).Any(d => Path.GetFileName(d).Equals(name, StringComparison.Ordinal))) return false;
}
catch (DirectoryNotFoundException)
{
return false;
}
path = Path.Combine(path, name);
}
return Directory.Exists(path);
}
private static string? Blank(string value) => string.IsNullOrWhiteSpace(value) ? null : value; private static string? Blank(string value) => string.IsNullOrWhiteSpace(value) ? null : value;
/// <summary> /// <summary>
/// The folder a sequence keeps (in the template's case) when it already is <paramref name="expanded"/>, or the /// The folder a sequence keeps (in the template's case) when it already is <paramref name="expanded"/>, or the
/// <c>" (n)"</c> of it that filing or an earlier Reorganize gave it beside another sequence of that name; null when it is /// <c>" (n)"</c> of it that filing or an earlier Reorganize gave it beside another sequence of that name; null when it is
/// neither, when another sequence holds that name exactly (a case-sensitive file system), or when this plan already gave /// neither, when another folder holds that name exactly (a sequence's, or any on a case-sensitive file system:
/// it to another sequence (<paramref name="given"/>, whatever its case: <c>trip (2)</c> and <c>TRIP (2)</c> both keep /// <paramref name="existsExactly"/>), which the change of case could never move onto, or when this plan already gave it
/// to another sequence (<paramref name="given"/>, whatever its case: <c>trip (2)</c> and <c>TRIP (2)</c> both keep
/// <c>Trip (2)</c> otherwise). Without it a sequence at <c>2026-09-28 (2)</c> would be planned to <c>(3)</c>, its own /// <c>Trip (2)</c> otherwise). Without it a sequence at <c>2026-09-28 (2)</c> would be planned to <c>(3)</c>, its own
/// folder being taken, and back to <c>(2)</c> by the next Reorganize. /// folder being taken, and back to <c>(2)</c> by the next Reorganize.
/// </summary> /// </summary>
private static string? Kept(string current, string expanded, IReadOnlyList<string> occupied, IReadOnlySet<string> given) private static string? Kept(string current, string expanded, IReadOnlyList<string> occupied, IReadOnlySet<string> given, Func<string, bool> existsExactly)
{ {
string? same = null; string? same = null;
if (current.Equals(expanded, StringComparison.OrdinalIgnoreCase)) same = expanded; if (current.Equals(expanded, StringComparison.OrdinalIgnoreCase)) same = expanded;
@@ -418,7 +461,8 @@ public static class RenamePlanner
same = string.Create(CultureInfo.InvariantCulture, $"{expanded} ({n})"); same = string.Create(CultureInfo.InvariantCulture, $"{expanded} ({n})");
// "(02)" is not a number Unique gives: that folder moves to a name of its own. // "(02)" is not a number Unique gives: that folder moves to a name of its own.
if (same is null || !same.Equals(current, StringComparison.OrdinalIgnoreCase) || given.Contains(same)) return null; if (same is null || !same.Equals(current, StringComparison.OrdinalIgnoreCase) || given.Contains(same)) return null;
return same.Equals(current, StringComparison.Ordinal) || !occupied.Any(o => o.Equals(same, StringComparison.Ordinal)) ? same : null; if (same.Equals(current, StringComparison.Ordinal)) return same;
return occupied.Any(o => o.Equals(same, StringComparison.Ordinal)) || existsExactly(same) ? null : same;
} }
private static string Unique(string folder, HashSet<string> claimed, Func<string, bool> existsOnDisk) private static string Unique(string folder, HashSet<string> claimed, Func<string, bool> existsOnDisk)
+6 -40
View File
@@ -94,21 +94,9 @@ public static class FrameNaming
} }
/// <summary> /// <summary>
/// <paramref name="directory"/> (empty or ending with '/') and the name <paramref name="template"/> gives, made unique /// <paramref name="directory"/> (empty or ending with '/') and the name <paramref name="template"/> gives, made unique in
/// in <paramref name="taken"/> with <c>_2</c>, <c>_3</c>… before the extension, then added to it. /// the set of <paramref name="names"/> with <c>_2</c>, <c>_3</c>… before the extension (<see cref="UniqueNames.Claim"/>),
/// </summary> /// then added to it.
public static string FileName(PathTemplate template, NamingContext context, ISet<string> taken, string directory = "")
{
ArgumentNullException.ThrowIfNull(taken);
var file = FileName(template, context, candidate => !taken.Contains(candidate), directory);
taken.Add(file);
return file;
}
/// <summary>
/// <paramref name="directory"/> (empty or ending with '/') and the name <paramref name="template"/> gives, made unique
/// in the set of <paramref name="names"/> as <see cref="FileName(PathTemplate, NamingContext, ISet{string}, string)"/>
/// does, then added to it.
/// </summary> /// </summary>
public static string FileName(PathTemplate template, NamingContext context, UniqueNames names, string directory = "") public static string FileName(PathTemplate template, NamingContext context, UniqueNames names, string directory = "")
{ {
@@ -118,28 +106,6 @@ public static class FrameNaming
return names.Claim(directory + template.ExpandFile(context)); return names.Claim(directory + template.ExpandFile(context));
} }
/// <summary>
/// <paramref name="directory"/> and the name <paramref name="template"/> gives, or the first of <c>stem_2.ext</c>,
/// <c>stem_3.ext</c>… that <paramref name="isFree"/> accepts.
/// </summary>
public static string FileName(PathTemplate template, NamingContext context, Func<string, bool> isFree, string directory = "")
{
ArgumentNullException.ThrowIfNull(template);
ArgumentNullException.ThrowIfNull(isFree);
ArgumentNullException.ThrowIfNull(directory);
return Unique(directory + template.ExpandFile(context), isFree);
}
/// <summary><paramref name="file"/>, or the first of <c>stem_2.ext</c>, <c>stem_3.ext</c>… that <paramref name="isFree"/> accepts.</summary>
public static string Unique(string file, Func<string, bool> isFree)
{
ArgumentNullException.ThrowIfNull(file);
ArgumentNullException.ThrowIfNull(isFree);
var candidate = file;
for (var n = 2; !isFree(candidate); n++) candidate = Numbered(file, n);
return candidate;
}
/// <summary><paramref name="file"/> itself for <paramref name="n"/> = 1, else <c>stem_n.ext</c> in its directory.</summary> /// <summary><paramref name="file"/> itself for <paramref name="n"/> = 1, else <c>stem_n.ext</c> in its directory.</summary>
internal static string Numbered(string file, int n) internal static string Numbered(string file, int n)
{ {
@@ -151,9 +117,9 @@ public static class FrameNaming
} }
/// <summary> /// <summary>
/// Unique file names in a set that only grows (BRIEF §7.1): exactly the names <see cref="FrameNaming.Unique"/> gives against /// Unique file names in a set that only grows (BRIEF §7.1): exactly the names a search from <c>_2</c> up gives against it,
/// it, without trying again for each photo the numbers earlier photos already took. A template that gives a whole session /// without trying again for each photo the numbers earlier photos already took. A template that gives a whole session one
/// one name (<c>{title}</c>) then costs about one check per photo instead of one per photo before it. /// name (<c>{title}</c>) then costs about one check per photo instead of one per photo before it.
/// </summary> /// </summary>
/// <param name="taken">The names given or held so far; every name claimed is added to it, and none may leave it while in use.</param> /// <param name="taken">The names given or held so far; every name claimed is added to it, and none may leave it while in use.</param>
public sealed class UniqueNames(ISet<string> taken) public sealed class UniqueNames(ISet<string> taken)
+31 -10
View File
@@ -24,6 +24,9 @@ public sealed class PathTemplate
/// <summary>The longest text <see cref="ExpandText"/> gives: the longest title a sequence takes.</summary> /// <summary>The longest text <see cref="ExpandText"/> gives: the longest title a sequence takes.</summary>
public const int MaxTextLength = 200; public const int MaxTextLength = 200;
/// <summary>The longest folder level or file name a template gives (<see cref="SanitizeSegment"/>), before an appended extension.</summary>
public const int MaxSegmentLength = 200;
private static readonly HashSet<string> TokenSet = new(Tokens, StringComparer.OrdinalIgnoreCase); private static readonly HashSet<string> TokenSet = new(Tokens, StringComparer.OrdinalIgnoreCase);
private static readonly char[] Illegal = ['<', '>', ':', '"', '|', '?', '*', '\\', '/', '\0']; private static readonly char[] Illegal = ['<', '>', ':', '"', '|', '?', '*', '\\', '/', '\0'];
private static readonly HashSet<string> ReservedNames = new(StringComparer.OrdinalIgnoreCase) private static readonly HashSet<string> ReservedNames = new(StringComparer.OrdinalIgnoreCase)
@@ -133,11 +136,18 @@ public sealed class PathTemplate
private IEnumerable<string> Levels(NamingContext context) => private IEnumerable<string> Levels(NamingContext context) =>
Expand(context, allowSeparators: true).Split('/', StringSplitOptions.RemoveEmptyEntries).Select(SanitizeSegment).Where(s => s.Length > 0); Expand(context, allowSeparators: true).Split('/', StringSplitOptions.RemoveEmptyEntries).Select(SanitizeSegment).Where(s => s.Length > 0);
/// <summary>Expands to a file name; the original extension is appended unless the template already ends with {ext}.</summary> /// <summary>
/// Expands to a file name; the original extension is appended unless the template already ends with {ext}. A name
/// longer than <see cref="MaxSegmentLength"/> is shortened before the <c>.{ext}</c> the template ends with, never through it.
/// </summary>
public string ExpandFile(NamingContext context) public string ExpandFile(NamingContext context)
{ {
var hasExt = _parts.Count > 0 && _parts[^1] is { IsToken: true, Text: "ext" }; var hasExt = _parts.Count > 0 && _parts[^1] is { IsToken: true, Text: "ext" };
var name = SanitizeSegment(Expand(context, allowSeparators: false)); var name = Clean(Expand(context, allowSeparators: false));
var ext = hasExt && context.Extension.Length > 0 ? "." + context.Extension : string.Empty;
name = ext.Length > 0 && name.Length > MaxSegmentLength && name.EndsWith(ext, StringComparison.Ordinal)
? Shorten(name[..^ext.Length], MaxSegmentLength - ext.Length) + ext
: Shorten(name, MaxSegmentLength);
if (name.Length == 0) name = SanitizeSegment(context.OriginalName); if (name.Length == 0) name = SanitizeSegment(context.OriginalName);
if (!hasExt && context.Extension.Length > 0) name += "." + context.Extension; if (!hasExt && context.Extension.Length > 0) name += "." + context.Extension;
return name; return name;
@@ -145,8 +155,8 @@ public sealed class PathTemplate
/// <summary> /// <summary>
/// Whether every file name the template gives ends with the photo's own extension: the template does not end with /// Whether every file name the template gives ends with the photo's own extension: the template does not end with
/// <c>{ext}</c> (the extension is appended), or ends with <c>.{ext}</c>. <c>{n}{ext}</c> would drop the dot, and with it /// <c>{ext}</c> (the extension is appended), or ends with <c>.{ext}</c>, which a long name keeps whole
/// the extension every reader of the photo goes by. /// (<see cref="ExpandFile"/>). <c>{n}{ext}</c> would drop the dot, and with it the extension every reader of the photo goes by.
/// </summary> /// </summary>
public bool KeepsExtension => public bool KeepsExtension =>
_parts is not [.., { IsToken: true, Text: "ext" }] || _parts is [.., { IsToken: false, Text: var before }, { IsToken: true, Text: "ext" }] && before.EndsWith('.'); _parts is not [.., { IsToken: true, Text: "ext" }] || _parts is [.., { IsToken: false, Text: var before }, { IsToken: true, Text: "ext" }] && before.EndsWith('.');
@@ -163,9 +173,14 @@ public sealed class PathTemplate
{ {
if (char.IsControl(text[i])) text[i] = ' '; if (char.IsControl(text[i])) text[i] = ' ';
} }
var s = text.ToString().Trim(); return Shorten(text.ToString().Trim(), MaxTextLength);
if (s.Length <= MaxTextLength) return s; }
var cut = char.IsHighSurrogate(s[MaxTextLength - 1]) ? MaxTextLength - 1 : MaxTextLength;
/// <summary>At most <paramref name="max"/> characters of <paramref name="s"/>, a character outside the basic plane never cut in two, trailing spaces trimmed.</summary>
private static string Shorten(string s, int max)
{
if (s.Length <= max) return s;
var cut = char.IsHighSurrogate(s[max - 1]) ? max - 1 : max;
return s[..cut].TrimEnd(); return s[..cut].TrimEnd();
} }
@@ -232,8 +247,14 @@ public sealed class PathTemplate
return "1-" + Math.Round(1 / t).ToString(CultureInfo.InvariantCulture); return "1-" + Math.Round(1 / t).ToString(CultureInfo.InvariantCulture);
} }
/// <summary>Replaces characters that are illegal on Windows or Linux and fixes reserved names and trailing dots/spaces.</summary> /// <summary>
public static string SanitizeSegment(string segment) /// Replaces characters that are illegal on Windows or Linux and fixes reserved names and trailing dots/spaces; at most
/// <see cref="MaxSegmentLength"/> characters.
/// </summary>
public static string SanitizeSegment(string segment) => Shorten(Clean(segment), MaxSegmentLength);
/// <summary><see cref="SanitizeSegment"/> without its length limit.</summary>
private static string Clean(string segment)
{ {
var sb = new StringBuilder(segment.Length); var sb = new StringBuilder(segment.Length);
foreach (var ch in segment) foreach (var ch in segment)
@@ -246,7 +267,7 @@ public sealed class PathTemplate
var stem = s.Split('.')[0]; var stem = s.Split('.')[0];
if (ReservedNames.Contains(stem)) s = "_" + s; if (ReservedNames.Contains(stem)) s = "_" + s;
if (s is "." or "..") s = "_"; if (s is "." or "..") s = "_";
return s.Length > 200 ? s[..200].TrimEnd() : s; return s;
} }
private readonly record struct Part(bool IsToken, string Text, string? Format) private readonly record struct Part(bool IsToken, string Text, string? Format)
+10 -4
View File
@@ -515,13 +515,19 @@ public sealed record ArchiveSettings(string Name, LayoutTemplates Templates, Pro
&& Proxies.LongEdge == archive.ProxyLongEdge; && Proxies.LongEdge == archive.ProxyLongEdge;
} }
/// <summary>The first invalid field by its API name (<c>name</c>, <c>folderTemplate</c>, <c>fileTemplate</c>, /// <summary>
/// <c>proxyLongEdge</c>, <c>thumbnailLongEdge</c>); null when every field is valid.</summary> /// The first invalid field by its API name (<c>name</c>, <c>folderTemplate</c>, <c>fileTemplate</c>,
/// <c>proxyLongEdge</c>, <c>thumbnailLongEdge</c>); null when every field is valid. The templates are held to the rules
/// they meet wherever they are typed (<see cref="RenameTemplates.Problem"/>, <see cref="TemplateRules"/>): besides
/// parsing, a folder template may not write a level scans never enter, and a file template must keep the photo's
/// extension, tell a session's photos apart and hold no slash.
/// </summary>
public string? Problem() public string? Problem()
{ {
if (string.IsNullOrWhiteSpace(Name) || Name.Trim().Length > MaxNameLength) return "name"; if (string.IsNullOrWhiteSpace(Name) || Name.Trim().Length > MaxNameLength) return "name";
if (string.IsNullOrWhiteSpace(Templates.Folder) || !PathTemplate.Parse(Templates.Folder).IsValid) return "folderTemplate"; if (string.IsNullOrWhiteSpace(Templates.Folder)) return "folderTemplate";
if (string.IsNullOrWhiteSpace(Templates.File) || !PathTemplate.Parse(Templates.File).IsValid) return "fileTemplate"; if (string.IsNullOrWhiteSpace(Templates.File)) return "fileTemplate";
if (new RenameTemplates(Templates.Folder, Templates.File).Problem() is { } template) return template;
if (!ProxyPolicy.IsValidLongEdge(Proxies.LongEdge) || Proxies.Quality is < 1 or > 100) return "proxyLongEdge"; if (!ProxyPolicy.IsValidLongEdge(Proxies.LongEdge) || Proxies.Quality is < 1 or > 100) return "proxyLongEdge";
if (!ThumbnailPolicy.IsValidLongEdge(Thumbnails.LongEdge) || Thumbnails.Quality is < 1 or > 100) return "thumbnailLongEdge"; if (!ThumbnailPolicy.IsValidLongEdge(Thumbnails.LongEdge) || Thumbnails.Quality is < 1 or > 100) return "thumbnailLongEdge";
return null; return null;
+6 -3
View File
@@ -124,7 +124,7 @@ public sealed class MassRenamer
} }
} }
return RenamePlanner.Plan(archive.Id, subjects, templates.Folder, templates.Title, locations.Select(l => l.Folder), return RenamePlanner.Plan(archive.Id, subjects, templates.Folder, templates.Title, locations.Select(l => l.Folder),
folder => Directory.Exists(paths.Sequence(folder).Folder), nested, templates.File); folder => Directory.Exists(paths.Sequence(folder).Folder), nested, templates.File, folder => RenamePlanner.ExistsExactly(paths, folder));
} }
private static RenameSubject Subject(Sequence s) => new(s.Id, s.Folder, s.Title, s.FirstCapture, s.CameraMake, s.CameraModel, s.Lens); private static RenameSubject Subject(Sequence s) => new(s.Id, s.Folder, s.Title, s.FirstCapture, s.CameraMake, s.CameraModel, s.Lens);
@@ -631,11 +631,14 @@ public sealed class MassRenamer
/// <summary> /// <summary>
/// Whether something took the new folder of a step whose folder has not moved yet: a folder there on disk, or a sequence /// Whether something took the new folder of a step whose folder has not moved yet: a folder there on disk, or a sequence
/// the index has there, around it or inside it (a restore from the trash, an upload or an import since the plan). A /// the index has there, around it or inside it (a restore from the trash, an upload or an import since the plan). A
/// change of case only is the step's own folder. /// change of case only is the step's own folder, unless another folder holds the new name exactly beside it (a
/// case-sensitive file system), which <see cref="RenamePlanner.MoveFolder"/> could never move onto.
/// </summary> /// </summary>
private static bool TargetTaken(ArchivePaths paths, RenameStep step, IReadOnlyList<SequenceLocation> locations) private static bool TargetTaken(ArchivePaths paths, RenameStep step, IReadOnlyList<SequenceLocation> locations)
{ {
if (!step.MovesFolder || step.FromFolder.Equals(step.ToFolder, StringComparison.OrdinalIgnoreCase) || Moved(paths, step)) return false; if (!step.MovesFolder || Moved(paths, step)) return false;
if (step.FromFolder.Equals(step.ToFolder, StringComparison.OrdinalIgnoreCase))
return RenamePlanner.ExistsExactly(paths, step.ToFolder) && RenamePlanner.ExistsExactly(paths, step.FromFolder);
return Directory.Exists(paths.FromRelative(step.ToFolder)) || locations.Any(l => l.Id != step.SequenceId return Directory.Exists(paths.FromRelative(step.ToFolder)) || locations.Any(l => l.Id != step.SequenceId
&& (l.Folder.Equals(step.ToFolder, StringComparison.OrdinalIgnoreCase) || RenamePlanner.IsInside(l.Folder, step.ToFolder) && (l.Folder.Equals(step.ToFolder, StringComparison.OrdinalIgnoreCase) || RenamePlanner.IsInside(l.Folder, step.ToFolder)
|| RenamePlanner.IsInside(step.ToFolder, l.Folder))); || RenamePlanner.IsInside(step.ToFolder, l.Folder)));
+6 -5
View File
@@ -97,17 +97,18 @@ public sealed record ReorganizeRequest(IReadOnlyList<Guid>? SequenceIds, bool Al
public sealed record ReorganizeFileDto(string From, string To); public sealed record ReorganizeFileDto(string From, string To);
/// <summary> /// <summary>
/// Photos of a sequence that keep their names in a Reorganize: <see cref="Reason"/> <c>in_place</c> (kept in place outside /// Why part of a sequence stays as it is in a Reorganize, as one localised sentence: photos that keep their names,
/// <c>originals/</c>), <c>unhashed</c> (never verified), <c>missing</c> or <c>unreadable</c> (the sequence's sidecar), how many /// <see cref="Reason"/> <c>in_place</c> (kept in place outside <c>originals/</c>), <c>unhashed</c> (never verified) or
/// (0 for <c>unreadable</c>), and the reason as one localised sentence. /// <c>missing</c>, with how many; or <c>unreadable</c> (0 photos): the sequence's sidecar cannot be read, so the sequence
/// keeps its folder, title and names, and so does every folder it is inside.
/// </summary> /// </summary>
public sealed record ReorganizeBlockedDto(string Reason, int Photos, string Message); public sealed record ReorganizeBlockedDto(string Reason, int Photos, string Message);
/// <summary> /// <summary>
/// One sequence of a Reorganize plan, in the order the steps apply: its folder and title before and after, /// One sequence of a Reorganize plan, in the order the steps apply: its folder and title before and after,
/// <see cref="Carried"/> when it only moves with a folder it is inside, the frames version its file names were planned at /// <see cref="Carried"/> when it only moves with a folder it is inside, the frames version its file names were planned at
/// (0 when none changes), how many photos get a new name with the first of them (<see cref="FileSamples"/>), and the photos /// (0 when none changes), how many photos get a new name with the first of them (<see cref="FileSamples"/>), and what stays
/// that keep their names. A step that changes nothing lists only those. /// as it is (<see cref="Blocked"/>). A step that changes nothing lists only that.
/// </summary> /// </summary>
public sealed record ReorganizeStepDto(Guid SequenceId, string FromFolder, string ToFolder, string? FromTitle, string? ToTitle, bool Carried, public sealed record ReorganizeStepDto(Guid SequenceId, string FromFolder, string ToFolder, string? FromTitle, string? ToTitle, bool Carried,
int FramesVersion, int FileChanges, IReadOnlyList<ReorganizeFileDto> FileSamples, IReadOnlyList<ReorganizeBlockedDto> Blocked); int FramesVersion, int FileChanges, IReadOnlyList<ReorganizeFileDto> FileSamples, IReadOnlyList<ReorganizeBlockedDto> Blocked);
@@ -91,9 +91,11 @@ export async function render(root, { api, setMeta }) {
}); });
savedToast(before, settings); savedToast(before, settings);
} catch (err) { } catch (err) {
// Errors name the field in details; the field gets the error border and the message as its tooltip. // Errors name the field in details, a template followed by the rule it breaks ("fileTemplate:extension"); the field
const field = err.details && form.elements[err.details]; // gets the error border and the message as its tooltip: for a broken rule the server's, which says why.
const message = field ? invalidText(field) : errorText(err); const [name, rule] = String(err.details ?? "").split(":");
const field = name && form.elements[name];
const message = field ? (rule && err.message ? err.message : invalidText(field)) : errorText(err);
if (field) { if (field) {
markInvalid(field, message); markInvalid(field, message);
field.focus(); field.focus();
+5 -2
View File
@@ -343,9 +343,12 @@ export function openReorganize({ api, target, names = new Map(), templates = nul
} }
} }
/** A refusal on the field it names (a template, or the folders for a nested target), else under the table. */ /**
* A refusal on the field it names (a template, with the rule it breaks after a colon and the message saying why; or the
* folders for a nested target), else under the table.
*/
function showProblem(err) { function showProblem(err) {
const part = PARTS.find((p) => p.field === err?.details); const part = PARTS.find((p) => p.field === String(err?.details ?? "").split(":")[0]);
if (err?.code === "invalid_template" && part) fieldError(part, err.message); if (err?.code === "invalid_template" && part) fieldError(part, err.message);
else if (err?.code === "nested_target") fieldError(PARTS[0], err.message, err.details); else if (err?.code === "nested_target") fieldError(PARTS[0], err.message, err.details);
else if (err?.code === "not_found") showError(t("Admin.Reorganize.Gone")); else if (err?.code === "not_found") showError(t("Admin.Reorganize.Gone"));
+28 -6
View File
@@ -70,7 +70,9 @@ public static class ArchiveEndpoints
/// <summary> /// <summary>
/// Writes the name, templates and proxy policy into the archive's <c>archive.json</c> through the archive engine (so a /// Writes the name, templates and proxy policy into the archive's <c>archive.json</c> through the archive engine (so a
/// restart and the proxy jobs see them), then into the index. 503 <c>archive_offline</c> while the archive cannot be /// restart and the proxy jobs see them), then into the index. 400 <c>bad_request</c> (details <c>name</c>,
/// <c>proxyLongEdge</c>), 400 <c>invalid_template</c> (<see cref="InvalidTemplate"/>: <c>folderTemplate</c> or
/// <c>fileTemplate</c>, with the rule it breaks); 503 <c>archive_offline</c> while the archive cannot be
/// written; 409 <c>archive_busy</c> while another process holds its settings; 409 <c>archive_manifest</c> when its /// written; 409 <c>archive_busy</c> while another process holds its settings; 409 <c>archive_manifest</c> when its
/// archive.json is damaged, written by a newer Chronos or of another archive; 409 <c>archive_policy</c> when it holds a /// archive.json is damaged, written by a newer Chronos or of another archive; 409 <c>archive_policy</c> when it holds a
/// thumbnail or proxy setting this API cannot set and Chronos cannot use (details: <c>thumbnailPolicy</c> or /// thumbnail or proxy setting this API cannot set and Chronos cannot use (details: <c>thumbnailPolicy</c> or
@@ -84,7 +86,7 @@ public static class ArchiveEndpoints
if (string.IsNullOrWhiteSpace(request.FolderTemplate)) return ApiErrors.BadRequest(context, "invalid_template", "folderTemplate"); if (string.IsNullOrWhiteSpace(request.FolderTemplate)) return ApiErrors.BadRequest(context, "invalid_template", "folderTemplate");
if (string.IsNullOrWhiteSpace(request.FileTemplate)) return ApiErrors.BadRequest(context, "invalid_template", "fileTemplate"); if (string.IsNullOrWhiteSpace(request.FileTemplate)) return ApiErrors.BadRequest(context, "invalid_template", "fileTemplate");
// The rules Reorganize checks: a folder scans never enter, a lost extension or names that repeat are refused alike. // The rules Reorganize checks: a folder scans never enter, a lost extension or names that repeat are refused alike.
if (new RenameTemplates(request.FolderTemplate, request.FileTemplate).Problem() is { } field) return ApiErrors.BadRequest(context, "invalid_template", field); if (new RenameTemplates(request.FolderTemplate, request.FileTemplate).Check() is { } problem) return InvalidTemplate(context, problem);
if (!ProxyPolicy.IsValidLongEdge(request.ProxyLongEdge)) return ApiErrors.BadRequest(context, "bad_request", "proxyLongEdge"); if (!ProxyPolicy.IsValidLongEdge(request.ProxyLongEdge)) return ApiErrors.BadRequest(context, "bad_request", "proxyLongEdge");
var engine = archives ?? new ArchiveService(db, new ArchiveServiceOptions { Owner = ArchiveModule.Owner }); var engine = archives ?? new ArchiveService(db, new ArchiveServiceOptions { Owner = ArchiveModule.Owner });
@@ -134,7 +136,8 @@ public static class ArchiveEndpoints
/// that plan's fingerprint and the server queues a <c>move</c> job (202) that applies exactly that plan, refused when the /// that plan's fingerprint and the server queues a <c>move</c> job (202) that applies exactly that plan, refused when the
/// archive changed before it ran. 400 <c>bad_request</c> (details <c>sequenceIds</c>: neither or both of them, none, or /// archive changed before it ran. 400 <c>bad_request</c> (details <c>sequenceIds</c>: neither or both of them, none, or
/// more than <see cref="LibraryEndpoints.MaxBulkIds"/>; <c>templates</c>: none; <c>fingerprint</c>), 400 /// more than <see cref="LibraryEndpoints.MaxBulkIds"/>; <c>templates</c>: none; <c>fingerprint</c>), 400
/// <c>invalid_template</c> (details: <c>folderTemplate</c>, <c>fileTemplate</c> or <c>titleTemplate</c>); 404 /// <c>invalid_template</c> (<see cref="InvalidTemplate"/>: <c>folderTemplate</c>, <c>fileTemplate</c> or
/// <c>titleTemplate</c>, with the rule it breaks); 404
/// <c>not_found</c> (<c>sequence</c>: not in the archive); 409 <c>nested_target</c> (details: the folder that would lie /// <c>not_found</c> (<c>sequence</c>: not in the archive); 409 <c>nested_target</c> (details: the folder that would lie
/// inside a sequence's folder), <c>plan_changed</c> (details: the fingerprint now), <c>job_unavailable</c>; 503 /// inside a sequence's folder), <c>plan_changed</c> (details: the fingerprint now), <c>job_unavailable</c>; 503
/// <c>archive_offline</c>. Audited; the job tells each sequence it changes as <c>sequenceChanged</c> (<c>reorganized</c>) /// <c>archive_offline</c>. Audited; the job tells each sequence it changes as <c>sequenceChanged</c> (<c>reorganized</c>)
@@ -152,7 +155,7 @@ public static class ArchiveEndpoints
return ApiErrors.BadRequest(context, "bad_request", "sequenceIds"); return ApiErrors.BadRequest(context, "bad_request", "sequenceIds");
var templates = new RenameTemplates(request.FolderTemplate, request.FileTemplate, request.TitleTemplate); var templates = new RenameTemplates(request.FolderTemplate, request.FileTemplate, request.TitleTemplate);
if (templates.IsEmpty) return ApiErrors.BadRequest(context, "bad_request", "templates"); if (templates.IsEmpty) return ApiErrors.BadRequest(context, "bad_request", "templates");
if (templates.Problem() is { } field) return ApiErrors.BadRequest(context, "invalid_template", field); if (templates.Check() is { } problem) return InvalidTemplate(context, problem);
if (!request.DryRun && string.IsNullOrWhiteSpace(request.Fingerprint)) return ApiErrors.BadRequest(context, "bad_request", "fingerprint"); if (!request.DryRun && string.IsNullOrWhiteSpace(request.Fingerprint)) return ApiErrors.BadRequest(context, "bad_request", "fingerprint");
if (ArchiveService.GetAvailability(archive.Current) != ArchiveAvailability.Online) if (ArchiveService.GetAvailability(archive.Current) != ArchiveAvailability.Online)
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline"); return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline");
@@ -183,7 +186,23 @@ public static class ArchiveEndpoints
return Results.Json(Dto.Job(job), ProtocolJson.Default.JobDto, statusCode: StatusCodes.Status202Accepted); return Results.Json(Dto.Job(job), ProtocolJson.Default.JobDto, statusCode: StatusCodes.Status202Accepted);
} }
/// <summary>The dry run as the API answers it, with each reason photos keep their names in the request's language.</summary> /// <summary>
/// 400 <c>invalid_template</c> for a template that cannot be used. The details name its field (<c>fileTemplate</c>); when
/// it parses but breaks a rule of the archive's templates (<see cref="TemplateRules"/>), the rule follows after a colon
/// (<c>folderTemplate:reserved_folder</c>, <c>fileTemplate:file_separator</c>, <c>fileTemplate:extension</c>,
/// <c>fileTemplate:not_unique</c>) and the message says why in the request's language, as the desktop's fields do
/// (<c>Errors.Template.&lt;Rule&gt;</c>); otherwise the message is that the template is not valid.
/// </summary>
private static IResult InvalidTemplate(HttpContext context, TemplateProblem problem)
{
if (problem.Rule is not { } rule) return ApiErrors.BadRequest(context, "invalid_template", problem.Field);
var message = Loc.Get("Errors.Template." + rule, RequestCulture.Of(context)) ?? ApiErrors.Message(context, "invalid_template");
var wire = string.Concat(rule.Select((c, i) => char.IsUpper(c) ? (i > 0 ? "_" : string.Empty) + char.ToLowerInvariant(c) : c.ToString()));
return Results.Json(new ApiError("invalid_template", message, $"{problem.Field}:{wire}"), ProtocolJson.Default.ApiError,
statusCode: StatusCodes.Status400BadRequest);
}
/// <summary>The dry run as the API answers it, with each reason something stays as it is in the request's language.</summary>
private static ReorganizePlanDto Plan(HttpContext context, RenamePlan plan, string fingerprint) private static ReorganizePlanDto Plan(HttpContext context, RenamePlan plan, string fingerprint)
{ {
var culture = RequestCulture.Of(context); var culture = RequestCulture.Of(context);
@@ -197,7 +216,10 @@ public static class ArchiveEndpoints
fingerprint); fingerprint);
} }
/// <summary>Wire name of a reason photos keep their names: <c>in_place</c>, <c>unhashed</c>, <c>missing</c>, <c>unreadable</c>.</summary> /// <summary>
/// Wire name of a reason something stays as it is: photos that keep their names (<c>in_place</c>, <c>unhashed</c>,
/// <c>missing</c>), or the whole sequence (<c>unreadable</c>).
/// </summary>
public static string Wire(RenameBlock reason) => reason switch public static string Wire(RenameBlock reason) => reason switch
{ {
RenameBlock.InPlace => "in_place", RenameBlock.InPlace => "in_place",
@@ -203,6 +203,8 @@ public sealed class ReorganizeTests(TestContext context)
Assert.Equal("fileTemplate", new RenameTemplates(File: "{nope}").Problem()); Assert.Equal("fileTemplate", new RenameTemplates(File: "{nope}").Problem());
Assert.Equal("fileTemplate", new RenameTemplates(File: "{date:%}").Problem()); Assert.Equal("fileTemplate", new RenameTemplates(File: "{date:%}").Problem());
Assert.Equal("titleTemplate", new RenameTemplates(Title: "{title").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); Assert.True(new RenameTemplates().IsEmpty);
} }
@@ -221,6 +223,7 @@ public sealed class ReorganizeTests(TestContext context)
var folder = field == "folderTemplate"; var folder = field == "folderTemplate";
var templates = folder ? new RenameTemplates(Folder: template) : new RenameTemplates(File: template); var templates = folder ? new RenameTemplates(Folder: template) : new RenameTemplates(File: template);
Assert.Equal(field, templates.Problem()); 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))); 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] [Test]
public void ExtensionsAPhotoLostComeBackFromItsName() 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. // 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; 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); reference.Add(expected);
Assert.Equal(expected, names.Claim("a/x.JPG", companion), $"photo {i}"); 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("DSC_0001", context.OriginalName);
Assert.Equal("jpg", context.Extension); Assert.Equal("jpg", context.Extension);
Assert.Equal(1, context.Number); 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] [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), 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); new DateTime(2026, 9, 28, 18, 0, 0), 1, null);
var taken = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "originals/2026-09-28.jpg" }; 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/")); var names = new UniqueNames(taken);
Assert.Equal("originals/2026-09-28_3.JPG", FrameNaming.FileName(template, context, taken, "originals/")); 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.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] [Test]
@@ -92,21 +102,7 @@ public sealed class FrameNamingTests(TestContext context)
var plan = await PlanAsync(card, context.CreateTempDirectory("archive"), new ImportOptions { FileTemplate = fileTemplate }); var plan = await PlanAsync(card, context.CreateTempDirectory("archive"), new ImportOptions { FileTemplate = fileTemplate });
var session = plan.Sessions.Single(); 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 manifest = Filed(card, session);
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)]); var reorganized = FileRenames.Plan(manifest, session.Title, PathTemplate.Parse(fileTemplate), [.. manifest.Frames.Select(f => f.File)]);
Assert.Empty(reorganized.Moves); Assert.Empty(reorganized.Moves);
Assert.Equal(0, reorganized.Frames); 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)))); 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] [Test]
public async Task ALensChangedDuringASessionNamesItsPhotosAsTheirSequenceDoes() 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)); 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] [Theory]
[Case("{title} 2026", "Paris: night", "Paris: night 2026")] [Case("{title} 2026", "Paris: night", "Paris: night 2026")]
[Case("{title} 2026", "24/7 roof", "24/7 roof 2026")] [Case("{title} 2026", "24/7 roof", "24/7 roof 2026")]
@@ -112,8 +112,8 @@ internal sealed class ArchiveFixture : IAsyncDisposable
return job; return job;
} }
/// <summary>Stages a verified upload-like file for ingest: returns its path, size and SHA-256.</summary> /// <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) 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"); var staging = Path.Combine(Paths.StagingDirectory, "uploads");
Directory.CreateDirectory(staging); 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> /// <summary>Small real JPEGs with Exif made by the in-house encoder; each seed gives distinct bytes.</summary>
internal static class Photos 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); using var image = new ImageBuffer(48, 32);
var random = new Random(seed); var random = new Random(seed);
@@ -90,6 +90,19 @@ public sealed class ArchiveSettingsTests(TestContext context)
var template = await Assert.ThrowsAsync<ArgumentException>(() => var template = await Assert.ThrowsAsync<ArgumentException>(() =>
fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Templates = s.Templates with { Folder = "{year/{date" } }, fx.Ct)); fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Templates = s.Templates with { Folder = "{year/{date" } }, fx.Ct));
Assert.Equal("folderTemplate", template.ParamName); 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>(() => var proxies = await Assert.ThrowsAsync<ArgumentException>(() =>
fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Proxies = s.Proxies with { LongEdge = 100 } }, fx.Ct)); fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Proxies = s.Proxies with { LongEdge = 100 } }, fx.Ct));
Assert.Equal("proxyLongEdge", proxies.ParamName); Assert.Equal("proxyLongEdge", proxies.ParamName);
@@ -177,6 +177,50 @@ public sealed class ReorganizeTests(TestContext context)
Assert.Empty(plan.Steps); 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] [Test]
public async Task ASequenceWhoseSidecarCannotBeReadStaysAsItIsAndTheOthersMove() public async Task ASequenceWhoseSidecarCannotBeReadStaysAsItIsAndTheOthersMove()
{ {
@@ -730,6 +774,42 @@ public sealed class ReorganizeTests(TestContext context)
Assert.Empty(RenameJournal.ListPending(fx.Paths)); 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] [Test]
public async Task PhotosHashedAfterThePlanKeepTheNamesItShowed() public async Task PhotosHashedAfterThePlanKeepTheNamesItShowed()
{ {
+11 -7
View File
@@ -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)) 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); 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. // Templates that would hide sequences from scans, drop extensions or repeat names: refused as Reorganize refuses them,
foreach (var (refused, field) in new[] // 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 { FolderTemplate = "Originals/{year}" }, "folderTemplate:reserved_folder", "ReservedFolder"),
(archive with { FileTemplate = "{n}{ext}" }, "fileTemplate"), (archive with { FileTemplate = "{n}{ext}" }, "fileTemplate:extension", "Extension"),
(archive with { FileTemplate = "{date}" }, "fileTemplate"), (archive with { FileTemplate = "{date}" }, "fileTemplate:not_unique", "NotUnique"),
(archive with { FileTemplate = " " }, "fileTemplate"), (archive with { FileTemplate = " " }, "fileTemplate", (string?)null),
}) })
{ {
using var response = await admin.PutAsJsonAsync("/api/v1/archive/settings", refused, ProtocolJson.Default.ArchiveSettingsDto); 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)) 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)) 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); 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. // The desktop's rules: no lost extension, names that tell the photos apart, no folder scans skip; each named after the
foreach (var (bad, field) in new[] // field, with the desktop's sentence.
foreach (var (bad, details, rule) in new[]
{ {
(valid with { FileTemplate = "{n}{ext}" }, "fileTemplate"), (valid with { FileTemplate = "{n}{ext}" }, "fileTemplate:extension", "Extension"),
(valid with { FileTemplate = "{title}" }, "fileTemplate"), (valid with { FileTemplate = "{title}" }, "fileTemplate:not_unique", "NotUnique"),
(valid with { FolderTemplate = "Exports/{title}" }, "folderTemplate"), (valid with { FileTemplate = "{year}/{n}" }, "fileTemplate:file_separator", "FileSeparator"),
(valid with { FolderTemplate = ".hidden/{date}" }, "folderTemplate"), (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); 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)) using (var blank = await admin.PostAsJsonAsync(Url, valid with { FolderTemplate = " " }, ProtocolJson.Default.ReorganizeRequest))
Assert.Equal("folderTemplate", (await blank.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_template")).Details); 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("fileTemplate", error.Details);
Assert.Equal(Loc.Get("Server.Error.InvalidTemplate", CultureInfo.GetCultureInfo("it")), error.Message); 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. // 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)}\""))) 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); Assert.Equal(fingerprint, (await stale.ExpectErrorAsync(HttpStatusCode.Conflict, "plan_changed")).Details);