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

+8 -2
View File
@@ -5,7 +5,10 @@ using Chronos.Core.Naming;
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
{
/// <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>
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,
}
+73 -29
View File
@@ -32,7 +32,8 @@ public sealed record SequenceFiles(SequenceManifest Manifest, IReadOnlyCollectio
/// <summary>
/// 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>
/// <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)
@@ -71,7 +72,7 @@ public sealed record RenameStep(Guid SequenceId, string FromFolder, string ToFol
/// </summary>
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; } = [];
}
@@ -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
/// 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
/// 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>
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<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 (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);
}
}
}
/// <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>
public sealed class NestedRenameException(string target, string 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
/// 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
/// 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),
/// 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
@@ -231,10 +245,15 @@ public static class RenamePlanner
/// </summary>
/// <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="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>
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 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).
/// </summary>
/// <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)
{
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));
/// <summary>
/// Whether the folder <paramref name="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.
/// </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;
/// <summary>
/// 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
/// neither, when another sequence holds that name exactly (a case-sensitive file system), 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
/// neither, when another folder holds that name exactly (a sequence's, or any on a case-sensitive file system:
/// <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
/// folder being taken, and back to <c>(2)</c> by the next Reorganize.
/// </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;
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<string> claimed, Func<string, bool> existsOnDisk)
+6 -40
View File
@@ -94,21 +94,9 @@ public static class FrameNaming
}
/// <summary>
/// <paramref name="directory"/> (empty or ending with '/') and the name <paramref name="template"/> gives, made unique
/// in <paramref name="taken"/> with <c>_2</c>, <c>_3</c>… before the extension, then added to it.
/// </summary>
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.
/// <paramref name="directory"/> (empty or ending with '/') and the name <paramref name="template"/> gives, made unique in
/// the set of <paramref name="names"/> with <c>_2</c>, <c>_3</c>… before the extension (<see cref="UniqueNames.Claim"/>),
/// then added to it.
/// </summary>
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));
}
/// <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>
internal static string Numbered(string file, int n)
{
@@ -151,9 +117,9 @@ public static class FrameNaming
}
/// <summary>
/// Unique file names in a set that only grows (BRIEF §7.1): exactly the names <see cref="FrameNaming.Unique"/> gives against
/// it, without trying again for each photo the numbers earlier photos already took. A template that gives a whole session
/// one name (<c>{title}</c>) 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 <c>_2</c> 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 (<c>{title}</c>) then costs about one check per photo instead of one per photo before it.
/// </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>
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>
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 char[] Illegal = ['<', '>', ':', '"', '|', '?', '*', '\\', '/', '\0'];
private static readonly HashSet<string> ReservedNames = new(StringComparer.OrdinalIgnoreCase)
@@ -133,11 +136,18 @@ public sealed class PathTemplate
private IEnumerable<string> Levels(NamingContext context) =>
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)
{
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
/// <summary>
/// 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
/// the extension every reader of the photo goes by.
/// <c>{ext}</c> (the extension is appended), or ends with <c>.{ext}</c>, which a long name keeps whole
/// (<see cref="ExpandFile"/>). <c>{n}{ext}</c> would drop the dot, and with it the extension every reader of the photo goes by.
/// </summary>
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);
}
/// <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();
}
@@ -232,8 +247,14 @@ public sealed class PathTemplate
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>
public static string SanitizeSegment(string segment)
/// <summary>
/// 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);
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)
+10 -4
View File
@@ -515,13 +515,19 @@ public sealed record ArchiveSettings(string Name, LayoutTemplates Templates, Pro
&& Proxies.LongEdge == archive.ProxyLongEdge;
}
/// <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.</summary>
/// <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()
{
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;
+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),
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
/// <summary>
/// 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 <see cref="RenamePlanner.MoveFolder"/> could never move onto.
/// </summary>
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
&& (l.Folder.Equals(step.ToFolder, StringComparison.OrdinalIgnoreCase) || RenamePlanner.IsInside(l.Folder, step.ToFolder)
|| 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);
/// <summary>
/// Photos of a sequence that keep their names in a Reorganize: <see cref="Reason"/> <c>in_place</c> (kept in place outside
/// <c>originals/</c>), <c>unhashed</c> (never verified), <c>missing</c> or <c>unreadable</c> (the sequence's sidecar), how many
/// (0 for <c>unreadable</c>), 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,
/// <see cref="Reason"/> <c>in_place</c> (kept in place outside <c>originals/</c>), <c>unhashed</c> (never verified) or
/// <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>
public sealed record ReorganizeBlockedDto(string Reason, int Photos, string Message);
/// <summary>
/// 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
/// (0 when none changes), how many photos get a new name with the first of them (<see cref="FileSamples"/>), 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 (<see cref="FileSamples"/>), and what stays
/// as it is (<see cref="Blocked"/>). A step that changes nothing lists only that.
/// </summary>
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);
@@ -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();
+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) {
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"));
+28 -6
View File
@@ -70,7 +70,9 @@ public static class ArchiveEndpoints
/// <summary>
/// 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
/// 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
@@ -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 <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
/// 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
/// 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>)
@@ -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);
}
/// <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)
{
var culture = RequestCulture.Of(context);
@@ -197,7 +216,10 @@ public static class ArchiveEndpoints
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
{
RenameBlock.InPlace => "in_place",