feat: owner review 2 phase 4a: Reorganize sequences after import (#12)
CI / Build and test (push) Successful in 9m15s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 15m35s
CI / PostgreSQL 16 integration (push) Successful in 7m26s
CI / PostgreSQL 17 integration (push) Successful in 6m47s
CI / Docker image (push) Successful in 59s
Release / Server image (push) Successful in 1m24s
CI / Build and test (push) Successful in 9m15s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 15m35s
CI / PostgreSQL 16 integration (push) Successful in 7m26s
CI / PostgreSQL 17 integration (push) Successful in 6m47s
CI / Docker image (push) Successful in 59s
Release / Server image (push) Successful in 1m24s
- Reorganize… on the web panel and the desktop: folder, file and title templates applied to existing sequences, with a dry run and an explicit Apply that runs as a job. - One naming rule (FrameNaming) for import, upload and Reorganize. - Crash-safe plan and file journals, held plans, stale-plan refusal; exports move with their folder. - Writers refuse a folder another program moved or gave to another sequence. - Server: POST /api/v1/archive/reorganize with a bounded plan cache; template rules. - Phase 3 docs and translations merged; strings in all 38 languages. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #12.
This commit is contained in:
1 parent
9aa818ed47
commit
7e4a3b481d
416 files changed
+15304
-1572
No files matched your search
@@ -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,270 @@
|
||||
using System.Globalization;
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the journal once its files are where it says; one whose temporary files are not all gone stays (logged), so
|
||||
/// no photo is ever left at a temporary name without a record of it: the next <see cref="Recover"/> completes it.
|
||||
/// </summary>
|
||||
public static void Delete(SequencePaths sequence)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sequence);
|
||||
if (!File.Exists(sequence.FileRenameJournalPath)) return;
|
||||
if (Read(sequence) is { } journal && journal.Files.FirstOrDefault(f => Exists(sequence, f.Temp)) is { } left)
|
||||
{
|
||||
Log.Error("archive", $"The rename journal of {sequence.RelativeFolder} stays: {sequence.ArchiveRelative(left.Temp)} is still at its temporary name");
|
||||
return;
|
||||
}
|
||||
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. Safe to run again from wherever it stopped (a failure, a crash, a sidecar that could not be
|
||||
/// written): once every file is at its temporary name the journal says phase 2, as <see cref="Run"/> does, so no file
|
||||
/// that reached its new name is ever moved again, but with its frame as follows. A new name something else took meanwhile
|
||||
/// is never written over: all the files of that frame, its photo and companions together, go back to their old names, or
|
||||
/// to the first free <c>_2</c>, <c>_3</c>… of them, recorded in the journal before they move on, and the frame names
|
||||
/// where its photo is (logged). 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>
|
||||
/// <exception cref="IOException">A file could not be moved (open elsewhere); the journal stays, and the next recovery goes on from there.</exception>
|
||||
public static SequenceManifest? Recover(SequencePaths sequence, SequenceManifest manifest)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sequence);
|
||||
ArgumentNullException.ThrowIfNull(manifest);
|
||||
if (Read(sequence) is not { } journal) return null;
|
||||
if (journal.Phase == 1)
|
||||
{
|
||||
foreach (var file in journal.Files)
|
||||
{
|
||||
// What is at an old name beside its file's temporary one came since, and stays.
|
||||
if (Exists(sequence, file.From) && !Exists(sequence, file.Temp)) Move(sequence, file.From, file.Temp);
|
||||
}
|
||||
// Every file is at its temporary name (or nowhere): from here on no old name is moved from again.
|
||||
journal = journal with { Phase = 2 };
|
||||
Write(sequence, journal);
|
||||
}
|
||||
journal = Redirected(sequence, journal);
|
||||
foreach (var file in journal.Files)
|
||||
{
|
||||
if (Exists(sequence, file.Temp)) 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>
|
||||
/// The journal with a new name for every file of a frame one of whose new names something else took since (a file, or a
|
||||
/// folder) while that file waits at its temporary name: all the files of that frame (its photo and companions, which stay
|
||||
/// together: one that reached its new name already goes back to its temporary name first) go back to their old names, or
|
||||
/// to the first <c>_2</c>, <c>_3</c>… of the photo's old name that is free for all of them, none ever a name the rename
|
||||
/// gives another file. Written before any of them moves on, so a recovery run again finds them.
|
||||
/// </summary>
|
||||
private static FileRenameJournal Redirected(SequencePaths sequence, FileRenameJournal journal)
|
||||
{
|
||||
var claimed = new HashSet<string>(journal.Files.Select(f => f.To), StringComparer.OrdinalIgnoreCase);
|
||||
List<FileRenameEntry>? files = null;
|
||||
foreach (var frame in journal.Files.Select((f, i) => (File: f, Index: i)).GroupBy(f => f.File.FrameId))
|
||||
{
|
||||
var taken = frame.Where(f => Exists(sequence, f.File.Temp) && Taken(sequence, f.File.To)).Select(f => f.File.To).ToList();
|
||||
if (taken.Count == 0) continue;
|
||||
// A photo whose companion's new name was taken never stays apart from it at its own new name, nor the other way round.
|
||||
foreach (var (file, _) in frame.Where(f => !Exists(sequence, f.File.Temp) && Exists(sequence, f.File.To))) Move(sequence, file.To, file.Temp);
|
||||
var waiting = frame.Where(f => Exists(sequence, f.File.Temp)).ToList();
|
||||
var photo = frame.FirstOrDefault(f => !f.File.Companion).File ?? frame.First().File;
|
||||
List<string> names;
|
||||
for (var n = 1; ; n++)
|
||||
{
|
||||
names = waiting.ConvertAll(f => Numbered(f.File, photo, n));
|
||||
if (names.TrueForAll(name => !claimed.Contains(name) && !Taken(sequence, name)) && names.Distinct(StringComparer.OrdinalIgnoreCase).Count() == names.Count) break;
|
||||
}
|
||||
files ??= [.. journal.Files];
|
||||
for (var i = 0; i < waiting.Count; i++)
|
||||
{
|
||||
var (file, index) = waiting[i];
|
||||
claimed.Add(names[i]);
|
||||
files[index] = file with { To = names[i] };
|
||||
}
|
||||
Log.Error("archive", $"{string.Join(", ", taken.Select(sequence.ArchiveRelative))} taken while "
|
||||
+ $"a rename was interrupted; the files of that photo go to {string.Join(", ", names.Select(sequence.ArchiveRelative))}");
|
||||
}
|
||||
if (files is null) return journal;
|
||||
journal = journal with { Files = files };
|
||||
Write(sequence, journal);
|
||||
return journal;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The old name of <paramref name="file"/> (<paramref name="n"/> = 1), or the photo's old name with <c>_n</c> and the
|
||||
/// companion's tail after it (<c>IMG_0001_2.CR2</c>, <c>IMG_0001_2.xmp</c>).
|
||||
/// </summary>
|
||||
private static string Numbered(FileRenameEntry file, FileRenameEntry photo, int n)
|
||||
{
|
||||
if (n == 1) return file.From;
|
||||
var stem = photo.From[..^Path.GetExtension(photo.From).Length] + "_" + n.ToString(CultureInfo.InvariantCulture);
|
||||
return file.Companion ? stem + FrameCompanions.Tail(file.From, photo.From) : stem + Path.GetExtension(photo.From);
|
||||
}
|
||||
|
||||
/// <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). A file a recovery
|
||||
/// sent back to its old name (<see cref="Recover"/>) leaves its frame as it is.
|
||||
/// </summary>
|
||||
public static SequenceManifest? Applied(SequenceManifest manifest, FileRenameJournal journal)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(manifest);
|
||||
ArgumentNullException.ThrowIfNull(journal);
|
||||
var renamed = journal.Files.Where(f => !f.Companion && !string.Equals(f.From, f.To, StringComparison.Ordinal)).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));
|
||||
|
||||
/// <summary>Whether a name is held, by a file or a folder: no file can be moved there.</summary>
|
||||
private static bool Taken(SequencePaths sequence, string file) => Path.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,161 @@
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Chronos.Core.Naming;
|
||||
|
||||
namespace Chronos.Core.Archiving;
|
||||
|
||||
/// <summary>
|
||||
/// Why frames of a sequence keep their file names in a Reorganize (owner review 2, R7), nothing of them touched; or, for
|
||||
/// <see cref="Unreadable"/>, why the whole sequence stays as it is.
|
||||
/// </summary>
|
||||
public enum RenameBlock
|
||||
{
|
||||
/// <summary>Photos adopted in place, outside <c>originals/</c>: they belong to a tree someone else keeps.</summary>
|
||||
InPlace,
|
||||
|
||||
/// <summary>Photos whose SHA-256 is not known yet (never verified): a verify hashes them first.</summary>
|
||||
Unhashed,
|
||||
|
||||
/// <summary>Photos whose file is not there.</summary>
|
||||
Missing,
|
||||
|
||||
/// <summary>
|
||||
/// The sequence's sidecar cannot be read, is of a newer format this build does not rewrite, or belongs to another
|
||||
/// sequence: the sequence keeps its folder, title and file names, and so does every folder it is inside (0 frames).
|
||||
/// </summary>
|
||||
Unreadable,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Frames of a sequence that keep their names, and why; or, for <see cref="RenameBlock.Unreadable"/> (0 frames), why the
|
||||
/// whole sequence stays as it is.
|
||||
/// </summary>
|
||||
public sealed record RenameBlocked(RenameBlock Reason, int Frames);
|
||||
|
||||
/// <summary>
|
||||
/// One file of a Reorganize: a frame's photo, or a companion that follows it (<see cref="Companion"/>), from its name to its
|
||||
/// new one; both relative to the sequence folder, forward slashes.
|
||||
/// </summary>
|
||||
public sealed record FileRename(Guid FrameId, string From, string To, bool Companion = false);
|
||||
|
||||
/// <summary>
|
||||
/// The file renames of one sequence: every move, companions included, in frame order; how many frames get a new name; the
|
||||
/// first of them (<see cref="FileRenames.SampleCount"/>) as samples; and the frames that keep their names.
|
||||
/// </summary>
|
||||
public sealed record FileRenamePlan(IReadOnlyList<FileRename> Moves, int Frames, IReadOnlyList<FileRename> Samples, IReadOnlyList<RenameBlocked> Blocked)
|
||||
{
|
||||
public static FileRenamePlan None { get; } = new([], 0, [], []);
|
||||
|
||||
/// <summary>A digest of every move in order (frame, old and new name, companion or not): two plans with the same one rename the same files the same way.</summary>
|
||||
public string Digest()
|
||||
{
|
||||
var text = new StringBuilder();
|
||||
foreach (var move in Moves) text.Append(CultureInfo.InvariantCulture, $"{move.FrameId:N}|{move.From}|{move.To}|{move.Companion}\n");
|
||||
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text.ToString())));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Plans the new file names of a sequence's frames from a file template (Reorganize, owner review 2, R7; BRIEF §7.1, §12.5).
|
||||
/// Frames are named in index order with the context an upload in capture order is filed with (<see cref="FrameNaming"/>,
|
||||
/// which says where filing gave other names); a name already given, or held by a file that stays (a frame left alone, a file
|
||||
/// no frame lists), gets <c>_2</c>, <c>_3</c>… as filing does, so the same frames, template and folder always give the same
|
||||
/// names. Only photos under <c>originals/</c> whose SHA-256 is known and
|
||||
/// whose file is there are renamed, each within its folder; the XMP companions of a photo follow it
|
||||
/// (<see cref="FrameCompanions"/>; one named by a stem two frames share follows the first). The sidecar's frame order never
|
||||
/// changes.
|
||||
/// </summary>
|
||||
public static class FileRenames
|
||||
{
|
||||
/// <summary>Renamed frames a plan shows as samples.</summary>
|
||||
public const int SampleCount = 3;
|
||||
|
||||
private const string Originals = ArchiveLayout.OriginalsFolder + "/";
|
||||
|
||||
/// <param name="title">The sequence title the names use (<c>{title}</c>): the new one when the same Reorganize retitles it.</param>
|
||||
/// <param name="present">Every file in the folders of the sequence's frames, relative to the sequence folder (<see cref="ListPresent"/>).</param>
|
||||
public static FileRenamePlan Plan(SequenceManifest manifest, string? title, PathTemplate template, IReadOnlyCollection<string> present)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(manifest);
|
||||
ArgumentNullException.ThrowIfNull(template);
|
||||
ArgumentNullException.ThrowIfNull(present);
|
||||
var onDisk = new HashSet<string>(present, StringComparer.OrdinalIgnoreCase);
|
||||
int inPlace = 0, unhashed = 0, missing = 0;
|
||||
var eligible = new List<SidecarFrame>();
|
||||
// Companions are claimed in frame order by every frame, renamed or not: one a frame left alone claims stays with it.
|
||||
var claimed = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var companions = new Dictionary<Guid, List<string>>();
|
||||
// By the name they give without ".xmp": a photo's path without its extension, or its whole path.
|
||||
var xmp = onDisk.Where(f => f.EndsWith(FrameCompanions.Extension, StringComparison.OrdinalIgnoreCase))
|
||||
.ToLookup(f => f[..^FrameCompanions.Extension.Length], StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var frame in manifest.Frames)
|
||||
{
|
||||
var own = xmp[Stem(frame.File)].Concat(xmp[frame.File]).Distinct(StringComparer.OrdinalIgnoreCase).Order(StringComparer.Ordinal)
|
||||
.Where(c => FrameCompanions.Names(c, frame.File) && claimed.Add(c)).ToList();
|
||||
if (!frame.File.StartsWith(Originals, StringComparison.OrdinalIgnoreCase)) inPlace++;
|
||||
else if (frame.Sha256 is null) unhashed++;
|
||||
else if (!onDisk.Contains(frame.File)) missing++;
|
||||
else
|
||||
{
|
||||
eligible.Add(frame);
|
||||
companions[frame.Id] = own;
|
||||
}
|
||||
}
|
||||
|
||||
// What stays where it is: files no renamed frame or companion moves away from, and every frame left alone.
|
||||
var moving = new HashSet<string>(eligible.Select(f => f.File).Concat(companions.Values.SelectMany(c => c)), StringComparer.OrdinalIgnoreCase);
|
||||
var taken = new HashSet<string>(onDisk.Where(f => !moving.Contains(f)), StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var frame in manifest.Frames.Where(f => !companions.ContainsKey(f.Id))) taken.Add(frame.File);
|
||||
|
||||
var moves = new List<FileRename>();
|
||||
var samples = new List<FileRename>();
|
||||
var renamed = 0;
|
||||
var names = new UniqueNames(taken);
|
||||
foreach (var frame in eligible)
|
||||
{
|
||||
var own = companions[frame.Id];
|
||||
var tails = own.ConvertAll(c => FrameCompanions.Tail(c, frame.File));
|
||||
var directory = frame.File[..(frame.File.LastIndexOf('/') + 1)];
|
||||
var file = names.Claim(directory + template.ExpandFile(FrameNaming.Context(frame, manifest, title)),
|
||||
candidate => tails.TrueForAll(t => !taken.Contains(Stem(candidate) + t)));
|
||||
foreach (var tail in tails) taken.Add(Stem(file) + tail);
|
||||
if (string.Equals(file, frame.File, StringComparison.Ordinal)) continue;
|
||||
var move = new FileRename(frame.Id, frame.File, file);
|
||||
moves.Add(move);
|
||||
if (samples.Count < SampleCount) samples.Add(move);
|
||||
renamed++;
|
||||
for (var c = 0; c < own.Count; c++)
|
||||
{
|
||||
var to = Stem(file) + tails[c];
|
||||
if (!string.Equals(to, own[c], StringComparison.Ordinal)) moves.Add(new FileRename(frame.Id, own[c], to, Companion: true));
|
||||
}
|
||||
}
|
||||
var blocked = new List<RenameBlocked>();
|
||||
if (inPlace > 0) blocked.Add(new RenameBlocked(RenameBlock.InPlace, inPlace));
|
||||
if (unhashed > 0) blocked.Add(new RenameBlocked(RenameBlock.Unhashed, unhashed));
|
||||
if (missing > 0) blocked.Add(new RenameBlocked(RenameBlock.Missing, missing));
|
||||
return new FileRenamePlan(moves, renamed, samples, blocked);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Every file in the folders that hold the sequence's frames (<c>originals/</c> as a rule), relative to the sequence
|
||||
/// folder; hidden files included, so no name a file holds is ever given.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<string> ListPresent(SequencePaths sequence, SequenceManifest manifest)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sequence);
|
||||
ArgumentNullException.ThrowIfNull(manifest);
|
||||
var files = new List<string>();
|
||||
foreach (var prefix in manifest.Frames.Select(f => f.File[..(f.File.LastIndexOf('/') + 1)]).Distinct(StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
var directory = prefix.Length == 0 ? sequence.Folder : sequence.File(prefix.TrimEnd('/'));
|
||||
// Listed as the trash lists companions (FrameCompanions), so both find the same XMP files.
|
||||
files.AddRange(FrameCompanions.List(directory).Select(n => prefix + n));
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
/// <summary>A file's path without its extension (<c>originals/2026-09-28_0001</c>).</summary>
|
||||
private static string Stem(string file) => file[..^Path.GetExtension(file).Length];
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,9 @@ public sealed class LeaseFile : IDisposable
|
||||
{
|
||||
public static readonly TimeSpan DefaultDuration = TimeSpan.FromMinutes(2);
|
||||
|
||||
/// <summary>The longest a writer waiting for a lease (<see cref="AcquireAsync"/>) sleeps between two tries.</summary>
|
||||
public static readonly TimeSpan LongestPoll = TimeSpan.FromMilliseconds(500);
|
||||
|
||||
private const string Extension = ".lease";
|
||||
private const string StaleExtension = ".stale";
|
||||
private const int ReadAttempts = 5;
|
||||
@@ -84,7 +87,7 @@ public sealed class LeaseFile : IDisposable
|
||||
if (TryAcquire(locksDirectory, name, owner, duration) is { } lease) return lease;
|
||||
if (DateTime.UtcNow >= deadline) throw new LeaseUnavailableException(name, Read(PathFor(locksDirectory, name)));
|
||||
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
|
||||
delay = TimeSpan.FromMilliseconds(System.Math.Min(delay.TotalMilliseconds * 2, 500));
|
||||
delay = TimeSpan.FromMilliseconds(System.Math.Min(delay.TotalMilliseconds * 2, LongestPoll.TotalMilliseconds));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,21 +1,136 @@
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Localization;
|
||||
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);
|
||||
/// <summary>
|
||||
/// What the planner needs to know about a sequence to rename it. Without its sidecar (<see cref="Files"/>) the templates see
|
||||
/// the index row's capture time, camera and lens, and a sequence without a capture time keeps its folder and title.
|
||||
/// </summary>
|
||||
public sealed record RenameSubject(Guid SequenceId, string Folder, string? Title, DateTime? FirstCapture, string? CameraMake, string? CameraModel, string? Lens)
|
||||
{
|
||||
/// <summary>
|
||||
/// The sidecar, whose first frame the folder and title templates see as filing saw it, and the files beside its frames,
|
||||
/// which a file template renames (empty without one); null when it was not read, or could not be.
|
||||
/// </summary>
|
||||
public SequenceFiles? Files { get; init; }
|
||||
|
||||
/// <summary>One sequence's change: its folder, its title, or both.</summary>
|
||||
/// <summary>
|
||||
/// The sidecar could not be read, or belongs to another sequence: the sequence stays as it is, and so does every folder
|
||||
/// it is inside, which could not take it along (<see cref="RenameBlock.Unreadable"/>).
|
||||
/// </summary>
|
||||
public bool Unreadable { get; init; }
|
||||
}
|
||||
|
||||
/// <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: frames that keep their file names, or a sequence that stays as it is
|
||||
/// because its sidecar cannot be read (<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 new folder or file names come from the sequence's title (the folder or file template uses <c>{title}</c>): a title
|
||||
/// edited since the plan would leave them named after the old one.
|
||||
/// </summary>
|
||||
public bool NamedByTitle { get; init; }
|
||||
|
||||
/// <summary>Whether what the step changes depends on the sequence's title: it changes it, or names the folder or files after it.</summary>
|
||||
public bool UsesTitle => Retitles || NamedByTitle;
|
||||
|
||||
/// <summary>
|
||||
/// The sidecar's frames version the file names were planned at; 0 when no file gets a new name. What the apply checks the
|
||||
/// files by only in a plan journaled without <see cref="FileDigest"/>.
|
||||
/// </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>
|
||||
/// Every file rename of the step, as a digest (<see cref="FileRenamePlan.Digest"/>): the apply renames the files only
|
||||
/// while they plan to exactly these. Null when no file gets a new name (or in a plan journaled before it existed).
|
||||
/// </summary>
|
||||
public string? FileDigest { get; init; }
|
||||
|
||||
/// <summary>Frames that keep their file names, and why; <see cref="RenameBlock.Unreadable"/> (0 frames) when the whole sequence stays as it is.</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 = TemplateRules.Sample()[0];
|
||||
|
||||
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 (<see cref="PathTemplate.IsValid"/>), with a format a sample cannot be written
|
||||
/// with (<c>{date:%}</c>), expanding to nothing, or, for a folder or file template, breaking a rule of the archive's
|
||||
/// templates (<see cref="TemplateRules"/>: a folder scans never enter; a slash, a lost extension or names that would
|
||||
/// repeat); null when every one given can. The archive settings' templates are checked alike, except for the rules a
|
||||
/// template <c>archive.json</c> already holds breaks (<c>ArchiveSettings.Problem</c>).
|
||||
/// </summary>
|
||||
public string? Problem() => Check()?.Field;
|
||||
|
||||
/// <summary>
|
||||
/// The first template that cannot be used (<see cref="Problem"/>), with the rule of <see cref="TemplateRules"/> it breaks
|
||||
/// when it parses and expands (<see cref="TemplateProblem.Rule"/>); null when every one given can.
|
||||
/// </summary>
|
||||
public TemplateProblem? Check() =>
|
||||
Unusable("folderTemplate", Folder, t => t.ExpandFolder(Sample), TemplateRules.FolderRule)
|
||||
?? Unusable("fileTemplate", File, t => t.ExpandFile(Sample), TemplateRules.FileRule)
|
||||
?? Unusable("titleTemplate", Title, t => t.ExpandText(Sample));
|
||||
|
||||
private static TemplateProblem? Unusable(string field, string? template, Func<PathTemplate, string> expand, Func<PathTemplate, string?>? rule = null)
|
||||
{
|
||||
if (template is null) return null;
|
||||
if (string.IsNullOrWhiteSpace(template)) return new TemplateProblem(field, null);
|
||||
var parsed = PathTemplate.Parse(template);
|
||||
if (!parsed.IsValid) return new TemplateProblem(field, null);
|
||||
try
|
||||
{
|
||||
if (expand(parsed).Length == 0) return new TemplateProblem(field, null);
|
||||
return rule?.Invoke(parsed) is { } broken ? new TemplateProblem(field, broken) : null;
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
return new TemplateProblem(field, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A template that cannot be used: its API name (<c>folderTemplate</c>, <c>fileTemplate</c>, <c>titleTemplate</c>) and the
|
||||
/// rule of <see cref="TemplateRules"/> it breaks (<c>ReservedFolder</c>, <c>FileSeparator</c>, <c>Extension</c>,
|
||||
/// <c>NotUnique</c>, each explained by <c>Errors.Template.<Rule></c>); no rule when it is blank, not valid or expands to nothing.
|
||||
/// </summary>
|
||||
public sealed record TemplateProblem(string Field, string? Rule);
|
||||
|
||||
/// <summary>A planned folder would lie inside a sequence's folder (nesting one sequence in another); nothing is planned.</summary>
|
||||
public sealed class NestedRenameException(string target, string folder)
|
||||
: ArgumentException(Loc.L("Archive.Error.NestedTarget", target, folder))
|
||||
@@ -25,11 +140,73 @@ 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 folder template the steps' folders come from; null when folders stay, or in a plan journaled before it was kept
|
||||
/// (whose steps' folders are then taken as planned).
|
||||
/// </summary>
|
||||
public string? FolderTemplate { get; init; }
|
||||
|
||||
/// <summary>The title template the steps' titles come from; null when titles stay, or in a plan journaled before it was kept.</summary>
|
||||
public string? TitleTemplate { 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, every file rename by its digest, and
|
||||
/// the file template), the same for two plans of the same archive state: what a confirmation sends back so the change
|
||||
/// made is the one that was shown. The frames version is not part of it: photos a sequence received since under the names
|
||||
/// the plan gives them (an upload filed with the same template) leave the plan as it was, and the apply renames the files
|
||||
/// only while they rename exactly as planned (<see cref="RenameStep.FileDigest"/>).
|
||||
/// </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.FileChanges}|{s.FileDigest}|");
|
||||
foreach (var sample in s.FileSamples) text.Append(sample.From).Append('>').Append(sample.To).Append(';');
|
||||
foreach (var blocked in s.Blocked) text.Append(CultureInfo.InvariantCulture, $"{blocked.Reason}:{blocked.Frames};");
|
||||
text.Append('\n');
|
||||
}
|
||||
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text.ToString())));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What the completed steps of a plan did, over every run that applied them (<see cref="RenameJournal.Done"/>): the
|
||||
/// sequences changed, the frames whose file got a new name, and the sequences not changed as planned: because they changed
|
||||
/// since, left as they were (<see cref="Dropped"/>), their file names kept (<see cref="FilesKept"/>) or their title and file
|
||||
/// names kept (<see cref="TitlesKept"/>); their file names kept because a photo was in use or a new name was taken
|
||||
/// (<see cref="FilesBusy"/>); their title and file names kept because a newer Chronos wrote their sidecar (<see cref="Newer"/>);
|
||||
/// left as they were because the folder around them that was to carry them stayed, for its own reason
|
||||
/// (<see cref="CarriedKept"/>).
|
||||
/// </summary>
|
||||
public sealed record RenameTally
|
||||
{
|
||||
public IReadOnlyList<Guid> Changed { get; init; } = [];
|
||||
public int Files { get; init; }
|
||||
public IReadOnlyList<Guid> Dropped { get; init; } = [];
|
||||
public IReadOnlyList<Guid> FilesKept { get; init; } = [];
|
||||
public IReadOnlyList<Guid> TitlesKept { get; init; } = [];
|
||||
public IReadOnlyList<Guid> FilesBusy { get; init; } = [];
|
||||
public IReadOnlyList<Guid> Newer { get; init; } = [];
|
||||
public IReadOnlyList<Guid> CarriedKept { get; init; } = [];
|
||||
}
|
||||
|
||||
/// <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, cancelled or failed between two steps: an archive open leaves the
|
||||
/// plan to that job, which completes it when it is resumed or retried.</param>
|
||||
public sealed record RenameJournal(RenamePlan Plan, IReadOnlyList<Guid> Completed, bool Held = false)
|
||||
{
|
||||
/// <summary>What the completed steps did, so a resumed run reports the whole plan.</summary>
|
||||
public RenameTally Done { get; init; } = new();
|
||||
|
||||
public static string PathFor(ArchivePaths archive, Guid planId) => Path.Combine(archive.JournalDirectory, $"rename-{planId:N}.json");
|
||||
|
||||
public static void Write(ArchivePaths archive, RenameJournal journal)
|
||||
@@ -38,64 +215,129 @@ 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. A journal that cannot be read (damaged by hand, or by a
|
||||
/// disk) is logged and left where it is, so the archive still opens; its plan is not resumed, and the file renames of
|
||||
/// its steps are completed by their own journals (<see cref="FileRenameJournal"/>).
|
||||
/// </summary>
|
||||
public static IReadOnlyList<RenameJournal> ListPending(ArchivePaths archive)
|
||||
{
|
||||
if (!Directory.Exists(archive.JournalDirectory)) return [];
|
||||
var list = new List<RenameJournal>();
|
||||
foreach (var path in Directory.EnumerateFiles(archive.JournalDirectory, "rename-*.json").Order(StringComparer.Ordinal))
|
||||
{
|
||||
if (JsonSerializer.Deserialize(File.ReadAllBytes(path), ArchiveJson.Default.RenameJournal) is { } journal) list.Add(journal);
|
||||
try
|
||||
{
|
||||
if (Parse(File.ReadAllBytes(path)) is { } journal) list.Add(journal);
|
||||
else Log.Warning("archive", $"The rename journal {Path.GetFileName(path)} is empty or incomplete; its plan is not resumed");
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
Log.Warning("archive", $"The rename journal {Path.GetFileName(path)} cannot be read; its plan is not resumed", ex);
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The journal of the plan <paramref name="planId"/>; null when there is none (the plan completed, or never started).
|
||||
/// Throws <see cref="InvalidDataException"/> when the journal is there but cannot be read, so its job fails with the
|
||||
/// reason instead of planning again over a half-applied plan.
|
||||
/// </summary>
|
||||
public static RenameJournal? Read(ArchivePaths archive, Guid planId)
|
||||
{
|
||||
var path = PathFor(archive, planId);
|
||||
if (!File.Exists(path)) return null;
|
||||
try
|
||||
{
|
||||
return Parse(File.ReadAllBytes(path)) ?? throw new InvalidDataException($"The rename journal {Path.GetFileName(path)} is incomplete.");
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
throw new InvalidDataException($"The rename journal {Path.GetFileName(path)} cannot be read.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static RenameJournal? Parse(byte[] bytes) =>
|
||||
JsonSerializer.Deserialize(bytes, ArchiveJson.Default.RenameJournal) is { Plan: not null, Completed: not null } journal ? journal : 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.
|
||||
/// <paramref name="folderTemplate"/> (where <c>{title}</c> is the new title) for every subject, from its first frame as
|
||||
/// filing saw it (<see cref="FrameNaming.Context(SidecarFrame, SequenceManifest, string?)"/>); a title is text, not a file
|
||||
/// name (<see cref="PathTemplate.ExpandText"/>). A target folder that is any current sequence folder, exists on disk or
|
||||
/// was given to an earlier subject (whatever its case) gets " (2)", " (3)"…; a sequence keeps its own folder in the
|
||||
/// template's case only while no other folder holds that exact name. 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 step whose
|
||||
/// new folder or file names come from <c>{title}</c> says so (<see cref="RenameStep.NamedByTitle"/>). A subject
|
||||
/// whose sidecar could not be read (<see cref="RenameSubject.Unreadable"/>, or no <see cref="RenameSubject.Files"/> for a
|
||||
/// file template) stays as it is, listed with the reason, and so does the folder of every subject it is inside. Null
|
||||
/// templates leave that part unchanged; subjects without a change produce no step, unless frames of theirs keep their
|
||||
/// names. A folder that moves takes the sequences inside it along: each gets a <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>
|
||||
/// <param name="existsExactly">Whether a folder of exactly that name, in every level's case, is on disk
|
||||
/// (<see cref="ExistsExactly"/>): on a case-sensitive file system <c>Trip (2)</c> beside a sequence at <c>trip (2)</c> is
|
||||
/// another folder, which a change of case could never move onto; on a case-insensitive one only the sequence's own
|
||||
/// folder can be found, under at most one of the two names (under neither when the disk spells it another way, such as
|
||||
/// <c>TRIP (2)</c>). Null when no folder but the sequences' own counts.</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,
|
||||
Func<string, bool>? existsExactly = null)
|
||||
{
|
||||
existsExactly ??= _ => false;
|
||||
var folder = folderTemplate is null ? null : PathTemplate.Parse(folderTemplate);
|
||||
var title = titleTemplate is null ? null : PathTemplate.Parse(titleTemplate);
|
||||
var file = fileTemplate is null ? null : PathTemplate.Parse(fileTemplate);
|
||||
bool folderByTitle = folder?.Uses("title") == true, filesByTitle = file?.Uses("title") == true;
|
||||
var taken = occupied.ToList();
|
||||
var claimed = new HashSet<string>(taken, StringComparer.OrdinalIgnoreCase);
|
||||
// The folders given in this plan so far: Kept never gives one twice (two folders that differ only in case).
|
||||
var given = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
bool Unreadable(RenameSubject s) => s.Unreadable || (file is not null && s.Files is null);
|
||||
// A folder that holds a sequence whose sidecar cannot be read cannot take it along.
|
||||
var stuck = subjects.Where(Unreadable).Concat((nested ?? []).Where(n => n.Unreadable)).ToList();
|
||||
var blockers = new HashSet<Guid>();
|
||||
var own = new List<RenameStep>(subjects.Count);
|
||||
foreach (var s in subjects)
|
||||
{
|
||||
var context = new NamingContext
|
||||
if (Unreadable(s))
|
||||
{
|
||||
CapturedAt = s.FirstCapture ?? DateTime.Today,
|
||||
SessionStart = s.FirstCapture ?? DateTime.Today,
|
||||
CameraMake = s.CameraMake,
|
||||
CameraModel = s.CameraModel,
|
||||
Lens = s.Lens,
|
||||
Title = s.Title,
|
||||
};
|
||||
var newTitle = title is null ? s.Title : Blank(title.ExpandFile(context)) ?? s.Title;
|
||||
own.Add(new RenameStep(s.SequenceId, s.Folder, s.Folder, s.Title, s.Title) { Blocked = [new RenameBlocked(RenameBlock.Unreadable, 0)] });
|
||||
continue;
|
||||
}
|
||||
var context = Context(s);
|
||||
var newTitle = NewTitle(context, s.Title, title);
|
||||
var newFolder = s.Folder;
|
||||
// The archive root itself (a folder adopted in place) cannot move; only its title changes.
|
||||
if (folder is not null && s.Folder.Length > 0 && Blank(folder.ExpandFolder(context with { Title = newTitle })) is { } expanded
|
||||
if (folder is not null && context is not null && s.Folder.Length > 0 && NewFolder(context, newTitle, folder) is { } expanded
|
||||
&& !expanded.Equals(s.Folder, StringComparison.Ordinal))
|
||||
{
|
||||
newFolder = expanded.Equals(s.Folder, StringComparison.OrdinalIgnoreCase) ? expanded : Unique(expanded, claimed, existsOnDisk);
|
||||
claimed.Add(newFolder);
|
||||
var inside = stuck.Where(u => IsInside(s.Folder, u.Folder)).Select(u => u.SequenceId).ToList();
|
||||
if (inside.Count > 0)
|
||||
{
|
||||
blockers.UnionWith(inside);
|
||||
}
|
||||
else
|
||||
{
|
||||
newFolder = Kept(s.Folder, expanded, taken, given, existsExactly) ?? Unique(expanded, claimed, existsOnDisk);
|
||||
claimed.Add(newFolder);
|
||||
given.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);
|
||||
if (file is not null) step = WithFiles(step, s.Files!, file, newTitle);
|
||||
own.Add(step with { NamedByTitle = (folderByTitle && step.MovesFolder) || (filesByTitle && step.FileChanges > 0) });
|
||||
}
|
||||
|
||||
var moving = own.Where(s => s.MovesFolder).ToList();
|
||||
@@ -106,7 +348,12 @@ public static class RenamePlanner
|
||||
if (host is not null) throw new NestedRenameException(step.ToFolder, host);
|
||||
}
|
||||
var steps = new List<(RenameStep Step, int Order)>();
|
||||
foreach (var step in own.Concat((nested ?? []).Select(n => new RenameStep(n.SequenceId, n.Folder, n.Folder, n.Title, n.Title))))
|
||||
// An unreadable sequence that kept a folder around it in place is listed with why, as an unreadable subject is.
|
||||
var inner = (nested ?? []).Select(n => new RenameStep(n.SequenceId, n.Folder, n.Folder, n.Title, n.Title)
|
||||
{
|
||||
Blocked = n.Unreadable && blockers.Contains(n.SequenceId) ? [new RenameBlocked(RenameBlock.Unreadable, 0)] : [],
|
||||
});
|
||||
foreach (var step in own.Concat(inner))
|
||||
{
|
||||
// The nearest folder around it that moves carries it; a sequence that moves elsewhere leaves before its folder does.
|
||||
var carrier = step.MovesFolder ? null : moving.Where(m => IsInside(m.FromFolder, step.FromFolder)).MaxBy(m => m.FromFolder.Length);
|
||||
@@ -114,11 +361,106 @@ 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,
|
||||
FolderTemplate = folderTemplate,
|
||||
TitleTemplate = titleTemplate,
|
||||
Subjects = [.. subjects.Select(s => s.SequenceId)],
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The title and the folder the templates give a sequence from its sidecar (<paramref name="manifest"/>) as
|
||||
/// <see cref="Plan"/> gives them, where <c>{title}</c> of the title template is <paramref name="title"/>: the title is
|
||||
/// <paramref name="title"/> without a title template or when it expands to nothing; the folder is the expansion itself,
|
||||
/// before any <c>" (2)"</c> (<see cref="Gives"/>), null without a folder template or when it expands to nothing.
|
||||
/// </summary>
|
||||
public static (string? Title, string? Folder) Names(SequenceManifest manifest, string? title, string? folderTemplate, string? titleTemplate)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(manifest);
|
||||
var context = Context(manifest, title);
|
||||
var newTitle = NewTitle(context, title, titleTemplate is null ? null : PathTemplate.Parse(titleTemplate));
|
||||
return (newTitle, folderTemplate is null ? null : NewFolder(context, newTitle, PathTemplate.Parse(folderTemplate)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether <paramref name="folder"/> is a folder a plan gives for the expansion <paramref name="expanded"/>
|
||||
/// (<see cref="Names"/>): that one, or the <c>" (n)"</c> of it that a folder of that name already there made it take.
|
||||
/// </summary>
|
||||
public static bool Gives(string expanded, string folder)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(expanded);
|
||||
ArgumentNullException.ThrowIfNull(folder);
|
||||
return folder.Equals(expanded, StringComparison.Ordinal) || (Numbered(folder, expanded, StringComparison.Ordinal) is { } n && n >= 2
|
||||
&& folder.Equals(string.Create(CultureInfo.InvariantCulture, $"{expanded} ({n})"), StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
/// <summary>The <c>n</c> of <paramref name="folder"/> when it is <paramref name="expanded"/> followed by <c>" (n)"</c>; null otherwise.</summary>
|
||||
private static int? Numbered(string folder, string expanded, StringComparison comparison) =>
|
||||
folder.Length > expanded.Length + 3 && folder.StartsWith(expanded + " (", comparison) && folder[^1] == ')'
|
||||
&& int.TryParse(folder.AsSpan(expanded.Length + 2, folder.Length - expanded.Length - 3), NumberStyles.None, CultureInfo.InvariantCulture, out var n)
|
||||
? n
|
||||
: null;
|
||||
|
||||
private static string? NewTitle(NamingContext? context, string? title, PathTemplate? template) =>
|
||||
template is null || context is null ? title : Blank(template.ExpandText(context)) ?? title;
|
||||
|
||||
private static string? NewFolder(NamingContext context, string? newTitle, PathTemplate template) => Blank(template.ExpandFolder(context with { Title = newTitle }));
|
||||
|
||||
/// <summary>
|
||||
/// What the folder and title templates of a subject see: its first frame in its sidecar, as an upload filed it and as
|
||||
/// Reorganize names its files (a sidecar without frames: when the sequence was made); without the sidecar, the index
|
||||
/// row's capture time, camera and lens. Null when no time is known: never today's date, which would move the folder
|
||||
/// again on another day.
|
||||
/// </summary>
|
||||
private static NamingContext? Context(RenameSubject s)
|
||||
{
|
||||
if (s.Files?.Manifest is { } manifest) return Context(manifest, s.Title);
|
||||
if (s.FirstCapture is not { } first) return null;
|
||||
return new NamingContext
|
||||
{
|
||||
CapturedAt = first,
|
||||
SessionStart = first,
|
||||
CameraMake = s.CameraMake,
|
||||
CameraModel = s.CameraModel,
|
||||
Lens = s.Lens,
|
||||
Title = s.Title,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>What the folder and title templates see in a sidecar: its first frame (<see cref="Context(RenameSubject)"/>).</summary>
|
||||
private static NamingContext Context(SequenceManifest manifest, string? title)
|
||||
{
|
||||
if (manifest.Frames.Count > 0) return FrameNaming.Context(manifest.Frames[0], manifest, title);
|
||||
var start = FrameNaming.SessionStart(manifest);
|
||||
return new NamingContext
|
||||
{
|
||||
CapturedAt = start,
|
||||
SessionStart = start,
|
||||
CameraMake = manifest.Camera?.Make,
|
||||
CameraModel = manifest.Camera?.Model,
|
||||
Lens = manifest.Lens,
|
||||
Title = title,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The step with the file renames of its sequence (<see cref="FileRenames.Plan"/>).</summary>
|
||||
private static RenameStep WithFiles(RenameStep step, SequenceFiles files, PathTemplate template, string? title)
|
||||
{
|
||||
var plan = FileRenames.Plan(files.Manifest, title, template, files.Present);
|
||||
return step with
|
||||
{
|
||||
FramesVersion = plan.Frames > 0 ? files.Manifest.Versions.Frames : 0,
|
||||
FileChanges = plan.Frames,
|
||||
FileSamples = plan.Samples,
|
||||
FileDigest = plan.Frames > 0 ? plan.Digest() : null,
|
||||
Blocked = plan.Blocked,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -132,16 +474,18 @@ public static class RenamePlanner
|
||||
/// Moves the folder of a step; idempotent so a resumed plan can repeat it: an already moved folder is accepted,
|
||||
/// a case-only change goes through a temporary name (case-insensitive file systems).
|
||||
/// </summary>
|
||||
/// <exception cref="IOException">The target is occupied by something else, or neither folder exists.</exception>
|
||||
/// <exception cref="IOException">The target is occupied by something else (for a case-only change, a folder of its own
|
||||
/// on a case-sensitive file system, which the plan and the apply refuse first), or neither folder exists.</exception>
|
||||
public static void MoveFolder(ArchivePaths archive, RenameStep step)
|
||||
{
|
||||
if (!step.MovesFolder) return;
|
||||
var from = archive.FromRelative(step.FromFolder);
|
||||
var to = archive.FromRelative(step.ToFolder);
|
||||
var caseOnly = step.FromFolder.Equals(step.ToFolder, StringComparison.OrdinalIgnoreCase);
|
||||
if (Directory.Exists(to) && (!caseOnly || HasExactName(to)))
|
||||
if (Directory.Exists(to) && (!caseOnly || ExistsExactly(archive, step.ToFolder)))
|
||||
{
|
||||
if (Directory.Exists(from) && !caseOnly) throw new IOException($"Rename target {step.ToFolder} already exists.");
|
||||
// Both names there: the target is another folder (for a case-only change, on a case-sensitive file system).
|
||||
if (Directory.Exists(from) && (!caseOnly || ExistsExactly(archive, step.FromFolder))) throw new IOException($"Rename target {step.ToFolder} already exists.");
|
||||
return;
|
||||
}
|
||||
if (!Directory.Exists(from)) throw new DirectoryNotFoundException($"Sequence folder {step.FromFolder} is missing.");
|
||||
@@ -158,12 +502,59 @@ public static class RenamePlanner
|
||||
}
|
||||
}
|
||||
|
||||
private static bool HasExactName(string path) =>
|
||||
Directory.EnumerateDirectories(Path.GetDirectoryName(path)!, Path.GetFileName(path))
|
||||
.Any(d => Path.GetFileName(d).Equals(Path.GetFileName(path), StringComparison.Ordinal));
|
||||
/// <summary>
|
||||
/// Whether the folder <paramref name="folder"/> (archive-relative, forward slashes) is on disk with exactly that name at
|
||||
/// every level. On a case-insensitive file system a folder whose name differs in case only does not count, so a change
|
||||
/// of case only finds its own folder under its old name alone; on a case-sensitive one this is any folder of that name.
|
||||
/// </summary>
|
||||
public static bool ExistsExactly(ArchivePaths archive, string folder)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archive);
|
||||
ArgumentNullException.ThrowIfNull(folder);
|
||||
var path = archive.Root;
|
||||
var options = new EnumerationOptions { MatchType = MatchType.Simple, AttributesToSkip = 0, IgnoreInaccessible = true };
|
||||
foreach (var name in folder.Split('/', StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
try
|
||||
{
|
||||
// The name as a pattern finds it whatever its case on Windows; only the exact one counts.
|
||||
if (!Directory.EnumerateDirectories(path, name, options).Any(d => Path.GetFileName(d).Equals(name, StringComparison.Ordinal))) return false;
|
||||
}
|
||||
catch (DirectoryNotFoundException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
path = Path.Combine(path, name);
|
||||
}
|
||||
return Directory.Exists(path);
|
||||
}
|
||||
|
||||
private static string? Blank(string value) => string.IsNullOrWhiteSpace(value) ? null : value;
|
||||
|
||||
/// <summary>
|
||||
/// The folder a sequence keeps (in the template's case) when it already is <paramref name="expanded"/>, or the
|
||||
/// <c>" (n)"</c> of it that filing or an earlier Reorganize gave it beside another sequence of that name; null when it is
|
||||
/// neither, when another folder holds that name exactly (a sequence's, or one on disk beside the sequence's own folder,
|
||||
/// on a case-sensitive file system: <paramref name="existsExactly"/> finds both names), which the change of case could
|
||||
/// never move onto, or when this plan already gave it to another sequence (<paramref name="given"/>, whatever its case:
|
||||
/// <c>trip (2)</c> and <c>TRIP (2)</c> both keep <c>Trip (2)</c> otherwise). Without it a sequence at
|
||||
/// <c>2026-09-28 (2)</c> would be planned to <c>(3)</c>, its own folder being taken, and back to <c>(2)</c> by the next
|
||||
/// Reorganize.
|
||||
/// </summary>
|
||||
private static string? Kept(string current, string expanded, IReadOnlyList<string> occupied, IReadOnlySet<string> given, Func<string, bool> existsExactly)
|
||||
{
|
||||
string? same = null;
|
||||
if (current.Equals(expanded, StringComparison.OrdinalIgnoreCase)) same = expanded;
|
||||
else if (Numbered(current, expanded, StringComparison.OrdinalIgnoreCase) is { } n && n >= 2) same = string.Create(CultureInfo.InvariantCulture, $"{expanded} ({n})");
|
||||
// "(02)" is not a number Unique gives: that folder moves to a name of its own.
|
||||
if (same is null || !same.Equals(current, StringComparison.OrdinalIgnoreCase) || given.Contains(same)) return null;
|
||||
if (same.Equals(current, StringComparison.Ordinal)) return same;
|
||||
// The new name on disk is another folder only while the sequence's own is there under the index's name too, as
|
||||
// MoveFolder throws: on a case-insensitive file system the disk may spell the sequence's own folder as the template
|
||||
// does (renamed in Explorer, or an outer level a change of case left as it was), and that folder is no other.
|
||||
return occupied.Any(o => o.Equals(same, StringComparison.Ordinal)) || (existsExactly(same) && existsExactly(current)) ? null : same;
|
||||
}
|
||||
|
||||
private static string Unique(string folder, HashSet<string> claimed, Func<string, bool> existsOnDisk)
|
||||
{
|
||||
var candidate = folder;
|
||||
|
||||
@@ -73,12 +73,15 @@ public static class ImportPlanner
|
||||
?? UniqueFolder(folderTemplate.ExpandFolder(context), claimedFolders, lookup);
|
||||
claimedFolders.Add(folder);
|
||||
|
||||
var names = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var names = new UniqueNames(new HashSet<string>(StringComparer.OrdinalIgnoreCase));
|
||||
var items = new List<PlannedItem>(members.Count);
|
||||
for (var i = 0; i < members.Count; i++)
|
||||
{
|
||||
var photo = members[i];
|
||||
var name = UniqueName(fileTemplate.ExpandFile(Context(photo, first.CaptureTime, s + 1, i + 1, title)), names);
|
||||
// With the camera and lens of the session's first photo, which its sequence carries: Reorganize names them alike.
|
||||
var metadata = photo.Metadata with { Make = first.Metadata.Make, Model = first.Metadata.Model, LensModel = first.Metadata.LensModel };
|
||||
var name = names.Claim(fileTemplate.ExpandFile(FrameNaming.Context(metadata, photo.File.RelativePath, photo.CaptureTime, first.CaptureTime,
|
||||
i + 1, title, s + 1)));
|
||||
items.Add(await PlanItemAsync(sourceRoot, photo, name, options, lookup, cancellationToken).ConfigureAwait(false));
|
||||
}
|
||||
sessions.Add(new PlannedSession
|
||||
@@ -137,23 +140,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}";
|
||||
@@ -200,16 +188,6 @@ public static class ImportPlanner
|
||||
return candidate;
|
||||
}
|
||||
|
||||
/// <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;
|
||||
}
|
||||
|
||||
private static long? FreeSpace(string path)
|
||||
{
|
||||
try
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
using System.Globalization;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Metadata;
|
||||
|
||||
namespace Chronos.Core.Naming;
|
||||
|
||||
/// <summary>
|
||||
/// The values a 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). Every photo of a sequence
|
||||
/// is named with the sequence's camera and lens (its first photo's, or the hint its creator gave), since the sidecar keeps
|
||||
/// no camera or lens per frame. An upload in capture order, and an import session filed whole into a sequence of its own,
|
||||
/// therefore get the names Reorganize gives them with the same templates. Reorganize gives other names, which its dry run
|
||||
/// lists, where filing could not know the sequence as it is now: <c>{session}</c> of a card's second session on (an import
|
||||
/// numbers its sessions; a sequence is one), <c>{n}</c> after photos skipped in the middle of a session (duplicates of
|
||||
/// photos elsewhere) or filed later out of capture order, and a folder another photo now comes first in.
|
||||
/// </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 in its sequence (an upload as it is filed, Reorganize, and the folder of either from the first
|
||||
/// frame): its sidecar record with the sequence's camera and lens, numbered by its index (<c>{n}</c> = index + 1), the
|
||||
/// sequence as one session (<c>{session}</c> = 1) 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, or of that name when the file has lost the extension of
|
||||
/// a photo. 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);
|
||||
var extension = Path.GetExtension(file);
|
||||
if (!ImageFormatInfo.IsSupportedExtension(file) && frame.Original is { } original && ImageFormatInfo.IsSupportedExtension(original))
|
||||
extension = Path.GetExtension(original);
|
||||
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 = extension.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
|
||||
/// the set of <paramref name="names"/> with <c>_2</c>, <c>_3</c>… before the extension (<see cref="UniqueNames.Claim"/>),
|
||||
/// then added to it.
|
||||
/// </summary>
|
||||
public static string FileName(PathTemplate template, NamingContext context, UniqueNames names, string directory = "")
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(template);
|
||||
ArgumentNullException.ThrowIfNull(names);
|
||||
ArgumentNullException.ThrowIfNull(directory);
|
||||
return names.Claim(directory + template.ExpandFile(context));
|
||||
}
|
||||
|
||||
/// <summary><paramref name="file"/> itself for <paramref name="n"/> = 1, else <c>stem_n.ext</c> in its directory.</summary>
|
||||
internal static string Numbered(string file, int n)
|
||||
{
|
||||
if (n == 1) return file;
|
||||
var slash = file.LastIndexOf('/');
|
||||
var name = file[(slash + 1)..];
|
||||
return string.Create(CultureInfo.InvariantCulture, $"{file[..(slash + 1)]}{Path.GetFileNameWithoutExtension(name)}_{n}{Path.GetExtension(name)}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unique file names in a set that only grows (BRIEF §7.1): exactly the names a search from <c>_2</c> up gives against it,
|
||||
/// without trying again for each photo the numbers earlier photos already took. A template that gives a whole session one
|
||||
/// name (<c>{title}</c>) then costs about one check per photo instead of one per photo before it.
|
||||
/// </summary>
|
||||
/// <param name="taken">The names given or held so far; every name claimed is added to it, and none may leave it while in use.</param>
|
||||
public sealed class UniqueNames(ISet<string> taken)
|
||||
{
|
||||
// Per name asked: the first number whose name the set did not hold when last tried. The set only grows, so every number
|
||||
// below it stays taken. Ordinal whatever the set compares: only that exact name's numbers are known.
|
||||
private readonly Dictionary<string, int> _first = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="file"/>, or the first of <c>stem_2.ext</c>, <c>stem_3.ext</c>… that the set does not hold and
|
||||
/// <paramref name="alsoFree"/> (when given) accepts; added to the set.
|
||||
/// </summary>
|
||||
public string Claim(string file, Func<string, bool>? alsoFree = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(file);
|
||||
var n = _first.GetValueOrDefault(file, 1);
|
||||
while (taken.Contains(FrameNaming.Numbered(file, n))) n++;
|
||||
_first[file] = n;
|
||||
for (var m = n; ; m++)
|
||||
{
|
||||
var candidate = FrameNaming.Numbered(file, m);
|
||||
if (taken.Contains(candidate) || alsoFree?.Invoke(candidate) == false) continue;
|
||||
taken.Add(candidate);
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Chronos.Core.Archiving;
|
||||
|
||||
namespace Chronos.Core.Naming;
|
||||
|
||||
@@ -20,6 +21,12 @@ public sealed class PathTemplate
|
||||
"iso", "shutter", "aperture", "n", "nsession", "name", "ext", "title",
|
||||
];
|
||||
|
||||
/// <summary>The longest text <see cref="ExpandText"/> gives: the longest title a sequence takes.</summary>
|
||||
public const int MaxTextLength = 200;
|
||||
|
||||
/// <summary>The longest folder level or file name a template gives (<see cref="SanitizeSegment"/>), before an appended extension.</summary>
|
||||
public const int MaxSegmentLength = 200;
|
||||
|
||||
private static readonly HashSet<string> TokenSet = new(Tokens, StringComparer.OrdinalIgnoreCase);
|
||||
private static readonly char[] Illegal = ['<', '>', ':', '"', '|', '?', '*', '\\', '/', '\0'];
|
||||
private static readonly HashSet<string> ReservedNames = new(StringComparer.OrdinalIgnoreCase)
|
||||
@@ -44,6 +51,9 @@ public sealed class PathTemplate
|
||||
|
||||
public bool IsValid => Errors.Count == 0;
|
||||
|
||||
/// <summary>Whether the template holds <paramref name="token"/> (<c>title</c> for <c>{title}</c>), whatever its case or format.</summary>
|
||||
public bool Uses(string token) => _parts.Any(p => p.IsToken && string.Equals(p.Text, token, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
/// <summary>Parses a template; '/' separates folder levels (only meaningful for folder templates).</summary>
|
||||
public static PathTemplate Parse(string template)
|
||||
{
|
||||
@@ -103,27 +113,79 @@ public sealed class PathTemplate
|
||||
return new PathTemplate(template, parts, errors);
|
||||
}
|
||||
|
||||
/// <summary>Expands to a relative folder path (forward slashes; each segment sanitized).</summary>
|
||||
public string ExpandFolder(NamingContext context)
|
||||
/// <summary>
|
||||
/// Expands to a relative folder path (forward slashes; each segment sanitized). A level archive scans never enter
|
||||
/// (<see cref="IsHiddenFolder"/>), which a token value such as a title can give, gets a leading <c>_</c>, so every
|
||||
/// sequence filed or moved by a template stays where a scan finds it.
|
||||
/// </summary>
|
||||
public string ExpandFolder(NamingContext context) => string.Join('/', Levels(context).Select(s => IsHiddenFolder(s) ? "_" + s : s));
|
||||
|
||||
/// <summary>Whether a level of the folder this template gives for <paramref name="context"/> is one scans never enter, before it is escaped.</summary>
|
||||
public bool WritesHiddenFolder(NamingContext context) => Levels(context).Any(IsHiddenFolder);
|
||||
|
||||
/// <summary>
|
||||
/// A folder name archive scans never enter (<see cref="ArchiveScanner"/>): one that starts with a dot, or a folder
|
||||
/// the layout keeps for itself (<c>.chronos</c>, <c>originals</c>, <c>proxies</c>, <c>exports</c>), whatever its case.
|
||||
/// </summary>
|
||||
public static bool IsHiddenFolder(string name)
|
||||
{
|
||||
var raw = Expand(context, allowSeparators: true);
|
||||
var segments = raw.Split('/', StringSplitOptions.RemoveEmptyEntries)
|
||||
.Select(SanitizeSegment)
|
||||
.Where(s => s.Length > 0);
|
||||
return string.Join('/', segments);
|
||||
ArgumentNullException.ThrowIfNull(name);
|
||||
return name.StartsWith('.') || ArchiveLayout.IsReservedFolder(name);
|
||||
}
|
||||
|
||||
/// <summary>Expands to a file name; the original extension is appended unless the template already ends with {ext}.</summary>
|
||||
private IEnumerable<string> Levels(NamingContext context) =>
|
||||
Expand(context, allowSeparators: true).Split('/', StringSplitOptions.RemoveEmptyEntries).Select(SanitizeSegment).Where(s => s.Length > 0);
|
||||
|
||||
/// <summary>
|
||||
/// Expands to a file name; the original extension is appended unless the template already ends with {ext}. A name
|
||||
/// longer than <see cref="MaxSegmentLength"/> is shortened before the <c>.{ext}</c> the template ends with, never through it.
|
||||
/// </summary>
|
||||
public string ExpandFile(NamingContext context)
|
||||
{
|
||||
var hasExt = _parts.Count > 0 && _parts[^1] is { IsToken: true, Text: "ext" };
|
||||
var name = SanitizeSegment(Expand(context, allowSeparators: false));
|
||||
var name = Clean(Expand(context, allowSeparators: false));
|
||||
var ext = hasExt && context.Extension.Length > 0 ? "." + context.Extension : string.Empty;
|
||||
name = ext.Length > 0 && name.Length > MaxSegmentLength && name.EndsWith(ext, StringComparison.Ordinal)
|
||||
? Shorten(name[..^ext.Length], MaxSegmentLength - ext.Length) + ext
|
||||
: Shorten(name, MaxSegmentLength);
|
||||
if (name.Length == 0) name = SanitizeSegment(context.OriginalName);
|
||||
if (!hasExt && context.Extension.Length > 0) name += "." + context.Extension;
|
||||
return name;
|
||||
}
|
||||
|
||||
private string Expand(NamingContext c, bool allowSeparators)
|
||||
/// <summary>
|
||||
/// Whether every file name the template gives ends with the photo's own extension: the template does not end with
|
||||
/// <c>{ext}</c> (the extension is appended), or ends with <c>.{ext}</c>, which a long name keeps whole
|
||||
/// (<see cref="ExpandFile"/>). <c>{n}{ext}</c> would drop the dot, and with it the extension every reader of the photo goes by.
|
||||
/// </summary>
|
||||
public bool KeepsExtension =>
|
||||
_parts is not [.., { IsToken: true, Text: "ext" }] || _parts is [.., { IsToken: false, Text: var before }, { IsToken: true, Text: "ext" }] && before.EndsWith('.');
|
||||
|
||||
/// <summary>
|
||||
/// Expands to plain text, such as a sequence title: the literals and the token values as they are, since a title may hold
|
||||
/// characters a file name cannot (<c>Paris: night</c>), control characters as spaces, trimmed, no extension; at most
|
||||
/// <see cref="MaxTextLength"/> characters.
|
||||
/// </summary>
|
||||
public string ExpandText(NamingContext context)
|
||||
{
|
||||
var text = new StringBuilder(Expand(context, allowSeparators: false, raw: true));
|
||||
for (var i = 0; i < text.Length; i++)
|
||||
{
|
||||
if (char.IsControl(text[i])) text[i] = ' ';
|
||||
}
|
||||
return Shorten(text.ToString().Trim(), MaxTextLength);
|
||||
}
|
||||
|
||||
/// <summary>At most <paramref name="max"/> characters of <paramref name="s"/>, a character outside the basic plane never cut in two, trailing spaces trimmed.</summary>
|
||||
private static string Shorten(string s, int max)
|
||||
{
|
||||
if (s.Length <= max) return s;
|
||||
var cut = char.IsHighSurrogate(s[max - 1]) ? max - 1 : max;
|
||||
return s[..cut].TrimEnd();
|
||||
}
|
||||
|
||||
/// <param name="raw">Token values as they are: text, not a path.</param>
|
||||
private string Expand(NamingContext c, bool allowSeparators, bool raw = false)
|
||||
{
|
||||
var inv = CultureInfo.InvariantCulture;
|
||||
var sb = new StringBuilder();
|
||||
@@ -158,7 +220,7 @@ public sealed class PathTemplate
|
||||
_ => string.Empty,
|
||||
};
|
||||
// Token values never introduce folder levels.
|
||||
sb.Append(value.Replace('/', '-').Replace('\\', '-'));
|
||||
sb.Append(raw ? value : value.Replace('/', '-').Replace('\\', '-'));
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
@@ -185,8 +247,14 @@ public sealed class PathTemplate
|
||||
return "1-" + Math.Round(1 / t).ToString(CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
/// <summary>Replaces characters that are illegal on Windows or Linux and fixes reserved names and trailing dots/spaces.</summary>
|
||||
public static string SanitizeSegment(string segment)
|
||||
/// <summary>
|
||||
/// Replaces characters that are illegal on Windows or Linux and fixes reserved names and trailing dots/spaces; at most
|
||||
/// <see cref="MaxSegmentLength"/> characters.
|
||||
/// </summary>
|
||||
public static string SanitizeSegment(string segment) => Shorten(Clean(segment), MaxSegmentLength);
|
||||
|
||||
/// <summary><see cref="SanitizeSegment"/> without its length limit.</summary>
|
||||
private static string Clean(string segment)
|
||||
{
|
||||
var sb = new StringBuilder(segment.Length);
|
||||
foreach (var ch in segment)
|
||||
@@ -199,7 +267,7 @@ public sealed class PathTemplate
|
||||
var stem = s.Split('.')[0];
|
||||
if (ReservedNames.Contains(stem)) s = "_" + s;
|
||||
if (s is "." or "..") s = "_";
|
||||
return s.Length > 200 ? s[..200].TrimEnd() : s;
|
||||
return s;
|
||||
}
|
||||
|
||||
private readonly record struct Part(bool IsToken, string Text, string? Format)
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace Chronos.Core.Naming;
|
||||
|
||||
/// <summary>
|
||||
/// What a folder or file template must give beyond parsing (BRIEF §7.1), the same wherever one is typed or sent: Settings ›
|
||||
/// Archive, an import, a Reorganize on the desktop or the server, the server's archive settings. Checked on a sample session
|
||||
/// of three photos, as the previews show it. Each rule is named by the key that explains it, <c>Errors.Template.<rule></c>.
|
||||
/// </summary>
|
||||
public static class TemplateRules
|
||||
{
|
||||
/// <summary>
|
||||
/// A sample session: three photos two seconds apart from a Canon EOS R5, each with its own original name, titled
|
||||
/// <paramref name="title"/> (made on each call).
|
||||
/// </summary>
|
||||
public static IReadOnlyList<NamingContext> Sample(string? title = "Sunset")
|
||||
{
|
||||
var start = new DateTime(2026, 9, 28, 18, 2, 11);
|
||||
return [.. Enumerable.Range(0, 3).Select(i => new NamingContext
|
||||
{
|
||||
CapturedAt = start.AddSeconds(2 * i),
|
||||
SessionStart = start,
|
||||
Session = 1,
|
||||
Number = i + 1,
|
||||
NumberInSession = i + 1,
|
||||
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 + i).ToString("0000", CultureInfo.InvariantCulture),
|
||||
Extension = "CR2",
|
||||
Title = title,
|
||||
})];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The rule a folder template breaks, for a template that parses and expands: <c>ReservedFolder</c> when a level it writes
|
||||
/// is one archive scans never enter (<see cref="PathTemplate.IsHiddenFolder"/>), so no index rebuilt from the disk would
|
||||
/// find the sequences filed there; null when it keeps them all.
|
||||
/// </summary>
|
||||
/// <exception cref="FormatException">A token's format cannot be written.</exception>
|
||||
public static string? FolderRule(PathTemplate template)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(template);
|
||||
return Sample().Any(template.WritesHiddenFolder) ? "ReservedFolder" : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The rule a file template breaks, for a template that parses and expands: <c>FileSeparator</c> (a slash: folders belong
|
||||
/// in the folder template), <c>Extension</c> (a name would not end with the photo's extension,
|
||||
/// <see cref="PathTemplate.KeepsExtension"/>), <c>NotUnique</c> (the photos of a session would get the same name: no frame
|
||||
/// number, time or original name tells them apart); null when it keeps them all.
|
||||
/// </summary>
|
||||
/// <exception cref="FormatException">A token's format cannot be written.</exception>
|
||||
public static string? FileRule(PathTemplate template)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(template);
|
||||
if (template.Source.Contains('/', StringComparison.Ordinal)) return "FileSeparator";
|
||||
if (!template.KeepsExtension) return "Extension";
|
||||
var names = Sample().Select(template.ExpandFile).ToList();
|
||||
return names.Distinct(StringComparer.OrdinalIgnoreCase).Count() == names.Count ? null : "NotUnique";
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user