feat(archive): reorganize existing sequences with folder, file and title templates

Owner review 2, R7 asks for renaming and moving after import, on the web panel and the
desktop. This is the engine and the server API both UIs build on.

- FrameNaming (Core/Naming) is the one naming context and unique-name rule of a frame:
  imports, uploads and Reorganize now produce identical names (behaviour of the ingest and
  the import planner unchanged).
- RenamePlanner takes a file template: each step counts its renamed frames, shows the first
  three and the frames version they were planned at, and lists what keeps its name (photos
  in place outside originals/, never hashed, missing, unreadable sidecar). Names are given
  in index order with _2, _3 as filing does; XMP companions follow their photo.
- MassRenamer renames a step's files under the same leases after its folder moved, checks
  the frames version, journals .chronos/rename-files.json and moves files in two phases
  through temporary names so chains and swaps never meet; then sidecar, index
  (FrameRepository.RenameFilesAsync, both dialects) and journal. A failure puts every file
  back; a crash is completed by the next writer or the plan's resume, the index following.
  Plans a paused or cancelled job holds are left to that job.
- JobKind.Move gets MoveJobHandler: it plans again and applies only the confirmed plan
  (fingerprint and frames versions), with progress and checkpoints per sequence.
- POST /api/v1/archive/reorganize: dry run with the plan and its fingerprint, otherwise a
  202 move job; validated templates, audited, sequenceChanged reorganized events.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit aae1c3eb18ea932b4a6251c5e2a282b9295a5785)
This commit is contained in:
Alby96 committed 2026-10-27 14:03:36 +01:00
1 parent 81cf58227d
commit eb2395d9b0
36 files changed
+2238 -164

No files matched your search

