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
@@ -41,8 +41,11 @@ public static class MassRename
|
||||
: new RenameRow(s.SequenceId, s.FromTitle ?? string.Empty, s.ToTitle ?? string.Empty)),
|
||||
];
|
||||
|
||||
/// <summary>"12 of 36 sequences change"; sequences that only move with a folder they are in are listed, not counted.</summary>
|
||||
public static string Summary(RenamePlan plan, int setSize) => Loc.Plural("Archive.Rename.Summary", plan.Steps.Count(s => !s.Carried), setSize);
|
||||
/// <summary>
|
||||
/// "12 of 36 sequences change"; sequences that only move with a folder they are in are listed, not counted, and so are
|
||||
/// those that change nothing (their files keep their names).
|
||||
/// </summary>
|
||||
public static string Summary(RenamePlan plan, int setSize) => Loc.Plural("Archive.Rename.Summary", plan.Steps.Count(s => s.Changes && !s.Carried), setSize);
|
||||
}
|
||||
|
||||
/// <summary>Adding and removing tags on a set of sequences (BRIEF §12.5 Retag).</summary>
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
@@ -137,23 +137,8 @@ public static class ImportPlanner
|
||||
};
|
||||
}
|
||||
|
||||
private static NamingContext Context(CardPhoto photo, DateTime sessionStart, int session, int number, string? title) => new()
|
||||
{
|
||||
CapturedAt = photo.CaptureTime,
|
||||
SessionStart = sessionStart,
|
||||
Session = session,
|
||||
Number = number,
|
||||
NumberInSession = number,
|
||||
CameraMake = photo.Metadata.Make,
|
||||
CameraModel = photo.Metadata.Model,
|
||||
Lens = photo.Metadata.LensModel,
|
||||
Iso = photo.Metadata.Iso,
|
||||
ExposureTime = photo.Metadata.ExposureTime,
|
||||
FNumber = photo.Metadata.FNumber,
|
||||
OriginalName = Path.GetFileNameWithoutExtension(photo.File.RelativePath),
|
||||
Extension = Path.GetExtension(photo.File.RelativePath).TrimStart('.'),
|
||||
Title = title,
|
||||
};
|
||||
private static NamingContext Context(CardPhoto photo, DateTime sessionStart, int session, int number, string? title) =>
|
||||
FrameNaming.Context(photo.Metadata, photo.File.RelativePath, photo.CaptureTime, sessionStart, number, title, session);
|
||||
|
||||
/// <summary>Camera body and file format: RAW+JPEG shooting yields two sequences instead of doubled frames.</summary>
|
||||
private static string BodyKey(CardPhoto p) => $"{CameraKey(p)}|{p.Metadata.Format}";
|
||||
@@ -201,14 +186,7 @@ public static class ImportPlanner
|
||||
}
|
||||
|
||||
/// <summary>Adds _2, _3… before the extension when the template gives two photos the same name.</summary>
|
||||
internal static string UniqueName(string name, HashSet<string> taken)
|
||||
{
|
||||
var candidate = name;
|
||||
var stem = Path.GetFileNameWithoutExtension(name);
|
||||
var extension = Path.GetExtension(name);
|
||||
for (var n = 2; !taken.Add(candidate); n++) candidate = string.Create(CultureInfo.InvariantCulture, $"{stem}_{n}{extension}");
|
||||
return candidate;
|
||||
}
|
||||
internal static string UniqueName(string name, HashSet<string> taken) => FrameNaming.Unique(name, taken.Add);
|
||||
|
||||
private static long? FreeSpace(string path)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
using System.Globalization;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Metadata;
|
||||
|
||||
namespace Chronos.Core.Naming;
|
||||
|
||||
/// <summary>
|
||||
/// The values a file template sees for one photo and the unique name it gives (BRIEF §7.1), shared by everything that
|
||||
/// names frames: a card or folder import (<see cref="Import.ImportPlanner"/>), an upload filed by the archive ingest, and
|
||||
/// Reorganize, which renames the frames of a sequence already in the archive (owner review 2, R7). The same photo in the
|
||||
/// same place therefore gets the same name whichever of them names it.
|
||||
/// </summary>
|
||||
public static class FrameNaming
|
||||
{
|
||||
/// <summary>The context of a photo being filed, from its metadata.</summary>
|
||||
/// <param name="fileName">The photo's name on the card or upload source: <c>{name}</c> is its stem, <c>{ext}</c> its extension.</param>
|
||||
/// <param name="capturedAt">The photo's capture time as the sequence orders it.</param>
|
||||
/// <param name="sessionStart">The capture time of the first photo of its session (<c>{sessionstart}</c>).</param>
|
||||
/// <param name="number">1-based number of the photo (<c>{n}</c>, <c>{nsession}</c>).</param>
|
||||
/// <param name="title">The sequence title (<c>{title}</c>).</param>
|
||||
/// <param name="session">1-based session number within the import (<c>{session}</c>); 1 for an upload.</param>
|
||||
public static NamingContext Context(FrameMetadata metadata, string fileName, DateTime capturedAt, DateTime sessionStart, int number, string? title,
|
||||
int session = 1)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(metadata);
|
||||
ArgumentNullException.ThrowIfNull(fileName);
|
||||
return new NamingContext
|
||||
{
|
||||
CapturedAt = capturedAt,
|
||||
SessionStart = sessionStart,
|
||||
Session = session,
|
||||
Number = number,
|
||||
NumberInSession = number,
|
||||
CameraMake = metadata.Make,
|
||||
CameraModel = metadata.Model,
|
||||
Lens = metadata.LensModel,
|
||||
Iso = metadata.Iso,
|
||||
ExposureTime = metadata.ExposureTime,
|
||||
FNumber = metadata.FNumber,
|
||||
OriginalName = Path.GetFileNameWithoutExtension(fileName),
|
||||
Extension = Path.GetExtension(fileName).TrimStart('.'),
|
||||
Title = title,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The context of a frame already in a sequence (Reorganize): its sidecar record with the sequence's camera and lens,
|
||||
/// numbered by its index (<c>{n}</c> = index + 1), the sequence as one session starting at its first frame. <c>{name}</c>
|
||||
/// is the name the photo had on the card, <c>{ext}</c> the extension of the file as it is now. These are the values an
|
||||
/// upload of the same photos in capture order was named with; a frame without a capture time takes the session start,
|
||||
/// so a dry run and its application always agree.
|
||||
/// </summary>
|
||||
public static NamingContext Context(SidecarFrame frame, SequenceManifest sequence, string? title)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(frame);
|
||||
ArgumentNullException.ThrowIfNull(sequence);
|
||||
var start = SessionStart(sequence);
|
||||
var file = Path.GetFileName(frame.File);
|
||||
return new NamingContext
|
||||
{
|
||||
CapturedAt = frame.CapturedAt ?? start,
|
||||
SessionStart = start,
|
||||
Session = 1,
|
||||
Number = frame.I + 1,
|
||||
NumberInSession = frame.I + 1,
|
||||
CameraMake = sequence.Camera?.Make,
|
||||
CameraModel = sequence.Camera?.Model,
|
||||
Lens = sequence.Lens,
|
||||
Iso = frame.Iso,
|
||||
ExposureTime = frame.Exposure,
|
||||
FNumber = frame.FNumber,
|
||||
OriginalName = Path.GetFileNameWithoutExtension(frame.Original ?? file),
|
||||
Extension = Path.GetExtension(file).TrimStart('.'),
|
||||
Title = title,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The start of a sequence as one session: its first frame's capture time, else when the sequence was made.</summary>
|
||||
public static DateTime SessionStart(SequenceManifest sequence)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sequence);
|
||||
return sequence.Frames.Count > 0 && sequence.Frames[0].CapturedAt is { } first
|
||||
? first
|
||||
: DateTime.SpecifyKind(sequence.Created.UtcDateTime, DateTimeKind.Unspecified);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="directory"/> (empty or ending with '/') and the name <paramref name="template"/> gives, made unique
|
||||
/// in <paramref name="taken"/> with <c>_2</c>, <c>_3</c>… before the extension, then added to it.
|
||||
/// </summary>
|
||||
public static string FileName(PathTemplate template, NamingContext context, ISet<string> taken, string directory = "")
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(taken);
|
||||
var file = FileName(template, context, candidate => !taken.Contains(candidate), directory);
|
||||
taken.Add(file);
|
||||
return file;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="directory"/> and the name <paramref name="template"/> gives, or the first of <c>stem_2.ext</c>,
|
||||
/// <c>stem_3.ext</c>… that <paramref name="isFree"/> accepts.
|
||||
/// </summary>
|
||||
public static string FileName(PathTemplate template, NamingContext context, Func<string, bool> isFree, string directory = "")
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(template);
|
||||
ArgumentNullException.ThrowIfNull(isFree);
|
||||
ArgumentNullException.ThrowIfNull(directory);
|
||||
return Unique(directory + template.ExpandFile(context), isFree);
|
||||
}
|
||||
|
||||
/// <summary><paramref name="file"/>, or the first of <c>stem_2.ext</c>, <c>stem_3.ext</c>… that <paramref name="isFree"/> accepts.</summary>
|
||||
public static string Unique(string file, Func<string, bool> isFree)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(file);
|
||||
ArgumentNullException.ThrowIfNull(isFree);
|
||||
var slash = file.LastIndexOf('/');
|
||||
var directory = file[..(slash + 1)];
|
||||
var name = file[(slash + 1)..];
|
||||
var stem = Path.GetFileNameWithoutExtension(name);
|
||||
var extension = Path.GetExtension(name);
|
||||
var candidate = file;
|
||||
for (var n = 2; !isFree(candidate); n++) candidate = string.Create(CultureInfo.InvariantCulture, $"{directory}{stem}_{n}{extension}");
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
@@ -435,10 +435,9 @@ public sealed class ArchiveIngest : IArchiveIngest
|
||||
if (!incoming.TryGetValue(frame.Id, out var entry)) continue;
|
||||
var staged = entry.Pending.Frame;
|
||||
var captured = frame.CapturedAt ?? DateTime.Now;
|
||||
var name = staged.PlannedName ?? template.ExpandFile(Naming(staged, captured, start ?? captured, frame.I + 1, manifest.Title));
|
||||
var file = directory + name;
|
||||
var stem = Path.GetFileNameWithoutExtension(name);
|
||||
for (var n = 2; !taken.Add(file); n++) file = string.Create(CultureInfo.InvariantCulture, $"{directory}{stem}_{n}{Path.GetExtension(name)}");
|
||||
var file = staged.PlannedName is { } planned
|
||||
? FrameNaming.Unique(directory + planned, taken.Add)
|
||||
: FrameNaming.FileName(template, Naming(staged, captured, start ?? captured, frame.I + 1, manifest.Title), taken, directory);
|
||||
named[frame.Id] = entry.Frame with { File = file };
|
||||
}
|
||||
return named;
|
||||
@@ -539,22 +538,8 @@ public sealed class ArchiveIngest : IArchiveIngest
|
||||
? client
|
||||
: frame.Metadata.CapturedAt ?? frame.ClientCapturedAt ?? DateTime.Now;
|
||||
|
||||
private static NamingContext Naming(StagedFrame frame, DateTime captured, DateTime sessionStart, int number, string? title) => new()
|
||||
{
|
||||
CapturedAt = captured,
|
||||
SessionStart = sessionStart,
|
||||
Number = number,
|
||||
NumberInSession = number,
|
||||
CameraMake = frame.Metadata.Make,
|
||||
CameraModel = frame.Metadata.Model,
|
||||
Lens = frame.Metadata.LensModel,
|
||||
Iso = frame.Metadata.Iso,
|
||||
ExposureTime = frame.Metadata.ExposureTime,
|
||||
FNumber = frame.Metadata.FNumber,
|
||||
OriginalName = Path.GetFileNameWithoutExtension(frame.OriginalFileName),
|
||||
Extension = Path.GetExtension(frame.OriginalFileName).TrimStart('.'),
|
||||
Title = title,
|
||||
};
|
||||
private static NamingContext Naming(StagedFrame frame, DateTime captured, DateTime sessionStart, int number, string? title) =>
|
||||
FrameNaming.Context(frame.Metadata, frame.OriginalFileName, captured, sessionStart, number, title);
|
||||
|
||||
private sealed class CommitQueue
|
||||
{
|
||||
|
||||
@@ -73,8 +73,8 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
|
||||
/// <summary>
|
||||
/// Handlers for scan, rebuild, verify, import, thumbs, proxies and maintenance jobs, the read-only duplicates and orphans
|
||||
/// reports, index backups and clean-ups (owner review 2, R10) and the emptying of the trash (R6); register them on the
|
||||
/// <see cref="JobEngine"/>.
|
||||
/// reports, index backups and clean-ups (owner review 2, R10), the emptying of the trash (R6) and Reorganize (R7,
|
||||
/// <see cref="JobKind.Move"/>); register them on the <see cref="JobEngine"/>.
|
||||
/// </summary>
|
||||
public IReadOnlyList<IJobHandler> CreateJobHandlers() =>
|
||||
[
|
||||
@@ -90,6 +90,7 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
new Housekeeping.BackupJobHandler(_db, _writer.Options.BackupDirectory),
|
||||
new Housekeeping.CleanupJobHandler(_db, CleanupSteps, TimeProvider.System),
|
||||
new EmptyTrashJobHandler(_db, Trash),
|
||||
new MoveJobHandler(_db, Renamer, _writer.Options.SequenceChanged),
|
||||
];
|
||||
|
||||
/// <summary>Makes <paramref name="root"/> a new, empty archive and indexes it.</summary>
|
||||
@@ -351,7 +352,23 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
await Renamer.PlanAsync(await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false), sequenceIds, folderTemplate, titleTemplate,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
|
||||
public async Task ApplyRenameAsync(RenamePlan plan, IProgress<int>? progress = null, CancellationToken cancellationToken = default) =>
|
||||
/// <summary>
|
||||
/// The dry run of a Reorganize (owner review 2, R7): <paramref name="templates"/> over <paramref name="sequenceIds"/>, or
|
||||
/// over every sequence of the archive (by folder) when null. Apply it in a job (<see cref="ArchiveJobs.Reorganize"/>) or
|
||||
/// with <see cref="ApplyRenameAsync"/>.
|
||||
/// </summary>
|
||||
/// <exception cref="ArgumentException">The archive is unknown, or a sequence is not in it.</exception>
|
||||
/// <exception cref="NestedRenameException">A new folder would lie inside a sequence's folder.</exception>
|
||||
public async Task<RenamePlan> PlanReorganizeAsync(Guid archiveId, IReadOnlyList<Guid>? sequenceIds, RenameTemplates templates,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(templates);
|
||||
var archive = await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false);
|
||||
var ids = sequenceIds ?? [.. (await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false)).Select(l => l.Id)];
|
||||
return await Renamer.PlanAsync(archive, ids, templates, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task<RenameResult> ApplyRenameAsync(RenamePlan plan, IProgress<int>? progress = null, CancellationToken cancellationToken = default) =>
|
||||
await Renamer.ApplyAsync(await LoadArchiveAsync(plan.ArchiveId, cancellationToken).ConfigureAwait(false), plan, progress, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
@@ -567,6 +584,24 @@ public static class ArchiveJobs
|
||||
JobPriority.User);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.Move"/>: applies the Reorganize <paramref name="plan"/> (the dry run of <paramref name="templates"/>,
|
||||
/// <see cref="ArchiveService.PlanReorganizeAsync"/>) as confirmed, refused when the archive changed since
|
||||
/// (<see cref="MoveJobParameters"/>; owner review 2, R7).
|
||||
/// </summary>
|
||||
public static ArchiveJobRequest Reorganize(Archive archive, RenamePlan plan, RenameTemplates templates)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archive);
|
||||
ArgumentNullException.ThrowIfNull(plan);
|
||||
ArgumentNullException.ThrowIfNull(templates);
|
||||
// The sequences that have a step, in the order the plan was made for: the others change nothing, now or when planned again.
|
||||
var steps = plan.Steps.ToDictionary(s => s.SequenceId);
|
||||
var sequences = plan.Subjects.Where(steps.ContainsKey).Select(id => new MoveSequence(id, steps[id].FramesVersion)).ToList();
|
||||
return new(JobKind.Move, [archive.Id], archive.Name,
|
||||
Json(new MoveJobParameters(templates.Folder, templates.File, templates.Title, sequences, plan.Fingerprint()), ArchiveJobJson.Default.MoveJobParameters),
|
||||
JobPriority.User);
|
||||
}
|
||||
|
||||
public static Task<Job> EnqueueAsync(this JobEngine engine, ArchiveJobRequest request, Guid? createdBy = null, CancellationToken cancellationToken = default) =>
|
||||
engine.EnqueueAsync(request.Kind, request.Targets, request.Label, request.ParametersJson, request.Priority, createdBy, cancellationToken);
|
||||
|
||||
|
||||
@@ -176,7 +176,7 @@ public sealed partial class FrameTrash
|
||||
continue;
|
||||
}
|
||||
var original = photo.Files[0];
|
||||
var tails = photo.Files.Skip(1).Select(c => CompanionTail(c.From, original.From)).ToList();
|
||||
var tails = photo.Files.Skip(1).Select(c => FrameCompanions.Tail(c.From, original.From)).ToList();
|
||||
var file = FreeName(folder, original.From, tails, taken);
|
||||
var stem = file[..^Path.GetExtension(file).Length];
|
||||
taken.Add(file);
|
||||
@@ -417,7 +417,7 @@ public sealed partial class FrameTrash
|
||||
if (folder is null && sequenceId is { } known && await _db.Sequences.GetAsync(known, CancellationToken.None).ConfigureAwait(false) is { } row)
|
||||
folder = paths.Sequence(row.Folder);
|
||||
var original = photo.Files[0];
|
||||
var tails = photo.Files.Skip(1).Select(c => CompanionTail(c.From, original.From)).ToList();
|
||||
var tails = photo.Files.Skip(1).Select(c => FrameCompanions.Tail(c.From, original.From)).ToList();
|
||||
var planned = FreeName(folder, ArchiveLayout.OriginalsFolder + "/" + Path.GetFileName(original.From), tails, names);
|
||||
var inEntry = Path.Combine(entryFolder, original.Path);
|
||||
var path = Path.Combine(staging, original.Path);
|
||||
@@ -475,7 +475,7 @@ public sealed partial class FrameTrash
|
||||
names.Add(ArchiveLayout.OriginalsFolder + "/" + Path.GetFileName(placed));
|
||||
foreach (var companion in photo.Files.Skip(1))
|
||||
{
|
||||
var beside = stem + CompanionTail(companion.From, original.From);
|
||||
var beside = stem + FrameCompanions.Tail(companion.From, original.From);
|
||||
names.Add(ArchiveLayout.OriginalsFolder + "/" + Path.GetFileName(beside));
|
||||
try
|
||||
{
|
||||
@@ -563,14 +563,6 @@ public sealed partial class FrameTrash
|
||||
return all.Count > 0 ? all : null;
|
||||
}
|
||||
|
||||
/// <summary>What a companion's name adds to its photo's stem (<c>.xmp</c>, <c>.CR2.xmp</c>).</summary>
|
||||
private static string CompanionTail(string companion, string 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>
|
||||
/// <paramref name="file"/> when it and its companions' names (<paramref name="tails"/> after its stem) are free in
|
||||
/// <paramref name="taken"/> and on disk in <paramref name="folder"/> (none yet: in <paramref name="taken"/> only), else
|
||||
|
||||
@@ -347,7 +347,7 @@ public sealed partial class FrameTrash
|
||||
var used = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var claimed = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var keptStems = kept.Select(f => Stem(f.File)).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var companions = new CompanionIndex(folder);
|
||||
var companions = new FrameCompanions.Index(folder);
|
||||
var photos = new List<TrashedPhoto>(removed.Count);
|
||||
foreach (var frame in removed)
|
||||
{
|
||||
@@ -431,35 +431,6 @@ public sealed partial class FrameTrash
|
||||
return Convert.ToHexStringLower(hash.GetHashAndReset());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The XMP files of a sequence's photo directories, each directory listed once (a deletion of thousands of photos does
|
||||
/// not list it again for each) and case-insensitively on every system (<c>IMG_0001.XMP</c> too).
|
||||
/// </summary>
|
||||
private sealed class CompanionIndex(SequencePaths folder)
|
||||
{
|
||||
private static readonly EnumerationOptions Listing = new() { MatchCasing = MatchCasing.CaseInsensitive, AttributesToSkip = 0 };
|
||||
private readonly Dictionary<string, ILookup<string, string>> _directories = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>The XMP files beside a photo that name it (<c>stem.xmp</c> or <c>file.xmp</c>), relative to the sequence folder.</summary>
|
||||
public IEnumerable<string> Of(string file)
|
||||
{
|
||||
var prefix = file.Contains('/') ? file[..(file.LastIndexOf('/') + 1)] : string.Empty;
|
||||
if (!_directories.TryGetValue(prefix, out var named))
|
||||
{
|
||||
var directory = Path.GetDirectoryName(folder.File(file))!;
|
||||
named = (System.IO.Directory.Exists(directory) ? System.IO.Directory.EnumerateFiles(directory, "*.xmp", Listing) : [])
|
||||
.Select(p => Path.GetFileName(p))
|
||||
.Where(n => Path.GetExtension(n).Equals(".xmp", 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A photo's stem with its folder (<c>originals/IMG_0001</c>): its companions share it.</summary>
|
||||
private static string Stem(string file)
|
||||
{
|
||||
|
||||
@@ -40,6 +40,17 @@ public sealed record EmptyTrashParameters(IReadOnlyList<EmptyTrashItem> Entries,
|
||||
/// <summary>One entry of a confirmed emptying: its name and fingerprint when it was planned.</summary>
|
||||
public sealed record EmptyTrashItem(string Name, string Fingerprint);
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.Move"/> (Reorganize, owner review 2, R7): target = the archive; the templates (null keeps that part),
|
||||
/// the sequences the confirmed plan changes in the order it was made for, each with the frames version its file names
|
||||
/// were planned at (0 when none is renamed), and the plan's fingerprint (<see cref="Core.Archiving.RenamePlan.Fingerprint"/>).
|
||||
/// No file list: the job plans again and refuses when the plan is no longer the one confirmed.
|
||||
/// </summary>
|
||||
public sealed record MoveJobParameters(string? FolderTemplate, string? FileTemplate, string? TitleTemplate, IReadOnlyList<MoveSequence> Sequences, string Fingerprint);
|
||||
|
||||
/// <summary>A sequence of a <see cref="MoveJobParameters"/> and the frames version its file names were planned at.</summary>
|
||||
public sealed record MoveSequence(Guid Id, int FramesVersion);
|
||||
|
||||
/// <summary>A job ready to enqueue.</summary>
|
||||
public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList<Guid> Targets, string? Label, string? ParametersJson, JobPriority Priority);
|
||||
|
||||
@@ -52,6 +63,7 @@ public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList<Guid> Targets
|
||||
[JsonSerializable(typeof(BackupParameters))]
|
||||
[JsonSerializable(typeof(CleanupParameters))]
|
||||
[JsonSerializable(typeof(EmptyTrashParameters))]
|
||||
[JsonSerializable(typeof(MoveJobParameters))]
|
||||
[JsonSerializable(typeof(CardProfile))]
|
||||
internal sealed partial class ArchiveJobJson : JsonSerializerContext
|
||||
{
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Jobs;
|
||||
|
||||
namespace Chronos.Data.Archiving.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.Move"/>: a Reorganize (owner review 2, R7; BRIEF §12.5) of existing sequences with new folder, file
|
||||
/// and title templates (<see cref="MoveJobParameters"/>). The job plans again from the templates and applies the plan only
|
||||
/// when it is still the one confirmed (its fingerprint and the frames versions its file names were planned at;
|
||||
/// <see cref="StaleRenamePlanException"/> otherwise, nothing changed), through <see cref="MassRenamer"/>, whose journal makes
|
||||
/// every step resumable. Progress counts the plan's steps (sequences); checkpoint: <c>plan:<id></c> once the plan's
|
||||
/// journal is written. Paused or cancelled, the job stops between two sequences and holds the plan
|
||||
/// (<see cref="MassRenamer.Hold"/>), which an archive open then leaves to it; resumed or retried, it completes the rest when
|
||||
/// it still fits. A plan whose journal is gone completed meanwhile (at an archive open). Sequences left as they were, or
|
||||
/// whose files kept their names, because they changed after the plan are logged and fail the job at the end, after the
|
||||
/// others changed. Each sequence changed is told to <see cref="ArchiveServiceOptions.SequenceChanged"/> (<see cref="Change"/>).
|
||||
/// </summary>
|
||||
internal sealed class MoveJobHandler(ChronosDatabase db, MassRenamer renamer, Func<Guid, string, CancellationToken, Task>? sequenceChanged) : IJobHandler
|
||||
{
|
||||
/// <summary>The change a Reorganize tells about a sequence (a server's <c>sequenceChanged</c> event).</summary>
|
||||
public const string Change = "reorganized";
|
||||
|
||||
private const string Prefix = "plan:";
|
||||
|
||||
public JobKind Kind => JobKind.Move;
|
||||
|
||||
public async Task RunAsync(JobContext context)
|
||||
{
|
||||
var archive = await JobArchive.LoadAsync(db, context.Job, context.Cancellation).ConfigureAwait(false);
|
||||
var parameters = ArchiveJobJson.Read(context.Job, ArchiveJobJson.Default.MoveJobParameters, new MoveJobParameters(null, null, null, [], string.Empty));
|
||||
if (parameters.Fingerprint.Length == 0) throw new InvalidOperationException($"Move job {context.Job.Id} has no confirmed plan.");
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
var planId = PlanOf(context.Checkpoint);
|
||||
RenamePlan plan;
|
||||
RenameResult? result;
|
||||
try
|
||||
{
|
||||
if (planId is { } resumed)
|
||||
{
|
||||
if (RenameJournal.Read(paths, resumed) is not { } journal || await ResumeAsync(context, archive, journal).ConfigureAwait(false) is not { } done)
|
||||
{
|
||||
context.Log(Loc.L("Archive.Log.ReorganizedEarlier"));
|
||||
await context.ReportAsync(context.Total, context.Total).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
(plan, result) = (journal.Plan, done);
|
||||
}
|
||||
else
|
||||
{
|
||||
plan = await renamer.PlanAsync(archive, [.. parameters.Sequences.Select(s => s.Id)],
|
||||
new RenameTemplates(parameters.FolderTemplate, parameters.FileTemplate, parameters.TitleTemplate), context.Cancellation).ConfigureAwait(false);
|
||||
if (!IsConfirmed(plan, parameters)) throw new StaleRenamePlanException(Guid.Empty);
|
||||
var total = Steps(plan);
|
||||
await context.ReportAsync(0, total).ConfigureAwait(false);
|
||||
result = await renamer.ApplyAsync(archive, plan, p =>
|
||||
{
|
||||
planId = p.Id;
|
||||
return context.CheckpointAsync(Checkpoint(p.Id), 0, total);
|
||||
}, n => context.CheckpointAsync(Checkpoint(plan.Id), n, total), context.Cancellation).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (planId is { } id && context.Cancellation.IsCancellationRequested)
|
||||
{
|
||||
// Paused or cancelled by a user, not a yield to another job or the host stopping: the rest waits for this job.
|
||||
if (await db.Jobs.GetAsync(context.Job.Id, CancellationToken.None).ConfigureAwait(false) is { State: JobState.Paused or JobState.Cancelled }
|
||||
&& MassRenamer.Hold(archive, id))
|
||||
Log.Info("archive", $"Reorganize {id} held by its job {context.Job.Id}");
|
||||
throw;
|
||||
}
|
||||
context.Log(Loc.L("Archive.Log.Reorganized", result.Changed.Count, result.Files));
|
||||
foreach (var id in result.Dropped) context.Log(Loc.L("Archive.Log.ReorganizeDropped", Name(plan, id)));
|
||||
foreach (var id in result.FilesKept) context.Log(Loc.L("Archive.Log.ReorganizeFilesKept", Name(plan, id)));
|
||||
await TellAsync(result.Changed).ConfigureAwait(false);
|
||||
var kept = result.Dropped.Count + result.FilesKept.Count;
|
||||
if (kept > 0) throw new InvalidOperationException(Loc.Plural("Archive.Error.ReorganizeKept", kept));
|
||||
}
|
||||
|
||||
/// <summary>Completes a plan this job started; null when its journal went meanwhile (completed at an archive open).</summary>
|
||||
private async Task<RenameResult?> ResumeAsync(JobContext context, Archive archive, RenameJournal journal)
|
||||
{
|
||||
var total = Steps(journal.Plan);
|
||||
await context.ReportAsync(journal.Completed.Count, total).ConfigureAwait(false);
|
||||
return await renamer.ResumeAsync(archive, journal.Plan.Id, n => context.CheckpointAsync(Checkpoint(journal.Plan.Id), n, total), context.Cancellation)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Whether the plan made now is the one confirmed: the same fingerprint, and the frames versions its file names were planned at.</summary>
|
||||
private static bool IsConfirmed(RenamePlan plan, MoveJobParameters parameters)
|
||||
{
|
||||
if (!string.Equals(plan.Fingerprint(), parameters.Fingerprint, StringComparison.Ordinal)) return false;
|
||||
var versions = parameters.Sequences.ToDictionary(s => s.Id, s => s.FramesVersion);
|
||||
return plan.Steps.Where(s => s.FileChanges > 0).All(s => versions.TryGetValue(s.SequenceId, out var version) && version == s.FramesVersion);
|
||||
}
|
||||
|
||||
/// <summary>Tells each sequence changed; a failure is logged, never passed on to the job.</summary>
|
||||
private async Task TellAsync(IReadOnlyList<Guid> changed)
|
||||
{
|
||||
if (sequenceChanged is null) return;
|
||||
foreach (var id in changed)
|
||||
{
|
||||
try
|
||||
{
|
||||
await sequenceChanged(id, Change, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Warning("archive", $"The change of sequence {id} was not told", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static int Steps(RenamePlan plan) => plan.Steps.Count(s => s.Changes);
|
||||
|
||||
/// <summary>How the job log names a sequence of the plan: its title, else its folder.</summary>
|
||||
private static string Name(RenamePlan plan, Guid id) =>
|
||||
plan.Steps.FirstOrDefault(s => s.SequenceId == id) is { } step ? step.ToTitle ?? step.FromTitle ?? step.FromFolder : id.ToString();
|
||||
|
||||
private static string Checkpoint(Guid planId) => Prefix + planId.ToString("N");
|
||||
|
||||
private static Guid? PlanOf(string? checkpoint) =>
|
||||
checkpoint is not null && checkpoint.StartsWith(Prefix, StringComparison.Ordinal) && Guid.TryParseExact(checkpoint[Prefix.Length..], "N", out var id)
|
||||
? id
|
||||
: null;
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,12 @@ public sealed record ArchiveServiceOptions
|
||||
/// </summary>
|
||||
public string? BackupDirectory { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Told after a job changed a sequence's folder, title or file names (change <c>reorganized</c>, a Reorganize): a server
|
||||
/// tells its connected clients (BRIEF §14.3). A failure is logged and never fails the job.
|
||||
/// </summary>
|
||||
public Func<Guid, string, CancellationToken, Task>? SequenceChanged { get; init; }
|
||||
|
||||
/// <summary>Half the logical cores, at least one: the parallelism when the host sets none.</summary>
|
||||
public static int DefaultParallelism => Math.Max(1, Environment.ProcessorCount / 2);
|
||||
|
||||
@@ -88,9 +94,11 @@ internal sealed class SequenceWriter(ArchiveServiceOptions options)
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the sidecar of a locked sequence, undoing an interrupted photo deletion (<see cref="FrameRemovalJournal"/>),
|
||||
/// settling an interrupted restore from the trash (<see cref="FrameRestoreJournal"/>; left for later while its trash
|
||||
/// entry is busy) and completing an interrupted ingest batch first.
|
||||
/// Reads the sidecar of a locked sequence, completing an interrupted Reorganize of its files (<see cref="FileRenameJournal"/>),
|
||||
/// undoing an interrupted photo deletion (<see cref="FrameRemovalJournal"/>), settling an interrupted restore from the
|
||||
/// trash (<see cref="FrameRestoreJournal"/>; left for later while its trash entry is busy) and completing an interrupted
|
||||
/// ingest batch first. A sidecar a rename recovery rewrites leaves the index behind it until the rename resumes or the
|
||||
/// next scan reads it.
|
||||
/// </summary>
|
||||
/// <param name="heldEntryLease">The trash entry lease the caller holds already (a restore of that entry), if any.</param>
|
||||
/// <exception cref="InvalidDataException">The sidecar in the folder belongs to another sequence.</exception>
|
||||
@@ -99,6 +107,15 @@ internal sealed class SequenceWriter(ArchiveServiceOptions options)
|
||||
var manifest = ManifestStore.ReadSequence(sequence.ManifestPath);
|
||||
if (manifest.Id != sequenceId)
|
||||
throw new InvalidDataException($"{sequence.ManifestPath} belongs to sequence {manifest.Id}, not {sequenceId}.");
|
||||
if (File.Exists(sequence.FileRenameJournalPath))
|
||||
{
|
||||
if (FileRenameJournal.Recover(sequence, manifest) is { } renamed)
|
||||
{
|
||||
ManifestStore.WriteSequence(sequence.ManifestPath, renamed);
|
||||
manifest = renamed;
|
||||
}
|
||||
FileRenameJournal.Delete(sequence);
|
||||
}
|
||||
FrameRemovalJournal.Recover(sequence, manifest);
|
||||
FrameTrash.RecoverRestore(sequence, manifest, heldEntryLease);
|
||||
if (IngestJournal.Recover(sequence, manifest) is { } recovered)
|
||||
|
||||
@@ -19,6 +19,9 @@ public readonly record struct FramePosition(Guid FrameId, int Index);
|
||||
/// <summary>A frame whose content (SHA-256) also exists elsewhere in the archive.</summary>
|
||||
public sealed record DuplicateFrame(string Sha256, Guid FrameId, Guid SequenceId, int Index, string RelativePath);
|
||||
|
||||
/// <summary>A frame's file after a Reorganize renamed it (owner review 2, R7): its archive-relative path and its file name.</summary>
|
||||
public readonly record struct FrameFileName(Guid FrameId, string RelativePath, string FileName);
|
||||
|
||||
/// <summary>Light statistics of one frame, written by the analysis job.</summary>
|
||||
public readonly record struct FrameLightStats(Guid FrameId, double? MeanLogLuminance, double? ClipLow, double? ClipHigh);
|
||||
|
||||
@@ -292,6 +295,60 @@ public sealed class FrameRepository
|
||||
[sequenceId, newFolder, length, length, prefix], cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rewrites the paths and file names of frames of one sequence after a Reorganize renamed their files (owner review 2,
|
||||
/// R7), in one transaction that locks the sequence's row first (<see cref="SequenceRepository.GetForUpdateAsync"/>'s
|
||||
/// order); with <paramref name="toVersion"/> the row's frames version becomes it, when it is still
|
||||
/// <paramref name="fromVersion"/> (the sidecar's before the renames). Frames of other sequences are never touched and
|
||||
/// repeating it is harmless. Returns the number of frames updated.
|
||||
/// </summary>
|
||||
public Task<int> RenameFilesAsync(Guid sequenceId, IReadOnlyList<FrameFileName> files, int? fromVersion = null, int? toVersion = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(files);
|
||||
return _db.InTransactionAsync(async session =>
|
||||
{
|
||||
var updated = 0;
|
||||
if (_db.Sql.IsPostgres)
|
||||
{
|
||||
// The row before its frames, as every writer of a sequence's frames; SQLite's write lock already serialises writers.
|
||||
await session.ExecuteAsync($"SELECT id FROM sequences WHERE id = $1{_db.Sql.ForUpdate}", [sequenceId], cancellationToken).ConfigureAwait(false);
|
||||
// One UPDATE … FROM (VALUES …) per batch instead of a round trip per frame.
|
||||
for (var start = 0; start < files.Count; start += Batch)
|
||||
{
|
||||
var count = Math.Min(Batch, files.Count - start);
|
||||
var sql = new StringBuilder("UPDATE frames AS f SET relative_path = v.p, file_name = v.n FROM (VALUES ");
|
||||
var args = new DbParam[count * 3 + 1];
|
||||
args[0] = sequenceId;
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var file = files[start + i];
|
||||
sql.Append(i > 0 ? ", (" : "(").Append('$').Append(3 * i + 2).Append(", $").Append(3 * i + 3).Append(", $").Append(3 * i + 4).Append(')');
|
||||
args[3 * i + 1] = file.FrameId;
|
||||
args[3 * i + 2] = file.RelativePath;
|
||||
args[3 * i + 3] = file.FileName;
|
||||
}
|
||||
sql.Append(") AS v(id, p, n) WHERE f.id = v.id AND f.sequence_id = $1");
|
||||
updated += await session.ExecuteAsync(sql.ToString(), args, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach (var file in files)
|
||||
{
|
||||
updated += await session.ExecuteAsync("UPDATE frames SET relative_path = $3, file_name = $4 WHERE id = $1 AND sequence_id = $2",
|
||||
[file.FrameId, sequenceId, file.RelativePath, file.FileName], cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
if (toVersion is { } to && fromVersion is { } from)
|
||||
{
|
||||
await session.ExecuteAsync("UPDATE sequences SET frames_version = $3, updated_at = $4 WHERE id = $1 AND frames_version = $2",
|
||||
[sequenceId, from, to, DateTimeOffset.UtcNow], cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
return updated;
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes what a verify found, in one transaction: the <see cref="FrameFlags.Missing"/> and <see cref="FrameFlags.Corrupt"/>
|
||||
/// bits and new hashes. Every other flag stays as stored: decode tiers, duplicates and exclusions belong to other
|
||||
|
||||
@@ -81,3 +81,39 @@ public sealed record FacetDto(string Value, int Sequences, string? Label = null)
|
||||
/// sequences first) and tags in use (by name) of the archive's sequences, for the admin panel's Library filters.
|
||||
/// </summary>
|
||||
public sealed record LibraryFacetsDto(IReadOnlyList<FacetDto> Years, IReadOnlyList<FacetDto> Cameras, IReadOnlyList<FacetDto> Tags);
|
||||
|
||||
/// <summary>
|
||||
/// <c>POST /api/v1/archive/reorganize</c> (owner review 2, R7; administrators of the archive): new folder, file and title
|
||||
/// templates applied to sequences already in the archive, <see cref="SequenceIds"/> or every one with <see cref="All"/>
|
||||
/// (exactly one of the two). A null template keeps that part; at least one is given, each valid as the archive settings'
|
||||
/// templates are. <see cref="DryRun"/> answers the plan (<see cref="ReorganizePlanDto"/>) and changes nothing; the change
|
||||
/// itself sends that plan's <see cref="Fingerprint"/> back (409 <c>plan_changed</c> when the archive changed since) and runs
|
||||
/// as a <c>move</c> job (202).
|
||||
/// </summary>
|
||||
public sealed record ReorganizeRequest(IReadOnlyList<Guid>? SequenceIds, bool All, string? FolderTemplate, string? FileTemplate, string? TitleTemplate,
|
||||
bool DryRun, string? Fingerprint = null);
|
||||
|
||||
/// <summary>A file a Reorganize renames: its name before and after, relative to the sequence folder (<c>originals/…</c>).</summary>
|
||||
public sealed record ReorganizeFileDto(string From, string To);
|
||||
|
||||
/// <summary>
|
||||
/// Photos of a sequence that keep their names in a Reorganize: <see cref="Reason"/> <c>in_place</c> (kept in place outside
|
||||
/// <c>originals/</c>), <c>unhashed</c> (never verified), <c>missing</c> or <c>unreadable</c> (the sequence's sidecar), how many
|
||||
/// (0 for <c>unreadable</c>), and the reason as one localised sentence.
|
||||
/// </summary>
|
||||
public sealed record ReorganizeBlockedDto(string Reason, int Photos, string Message);
|
||||
|
||||
/// <summary>
|
||||
/// One sequence of a Reorganize plan, in the order the steps apply: its folder and title before and after,
|
||||
/// <see cref="Carried"/> when it only moves with a folder it is inside, the frames version its file names were planned at
|
||||
/// (0 when none changes), how many photos get a new name with the first of them (<see cref="FileSamples"/>), and the photos
|
||||
/// that keep their names. A step that changes nothing lists only those.
|
||||
/// </summary>
|
||||
public sealed record ReorganizeStepDto(Guid SequenceId, string FromFolder, string ToFolder, string? FromTitle, string? ToTitle, bool Carried,
|
||||
int FramesVersion, int FileChanges, IReadOnlyList<ReorganizeFileDto> FileSamples, IReadOnlyList<ReorganizeBlockedDto> Blocked);
|
||||
|
||||
/// <summary>
|
||||
/// The dry run of a Reorganize: its steps, the sequences that change (carried ones included), the photos renamed, the photos
|
||||
/// that keep their names, and the fingerprint the change sends back.
|
||||
/// </summary>
|
||||
public sealed record ReorganizePlanDto(IReadOnlyList<ReorganizeStepDto> Steps, int Sequences, int Files, int Kept, string Fingerprint);
|
||||
@@ -87,4 +87,6 @@ namespace Chronos.Protocol;
|
||||
[JsonSerializable(typeof(BulkItemResult))]
|
||||
[JsonSerializable(typeof(BulkResultDto))]
|
||||
[JsonSerializable(typeof(LibraryFacetsDto))]
|
||||
[JsonSerializable(typeof(ReorganizeRequest))]
|
||||
[JsonSerializable(typeof(ReorganizePlanDto))]
|
||||
public sealed partial class ProtocolJson : JsonSerializerContext;
|
||||
@@ -1,5 +1,6 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Naming;
|
||||
using Chronos.Data;
|
||||
@@ -13,12 +14,16 @@ using Chronos.Server.Storage;
|
||||
|
||||
namespace Chronos.Server.Api;
|
||||
|
||||
/// <summary><c>/api/v1/archive</c> (admin): templates and proxy policy, scan/rebuild/verify/maintenance jobs, statistics.</summary>
|
||||
/// <summary>
|
||||
/// <c>/api/v1/archive</c> (admin): templates and proxy policy, scan/rebuild/verify/maintenance jobs, statistics, and
|
||||
/// Reorganize (owner review 2, R7): new templates applied to sequences already in the archive.
|
||||
/// </summary>
|
||||
public static class ArchiveEndpoints
|
||||
{
|
||||
public static void Map(RouteGroupBuilder api)
|
||||
{
|
||||
var archive = api.MapGroup("/archive").Requires(Permissions.ManageArchive);
|
||||
archive.MapPost("/reorganize", ReorganizeAsync);
|
||||
// The form saves every field: it starts from what archive.json holds now, also a desktop's change since the last poll.
|
||||
archive.MapGet("/settings", async (HttpContext c, ServerArchive a, ChronosDatabase db, [FromServices] ArchiveService? archives) =>
|
||||
Results.Json(Settings(archives is null ? a.Current : await a.RefreshAsync(archives, db, c.RequestAborted)), ProtocolJson.Default.ArchiveSettingsDto));
|
||||
@@ -122,6 +127,77 @@ public static class ArchiveEndpoints
|
||||
return Results.Json(Settings(updated), ProtocolJson.Default.ArchiveSettingsDto);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reorganize: folder, file and title templates applied to <c>sequenceIds</c> or, with <c>all</c>, to every sequence of the
|
||||
/// archive (BRIEF §12.5). With <c>dryRun</c> the plan, nothing touched: per sequence its folder and title before and after,
|
||||
/// the photos renamed with the first of them, and the photos that keep their names and why. Otherwise the request carries
|
||||
/// that plan's fingerprint and the server queues a <c>move</c> job (202) that applies exactly that plan, refused when the
|
||||
/// archive changed before it ran. 400 <c>bad_request</c> (details <c>sequenceIds</c>: neither or both of them, none, or
|
||||
/// more than <see cref="LibraryEndpoints.MaxBulkIds"/>; <c>templates</c>: none; <c>fingerprint</c>), 400
|
||||
/// <c>invalid_template</c> (details: <c>folderTemplate</c>, <c>fileTemplate</c> or <c>titleTemplate</c>); 404
|
||||
/// <c>not_found</c> (<c>sequence</c>: not in the archive); 409 <c>nested_target</c> (details: the folder that would lie
|
||||
/// inside a sequence's folder), <c>plan_changed</c> (details: the fingerprint now), <c>job_unavailable</c>; 503
|
||||
/// <c>archive_offline</c>. Audited; the job tells every sequence it changes as <c>sequenceChanged</c>
|
||||
/// (<c>reorganized</c>).
|
||||
/// </summary>
|
||||
private static async Task<IResult> ReorganizeAsync(HttpContext context, Caller caller, ReorganizeRequest request, ChronosDatabase db, ServerArchive archive,
|
||||
[FromServices] ArchiveService? archives, JobEngineHost host, AuditLog audit)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (request.All == (request.SequenceIds is not null) || request.SequenceIds is { Count: 0 or > LibraryEndpoints.MaxBulkIds })
|
||||
return ApiErrors.BadRequest(context, "bad_request", "sequenceIds");
|
||||
var templates = new RenameTemplates(request.FolderTemplate, request.FileTemplate, request.TitleTemplate);
|
||||
if (templates.IsEmpty) return ApiErrors.BadRequest(context, "bad_request", "templates");
|
||||
if (templates.Problem() is { } field) return ApiErrors.BadRequest(context, "invalid_template", field);
|
||||
if (!request.DryRun && string.IsNullOrWhiteSpace(request.Fingerprint)) return ApiErrors.BadRequest(context, "bad_request", "fingerprint");
|
||||
if (ArchiveService.GetAvailability(archive.Current) != ArchiveAvailability.Online)
|
||||
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline");
|
||||
RenamePlan plan;
|
||||
try
|
||||
{
|
||||
plan = await LibraryEndpoints.Engine(archives, db).PlanReorganizeAsync(archive.Id, request.All ? null : request.SequenceIds, templates, ct);
|
||||
}
|
||||
catch (NestedRenameException ex)
|
||||
{
|
||||
return ApiErrors.Conflict(context, "nested_target", ex.Target);
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return ApiErrors.NotFound(context, "sequence");
|
||||
}
|
||||
var fingerprint = plan.Fingerprint();
|
||||
if (request.DryRun) return Results.Json(Plan(context, plan, fingerprint), ProtocolJson.Default.ReorganizePlanDto);
|
||||
if (!string.Equals(fingerprint, request.Fingerprint, StringComparison.Ordinal)) return ApiErrors.Conflict(context, "plan_changed", fingerprint);
|
||||
if (!host.CanRun(JobKind.Move)) return ApiErrors.Conflict(context, "job_unavailable", JobWire.Kind(JobKind.Move));
|
||||
var job = await host.Engine.EnqueueAsync(ArchiveJobs.Reorganize(archive.Current, plan, templates), caller.Id, ct);
|
||||
await audit.WriteAsync(caller, context, "archive_reorganized", "job", job.Id.ToString(),
|
||||
$"{plan.Steps.Count(s => s.Changes)} · {plan.Steps.Sum(s => s.FileChanges)} · {templates.Folder} · {templates.File} · {templates.Title}");
|
||||
return Results.Json(Dto.Job(job), ProtocolJson.Default.JobDto, statusCode: StatusCodes.Status202Accepted);
|
||||
}
|
||||
|
||||
/// <summary>The dry run as the API answers it, with each reason photos keep their names in the request's language.</summary>
|
||||
private static ReorganizePlanDto Plan(HttpContext context, RenamePlan plan, string fingerprint)
|
||||
{
|
||||
var culture = RequestCulture.Of(context);
|
||||
return new ReorganizePlanDto(
|
||||
[.. plan.Steps.Select(s => new ReorganizeStepDto(s.SequenceId, s.FromFolder, s.ToFolder, s.FromTitle, s.ToTitle, s.Carried, s.FramesVersion,
|
||||
s.FileChanges, [.. s.FileSamples.Select(f => new ReorganizeFileDto(f.From, f.To))],
|
||||
[.. s.Blocked.Select(b => new ReorganizeBlockedDto(Wire(b.Reason), b.Frames, Loc.Get("Archive.Reorganize.Blocked." + b.Reason, culture) ?? Wire(b.Reason)))]))],
|
||||
plan.Steps.Count(s => s.Changes),
|
||||
plan.Steps.Sum(s => s.FileChanges),
|
||||
plan.Steps.Sum(s => s.Blocked.Sum(b => b.Frames)),
|
||||
fingerprint);
|
||||
}
|
||||
|
||||
/// <summary>Wire name of a reason photos keep their names: <c>in_place</c>, <c>unhashed</c>, <c>missing</c>, <c>unreadable</c>.</summary>
|
||||
public static string Wire(RenameBlock reason) => reason switch
|
||||
{
|
||||
RenameBlock.InPlace => "in_place",
|
||||
RenameBlock.Unhashed => "unhashed",
|
||||
RenameBlock.Missing => "missing",
|
||||
_ => "unreadable",
|
||||
};
|
||||
|
||||
private static async Task<IResult> EnqueueAsync(HttpContext context, Caller caller, ServerArchive archive, JobEngineHost host, AuditLog audit, JobKind kind)
|
||||
{
|
||||
if (!host.CanRun(kind)) return ApiErrors.Conflict(context, "job_unavailable", JobWire.Kind(kind));
|
||||
|
||||
@@ -3,14 +3,17 @@ using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Housekeeping;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Configuration;
|
||||
using Chronos.Server.Events;
|
||||
|
||||
namespace Chronos.Server.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// The archive engine behind the server (BRIEF §7, §14.4): ingest of verified uploads, lookup of proxies and
|
||||
/// thumbnails, and its job handlers (scan, rebuild, verify, import, thumbnails, proxies, maintenance, the duplicates and
|
||||
/// orphans reports, index backups and clean-ups with the server's own steps, the <see cref="ICleanupStep"/>s in DI); a scan
|
||||
/// orphans reports, index backups and clean-ups with the server's own steps, the <see cref="ICleanupStep"/>s in DI, and Reorganize's
|
||||
/// <c>move</c> jobs, which tell connected clients of the sequences they change); a scan
|
||||
/// queues thumbnails and proxies of what it indexes, as an upload does. Decoding is managed only (BRIEF §4.2). Recurring
|
||||
/// work (the periodic scan, the nightly backup of an SQLite index, clean-ups) is queued by the server's system schedules
|
||||
/// (<see cref="Jobs.ServerScheduleHost"/>, owner review 2, R10).
|
||||
@@ -25,9 +28,17 @@ public static class ArchiveModule
|
||||
services.AddSingleton(sp =>
|
||||
{
|
||||
var options = sp.GetRequiredService<ServerOptions>();
|
||||
var db = sp.GetRequiredService<ChronosDatabase>();
|
||||
var events = sp.GetRequiredService<EventHub>();
|
||||
// Photos the running job processes at once: the settings' value as it is when each sequence starts (owner review 1).
|
||||
return new ArchiveService(sp.GetRequiredService<ChronosDatabase>(), new ArchiveServiceOptions
|
||||
return new ArchiveService(db, new ArchiveServiceOptions
|
||||
{
|
||||
// A Reorganize tells connected clients of every sequence it changed (BRIEF §14.3).
|
||||
SequenceChanged = async (id, change, ct) =>
|
||||
{
|
||||
if (await db.Sequences.GetAsync(id, ct) is { } sequence)
|
||||
events.Publish(new SequenceChangedEvent(id, change, sequence.FramesVersion, sequence.SettingsVersion));
|
||||
},
|
||||
Decoder = DecoderFactory.CreateServer(),
|
||||
Owner = Owner,
|
||||
ImagesAfterScan = true,
|
||||
|
||||
Reference in new issue
Block a user