diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 19f224e8..8cea1695 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -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) |
| `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) |
-| `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 |
| `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) |
diff --git a/src/Chronos.Core/Archiving/FileRenames.cs b/src/Chronos.Core/Archiving/FileRenames.cs
index b3241d0f..ebfaebe0 100644
--- a/src/Chronos.Core/Archiving/FileRenames.cs
+++ b/src/Chronos.Core/Archiving/FileRenames.cs
@@ -5,7 +5,10 @@ using Chronos.Core.Naming;
namespace Chronos.Core.Archiving;
-/// Why frames of a sequence keep their file names in a Reorganize (owner review 2, R7); nothing of them is touched.
+///
+/// Why frames of a sequence keep their file names in a Reorganize (owner review 2, R7), nothing of them touched; or, for
+/// , why the whole sequence stays as it is.
+///
public enum RenameBlock
{
/// Photos adopted in place, outside originals/: they belong to a tree someone else keeps.
@@ -17,7 +20,10 @@ public enum RenameBlock
/// Photos whose file is not there.
Missing,
- /// The sequence's sidecar cannot be read, is of a newer format this build does not rewrite, or belongs to another sequence.
+ ///
+ /// 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).
+ ///
Unreadable,
}
diff --git a/src/Chronos.Core/Archiving/MassRename.cs b/src/Chronos.Core/Archiving/MassRename.cs
index 04aa0564..ef1f96f5 100644
--- a/src/Chronos.Core/Archiving/MassRename.cs
+++ b/src/Chronos.Core/Archiving/MassRename.cs
@@ -32,7 +32,8 @@ public sealed record SequenceFiles(SequenceManifest Manifest, IReadOnlyCollectio
///
/// 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 ().
+/// 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 ().
///
/// The folder moves only because a folder it is inside moves (a sequence nested in another).
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
///
public string? FileDigest { get; init; }
- /// Frames that keep their file names, and why.
+ /// Frames that keep their file names, and why; (0 frames) when the whole sequence stays as it is.
public IReadOnlyList Blocked { get; init; } = [];
}
@@ -90,33 +91,45 @@ public sealed record RenameTemplates(string? Folder = null, string? File = null,
/// titleTemplate): blank, not valid (), with a format a sample cannot be written
/// with ({date:%}), expanding to nothing, or, for a folder or file template, breaking a rule of the archive's
/// templates (: 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
+ /// (ArchiveSettings.Problem).
///
- public string? Problem()
- {
- 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;
- }
+ public string? Problem() => Check()?.Field;
- private static bool Unusable(string? template, Func expand, Func? rule = null)
+ ///
+ /// The first template that cannot be used (), with the rule of it breaks
+ /// when it parses and expands (); null when every one given can.
+ ///
+ 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 expand, Func? rule = null)
{
- if (template is null) return false;
- if (string.IsNullOrWhiteSpace(template)) return true;
+ if (template is null) return null;
+ if (string.IsNullOrWhiteSpace(template)) return new TemplateProblem(field, null);
var parsed = PathTemplate.Parse(template);
- if (!parsed.IsValid) return true;
+ if (!parsed.IsValid) return new TemplateProblem(field, null);
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)
{
- return true;
+ return new TemplateProblem(field, null);
}
}
}
+///
+/// A template that cannot be used: its API name (folderTemplate, fileTemplate, titleTemplate) and the
+/// rule of it breaks (ReservedFolder, FileSeparator, Extension,
+/// NotUnique, each explained by Errors.Template.<Rule>); no rule when it is blank, not valid or expands to nothing.
+///
+public sealed record TemplateProblem(string Field, string? Rule);
+
/// A planned folder would lie inside a sequence's folder (nesting one sequence in another); nothing is planned.
public sealed class NestedRenameException(string target, string folder)
: ArgumentException(Loc.L("Archive.Error.NestedTarget", target, folder))
@@ -219,7 +232,8 @@ public static class RenamePlanner
/// (where {title} is the new title) for every subject, from its first frame as
/// filing saw it (); a title is text, not a file
/// name (). 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 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 every
/// subject's frames get their names from it as filing names them (, 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
/// new folder or file names come from {title} says so (). A subject
@@ -231,10 +245,15 @@ public static class RenamePlanner
///
/// Every sequence folder of the archive (renamed or not).
/// The archive's other sequences inside a subject's folder, with their titles.
+ /// Whether a folder of exactly that name, in every level's case, is on disk
+ /// (): on a case-sensitive file system Trip (2) beside a sequence at trip (2) is
+ /// another folder, which a change of case could never move onto. Null when no folder but the sequences' own counts.
/// A target lies inside a sequence's folder, or inside another target.
public static RenamePlan Plan(Guid archiveId, IReadOnlyList subjects, string? folderTemplate, string? titleTemplate,
- IEnumerable occupied, Func existsOnDisk, IReadOnlyList? nested = null, string? fileTemplate = null)
+ IEnumerable occupied, Func existsOnDisk, IReadOnlyList? nested = null, string? fileTemplate = null,
+ Func? existsExactly = null)
{
+ existsExactly ??= _ => false;
var folder = folderTemplate is null ? null : PathTemplate.Parse(folderTemplate);
var title = titleTemplate is null ? null : PathTemplate.Parse(titleTemplate);
var file = fileTemplate is null ? null : PathTemplate.Parse(fileTemplate);
@@ -269,7 +288,7 @@ public static class RenamePlanner
}
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);
given.Add(newFolder);
}
@@ -367,17 +386,17 @@ public static class RenamePlanner
/// a case-only change goes through a temporary name (case-insensitive file systems).
///
/// 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.
+ /// on a case-sensitive file system, which the plan and the apply refuse first), or neither folder exists.
public static void MoveFolder(ArchivePaths archive, RenameStep step)
{
if (!step.MovesFolder) return;
var from = archive.FromRelative(step.FromFolder);
var to = archive.FromRelative(step.ToFolder);
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).
- 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;
}
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) =>
- Directory.EnumerateDirectories(Path.GetDirectoryName(path)!, Path.GetFileName(path))
- .Any(d => Path.GetFileName(d).Equals(Path.GetFileName(path), StringComparison.Ordinal));
+ ///
+ /// Whether the folder (archive-relative, forward slashes) is on disk with exactly that name at
+ /// 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.
+ ///
+ 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;
///
/// The folder a sequence keeps (in the template's case) when it already is , or the
/// " (n)" 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
- /// it to another sequence (, whatever its case: trip (2) and TRIP (2) both keep
+ /// neither, when another folder holds that name exactly (a sequence's, or any on a case-sensitive file system:
+ /// ), which the change of case could never move onto, or when this plan already gave it
+ /// to another sequence (, whatever its case: trip (2) and TRIP (2) both keep
/// Trip (2) otherwise). Without it a sequence at 2026-09-28 (2) would be planned to (3), its own
/// folder being taken, and back to (2) by the next Reorganize.
///
- private static string? Kept(string current, string expanded, IReadOnlyList occupied, IReadOnlySet given)
+ private static string? Kept(string current, string expanded, IReadOnlyList occupied, IReadOnlySet given, Func existsExactly)
{
string? same = null;
if (current.Equals(expanded, StringComparison.OrdinalIgnoreCase)) same = expanded;
@@ -418,7 +461,8 @@ public static class RenamePlanner
same = string.Create(CultureInfo.InvariantCulture, $"{expanded} ({n})");
// "(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;
- 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 claimed, Func existsOnDisk)
diff --git a/src/Chronos.Core/Naming/FrameNaming.cs b/src/Chronos.Core/Naming/FrameNaming.cs
index be7c9609..83e61604 100644
--- a/src/Chronos.Core/Naming/FrameNaming.cs
+++ b/src/Chronos.Core/Naming/FrameNaming.cs
@@ -94,21 +94,9 @@ public static class FrameNaming
}
///
- /// (empty or ending with '/') and the name gives, made unique
- /// in with _2, _3… before the extension, then added to it.
- ///
- public static string FileName(PathTemplate template, NamingContext context, ISet taken, string directory = "")
- {
- ArgumentNullException.ThrowIfNull(taken);
- var file = FileName(template, context, candidate => !taken.Contains(candidate), directory);
- taken.Add(file);
- return file;
- }
-
- ///
- /// (empty or ending with '/') and the name gives, made unique
- /// in the set of as
- /// does, then added to it.
+ /// (empty or ending with '/') and the name gives, made unique in
+ /// the set of with _2, _3… before the extension (),
+ /// then added to it.
///
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));
}
- ///
- /// and the name gives, or the first of stem_2.ext,
- /// stem_3.ext… that accepts.
- ///
- public static string FileName(PathTemplate template, NamingContext context, Func isFree, string directory = "")
- {
- ArgumentNullException.ThrowIfNull(template);
- ArgumentNullException.ThrowIfNull(isFree);
- ArgumentNullException.ThrowIfNull(directory);
- return Unique(directory + template.ExpandFile(context), isFree);
- }
-
- /// , or the first of stem_2.ext, stem_3.ext… that accepts.
- public static string Unique(string file, Func isFree)
- {
- ArgumentNullException.ThrowIfNull(file);
- ArgumentNullException.ThrowIfNull(isFree);
- var candidate = file;
- for (var n = 2; !isFree(candidate); n++) candidate = Numbered(file, n);
- return candidate;
- }
-
/// itself for = 1, else stem_n.ext in its directory.
internal static string Numbered(string file, int n)
{
@@ -151,9 +117,9 @@ public static class FrameNaming
}
///
-/// Unique file names in a set that only grows (BRIEF §7.1): exactly the names gives against
-/// it, without trying again for each photo the numbers earlier photos already took. A template that gives a whole session
-/// one name ({title}) then costs about one check per photo instead of one per photo before it.
+/// Unique file names in a set that only grows (BRIEF §7.1): exactly the names a search from _2 up gives against it,
+/// without trying again for each photo the numbers earlier photos already took. A template that gives a whole session one
+/// name ({title}) then costs about one check per photo instead of one per photo before it.
///
/// The names given or held so far; every name claimed is added to it, and none may leave it while in use.
public sealed class UniqueNames(ISet taken)
diff --git a/src/Chronos.Core/Naming/PathTemplate.cs b/src/Chronos.Core/Naming/PathTemplate.cs
index 7fa9c1dd..8237fffc 100644
--- a/src/Chronos.Core/Naming/PathTemplate.cs
+++ b/src/Chronos.Core/Naming/PathTemplate.cs
@@ -24,6 +24,9 @@ public sealed class PathTemplate
/// The longest text gives: the longest title a sequence takes.
public const int MaxTextLength = 200;
+ /// The longest folder level or file name a template gives (), before an appended extension.
+ public const int MaxSegmentLength = 200;
+
private static readonly HashSet TokenSet = new(Tokens, StringComparer.OrdinalIgnoreCase);
private static readonly char[] Illegal = ['<', '>', ':', '"', '|', '?', '*', '\\', '/', '\0'];
private static readonly HashSet ReservedNames = new(StringComparer.OrdinalIgnoreCase)
@@ -133,11 +136,18 @@ public sealed class PathTemplate
private IEnumerable Levels(NamingContext context) =>
Expand(context, allowSeparators: true).Split('/', StringSplitOptions.RemoveEmptyEntries).Select(SanitizeSegment).Where(s => s.Length > 0);
- /// Expands to a file name; the original extension is appended unless the template already ends with {ext}.
+ ///
+ /// Expands to a file name; the original extension is appended unless the template already ends with {ext}. A name
+ /// longer than is shortened before the .{ext} the template ends with, never through it.
+ ///
public string ExpandFile(NamingContext context)
{
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 (!hasExt && context.Extension.Length > 0) name += "." + context.Extension;
return name;
@@ -145,8 +155,8 @@ public sealed class PathTemplate
///
/// Whether every file name the template gives ends with the photo's own extension: the template does not end with
- /// {ext} (the extension is appended), or ends with .{ext}. {n}{ext} would drop the dot, and with it
- /// the extension every reader of the photo goes by.
+ /// {ext} (the extension is appended), or ends with .{ext}, which a long name keeps whole
+ /// (). {n}{ext} would drop the dot, and with it the extension every reader of the photo goes by.
///
public bool KeepsExtension =>
_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] = ' ';
}
- var s = text.ToString().Trim();
- if (s.Length <= MaxTextLength) return s;
- var cut = char.IsHighSurrogate(s[MaxTextLength - 1]) ? MaxTextLength - 1 : MaxTextLength;
+ return Shorten(text.ToString().Trim(), MaxTextLength);
+ }
+
+ /// At most characters of , a character outside the basic plane never cut in two, trailing spaces trimmed.
+ 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();
}
@@ -232,8 +247,14 @@ public sealed class PathTemplate
return "1-" + Math.Round(1 / t).ToString(CultureInfo.InvariantCulture);
}
- /// Replaces characters that are illegal on Windows or Linux and fixes reserved names and trailing dots/spaces.
- 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
+ /// characters.
+ ///
+ public static string SanitizeSegment(string segment) => Shorten(Clean(segment), MaxSegmentLength);
+
+ /// without its length limit.
+ private static string Clean(string segment)
{
var sb = new StringBuilder(segment.Length);
foreach (var ch in segment)
@@ -246,7 +267,7 @@ public sealed class PathTemplate
var stem = s.Split('.')[0];
if (ReservedNames.Contains(stem)) s = "_" + 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)
diff --git a/src/Chronos.Data/Archiving/ArchiveService.cs b/src/Chronos.Data/Archiving/ArchiveService.cs
index df44a6df..4f01ae4b 100644
--- a/src/Chronos.Data/Archiving/ArchiveService.cs
+++ b/src/Chronos.Data/Archiving/ArchiveService.cs
@@ -515,13 +515,19 @@ public sealed record ArchiveSettings(string Name, LayoutTemplates Templates, Pro
&& Proxies.LongEdge == archive.ProxyLongEdge;
}
- /// The first invalid field by its API name (name, folderTemplate, fileTemplate,
- /// proxyLongEdge, thumbnailLongEdge); null when every field is valid.
+ ///
+ /// The first invalid field by its API name (name, folderTemplate, fileTemplate,
+ /// proxyLongEdge, thumbnailLongEdge); null when every field is valid. The templates are held to the rules
+ /// they meet wherever they are typed (, ): 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.
+ ///
public string? Problem()
{
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.File) || !PathTemplate.Parse(Templates.File).IsValid) return "fileTemplate";
+ if (string.IsNullOrWhiteSpace(Templates.Folder)) return "folderTemplate";
+ 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 (!ThumbnailPolicy.IsValidLongEdge(Thumbnails.LongEdge) || Thumbnails.Quality is < 1 or > 100) return "thumbnailLongEdge";
return null;
diff --git a/src/Chronos.Data/Archiving/MassRenamer.cs b/src/Chronos.Data/Archiving/MassRenamer.cs
index babda93d..23a9abf7 100644
--- a/src/Chronos.Data/Archiving/MassRenamer.cs
+++ b/src/Chronos.Data/Archiving/MassRenamer.cs
@@ -124,7 +124,7 @@ public sealed class MassRenamer
}
}
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);
@@ -631,11 +631,14 @@ public sealed class MassRenamer
///
/// 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
- /// 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 could never move onto.
///
private static bool TargetTaken(ArchivePaths paths, RenameStep step, IReadOnlyList 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
&& (l.Folder.Equals(step.ToFolder, StringComparison.OrdinalIgnoreCase) || RenamePlanner.IsInside(l.Folder, step.ToFolder)
|| RenamePlanner.IsInside(step.ToFolder, l.Folder)));
diff --git a/src/Chronos.Protocol/Library.cs b/src/Chronos.Protocol/Library.cs
index 75efd271..e9be1216 100644
--- a/src/Chronos.Protocol/Library.cs
+++ b/src/Chronos.Protocol/Library.cs
@@ -97,17 +97,18 @@ public sealed record ReorganizeRequest(IReadOnlyList? SequenceIds, bool Al
public sealed record ReorganizeFileDto(string From, string To);
///
-/// Photos of a sequence that keep their names in a Reorganize: in_place (kept in place outside
-/// originals/), unhashed (never verified), missing or unreadable (the sequence's sidecar), how many
-/// (0 for unreadable), and the reason as one localised sentence.
+/// Why part of a sequence stays as it is in a Reorganize, as one localised sentence: photos that keep their names,
+/// in_place (kept in place outside originals/), unhashed (never verified) or
+/// missing, with how many; or unreadable (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.
///
public sealed record ReorganizeBlockedDto(string Reason, int Photos, string Message);
///
/// One sequence of a Reorganize plan, in the order the steps apply: its folder and title before and after,
/// 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 (), and the photos
-/// that keep their names. A step that changes nothing lists only those.
+/// (0 when none changes), how many photos get a new name with the first of them (), and what stays
+/// as it is (). A step that changes nothing lists only that.
///
public sealed record ReorganizeStepDto(Guid SequenceId, string FromFolder, string ToFolder, string? FromTitle, string? ToTitle, bool Carried,
int FramesVersion, int FileChanges, IReadOnlyList FileSamples, IReadOnlyList Blocked);
diff --git a/src/Chronos.Server/Admin/web/pages/archive.js b/src/Chronos.Server/Admin/web/pages/archive.js
index dcb77e65..3246a3c4 100644
--- a/src/Chronos.Server/Admin/web/pages/archive.js
+++ b/src/Chronos.Server/Admin/web/pages/archive.js
@@ -91,9 +91,11 @@ export async function render(root, { api, setMeta }) {
});
savedToast(before, settings);
} catch (err) {
- // Errors name the field in details; the field gets the error border and the message as its tooltip.
- const field = err.details && form.elements[err.details];
- const message = field ? invalidText(field) : errorText(err);
+ // Errors name the field in details, a template followed by the rule it breaks ("fileTemplate:extension"); the field
+ // gets the error border and the message as its tooltip: for a broken rule the server's, which says why.
+ 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) {
markInvalid(field, message);
field.focus();
diff --git a/src/Chronos.Server/Admin/web/reorganize.js b/src/Chronos.Server/Admin/web/reorganize.js
index 09c68cda..8d8daf70 100644
--- a/src/Chronos.Server/Admin/web/reorganize.js
+++ b/src/Chronos.Server/Admin/web/reorganize.js
@@ -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) {
- 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);
else if (err?.code === "nested_target") fieldError(PARTS[0], err.message, err.details);
else if (err?.code === "not_found") showError(t("Admin.Reorganize.Gone"));
diff --git a/src/Chronos.Server/Api/ArchiveEndpoints.cs b/src/Chronos.Server/Api/ArchiveEndpoints.cs
index 627efbe8..cca6f611 100644
--- a/src/Chronos.Server/Api/ArchiveEndpoints.cs
+++ b/src/Chronos.Server/Api/ArchiveEndpoints.cs
@@ -70,7 +70,9 @@ public static class ArchiveEndpoints
///
/// Writes the name, templates and proxy policy into the archive's archive.json through the archive engine (so a
- /// restart and the proxy jobs see them), then into the index. 503 archive_offline while the archive cannot be
+ /// restart and the proxy jobs see them), then into the index. 400 bad_request (details name,
+ /// proxyLongEdge), 400 invalid_template (: folderTemplate or
+ /// fileTemplate, with the rule it breaks); 503 archive_offline while the archive cannot be
/// written; 409 archive_busy while another process holds its settings; 409 archive_manifest when its
/// archive.json is damaged, written by a newer Chronos or of another archive; 409 archive_policy when it holds a
/// thumbnail or proxy setting this API cannot set and Chronos cannot use (details: thumbnailPolicy 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.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.
- 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");
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 move job (202) that applies exactly that plan, refused when the
/// archive changed before it ran. 400 bad_request (details sequenceIds: neither or both of them, none, or
/// more than ; templates: none; fingerprint), 400
- /// invalid_template (details: folderTemplate, fileTemplate or titleTemplate); 404
+ /// invalid_template (: folderTemplate, fileTemplate or
+ /// titleTemplate, with the rule it breaks); 404
/// not_found (sequence: not in the archive); 409 nested_target (details: the folder that would lie
/// inside a sequence's folder), plan_changed (details: the fingerprint now), job_unavailable; 503
/// archive_offline. Audited; the job tells each sequence it changes as sequenceChanged (reorganized)
@@ -152,7 +155,7 @@ public static class ArchiveEndpoints
return ApiErrors.BadRequest(context, "bad_request", "sequenceIds");
var templates = new RenameTemplates(request.FolderTemplate, request.FileTemplate, request.TitleTemplate);
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 (ArchiveService.GetAvailability(archive.Current) != ArchiveAvailability.Online)
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);
}
- /// The dry run as the API answers it, with each reason photos keep their names in the request's language.
+ ///
+ /// 400 invalid_template for a template that cannot be used. The details name its field (fileTemplate); when
+ /// it parses but breaks a rule of the archive's templates (), the rule follows after a colon
+ /// (folderTemplate:reserved_folder, fileTemplate:file_separator, fileTemplate:extension,
+ /// fileTemplate:not_unique) and the message says why in the request's language, as the desktop's fields do
+ /// (Errors.Template.<Rule>); otherwise the message is that the template is not valid.
+ ///
+ 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);
+ }
+
+ /// The dry run as the API answers it, with each reason something stays as it is in the request's language.
private static ReorganizePlanDto Plan(HttpContext context, RenamePlan plan, string fingerprint)
{
var culture = RequestCulture.Of(context);
@@ -197,7 +216,10 @@ public static class ArchiveEndpoints
fingerprint);
}
- /// Wire name of a reason photos keep their names: in_place, unhashed, missing, unreadable.
+ ///
+ /// Wire name of a reason something stays as it is: photos that keep their names (in_place, unhashed,
+ /// missing), or the whole sequence (unreadable).
+ ///
public static string Wire(RenameBlock reason) => reason switch
{
RenameBlock.InPlace => "in_place",
diff --git a/tests/Chronos.Core.Tests/Archiving/ReorganizeTests.cs b/tests/Chronos.Core.Tests/Archiving/ReorganizeTests.cs
index e9137da0..2b98d7ef 100644
--- a/tests/Chronos.Core.Tests/Archiving/ReorganizeTests.cs
+++ b/tests/Chronos.Core.Tests/Archiving/ReorganizeTests.cs
@@ -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(["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 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}");
}
diff --git a/tests/Chronos.Core.Tests/Naming/FrameNamingTests.cs b/tests/Chronos.Core.Tests/Naming/FrameNamingTests.cs
index 69b30c4c..4408d442 100644
--- a/tests/Chronos.Core.Tests/Naming/FrameNamingTests.cs
+++ b/tests/Chronos.Core.Tests/Naming/FrameNamingTests.cs
@@ -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(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(["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))));
}
+ ///
+ /// The sequence an import files of into: the plan's names, each
+ /// frame from its photo's metadata, the camera and lens of the first.
+ ///
+ 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 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()
{
diff --git a/tests/Chronos.Core.Tests/Naming/PathTemplateTests.cs b/tests/Chronos.Core.Tests/Naming/PathTemplateTests.cs
index 00ec3664..655cf05d 100644
--- a/tests/Chronos.Core.Tests/Naming/PathTemplateTests.cs
+++ b/tests/Chronos.Core.Tests/Naming/PathTemplateTests.cs
@@ -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")]
diff --git a/tests/Chronos.Data.Tests/Archiving/ArchiveFixture.cs b/tests/Chronos.Data.Tests/Archiving/ArchiveFixture.cs
index 2e2af950..63c31841 100644
--- a/tests/Chronos.Data.Tests/Archiving/ArchiveFixture.cs
+++ b/tests/Chronos.Data.Tests/Archiving/ArchiveFixture.cs
@@ -112,8 +112,8 @@ internal sealed class ArchiveFixture : IAsyncDisposable
return job;
}
- /// Stages a verified upload-like file for ingest: returns its path, size and SHA-256.
- public (string Path, long Size, string Sha256) Stage(DateTime captured, int seed, string? make = "Canon", string? model = "Canon EOS R5", string? lens = null)
+ /// Stages a verified upload-like file for ingest ( null: a photo that records no time): returns its path, size and SHA-256.
+ 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
/// Small real JPEGs with Exif made by the in-house encoder; each seed gives distinct bytes.
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);
diff --git a/tests/Chronos.Data.Tests/Archiving/ArchiveSettingsTests.cs b/tests/Chronos.Data.Tests/Archiving/ArchiveSettingsTests.cs
index 3eef7682..bb9d37e4 100644
--- a/tests/Chronos.Data.Tests/Archiving/ArchiveSettingsTests.cs
+++ b/tests/Chronos.Data.Tests/Archiving/ArchiveSettingsTests.cs
@@ -90,6 +90,19 @@ public sealed class ArchiveSettingsTests(TestContext context)
var template = await Assert.ThrowsAsync(() =>
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(() =>
+ 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(() =>
+ 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(() =>
fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Proxies = s.Proxies with { LongEdge = 100 } }, fx.Ct));
Assert.Equal("proxyLongEdge", proxies.ParamName);
diff --git a/tests/Chronos.Data.Tests/Archiving/ReorganizeTests.cs b/tests/Chronos.Data.Tests/Archiving/ReorganizeTests.cs
index 68b1e533..f545e70d 100644
--- a/tests/Chronos.Data.Tests/Archiving/ReorganizeTests.cs
+++ b/tests/Chronos.Data.Tests/Archiving/ReorganizeTests.cs
@@ -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(() => 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()
{
diff --git a/tests/Chronos.Server.Tests/Api/AdminTests.cs b/tests/Chronos.Server.Tests/Api/AdminTests.cs
index dcf2dd00..74b55e16 100644
--- a/tests/Chronos.Server.Tests/Api/AdminTests.cs
+++ b/tests/Chronos.Server.Tests/Api/AdminTests.cs
@@ -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))
{
diff --git a/tests/Chronos.Server.Tests/Api/ReorganizeTests.cs b/tests/Chronos.Server.Tests/Api/ReorganizeTests.cs
index 6ec1a841..8bed604b 100644
--- a/tests/Chronos.Server.Tests/Api/ReorganizeTests.cs
+++ b/tests/Chronos.Server.Tests/Api/ReorganizeTests.cs
@@ -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);
diff --git a/tests/Chronos.Server.Tests/Hosting/AdminReorganizeTests.cs b/tests/Chronos.Server.Tests/Hosting/AdminReorganizeTests.cs
index 9115cded..c3408506 100644
--- a/tests/Chronos.Server.Tests/Hosting/AdminReorganizeTests.cs
+++ b/tests/Chronos.Server.Tests/Hosting/AdminReorganizeTests.cs
@@ -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);