@@ -16,6 +16,7 @@ namespace Chronos.Core.Archiving;
[JsonSerializable(typeof(IngestJournal))]
[JsonSerializable(typeof(FrameRemovalJournal))]
[JsonSerializable(typeof(RenameJournal))]
[JsonSerializable(typeof(FileRenameJournal))]
internal sealed partial class ArchiveJson : JsonSerializerContext;
/// <summary>Indented output for the small files people may open (<c>archive.json</c>, rename journals).</summary>
@@ -36,6 +36,9 @@ public static class ArchiveLayout
/// <summary>Moves of photos restored from the trash that were started but not yet settled in <see cref="SequenceManifestFile"/> and the trash record.</summary>
public const string RestoreJournalFile = "restore.pending.json";
/// <summary>File renames of a Reorganize that were started but not yet recorded in <see cref="SequenceManifestFile"/> and the index.</summary>
public const string FileRenameJournalFile = "rename-files.json";
/// <summary>Folder names inside a sequence folder that never hold a sequence of their own.</summary>
public static bool IsReservedFolder(string name) =>
name.Equals(MetaFolder, StringComparison.OrdinalIgnoreCase)
@@ -104,6 +107,7 @@ public sealed class SequencePaths
public string IngestJournalPath => Path.Combine(MetaDirectory, ArchiveLayout.IngestJournalFile);
public string RemovalJournalPath => Path.Combine(MetaDirectory, ArchiveLayout.RemovalJournalFile);
public string RestoreJournalPath => Path.Combine(MetaDirectory, ArchiveLayout.RestoreJournalFile);
public string FileRenameJournalPath => Path.Combine(MetaDirectory, ArchiveLayout.FileRenameJournalFile);
public string Proxy(int index) => Path.Combine(Proxies, ArchiveLayout.ProxyFileName(index));
@@ -0,0 +1,190 @@
using System.Text.Json;
using Chronos.Core.Diagnostics;
using Chronos.Core.IO;
namespace Chronos.Core.Archiving;
/// <summary>One file of <see cref="FileRenameJournal"/>: its name, the temporary name it passes through and its new name, relative to the sequence folder.</summary>
public sealed record FileRenameEntry(Guid FrameId, string From, string Temp, string To, bool Companion = false);
/// <summary>
/// Write-ahead record of the file renames of one sequence (<c>.chronos/rename-files.json</c>, Reorganize, owner review 2, R7):
/// the sidecar's frames version they were planned at and every file with its old, temporary and new name. The files move
/// in two phases, every file to its temporary name (<see cref="Phase"/> 1) and then every file to its new name (phase 2), so
/// chains such as A→B, B→C and swaps never meet a name another file still holds; nothing is ever written over. The journal
/// is written before the first move and goes once the sidecar and the index name the new files, so a crash in between is
/// completed by <see cref="Recover"/> (which a writer runs under the sequence's lease, <c>SequenceWriter.ReadLocked</c>):
/// files still at their old name go on to their new one, those at their temporary name too, and the sidecar follows. A
/// failure while the files move (a file open elsewhere) puts every file back instead (<see cref="Run"/>).
/// </summary>
/// <param name="FramesVersion">The sidecar's frames version before the renames; the sidecar written after them has the next.</param>
/// <param name="Phase">1 while files go to their temporary names, 2 while they go to their new names.</param>
public sealed record FileRenameJournal(int FramesVersion, int Phase, IReadOnlyList<FileRenameEntry> Files)
{
private const string TempPrefix = ".chronos-rename-";
/// <summary>
/// The journal of <paramref name="moves"/> (<see cref="FileRenames.Plan"/>) at <paramref name="framesVersion"/>, each file
/// with a temporary name beside it: hidden, of no photo format, unique to this rename (<paramref name="token"/>).
/// </summary>
public static FileRenameJournal Create(int framesVersion, IReadOnlyList<FileRename> moves, string token)
{
ArgumentNullException.ThrowIfNull(moves);
ArgumentException.ThrowIfNullOrWhiteSpace(token);
var files = new List<FileRenameEntry>(moves.Count);
for (var i = 0; i < moves.Count; i++)
{
var move = moves[i];
var directory = move.From[..(move.From.LastIndexOf('/') + 1)];
files.Add(new FileRenameEntry(move.FrameId, move.From, $"{directory}{TempPrefix}{token}-{i:D6}.tmp", move.To, move.Companion));
}
return new FileRenameJournal(framesVersion, 1, files);
}
public static void Write(SequencePaths sequence, FileRenameJournal journal)
{
ArgumentNullException.ThrowIfNull(sequence);
Directory.CreateDirectory(sequence.MetaDirectory);
AtomicFile.WriteAllBytes(sequence.FileRenameJournalPath, JsonSerializer.SerializeToUtf8Bytes(journal, ArchiveJson.Default.FileRenameJournal));
}
/// <summary>The journal of the sequence; null when there is none, or it was torn while first written (nothing had moved).</summary>
public static FileRenameJournal? Read(SequencePaths sequence)
{
ArgumentNullException.ThrowIfNull(sequence);
if (!File.Exists(sequence.FileRenameJournalPath)) return null;
try
{
return JsonSerializer.Deserialize(AtomicFile.ReadAllBytes(sequence.FileRenameJournalPath), ArchiveJson.Default.FileRenameJournal);
}
catch (JsonException)
{
return null;
}
}
public static void Delete(SequencePaths sequence)
{
ArgumentNullException.ThrowIfNull(sequence);
if (File.Exists(sequence.FileRenameJournalPath)) File.Delete(sequence.FileRenameJournalPath);
}
/// <summary>
/// Moves the files of a journal just written (<see cref="Write"/>): every file to its temporary name, the journal at
/// phase 2, every file to its new name. On a failure every file goes back to its old name, the journal goes, and the
/// failure is thrown: nothing changed. When even that fails the journal stays, and <see cref="Recover"/> completes the
/// renames later. The caller holds the sequence's lease.
/// </summary>
/// <exception cref="IOException">A file could not be moved (open elsewhere, or a name taken meanwhile); nothing changed.</exception>
public static FileRenameJournal Run(SequencePaths sequence, FileRenameJournal journal)
{
ArgumentNullException.ThrowIfNull(sequence);
ArgumentNullException.ThrowIfNull(journal);
var done = 0;
var phase = 1;
try
{
foreach (var file in journal.Files)
{
Move(sequence, file.From, file.Temp);
done++;
}
journal = journal with { Phase = 2 };
Write(sequence, journal);
phase = 2;
done = 0;
foreach (var file in journal.Files)
{
Move(sequence, file.Temp, file.To);
done++;
}
return journal;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("archive", $"Renaming the files of {sequence.RelativeFolder} failed; they go back to their names", ex);
if (Undo(sequence, journal, phase, done)) Delete(sequence);
throw;
}
}
/// <summary>
/// Completes a rename a crash interrupted (the caller holds the sequence's lease): the files go on to their new names,
/// and <paramref name="manifest"/> names them (<see cref="Applied"/>), unless it does already. Returns
/// the sidecar to write, or null when it is right as it is; the journal is left in place, <see cref="Delete"/> it once
/// the result is written. A file found nowhere is logged, and its frame names the new file all the same (a verify then
/// flags it missing, as it would have at its old name).
/// </summary>
public static SequenceManifest? Recover(SequencePaths sequence, SequenceManifest manifest)
{
ArgumentNullException.ThrowIfNull(sequence);
ArgumentNullException.ThrowIfNull(manifest);
if (Read(sequence) is not { } journal) return null;
foreach (var file in journal.Files)
{
// In phase 2 no file is at its old name any more: what is there now came since, and stays.
if (journal.Phase == 1 && Exists(sequence, file.From) && !Exists(sequence, file.Temp)) Move(sequence, file.From, file.Temp);
}
foreach (var file in journal.Files)
{
if (Exists(sequence, file.Temp) && !Exists(sequence, file.To)) Move(sequence, file.Temp, file.To);
else if (!Exists(sequence, file.To)) Log.Warning("archive", $"{sequence.ArchiveRelative(file.To)} was not found after an interrupted rename");
}
Log.Warning("archive", $"An interrupted rename of the files of {sequence.RelativeFolder} was completed");
return Applied(manifest, journal);
}
/// <summary>
/// <paramref name="manifest"/> naming the new files of <paramref name="journal"/> (frame order unchanged) one frames
/// version further; null when no frame names an old file any more (the sidecar was written already).
/// </summary>
public static SequenceManifest? Applied(SequenceManifest manifest, FileRenameJournal journal)
{
ArgumentNullException.ThrowIfNull(manifest);
ArgumentNullException.ThrowIfNull(journal);
var renamed = journal.Files.Where(f => !f.Companion).ToDictionary(f => f.FrameId, f => f);
var changed = false;
var frames = manifest.Frames.Select(f =>
{
if (!renamed.TryGetValue(f.Id, out var file) || !string.Equals(f.File, file.From, StringComparison.Ordinal)) return f;
changed = true;
return f with { File = file.To };
}).ToList();
if (!changed) return null;
return manifest with
{
Frames = frames,
Versions = manifest.Versions with { Frames = manifest.Versions.Frames + 1 },
UpdatedAt = DateTimeOffset.UtcNow,
};
}
/// <summary>
/// Puts the files back after a failure in <paramref name="phase"/> once <paramref name="done"/> of its moves were made;
/// false when one could not go back. Once every file is at its temporary name again the journal says phase 1, so a
/// failure from there on leaves a journal that completes the renames instead.
/// </summary>
private static bool Undo(SequencePaths sequence, FileRenameJournal journal, int phase, int done)
{
try
{
if (phase == 2)
{
for (var i = done - 1; i >= 0; i--) Move(sequence, journal.Files[i].To, journal.Files[i].Temp);
Write(sequence, journal with { Phase = 1 });
done = journal.Files.Count;
}
for (var i = done - 1; i >= 0; i--) Move(sequence, journal.Files[i].Temp, journal.Files[i].From);
return true;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Error("archive", $"The files of {sequence.RelativeFolder} could not all go back after a failed rename; the journal completes it later", ex);
return false;
}
}
private static bool Exists(SequencePaths sequence, string file) => File.Exists(sequence.File(file));
private static void Move(SequencePaths sequence, string from, string to) => File.Move(sequence.File(from), sequence.File(to), overwrite: false);
}
+140
View File
@@ -0,0 +1,140 @@
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>
public enum RenameBlock
{
/// <summary>Photos adopted in place, outside <c>originals/</c>: they belong to a tree someone else keeps.</summary>
InPlace,
/// <summary>Photos whose SHA-256 is not known yet (never verified): a verify hashes them first.</summary>
Unhashed,
/// <summary>Photos whose file is not there.</summary>
Missing,
/// <summary>The sequence's sidecar cannot be read, or belongs to another sequence.</summary>
Unreadable,
}
/// <summary>Frames of a sequence that keep their names, and why.</summary>
public sealed record RenameBlocked(RenameBlock Reason, int Frames);
/// <summary>
/// One file of a Reorganize: a frame's photo, or a companion that follows it (<see cref="Companion"/>), from its name to its
/// new one; both relative to the sequence folder, forward slashes.
/// </summary>
public sealed record FileRename(Guid FrameId, string From, string To, bool Companion = false);
/// <summary>
/// The file renames of one sequence: every move, companions included, in frame order; how many frames get a new name; the
/// first of them (<see cref="FileRenames.SampleCount"/>) as samples; and the frames that keep their names.
/// </summary>
public sealed record FileRenamePlan(IReadOnlyList<FileRename> Moves, int Frames, IReadOnlyList<FileRename> Samples, IReadOnlyList<RenameBlocked> Blocked)
{
public static FileRenamePlan None { get; } = new([], 0, [], []);
}
/// <summary>
/// Plans the new file names of a sequence's frames from a file template (Reorganize, owner review 2, R7; BRIEF §7.1, §12.5).
/// Frames are named in index order exactly as filing names them (<see cref="FrameNaming"/>); a name already given, or held
/// by a file that stays (a frame left alone, a file no frame lists), gets <c>_2</c>, <c>_3</c>… as filing does, so the same
/// frames, template and folder always give the same names. Only photos under <c>originals/</c> whose SHA-256 is known and
/// whose file is there are renamed, each within its folder; the XMP companions of a photo follow it
/// (<see cref="FrameCompanions"/>; one named by a stem two frames share follows the first). The sidecar's frame order never
/// changes.
/// </summary>
public static class FileRenames
{
/// <summary>Renamed frames a plan shows as samples.</summary>
public const int SampleCount = 3;
private const string Originals = ArchiveLayout.OriginalsFolder + "/";
/// <param name="title">The sequence title the names use (<c>{title}</c>): the new one when the same Reorganize retitles it.</param>
/// <param name="present">Every file in the folders of the sequence's frames, relative to the sequence folder (<see cref="ListPresent"/>).</param>
public static FileRenamePlan Plan(SequenceManifest manifest, string? title, PathTemplate template, IReadOnlyCollection<string> present)
{
ArgumentNullException.ThrowIfNull(manifest);
ArgumentNullException.ThrowIfNull(template);
ArgumentNullException.ThrowIfNull(present);
var onDisk = new HashSet<string>(present, StringComparer.OrdinalIgnoreCase);
int inPlace = 0, unhashed = 0, missing = 0;
var eligible = new List<SidecarFrame>();
// Companions are claimed in frame order by every frame, renamed or not: one a frame left alone claims stays with it.
var claimed = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var companions = new Dictionary<Guid, List<string>>();
// By the name they give without ".xmp": a photo's path without its extension, or its whole path.
var xmp = onDisk.Where(f => f.EndsWith(FrameCompanions.Extension, StringComparison.OrdinalIgnoreCase))
.ToLookup(f => f[..^FrameCompanions.Extension.Length], StringComparer.OrdinalIgnoreCase);
foreach (var frame in manifest.Frames)
{
var own = xmp[Stem(frame.File)].Concat(xmp[frame.File]).Distinct(StringComparer.OrdinalIgnoreCase).Order(StringComparer.Ordinal)
.Where(c => FrameCompanions.Names(c, frame.File) && claimed.Add(c)).ToList();
if (!frame.File.StartsWith(Originals, StringComparison.OrdinalIgnoreCase)) inPlace++;
else if (frame.Sha256 is null) unhashed++;
else if (!onDisk.Contains(frame.File)) missing++;
else
{
eligible.Add(frame);
companions[frame.Id] = own;
}
}
// What stays where it is: files no renamed frame or companion moves away from, and every frame left alone.
var moving = new HashSet<string>(eligible.Select(f => f.File).Concat(companions.Values.SelectMany(c => c)), StringComparer.OrdinalIgnoreCase);
var taken = new HashSet<string>(onDisk.Where(f => !moving.Contains(f)), StringComparer.OrdinalIgnoreCase);
foreach (var frame in manifest.Frames.Where(f => !companions.ContainsKey(f.Id))) taken.Add(frame.File);
var moves = new List<FileRename>();
var samples = new List<FileRename>();
var renamed = 0;
foreach (var frame in eligible)
{
var own = companions[frame.Id];
var tails = own.ConvertAll(c => FrameCompanions.Tail(c, frame.File));
var directory = frame.File[..(frame.File.LastIndexOf('/') + 1)];
var file = FrameNaming.FileName(template, FrameNaming.Context(frame, manifest, title),
candidate => !taken.Contains(candidate) && tails.TrueForAll(t => !taken.Contains(Stem(candidate) + t)), directory);
taken.Add(file);
foreach (var tail in tails) taken.Add(Stem(file) + tail);
if (string.Equals(file, frame.File, StringComparison.Ordinal)) continue;
var move = new FileRename(frame.Id, frame.File, file);
moves.Add(move);
if (samples.Count < SampleCount) samples.Add(move);
renamed++;
for (var c = 0; c < own.Count; c++)
{
var to = Stem(file) + tails[c];
if (!string.Equals(to, own[c], StringComparison.Ordinal)) moves.Add(new FileRename(frame.Id, own[c], to, Companion: true));
}
}
var blocked = new List<RenameBlocked>();
if (inPlace > 0) blocked.Add(new RenameBlocked(RenameBlock.InPlace, inPlace));
if (unhashed > 0) blocked.Add(new RenameBlocked(RenameBlock.Unhashed, unhashed));
if (missing > 0) blocked.Add(new RenameBlocked(RenameBlock.Missing, missing));
return new FileRenamePlan(moves, renamed, samples, blocked);
}
/// <summary>
/// Every file in the folders that hold the sequence's frames (<c>originals/</c> as a rule), relative to the sequence
/// folder; hidden files included, so no name a file holds is ever given.
/// </summary>
public static IReadOnlyList<string> ListPresent(SequencePaths sequence, SequenceManifest manifest)
{
ArgumentNullException.ThrowIfNull(sequence);
ArgumentNullException.ThrowIfNull(manifest);
var files = new List<string>();
foreach (var prefix in manifest.Frames.Select(f => f.File[..(f.File.LastIndexOf('/') + 1)]).Distinct(StringComparer.OrdinalIgnoreCase))
{
var directory = prefix.Length == 0 ? sequence.Folder : sequence.File(prefix.TrimEnd('/'));
// Listed as the trash lists companions (FrameCompanions), so both find the same XMP files.
files.AddRange(FrameCompanions.List(directory).Select(n => prefix + n));
}
return files;
}
/// <summary>A file's path without its extension (<c>originals/2026-09-28_0001</c>).</summary>
private static string Stem(string file) => file[..^Path.GetExtension(file).Length];
}
@@ -0,0 +1,83 @@
namespace Chronos.Core.Archiving;
/// <summary>
/// The XMP companions of a photo (<c>IMG_0001.xmp</c> or <c>IMG_0001.CR2.xmp</c> beside <c>IMG_0001.CR2</c>): files that go
/// where their photo goes, into the trash with it (owner review 2, R6) and to its new name when Reorganize renames it (R7).
/// One rule for both: an XMP file in the photo's folder named after its stem or its whole name, whatever their case, on
/// every system (<c>IMG_0001.XMP</c> too), hidden files included.
/// </summary>
public static class FrameCompanions
{
/// <summary>The extension of a companion.</summary>
public const string Extension = ".xmp";
/// <summary>Listing of a photo folder: case-insensitive on every system, nothing skipped.</summary>
private static readonly EnumerationOptions Listing = new() { MatchCasing = MatchCasing.CaseInsensitive, AttributesToSkip = 0 };
/// <summary>The companions beside <paramref name="file"/> (relative to the sequence folder), relative to the sequence folder.</summary>
public static IEnumerable<string> Of(SequencePaths folder, string file) => new Index(folder).Of(file);
/// <summary>
/// Whether <paramref name="companion"/> is a companion of <paramref name="file"/> (both relative to the sequence folder):
/// an XMP file in the same folder named after the photo's stem or after its whole name, whatever their case.
/// </summary>
public static bool Names(string companion, string file)
{
ArgumentNullException.ThrowIfNull(companion);
ArgumentNullException.ThrowIfNull(file);
if (!Prefix(companion).Equals(Prefix(file), StringComparison.OrdinalIgnoreCase)) return false;
var name = Path.GetFileName(companion);
if (!Path.GetExtension(name).Equals(Extension, StringComparison.OrdinalIgnoreCase)) return false;
var named = Path.GetFileNameWithoutExtension(name);
var photo = Path.GetFileName(file);
return named.Equals(Path.GetFileNameWithoutExtension(photo), StringComparison.OrdinalIgnoreCase)
|| named.Equals(photo, StringComparison.OrdinalIgnoreCase);
}
/// <summary>What a companion's name adds to its photo's stem (<c>.xmp</c>, <c>.CR2.xmp</c>).</summary>
public static string Tail(string companion, string photo)
{
ArgumentNullException.ThrowIfNull(companion);
ArgumentNullException.ThrowIfNull(photo);
var stem = Path.GetFileNameWithoutExtension(Path.GetFileName(photo));
var name = Path.GetFileName(companion);
return name.StartsWith(stem, StringComparison.OrdinalIgnoreCase) ? name[stem.Length..] : Path.GetExtension(name);
}
/// <summary>
/// Every file in <paramref name="directory"/> (absolute), by name, hidden ones included: what <see cref="Names"/> is
/// asked about, and every name a file holds there.
/// </summary>
public static IEnumerable<string> List(string directory) =>
Directory.Exists(directory) ? Directory.EnumerateFiles(directory, "*", Listing).Select(p => Path.GetFileName(p)) : [];
/// <summary>The folder part of a sequence-relative path with its trailing '/', or empty.</summary>
private static string Prefix(string file) => file.Contains('/') ? file[..(file.LastIndexOf('/') + 1)] : string.Empty;
/// <summary>
/// The XMP files of a sequence's photo folders, each folder listed once (a deletion of thousands of photos does not list
/// it again for each), matched by <see cref="Names"/>.
/// </summary>
public sealed class Index(SequencePaths folder)
{
private readonly Dictionary<string, ILookup<string, string>> _directories = new(StringComparer.Ordinal);
/// <summary>The companions beside <paramref name="file"/> (relative to the sequence folder), relative to the sequence folder.</summary>
public IEnumerable<string> Of(string file)
{
ArgumentNullException.ThrowIfNull(file);
var prefix = Prefix(file);
if (!_directories.TryGetValue(prefix, out var named))
{
named = List(Path.GetDirectoryName(folder.File(file))!)
.Where(n => Path.GetExtension(n).Equals(Extension, StringComparison.OrdinalIgnoreCase))
.ToLookup(n => Path.GetFileNameWithoutExtension(n), StringComparer.OrdinalIgnoreCase);
_directories[prefix] = named;
}
var name = Path.GetFileName(file);
var stem = Path.GetFileNameWithoutExtension(name);
var matches = stem.Equals(name, StringComparison.OrdinalIgnoreCase) ? named[stem] : named[stem].Concat(named[name]);
return matches.Select(n => prefix + n).Where(c => Names(c, file));
}
}
}
+148 -13
View File
@@ -1,4 +1,6 @@
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Chronos.Core.IO;
using Chronos.Core.Localization;
@@ -7,13 +9,93 @@ using Chronos.Core.Naming;
namespace Chronos.Core.Archiving;
/// <summary>What the planner needs to know about a sequence to rename it.</summary>
public sealed record RenameSubject(Guid SequenceId, string Folder, string? Title, DateTime? FirstCapture, string? CameraMake, string? CameraModel, string? Lens);
public sealed record RenameSubject(Guid SequenceId, string Folder, string? Title, DateTime? FirstCapture, string? CameraMake, string? CameraModel, string? Lens)
{
/// <summary>The sidecar and the files beside its frames, which a file template renames; null when they cannot be read.</summary>
public SequenceFiles? Files { get; init; }
}
/// <summary>One sequence's change: its folder, its title, or both.</summary>
/// <summary>A sequence's sidecar as read for a plan, and every file in the folders of its frames (<see cref="FileRenames.ListPresent"/>).</summary>
public sealed record SequenceFiles(SequenceManifest Manifest, IReadOnlyCollection<string> Present);
/// <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"/>).
/// </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)
{
public bool MovesFolder => !string.Equals(FromFolder, ToFolder, StringComparison.Ordinal);
public bool Retitles => !string.Equals(FromTitle, ToTitle, StringComparison.Ordinal);
/// <summary>Whether applying the step changes anything: the folder, the title or file names.</summary>
public bool Changes => MovesFolder || Retitles || FileChanges > 0;
/// <summary>The sidecar's frames version the file names were planned at; 0 when no file gets a new name.</summary>
public int FramesVersion { get; init; }
/// <summary>Frames whose file gets a new name (their companions follow them).</summary>
public int FileChanges { get; init; }
/// <summary>The first renamed frames (<see cref="FileRenames.SampleCount"/>), old and new name relative to the sequence folder.</summary>
public IReadOnlyList<FileRename> FileSamples { get; init; } = [];
/// <summary>Frames that keep their file names, and why.</summary>
public IReadOnlyList<RenameBlocked> Blocked { get; init; } = [];
}
/// <summary>
/// The templates of a Reorganize (owner review 2, R7): the folder (<c>{title}</c> = the new title), the file names and the
/// title (<c>{title}</c> = the current title); null leaves that part as it is.
/// </summary>
public sealed record RenameTemplates(string? Folder = null, string? File = null, string? Title = null)
{
private static readonly NamingContext Sample = new()
{
CapturedAt = new DateTime(2026, 9, 28, 18, 2, 11),
SessionStart = new DateTime(2026, 9, 28, 18, 2, 11),
CameraMake = "Canon",
CameraModel = "Canon EOS R5",
Lens = "RF15-35mm F2.8 L IS USM",
Iso = 100,
ExposureTime = 1.0 / 250,
FNumber = 8,
OriginalName = "IMG_4211",
Extension = "CR2",
Title = "Sunset",
};
public bool IsEmpty => Folder is null && File is null && Title is null;
/// <summary>
/// The first template that cannot be used, by its API name (<c>folderTemplate</c>, <c>fileTemplate</c>,
/// <c>titleTemplate</c>): blank, not valid as the archive settings' templates (<see cref="PathTemplate.IsValid"/>), or
/// with a format a sample cannot be written with (<c>{date:%}</c>); null when every one given can.
/// </summary>
public string? Problem()
{
if (Unusable(Folder, t => t.ExpandFolder(Sample))) return "folderTemplate";
if (Unusable(File, t => t.ExpandFile(Sample))) return "fileTemplate";
if (Unusable(Title, t => t.ExpandFile(Sample))) return "titleTemplate";
return null;
}
private static bool Unusable(string? template, Func<PathTemplate, string> expand)
{
if (template is null) return false;
if (string.IsNullOrWhiteSpace(template)) return true;
var parsed = PathTemplate.Parse(template);
if (!parsed.IsValid) return true;
try
{
return expand(parsed).Length == 0;
}
catch (FormatException)
{
return true;
}
}
}
/// <summary>A planned folder would lie inside a sequence's folder (nesting one sequence in another); nothing is planned.</summary>
@@ -25,10 +107,36 @@ public sealed class NestedRenameException(string target, string folder)
}
/// <summary>The exact changes a mass rename will make (its dry run); applying it makes exactly these.</summary>
public sealed record RenamePlan(Guid Id, Guid ArchiveId, IReadOnlyList<RenameStep> Steps);
public sealed record RenamePlan(Guid Id, Guid ArchiveId, IReadOnlyList<RenameStep> Steps)
{
/// <summary>The file template the steps' file names come from; null when files keep their names.</summary>
public string? FileTemplate { get; init; }
/// <summary>The sequences the plan was made for, in the order they were given (the order that decides which new folder gets " (2)").</summary>
public IReadOnlyList<Guid> Subjects { get; init; } = [];
/// <summary>
/// A digest of what the plan changes (its steps in order, as a dry run shows them, and the file template), the same for
/// two plans of the same archive state: what a confirmation sends back so the change made is the one that was shown.
/// </summary>
public string Fingerprint()
{
var text = new StringBuilder(FileTemplate).Append('\n');
foreach (var s in Steps)
{
text.Append(CultureInfo.InvariantCulture, $"{s.SequenceId:N}|{s.FromFolder}|{s.ToFolder}|{s.FromTitle}|{s.ToTitle}|{s.Carried}|{s.FramesVersion}|{s.FileChanges}|");
foreach (var sample in s.FileSamples) text.Append(sample.From).Append('>').Append(sample.To).Append(';');
foreach (var blocked in s.Blocked) text.Append(CultureInfo.InvariantCulture, $"{blocked.Reason}:{blocked.Frames};");
text.Append('\n');
}
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text.ToString())));
}
}
/// <summary>A plan being applied, with the steps already completed; lets an interrupted rename resume (BRIEF §7).</summary>
public sealed record RenameJournal(RenamePlan Plan, IReadOnlyList<Guid> Completed)
/// <param name="Held">The job applying the plan was paused or cancelled between two steps: an archive open leaves the plan to
/// that job, which completes it when it runs again.</param>
public sealed record RenameJournal(RenamePlan Plan, IReadOnlyList<Guid> Completed, bool Held = false)
{
public static string PathFor(ArchivePaths archive, Guid planId) => Path.Combine(archive.JournalDirectory, $"rename-{planId:N}.json");
@@ -38,7 +146,7 @@ public sealed record RenameJournal(RenamePlan Plan, IReadOnlyList<Guid> Complete
AtomicFile.WriteAllBytes(PathFor(archive, journal.Plan.Id), JsonSerializer.SerializeToUtf8Bytes(journal, ArchiveJsonIndented.Default.RenameJournal));
}
/// <summary>Journals left by interrupted renames.</summary>
/// <summary>Journals left by interrupted renames, held ones included.</summary>
public static IReadOnlyList<RenameJournal> ListPending(ArchivePaths archive)
{
if (!Directory.Exists(archive.JournalDirectory)) return [];
@@ -50,28 +158,40 @@ public sealed record RenameJournal(RenamePlan Plan, IReadOnlyList<Guid> Complete
return list;
}
/// <summary>The journal of the plan <paramref name="planId"/>; null when there is none (the plan completed, or never started).</summary>
public static RenameJournal? Read(ArchivePaths archive, Guid planId)
{
var path = PathFor(archive, planId);
return File.Exists(path) ? JsonSerializer.Deserialize(File.ReadAllBytes(path), ArchiveJson.Default.RenameJournal) : null;
}
public static void Delete(ArchivePaths archive, Guid planId) => File.Delete(PathFor(archive, planId));
}
/// <summary>Builds rename plans from folder/title templates (BRIEF §7.1, §12.5).</summary>
/// <summary>Builds rename plans from folder, title and file templates (BRIEF §7.1, §12.5; Reorganize, owner review 2, R7).</summary>
public static class RenamePlanner
{
/// <summary>
/// Expands <paramref name="titleTemplate"/> (where <c>{title}</c> is the current title) and then
/// <paramref name="folderTemplate"/> (where <c>{title}</c> is the new title) for every subject. A target folder
/// that is any current sequence folder, exists on disk or was given to an earlier subject gets " (2)", " (3)"….
/// Null templates leave that part unchanged; subjects without a change produce no step. A folder that moves takes
/// the sequences inside it along: each gets a <see cref="RenameStep.Carried"/> step after every move, so the index
/// follows its files; a selected sequence inside a moving folder that moves elsewhere leaves first.
/// 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 subject whose sidecar could not be read
/// (<see cref="RenameSubject.Files"/> null) keeps them all. Null templates leave that part unchanged; subjects without a
/// change produce no step, unless frames of theirs keep their names. A folder that moves takes the sequences inside
/// it along: each gets a <see cref="RenameStep.Carried"/> step after every move, so the index follows its files; a
/// selected sequence inside a moving folder that moves elsewhere leaves first.
/// </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>
/// <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)
IEnumerable<string> occupied, Func<string, bool> existsOnDisk, IReadOnlyList<RenameSubject>? nested = null, string? fileTemplate = null)
{
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);
var taken = occupied.ToList();
var claimed = new HashSet<string>(taken, StringComparer.OrdinalIgnoreCase);
var own = new List<RenameStep>(subjects.Count);
@@ -95,7 +215,8 @@ public static class RenamePlanner
newFolder = expanded.Equals(s.Folder, StringComparison.OrdinalIgnoreCase) ? expanded : Unique(expanded, claimed, existsOnDisk);
claimed.Add(newFolder);
}
own.Add(new RenameStep(s.SequenceId, s.Folder, newFolder, s.Title, newTitle));
var step = new RenameStep(s.SequenceId, s.Folder, newFolder, s.Title, newTitle);
own.Add(file is null ? step : WithFiles(step, s.Files, file, newTitle));
}
var moving = own.Where(s => s.MovesFolder).ToList();
@@ -114,11 +235,25 @@ public static class RenamePlanner
steps.Add((step with { ToFolder = carrier.ToFolder + step.FromFolder[carrier.FromFolder.Length..], Carried = true }, 1));
else if (step.MovesFolder)
steps.Add((step, -moving.Count(m => m != step && IsInside(m.FromFolder, step.FromFolder))));
else if (step.FromTitle != step.ToTitle)
else if (step.Retitles || step.FileChanges > 0 || step.Blocked.Count > 0)
steps.Add((step, 0));
}
// Stable: subjects keep their order, sequences inside moving folders move out first, carried ones come last.
return new RenamePlan(Guid.CreateVersion7(), archiveId, [.. steps.OrderBy(s => s.Order).Select(s => s.Step)]);
return new RenamePlan(Guid.CreateVersion7(), archiveId, [.. steps.OrderBy(s => s.Order).Select(s => s.Step)]) { FileTemplate = fileTemplate, Subjects = [.. subjects.Select(s => s.SequenceId)] };
}
/// <summary>The step with the file renames of its sequence (<see cref="FileRenames.Plan"/>), or all its frames kept when its sidecar could not be read.</summary>
private static RenameStep WithFiles(RenameStep step, SequenceFiles? files, PathTemplate template, string? title)
{
if (files is null) return step with { Blocked = [new RenameBlocked(RenameBlock.Unreadable, 0)] };
var plan = FileRenames.Plan(files.Manifest, title, template, files.Present);
return step with
{
FramesVersion = plan.Frames > 0 ? files.Manifest.Versions.Frames : 0,
FileChanges = plan.Frames,
FileSamples = plan.Samples,
Blocked = plan.Blocked,
};
}
/// <summary>