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
@@ -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