Files
Chronos/src/Chronos.Core/Archiving/FileRenames.cs
T
Alby96andClaude Opus 5.5 7e4a3b481d
CI / Build and test (push) Successful in 9m15s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 15m35s
CI / PostgreSQL 16 integration (push) Successful in 7m26s
CI / PostgreSQL 17 integration (push) Successful in 6m47s
CI / Docker image (push) Successful in 59s
Release / Server image (push) Successful in 1m24s
feat: owner review 2 phase 4a: Reorganize sequences after import (#12)
- Reorganize… on the web panel and the desktop: folder, file and title templates applied to existing sequences, with a dry run and an explicit Apply that runs as a job.
- One naming rule (FrameNaming) for import, upload and Reorganize.
- Crash-safe plan and file journals, held plans, stale-plan refusal; exports move with their folder.
- Writers refuse a folder another program moved or gave to another sequence.
- Server: POST /api/v1/archive/reorganize with a bounded plan cache; template rules.
- Phase 3 docs and translations merged; strings in all 38 languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
2026-10-27 21:58:39 +01:00

162 lines
8.7 KiB
C#

using System.Globalization;
using System.Security.Cryptography;
using System.Text;
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 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>
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, 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,
}
/// <summary>
/// Frames of a sequence that keep their names, and why; or, for <see cref="RenameBlock.Unreadable"/> (0 frames), why the
/// whole sequence stays as it is.
/// </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>A digest of every move in order (frame, old and new name, companion or not): two plans with the same one rename the same files the same way.</summary>
public string Digest()
{
var text = new StringBuilder();
foreach (var move in Moves) text.Append(CultureInfo.InvariantCulture, $"{move.FrameId:N}|{move.From}|{move.To}|{move.Companion}\n");
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text.ToString())));
}
}
/// <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 with the context an upload in capture order is filed with (<see cref="FrameNaming"/>,
/// which says where filing gave other names); 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;
var names = new UniqueNames(taken);
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 = names.Claim(directory + template.ExpandFile(FrameNaming.Context(frame, manifest, title)),
candidate => tails.TrueForAll(t => !taken.Contains(Stem(candidate) + t)));
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];
}