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:
1 parent
81cf58227d
commit
eb2395d9b0
36 files changed
+2238
-164
No files matched your search
@@ -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>
|
||||
|
||||
Reference in new issue
Block a user