using System.Globalization; using System.Security.Cryptography; using System.Text; using System.Text.Json; using Chronos.Core.IO; using Chronos.Core.Localization; using Chronos.Core.Naming; namespace Chronos.Core.Archiving; /// /// What the planner needs to know about a sequence to rename it. Without its sidecar () the templates see /// the index row's capture time, camera and lens, and a sequence without a capture time keeps its folder and title. /// public sealed record RenameSubject(Guid SequenceId, string Folder, string? Title, DateTime? FirstCapture, string? CameraMake, string? CameraModel, string? Lens) { /// /// The sidecar, whose first frame the folder and title templates see as filing saw it, and the files beside its frames, /// which a file template renames (empty without one); null when it was not read, or could not be. /// public SequenceFiles? Files { get; init; } /// /// The sidecar could not be read, or belongs to another sequence: the sequence stays as it is, and so does every folder /// it is inside, which could not take it along (). /// public bool Unreadable { get; init; } } /// A sequence's sidecar as read for a plan, and every file in the folders of its frames (). public sealed record SequenceFiles(SequenceManifest Manifest, IReadOnlyCollection Present); /// /// 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 (). /// /// 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) { public bool MovesFolder => !string.Equals(FromFolder, ToFolder, StringComparison.Ordinal); public bool Retitles => !string.Equals(FromTitle, ToTitle, StringComparison.Ordinal); /// Whether applying the step changes anything: the folder, the title or file names. public bool Changes => MovesFolder || Retitles || FileChanges > 0; /// /// The new folder or file names come from the sequence's title (the folder or file template uses {title}): a title /// edited since the plan would leave them named after the old one. /// public bool NamedByTitle { get; init; } /// Whether what the step changes depends on the sequence's title: it changes it, or names the folder or files after it. public bool UsesTitle => Retitles || NamedByTitle; /// /// The sidecar's frames version the file names were planned at; 0 when no file gets a new name. What the apply checks the /// files by only in a plan journaled without . /// public int FramesVersion { get; init; } /// Frames whose file gets a new name (their companions follow them). public int FileChanges { get; init; } /// The first renamed frames (), old and new name relative to the sequence folder. public IReadOnlyList FileSamples { get; init; } = []; /// /// Every file rename of the step, as a digest (): the apply renames the files only /// while they plan to exactly these. Null when no file gets a new name (or in a plan journaled before it existed). /// public string? FileDigest { get; init; } /// Frames that keep their file names, and why. public IReadOnlyList Blocked { get; init; } = []; } /// /// The templates of a Reorganize (owner review 2, R7): the folder ({title} = the new title), the file names and the /// title ({title} = the current title); null leaves that part as it is. /// public sealed record RenameTemplates(string? Folder = null, string? File = null, string? Title = null) { private static readonly NamingContext Sample = TemplateRules.Sample()[0]; public bool IsEmpty => Folder is null && File is null && Title is null; /// /// The first template that cannot be used, by its API name (folderTemplate, fileTemplate, /// 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. /// 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; } private static bool Unusable(string? template, Func expand, Func? rule = null) { 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 || rule?.Invoke(parsed) is not null; } catch (FormatException) { return true; } } } /// 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)) { public string Target { get; } = target; public string Folder { get; } = folder; } /// The exact changes a mass rename will make (its dry run); applying it makes exactly these. public sealed record RenamePlan(Guid Id, Guid ArchiveId, IReadOnlyList Steps) { /// The file template the steps' file names come from; null when files keep their names. public string? FileTemplate { get; init; } /// The sequences the plan was made for, in the order they were given (the order that decides which new folder gets " (2)"). public IReadOnlyList Subjects { get; init; } = []; /// /// A digest of what the plan changes (its steps in order, as a dry run shows them, every file rename by its digest, 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. The frames version is not part of it: photos a sequence received since under the names /// the plan gives them (an upload filed with the same template) leave the plan as it was, and the apply renames the files /// only while they rename exactly as planned (). /// 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.FileChanges}|{s.FileDigest}|"); 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()))); } } /// /// What the completed steps of a plan did, over every run that applied them (): the /// sequences changed, the frames whose file got a new name, and the sequences not changed as planned: because they changed /// since, left as they were (), their file names kept () or their title and file /// names kept (); their file names kept because a photo was in use or a new name was taken /// (); their title and file names kept because a newer Chronos wrote their sidecar (). /// public sealed record RenameTally { public IReadOnlyList Changed { get; init; } = []; public int Files { get; init; } public IReadOnlyList Dropped { get; init; } = []; public IReadOnlyList FilesKept { get; init; } = []; public IReadOnlyList TitlesKept { get; init; } = []; public IReadOnlyList FilesBusy { get; init; } = []; public IReadOnlyList Newer { get; init; } = []; } /// A plan being applied, with the steps already completed; lets an interrupted rename resume (BRIEF §7). /// The job applying the plan was paused, cancelled or failed between two steps: an archive open leaves the /// plan to that job, which completes it when it is resumed or retried. public sealed record RenameJournal(RenamePlan Plan, IReadOnlyList Completed, bool Held = false) { /// What the completed steps did, so a resumed run reports the whole plan. public RenameTally Done { get; init; } = new(); public static string PathFor(ArchivePaths archive, Guid planId) => Path.Combine(archive.JournalDirectory, $"rename-{planId:N}.json"); public static void Write(ArchivePaths archive, RenameJournal journal) { Directory.CreateDirectory(archive.JournalDirectory); AtomicFile.WriteAllBytes(PathFor(archive, journal.Plan.Id), JsonSerializer.SerializeToUtf8Bytes(journal, ArchiveJsonIndented.Default.RenameJournal)); } /// Journals left by interrupted renames, held ones included. public static IReadOnlyList ListPending(ArchivePaths archive) { if (!Directory.Exists(archive.JournalDirectory)) return []; var list = new List(); foreach (var path in Directory.EnumerateFiles(archive.JournalDirectory, "rename-*.json").Order(StringComparer.Ordinal)) { if (JsonSerializer.Deserialize(File.ReadAllBytes(path), ArchiveJson.Default.RenameJournal) is { } journal) list.Add(journal); } return list; } /// The journal of the plan ; null when there is none (the plan completed, or never started). 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)); } /// Builds rename plans from folder, title and file templates (BRIEF §7.1, §12.5; Reorganize, owner review 2, R7). public static class RenamePlanner { /// /// Expands (where {title} is the current title) and then /// (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 /// 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 /// whose sidecar could not be read (, or no for a /// file template) stays as it is, listed with the reason, and so does the folder of every subject it is inside. 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 step after /// every move, so the index follows its files; a selected sequence inside a moving folder that moves elsewhere leaves first. /// /// Every sequence folder of the archive (renamed or not). /// The archive's other sequences inside a subject's folder, with their titles. /// 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) { 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); bool folderByTitle = folder?.Uses("title") == true, filesByTitle = file?.Uses("title") == true; var taken = occupied.ToList(); var claimed = new HashSet(taken, StringComparer.OrdinalIgnoreCase); // The folders given in this plan so far: Kept never gives one twice (two folders that differ only in case). var given = new HashSet(StringComparer.OrdinalIgnoreCase); bool Unreadable(RenameSubject s) => s.Unreadable || (file is not null && s.Files is null); // A folder that holds a sequence whose sidecar cannot be read cannot take it along. var stuck = subjects.Where(Unreadable).Concat((nested ?? []).Where(n => n.Unreadable)).ToList(); var blockers = new HashSet(); var own = new List(subjects.Count); foreach (var s in subjects) { if (Unreadable(s)) { own.Add(new RenameStep(s.SequenceId, s.Folder, s.Folder, s.Title, s.Title) { Blocked = [new RenameBlocked(RenameBlock.Unreadable, 0)] }); continue; } var context = Context(s); var newTitle = title is null || context is null ? s.Title : Blank(title.ExpandText(context)) ?? s.Title; var newFolder = s.Folder; // The archive root itself (a folder adopted in place) cannot move; only its title changes. if (folder is not null && context is not null && s.Folder.Length > 0 && Blank(folder.ExpandFolder(context with { Title = newTitle })) is { } expanded && !expanded.Equals(s.Folder, StringComparison.Ordinal)) { var inside = stuck.Where(u => IsInside(s.Folder, u.Folder)).Select(u => u.SequenceId).ToList(); if (inside.Count > 0) { blockers.UnionWith(inside); } else { newFolder = Kept(s.Folder, expanded, taken, given) ?? Unique(expanded, claimed, existsOnDisk); claimed.Add(newFolder); given.Add(newFolder); } } var step = new RenameStep(s.SequenceId, s.Folder, newFolder, s.Title, newTitle); if (file is not null) step = WithFiles(step, s.Files!, file, newTitle); own.Add(step with { NamedByTitle = (folderByTitle && step.MovesFolder) || (filesByTitle && step.FileChanges > 0) }); } var moving = own.Where(s => s.MovesFolder).ToList(); foreach (var step in moving) { // Into a sequence's folder (its own included) or another target: one sequence would end up inside another. var host = taken.Concat(moving.Where(m => m != step).Select(m => m.ToFolder)).FirstOrDefault(f => IsInside(f, step.ToFolder)); if (host is not null) throw new NestedRenameException(step.ToFolder, host); } var steps = new List<(RenameStep Step, int Order)>(); // An unreadable sequence that kept a folder around it in place is listed with why, as an unreadable subject is. var inner = (nested ?? []).Select(n => new RenameStep(n.SequenceId, n.Folder, n.Folder, n.Title, n.Title) { Blocked = n.Unreadable && blockers.Contains(n.SequenceId) ? [new RenameBlocked(RenameBlock.Unreadable, 0)] : [], }); foreach (var step in own.Concat(inner)) { // The nearest folder around it that moves carries it; a sequence that moves elsewhere leaves before its folder does. var carrier = step.MovesFolder ? null : moving.Where(m => IsInside(m.FromFolder, step.FromFolder)).MaxBy(m => m.FromFolder.Length); if (carrier is not null) 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.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)]) { FileTemplate = fileTemplate, Subjects = [.. subjects.Select(s => s.SequenceId)] }; } /// /// What the folder and title templates of a subject see: its first frame in its sidecar, as an upload filed it and as /// Reorganize names its files (a sidecar without frames: when the sequence was made); without the sidecar, the index /// row's capture time, camera and lens. Null when no time is known: never today's date, which would move the folder /// again on another day. /// private static NamingContext? Context(RenameSubject s) { if (s.Files?.Manifest is { } manifest) { if (manifest.Frames.Count > 0) return FrameNaming.Context(manifest.Frames[0], manifest, s.Title); var start = FrameNaming.SessionStart(manifest); return new NamingContext { CapturedAt = start, SessionStart = start, CameraMake = manifest.Camera?.Make, CameraModel = manifest.Camera?.Model, Lens = manifest.Lens, Title = s.Title, }; } if (s.FirstCapture is not { } first) return null; return new NamingContext { CapturedAt = first, SessionStart = first, CameraMake = s.CameraMake, CameraModel = s.CameraModel, Lens = s.Lens, Title = s.Title, }; } /// The step with the file renames of its sequence (). private static RenameStep WithFiles(RenameStep step, SequenceFiles files, PathTemplate template, string? title) { 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, FileDigest = plan.Frames > 0 ? plan.Digest() : null, Blocked = plan.Blocked, }; } /// /// Whether lies inside (archive-relative, forward slashes); the /// archive root, a sequence only when a folder was adopted in place, counts as containing nothing. /// public static bool IsInside(string folder, string path) => folder.Length > 0 && path.Length > folder.Length + 1 && path[folder.Length] == '/' && path.StartsWith(folder, StringComparison.OrdinalIgnoreCase); /// /// Moves the folder of a step; idempotent so a resumed plan can repeat it: an already moved folder is accepted, /// 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. 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))) { // 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."); return; } if (!Directory.Exists(from)) throw new DirectoryNotFoundException($"Sequence folder {step.FromFolder} is missing."); Directory.CreateDirectory(Path.GetDirectoryName(to)!); if (caseOnly) { var temp = from + ".rename-" + Guid.NewGuid().ToString("N")[..8]; Directory.Move(from, temp); Directory.Move(temp, to); } else { Directory.Move(from, to); } } 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)); 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 /// 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) { string? same = null; if (current.Equals(expanded, StringComparison.OrdinalIgnoreCase)) same = expanded; else if (current.Length > expanded.Length + 3 && current.StartsWith(expanded + " (", StringComparison.OrdinalIgnoreCase) && current[^1] == ')' && int.TryParse(current.AsSpan(expanded.Length + 2, current.Length - expanded.Length - 3), NumberStyles.None, CultureInfo.InvariantCulture, out var n) && n >= 2) 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; } private static string Unique(string folder, HashSet claimed, Func existsOnDisk) { var candidate = folder; for (var n = 2; claimed.Contains(candidate) || existsOnDisk(candidate); n++) candidate = string.Create(CultureInfo.InvariantCulture, $"{folder} ({n})"); return candidate; } }