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

+268 -45
View File
@@ -2,13 +2,14 @@ using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Naming;
using Chronos.Data.Repositories;
namespace Chronos.Data.Archiving;
/// <summary>
/// The plan no longer matches the archive: a sequence moved or vanished since it was made, or one was indexed inside a
/// folder the plan moves.
/// folder the plan moves, or the photos of a sequence whose files it renames changed.
/// </summary>
public sealed class StaleRenamePlanException(Guid sequenceId)
: InvalidOperationException(Loc.L("Archive.Error.StalePlan"))
@@ -17,9 +18,19 @@ public sealed class StaleRenamePlanException(Guid sequenceId)
}
/// <summary>
/// Mass rename of sequence folders and titles (BRIEF §7, §12.5): <see cref="PlanAsync"/> is the dry run;
/// <see cref="ApplyAsync"/> makes exactly the planned changes to folders, sidecars and the index, step by step, with a
/// journal on the archive so an interrupted rename is completed by <see cref="ResumePendingAsync"/>.
/// What applying a plan did: the sequences changed (in the order of the plan), the frames whose files got a new name, the
/// sequences left as they were because they changed since the plan (<see cref="Dropped"/>, only when resuming) and those
/// whose files kept their names because their photos changed since (<see cref="FilesKept"/>; their folder and title changed).
/// </summary>
public sealed record RenameResult(IReadOnlyList<Guid> Changed, int Files, IReadOnlyList<Guid> Dropped, IReadOnlyList<Guid> FilesKept);
/// <summary>
/// Mass rename of sequence folders, titles and file names (BRIEF §7, §12.5; Reorganize, owner review 2, R7):
/// <see cref="PlanAsync(Archive, IReadOnlyList{Guid}, RenameTemplates, CancellationToken)"/> is the dry run;
/// <see cref="ApplyAsync(Archive, RenamePlan, IProgress{int}?, CancellationToken)"/> makes exactly the planned changes to
/// folders, files, sidecars and the index, step by step, with a journal on the archive so an interrupted rename is
/// completed by <see cref="ResumePendingAsync"/> (or, for a plan its job held, by <see cref="ResumeAsync"/>). A step's file
/// renames have their own journal in the sequence (<see cref="FileRenameJournal"/>).
/// </summary>
public sealed class MassRenamer
{
@@ -38,20 +49,35 @@ public sealed class MassRenamer
/// <param name="titleTemplate">New title template (<c>{title}</c> = the current title), or null to keep titles.</param>
/// <remarks>Sequences nested in a folder that moves are part of the plan (they move with it); see <see cref="RenamePlanner.Plan"/>.</remarks>
/// <exception cref="NestedRenameException">A new folder would lie inside a sequence's folder.</exception>
public async Task<RenamePlan> PlanAsync(Archive archive, IReadOnlyList<Guid> sequenceIds, string? folderTemplate, string? titleTemplate,
CancellationToken cancellationToken = default)
public Task<RenamePlan> PlanAsync(Archive archive, IReadOnlyList<Guid> sequenceIds, string? folderTemplate, string? titleTemplate,
CancellationToken cancellationToken = default) =>
PlanAsync(archive, sequenceIds, new RenameTemplates(folderTemplate, null, titleTemplate), cancellationToken);
/// <summary>
/// The dry run of a Reorganize: the plan of <paramref name="templates"/> over <paramref name="sequenceIds"/>. With a file
/// template each sequence's sidecar is read (without its lease) with the files beside its frames, so the plan names
/// exactly the files the apply will rename while nothing changes. A sequence created without photos, which has no
/// folder yet, is left out.
/// </summary>
/// <exception cref="ArgumentException">A sequence is not in the archive.</exception>
/// <exception cref="NestedRenameException">A new folder would lie inside a sequence's folder.</exception>
public async Task<RenamePlan> PlanAsync(Archive archive, IReadOnlyList<Guid> sequenceIds, RenameTemplates templates, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(archive);
ArgumentNullException.ThrowIfNull(sequenceIds);
ArgumentNullException.ThrowIfNull(templates);
var paths = new ArchivePaths(archive.RootPath);
var locations = await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false);
var subjects = new List<RenameSubject>(sequenceIds.Count);
foreach (var id in sequenceIds)
foreach (var id in sequenceIds.Distinct())
{
if (await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } s || s.ArchiveId != archive.Id)
throw new ArgumentException($"Sequence {id} is not in archive {archive.Id}.", nameof(sequenceIds));
subjects.Add(Subject(s));
if (ArchiveIngest.AwaitsFolder(s, paths)) continue;
subjects.Add(Subject(s) with { Files = templates.File is null ? null : ReadFiles(paths, s) });
}
var nested = new List<RenameSubject>();
if (folderTemplate is not null)
if (templates.Folder is not null)
{
var selected = sequenceIds.ToHashSet();
foreach (var location in locations.Where(l => !selected.Contains(l.Id) && subjects.Any(s => RenamePlanner.IsInside(s.Folder, l.Folder))))
@@ -59,51 +85,115 @@ public sealed class MassRenamer
if (await _db.Sequences.GetAsync(location.Id, cancellationToken).ConfigureAwait(false) is { } inner) nested.Add(Subject(inner));
}
}
return RenamePlanner.Plan(archive.Id, subjects, folderTemplate, titleTemplate, locations.Select(l => l.Folder),
folder => Directory.Exists(paths.Sequence(folder).Folder), nested);
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);
}
private static RenameSubject Subject(Sequence s) => new(s.Id, s.Folder, s.Title, s.FirstCapture, s.CameraMake, s.CameraModel, s.Lens);
/// <summary>Applies a plan; each completed step is journaled before the next starts.</summary>
/// <exception cref="StaleRenamePlanException">A sequence is no longer where the plan expects it, or a folder that moves holds
/// a sequence the plan does not take along; nothing of that step was changed.</exception>
public Task ApplyAsync(Archive archive, RenamePlan plan, IProgress<int>? progress = null, CancellationToken cancellationToken = default) =>
RunAsync(archive, new RenameJournal(plan, []), resuming: false, progress, cancellationToken);
/// <summary>The sidecar of a sequence and the files beside its frames; null (logged) when it cannot be read or is another sequence's.</summary>
private static SequenceFiles? ReadFiles(ArchivePaths paths, Sequence sequence)
{
var folder = paths.Sequence(sequence.Folder);
try
{
var manifest = ManifestStore.ReadSequence(folder.ManifestPath);
if (manifest.Id == sequence.Id) return new SequenceFiles(manifest, FileRenames.ListPresent(folder, manifest));
Log.Warning("archive", $"{folder.ManifestPath} belongs to sequence {manifest.Id}, not {sequence.Id}; its files keep their names");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
{
Log.Warning("archive", $"The sidecar of {sequence.DisplayTitle} cannot be read; its files keep their names", ex);
}
return null;
}
/// <summary>Completes renames interrupted by a crash; returns how many plans were resumed.</summary>
/// <summary>Applies a plan; each completed step is journaled before the next starts.</summary>
/// <exception cref="StaleRenamePlanException">A sequence is no longer where the plan expects it, a folder that moves holds
/// a sequence the plan does not take along, or the photos of a sequence whose files it renames changed; nothing of that
/// step was changed (a step found stale only once its folder moved keeps its folder and title, and its journal has the
/// next open complete the rest).</exception>
/// <exception cref="IOException">A file could not be renamed (open elsewhere); the step's files went back to their names.</exception>
public Task<RenameResult> ApplyAsync(Archive archive, RenamePlan plan, IProgress<int>? progress = null, CancellationToken cancellationToken = default) =>
ApplyAsync(archive, plan, null, progress is null ? null : n =>
{
progress.Report(n);
return ValueTask.CompletedTask;
}, cancellationToken);
/// <inheritdoc cref="ApplyAsync(Archive, RenamePlan, IProgress{int}?, CancellationToken)"/>
/// <param name="started">Told once the plan's journal is written, before any step (a job saves the plan's id as its checkpoint).</param>
/// <param name="stepDone">Told after each step with the number of steps done.</param>
public Task<RenameResult> ApplyAsync(Archive archive, RenamePlan plan, Func<RenamePlan, ValueTask>? started, Func<int, ValueTask>? stepDone,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(plan);
return RunAsync(archive, new RenameJournal(plan, []), resuming: false, started, stepDone, cancellationToken);
}
/// <summary>
/// Completes the plan <paramref name="planId"/> from its journal: one an interruption left (as <see cref="ResumePendingAsync"/>
/// does), or one its job held, whose remaining steps are checked as a plan applied anew (a sequence changed since refuses
/// the rest, and that journal goes). Null when there is no journal: the plan completed (here, or at an archive open).
/// </summary>
/// <exception cref="StaleRenamePlanException">A held plan's remaining steps no longer match the archive; nothing more changed.</exception>
public async Task<RenameResult?> ResumeAsync(Archive archive, Guid planId, Func<int, ValueTask>? stepDone = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(archive);
if (RenameJournal.Read(new ArchivePaths(archive.RootPath), planId) is not { } journal) return null;
return await RunAsync(archive, journal with { Held = false }, resuming: !journal.Held, null, stepDone, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Marks the plan <paramref name="planId"/> held (<see cref="RenameJournal.Held"/>): its job was paused or cancelled between
/// two steps, so an archive open leaves the rest to that job. False when it has no journal (it completed).
/// </summary>
public static bool Hold(Archive archive, Guid planId)
{
ArgumentNullException.ThrowIfNull(archive);
var paths = new ArchivePaths(archive.RootPath);
if (RenameJournal.Read(paths, planId) is not { } journal) return false;
RenameJournal.Write(paths, journal with { Held = true });
return true;
}
/// <summary>Completes renames interrupted by a crash (not those their job held); returns how many plans were resumed.</summary>
public async Task<int> ResumePendingAsync(Archive archive, CancellationToken cancellationToken = default)
{
var paths = new ArchivePaths(archive.RootPath);
var pending = RenameJournal.ListPending(paths).Where(j => j.Plan.ArchiveId == archive.Id).ToList();
foreach (var journal in pending) await RunAsync(archive, journal, resuming: true, null, cancellationToken).ConfigureAwait(false);
var pending = RenameJournal.ListPending(paths).Where(j => j.Plan.ArchiveId == archive.Id && !j.Held).ToList();
foreach (var journal in pending) await RunAsync(archive, journal, resuming: true, null, null, cancellationToken).ConfigureAwait(false);
return pending.Count;
}
/// <param name="resuming">Steps whose sequence the index no longer knows are dropped instead of failing the rename:
/// their sidecars still carry the ids, so the next scan indexes them wherever they ended up.</param>
private async Task RunAsync(Archive archive, RenameJournal journal, bool resuming, IProgress<int>? progress, CancellationToken cancellationToken)
private async Task<RenameResult> RunAsync(Archive archive, RenameJournal journal, bool resuming, Func<RenamePlan, ValueTask>? started,
Func<int, ValueTask>? stepDone, CancellationToken cancellationToken)
{
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
if (journal.Plan.ArchiveId != archive.Id) throw new ArgumentException("The plan belongs to another archive.", nameof(journal));
var completed = journal.Completed.ToHashSet();
// A step that changes nothing (its files kept their names, and why) has nothing to apply.
var steps = journal.Plan.Steps.Where(s => s.Changes).ToList();
if (!resuming)
{
// A plan made before another change is refused before anything moves: a sequence moved, or one was indexed
// inside a folder that moves (a scan adopted a subfolder copied in since the dry run).
foreach (var step in journal.Plan.Steps)
try
{
if ((await _db.Sequences.GetAsync(step.SequenceId, cancellationToken).ConfigureAwait(false))?.Folder != step.FromFolder)
throw new StaleRenamePlanException(step.SequenceId);
await RefuseStaleAsync(archive, paths, journal.Plan, [.. steps.Where(s => !completed.Contains(s.SequenceId))], cancellationToken).ConfigureAwait(false);
}
catch (StaleRenamePlanException) when (completed.Count > 0 || File.Exists(RenameJournal.PathFor(paths, journal.Plan.Id)))
{
// A held plan that no longer fits: what it applied stays, the rest never will.
RenameJournal.Delete(paths, journal.Plan.Id);
Log.Warning("archive", $"The rest of rename {journal.Plan.Id} no longer matches the archive; it was given up");
throw;
}
var planned = journal.Plan.Steps.Select(s => s.SequenceId).ToHashSet();
if (await StrangerInsideAsync(archive, journal.Plan.Steps.Where(s => s.MovesFolder && !s.Carried), planned, cancellationToken)
.ConfigureAwait(false) is { } stranger)
throw new StaleRenamePlanException(stranger.Id);
}
RenameJournal.Write(paths, journal);
var steps = journal.Plan.Steps;
if (started is not null) await started(journal.Plan).ConfigureAwait(false);
var result = new Tally();
foreach (var step in steps)
{
if (completed.Contains(step.SequenceId)) continue;
@@ -112,13 +202,50 @@ public sealed class MassRenamer
IReadOnlyList<RenameStep> carried = step.MovesFolder && !step.Carried
? [.. steps.Where(c => c.Carried && !completed.Contains(c.SequenceId) && Carrier(steps, c) == step)]
: [];
await ApplyStepAsync(archive, paths, step, carried, resuming, cancellationToken).ConfigureAwait(false);
await ApplyStepAsync(archive, paths, journal.Plan.FileTemplate, step, carried, resuming, result, cancellationToken).ConfigureAwait(false);
completed.Add(step.SequenceId);
foreach (var c in carried) completed.Add(c.SequenceId);
RenameJournal.Write(paths, journal with { Completed = [.. completed] });
progress?.Report(completed.Count);
if (stepDone is not null) await stepDone(completed.Count).ConfigureAwait(false);
}
RenameJournal.Delete(paths, journal.Plan.Id);
return new RenameResult(result.Changed, result.Files, result.Dropped, result.FilesKept);
}
/// <summary>
/// A plan made before another change is refused before anything moves: a sequence moved, one was indexed inside a
/// folder that moves (a scan adopted a subfolder copied in since the dry run), or the photos of a sequence whose files
/// it renames changed (another frames version in its sidecar).
/// </summary>
private async Task RefuseStaleAsync(Archive archive, ArchivePaths paths, RenamePlan plan, IReadOnlyList<RenameStep> remaining, CancellationToken cancellationToken)
{
foreach (var step in remaining)
{
if ((await _db.Sequences.GetAsync(step.SequenceId, cancellationToken).ConfigureAwait(false))?.Folder != step.FromFolder)
throw new StaleRenamePlanException(step.SequenceId);
}
var planned = plan.Steps.Select(s => s.SequenceId).ToHashSet();
if (await StrangerInsideAsync(archive, remaining.Where(s => s.MovesFolder && !s.Carried), planned, cancellationToken).ConfigureAwait(false) is { } stranger)
throw new StaleRenamePlanException(stranger.Id);
if (plan.FileTemplate is null) return;
foreach (var step in remaining.Where(s => s.FileChanges > 0))
{
if (FramesVersionOf(paths.Sequence(step.FromFolder), step.SequenceId) != step.FramesVersion) throw new StaleRenamePlanException(step.SequenceId);
}
}
/// <summary>The frames version of a sequence's sidecar (read without its lease); null when it cannot be read or is another sequence's.</summary>
private static int? FramesVersionOf(SequencePaths sequence, Guid sequenceId)
{
try
{
var manifest = ManifestStore.ReadSequence(sequence.ManifestPath);
return manifest.Id == sequenceId ? manifest.Versions.Frames : null;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
{
return null;
}
}
/// <summary>The step whose folder move carries <paramref name="carried"/>: the nearest moving folder around it (as planned).</summary>
@@ -127,14 +254,15 @@ public sealed class MassRenamer
/// <summary>
/// Applies a step, and the steps of the sequences its folder carries, under all their leases: sequence leases, then
/// for a move the thumbnail leases, each by sequence id (the order trash and pack compaction take them in). No
/// writer of a carried sequence (ingest, an editor save, a thumbnail pass) works in the folder while it moves or
/// before its index row follows.
/// for a move or file renames the thumbnail leases, each by sequence id (the order trash and pack compaction take them
/// in). No writer of a carried sequence (ingest, an editor save, a thumbnail pass) works in the folder while it moves or
/// its files are renamed, or before its index row follows. Once the folder moved the step goes to its end whatever
/// the caller cancels.
/// </summary>
/// <param name="resuming">A step whose sequence the index no longer has where the plan says is dropped instead of
/// failing the rename: its sidecar still carries the id, so the next scan indexes it wherever it ended up.</param>
private async Task ApplyStepAsync(Archive archive, ArchivePaths paths, RenameStep step, IReadOnlyList<RenameStep> carried, bool resuming,
CancellationToken cancellationToken)
private async Task ApplyStepAsync(Archive archive, ArchivePaths paths, string? fileTemplate, RenameStep step, IReadOnlyList<RenameStep> carried,
bool resuming, Tally result, CancellationToken cancellationToken)
{
var ids = carried.Select(c => c.SequenceId).Append(step.SequenceId).Order().ToList();
var locks = new List<IAsyncDisposable>(ids.Count);
@@ -142,7 +270,7 @@ public sealed class MassRenamer
try
{
foreach (var id in ids) locks.Add(await _writer.LockAsync(paths, id, cancellationToken).ConfigureAwait(false));
if (step.MovesFolder)
if (step.MovesFolder || step.FileChanges > 0 || carried.Any(c => c.FileChanges > 0))
{
foreach (var id in ids)
{
@@ -151,17 +279,31 @@ public sealed class MassRenamer
}
}
// Checked before anything moves; a dropped step drops the sequences it would have carried, which stay inside it.
if (!await StandsAsync(step, resuming, cancellationToken).ConfigureAwait(false)) return;
if (!await StandsAsync(step, resuming, cancellationToken).ConfigureAwait(false))
{
result.Dropped.Add(step.SequenceId);
return;
}
var follow = new List<RenameStep>(carried.Count);
foreach (var c in carried)
{
if (await StandsAsync(c, resuming, cancellationToken).ConfigureAwait(false)) follow.Add(c);
else result.Dropped.Add(c.SequenceId);
}
if (!await CarriesAllInsideAsync(archive, paths, step, carried, resuming, cancellationToken).ConfigureAwait(false))
{
result.Dropped.Add(step.SequenceId);
result.Dropped.AddRange(follow.Select(c => c.SequenceId));
return;
}
if (!await CarriesAllInsideAsync(archive, paths, step, carried, resuming, cancellationToken).ConfigureAwait(false)) return;
RenamePlanner.MoveFolder(paths, step);
await RecordAsync(archive, paths, step, cancellationToken).ConfigureAwait(false);
// Moved with their carrier: only their sidecars and index rows follow.
foreach (var c in follow) await RecordAsync(archive, paths, c, cancellationToken).ConfigureAwait(false);
// Moved with their carrier: only their sidecars and index rows follow, and the names of their files.
foreach (var s in follow.Prepend(step))
{
await RecordAsync(archive, paths, s, CancellationToken.None).ConfigureAwait(false);
var renamed = await RenameFilesAsync(archive, paths, fileTemplate, s, resuming, result, CancellationToken.None).ConfigureAwait(false);
if (s.MovesFolder || s.Retitles || renamed) result.Changed.Add(s.SequenceId);
}
}
finally
{
@@ -215,16 +357,18 @@ public sealed class MassRenamer
/// The index row changes in its folder and title only (<see cref="SequenceRepository.RelocateAsync"/>): a settings edit
/// committed meanwhile stays, and frames another process listed in the sidecar are left to the next scan, for which
/// the folder keeps no stamps unless the index held it as it was
/// (<see cref="ArchiveIndexer.InStepAsync(Archive, string, SequencePaths, SequenceManifest, CancellationToken)"/>).
/// (<see cref="ArchiveIndexer.InStepAsync(Archive, string, SequencePaths, SequenceManifest, CancellationToken)"/>). A step
/// that only renames files has nothing to record here.
/// </summary>
private async Task RecordAsync(Archive archive, ArchivePaths paths, RenameStep step, CancellationToken cancellationToken)
{
if (!step.MovesFolder && !step.Retitles) return;
var sequence = paths.Sequence(step.ToFolder);
var manifest = SequenceWriter.ReadLocked(sequence, step.SequenceId);
// The folder moved with its files' stamps, which the index recorded at its old place.
var inStep = await _indexer.InStepAsync(archive, step.FromFolder, sequence, manifest, cancellationToken).ConfigureAwait(false);
// A step that only moves the folder keeps the title, which an edit may have changed since the plan.
var retitle = step.FromTitle != step.ToTitle;
var retitle = step.Retitles;
if (retitle && manifest.Title != step.ToTitle)
{
manifest = manifest with
@@ -244,4 +388,83 @@ public sealed class MassRenamer
}
if (inStep) await _indexer.RecordStampsAsync(archive, sequence, step.SequenceId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The file renames of a step, under the leases its step holds, once its folder is in place (Reorganize, owner review 2,
/// R7). The renames are planned again from the sidecar read under the lease (<see cref="FileRenames.Plan"/>, with the
/// step's title, the one the dry run showed), which names exactly what the dry run showed while its frames version is the plan's: another one
/// refuses the step (<see cref="StaleRenamePlanException"/>), or, when resuming, leaves its files as they are. The files
/// move in two phases through temporary names under the sequence's journal (<see cref="FileRenameJournal"/>), then the
/// sidecar names them (the frame order unchanged, frames version + 1), then the index (<see cref="FrameRepository.RenameFilesAsync"/>),
/// then the journal goes. When nothing moves here but the index names other files than the sidecar, a writer completed
/// the renames after a crash (<see cref="SequenceWriter.ReadLocked"/>) before the index followed, and the index is synced
/// from the sidecar. Proxies (named by frame index), thumbnails (by index and content hash), renders and exports need
/// nothing.
/// </summary>
/// <returns>False when the step renames no file, or its files kept their names.</returns>
private async Task<bool> RenameFilesAsync(Archive archive, ArchivePaths paths, string? fileTemplate, RenameStep step, bool resuming, Tally result,
CancellationToken cancellationToken)
{
if (fileTemplate is null || step.FileChanges == 0) return false;
var sequence = paths.Sequence(step.ToFolder);
var manifest = SequenceWriter.ReadLocked(sequence, step.SequenceId);
var inStep = await _indexer.InStepAsync(archive, sequence, manifest, cancellationToken).ConfigureAwait(false);
var plan = FileRenames.Plan(manifest, step.ToTitle, PathTemplate.Parse(fileTemplate), FileRenames.ListPresent(sequence, manifest));
var before = manifest.Versions.Frames;
if (plan.Moves.Count > 0 && before != step.FramesVersion)
{
if (!resuming) throw new StaleRenamePlanException(step.SequenceId);
Log.Warning("archive", $"The files of {sequence.RelativeFolder} keep their names: its photos changed after the plan was made");
result.FilesKept.Add(step.SequenceId);
return false;
}
if (plan.Moves.Count > 0)
{
var journal = FileRenameJournal.Create(before, plan.Moves, Guid.NewGuid().ToString("N")[..8]);
FileRenameJournal.Write(sequence, journal);
journal = FileRenameJournal.Run(sequence, journal);
manifest = FileRenameJournal.Applied(manifest, journal) ?? manifest;
ManifestStore.WriteSequence(sequence.ManifestPath, manifest);
result.Files += plan.Frames;
Log.Info("archive", $"{sequence.RelativeFolder}: {plan.Frames} file(s) renamed, {plan.Moves.Count - plan.Frames} companion(s) with them");
await _db.Frames.RenameFilesAsync(manifest.Id, await BehindAsync(sequence, manifest, cancellationToken).ConfigureAwait(false), before,
manifest.Versions.Frames, cancellationToken).ConfigureAwait(false);
if (inStep) await _indexer.RecordStampsAsync(archive, sequence, step.SequenceId, cancellationToken).ConfigureAwait(false);
}
else if ((await BehindAsync(sequence, manifest, cancellationToken).ConfigureAwait(false)).Count > 0)
{
// Photos copied in by hand meanwhile are left to the next scan's reconcile (the photo stamp stays as recorded).
await _indexer.SyncAsync(archive, sequence, manifest, null, SequenceStatus.None, photosChanged: true, cancellationToken).ConfigureAwait(false);
}
FileRenameJournal.Delete(sequence);
return true;
}
/// <summary>The frames the index names by another file than the sidecar does, with the sidecar's path and name; frames the index does not have are left to the next scan.</summary>
private async Task<List<FrameFileName>> BehindAsync(SequencePaths sequence, SequenceManifest manifest, CancellationToken cancellationToken)
{
const int page = 1000;
var files = manifest.Frames.ToDictionary(f => f.Id, f => f.File);
var behind = new List<FrameFileName>();
for (var last = -1; ;)
{
var rows = await _db.Frames.ListBySequenceAsync(manifest.Id, last, page, cancellationToken).ConfigureAwait(false);
foreach (var row in rows)
{
if (!files.TryGetValue(row.Id, out var file)) continue;
var path = sequence.ArchiveRelative(file);
if (row.RelativePath != path) behind.Add(new FrameFileName(row.Id, path, Path.GetFileName(file)));
}
if (rows.Count < page) return behind;
last = rows[^1].Index;
}
}
/// <summary>What a run did, as it goes.</summary>
private sealed class Tally
{
public List<Guid> Changed { get; } = [];
public List<Guid> Dropped { get; } = [];
public List<Guid> FilesKept { get; } = [];
public int Files { get; set; }
}
}