feat(app): import and archive manager logic (plans, card pool, card gate, server sink, tree, charts, reports)

Plain classes behind the Import and Archive screens: plan totals, session
rows and the Show plan listing; duplicate and title choices without a new
scan; folder and server destinations with the protocol client's chunked,
hash-verified uploads; the after-import gate that allows deleting or
formatting a card only after a verified archive import and a dry run; the
archive tree, chart aggregation, mass rename/retag and maintenance reports.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 17:39:03 +00:00
1 parent 7d95536096
commit f7affe7840
22 files changed
+2258

No files matched your search

+168
View File
@@ -0,0 +1,168 @@
using System.Globalization;
using Titano.App.Infrastructure;
using Titano.Core.Imaging;
using Titano.Core.Localization;
using Titano.Core.Naming;
using Titano.Data.Repositories;
namespace Titano.App.Archiving;
/// <summary>A bar of a chart: label, magnitude, the text after the bar and the hover text.</summary>
public sealed record BarValue(string Label, double Value, string ValueText, string ToolTip);
/// <summary>A heatmap row (one year): photos per month, NaN for months still to come.</summary>
public sealed record HeatRow(string Label, IReadOnlyList<double> Values, IReadOnlyList<string?> ToolTips);
/// <summary>A figure tile of the Archive screen ("618,204" over "photos").</summary>
public sealed record ArchiveTile(string Value, string Caption);
public enum HealthAction
{
None,
Verify,
Proxies,
Analyse,
Duplicates,
Orphans,
}
/// <summary>One line of "Index health": ok or warning, what it found, and the fix it offers.</summary>
public sealed record HealthLine(bool IsOk, string Text, HealthAction Action);
/// <summary>
/// Turns the index statistics into the Archive screen's figures (BRIEF §12.5, Archive.html): tiles, photos per month
/// (heatmap, year rows × 12 months), storage by year, the top cameras and formats by photos (the rest folded into one
/// bar), and the index health lines.
/// </summary>
public static class ArchiveFigures
{
public const int TopCameras = 5;
public const int TopFormats = 6;
public static IReadOnlyList<ArchiveTile> Tiles(ArchiveStats stats)
{
var years = stats.ByYear.Select(y => y.Year).ToList();
var range = years.Count == 0 ? "—"
: years.Min() == years.Max() ? Year(years.Min())
: Loc.L("Archive.Tile.YearRange", Year(years.Min()), Year(years.Max()));
var cameras = stats.ByCamera.Count(c => !string.IsNullOrWhiteSpace(c.Model) || !string.IsNullOrWhiteSpace(c.Make));
return
[
new(Formatting.Count(stats.Photos), Loc.Plural("Archive.Tile.Photos", stats.Photos)),
new(Formatting.Count(stats.Sequences), Loc.Plural("Archive.Tile.Sequences", stats.Sequences)),
new(Formatting.Bytes(stats.Bytes), Loc.L("Archive.Tile.Originals")),
new(Formatting.Count(cameras), Loc.Plural("Archive.Tile.Cameras", cameras) + " · " + Loc.Plural("Archive.Tile.Formats", stats.ByFormat.Count)),
new(range, Loc.L("Archive.Tile.Pending", Formatting.Count(stats.Health.NotAnalyzed), Formatting.Count(stats.Health.Unverified))),
];
}
/// <summary>Culture month initials for the heatmap columns ("J F M …", "G F M …").</summary>
public static IReadOnlyList<string> MonthLabels() =>
[.. Loc.Culture.DateTimeFormat.AbbreviatedMonthNames.Take(12).Select(m => m.Length == 0 ? string.Empty : char.ToUpper(m[0], Loc.Culture).ToString())];
/// <summary>One row per year from the first to the last with photos, oldest first; months after <paramref name="today"/> are NaN.</summary>
public static IReadOnlyList<HeatRow> PhotosPerMonth(ArchiveStats stats, DateTime today)
{
if (stats.ByMonth.Count == 0) return [];
var byKey = stats.ByMonth.ToDictionary(m => (m.Year, m.Month));
var first = stats.ByMonth.Min(m => m.Year);
var last = System.Math.Max(stats.ByMonth.Max(m => m.Year), first);
var rows = new List<HeatRow>(last - first + 1);
for (var year = first; year <= last; year++)
{
var values = new double[12];
var tips = new string?[12];
for (var month = 1; month <= 12; month++)
{
var future = year > today.Year || (year == today.Year && month > today.Month);
byKey.TryGetValue((year, month), out var bucket);
values[month - 1] = future ? double.NaN : bucket?.Photos ?? 0;
tips[month - 1] = future ? null : Loc.L("Archive.Chart.MonthTip", new DateTime(year, month, 1).ToString("Y", Loc.Culture),
Loc.Plural("Shell.Status.Photos", bucket?.Photos ?? 0), Loc.Plural("Shell.Status.Sequences", bucket?.Sequences ?? 0));
}
rows.Add(new HeatRow(Year(year), values, tips));
}
return rows;
}
/// <summary>Bytes of originals per capture year, oldest first.</summary>
public static IReadOnlyList<BarValue> StorageByYear(ArchiveStats stats) =>
[
.. stats.ByYear.OrderBy(y => y.Year).Select(y => new BarValue(Year(y.Year), y.Bytes, Formatting.Bytes(y.Bytes),
Loc.L("Archive.Chart.YearTip", Year(y.Year), Formatting.Bytes(y.Bytes), Loc.Plural("Shell.Status.Sequences", y.Sequences)))),
];
/// <summary>Photos per camera: the <see cref="TopCameras"/> largest, then "n others".</summary>
public static IReadOnlyList<BarValue> ByCamera(ArchiveStats stats)
{
var cameras = stats.ByCamera
.GroupBy(c => PathTemplate.CameraName(c.Make, c.Model) is { Length: > 0 } name ? name : Loc.L("Archive.Chart.UnknownCamera"), StringComparer.Ordinal)
.Select(g => (Name: g.Key, Photos: g.Sum(c => c.Photos)))
.OrderByDescending(c => c.Photos).ThenBy(c => c.Name, StringComparer.CurrentCultureIgnoreCase)
.ToList();
return Shares(cameras, TopCameras, rest => Loc.Plural("Archive.Chart.OtherCameras", rest), stats.Photos);
}
/// <summary>Photos per file format: the <see cref="TopFormats"/> largest, then "Other".</summary>
public static IReadOnlyList<BarValue> ByFormat(ArchiveStats stats)
{
var formats = stats.ByFormat
.GroupBy(f => FormatName(f.Format), StringComparer.Ordinal)
.Select(g => (Name: g.Key, Photos: g.Sum(f => f.Photos)))
.OrderByDescending(f => f.Photos).ThenBy(f => f.Name, StringComparer.Ordinal)
.ToList();
return Shares(formats, TopFormats, _ => Loc.L("Archive.Chart.OtherFormats"), formats.Sum(f => f.Photos));
}
/// <summary>"CR2", "JPEG", "3FR": the format as photographers name it.</summary>
public static string FormatName(ImageFileFormat format) => format switch
{
ImageFileFormat.Unknown => Loc.L("Archive.Chart.OtherFormats"),
ImageFileFormat.ThreeFr => "3FR",
ImageFileFormat.JpegXl => "JXL",
ImageFileFormat.JpegXr => "JXR",
ImageFileFormat.WebP => "WebP",
_ => format.ToString().ToUpperInvariant(),
};
/// <summary>Index health (Archive.html): what needs attention, each with its fix.</summary>
public static IReadOnlyList<HealthLine> Health(ArchiveStats stats, int withoutProxies)
{
var h = stats.Health;
var damaged = h.MissingFrames + h.CorruptFrames;
return
[
h.Unverified == 0
? new HealthLine(true, Loc.L("Archive.Health.AllVerified"), HealthAction.None)
: new HealthLine(false, Loc.Plural("Archive.Health.Unverified", h.Unverified), HealthAction.Verify),
damaged == 0
? new HealthLine(true, Loc.L("Archive.Health.FramesOk"), HealthAction.None)
: new HealthLine(false, Loc.L("Archive.Health.Damaged", Formatting.Count(h.MissingFrames), Formatting.Count(h.CorruptFrames)), HealthAction.Orphans),
withoutProxies == 0
? new HealthLine(true, Loc.L("Archive.Health.ProxiesOk"), HealthAction.None)
: new HealthLine(false, Loc.Plural("Archive.Health.NoProxies", withoutProxies), HealthAction.Proxies),
h.NotAnalyzed == 0
? new HealthLine(true, Loc.L("Archive.Health.AnalysedOk"), HealthAction.None)
: new HealthLine(false, Loc.Plural("Archive.Health.NotAnalysed", h.NotAnalyzed), HealthAction.Analyse),
h.DuplicateFrames == 0
? new HealthLine(true, Loc.L("Archive.Health.NoDuplicates"), HealthAction.None)
: new HealthLine(false, Loc.Plural("Archive.Health.Duplicates", h.DuplicateFrames), HealthAction.Duplicates),
];
}
private static IReadOnlyList<BarValue> Shares(List<(string Name, long Photos)> ranked, int top, Func<int, string> restLabel, long total)
{
var bars = new List<BarValue>(top + 1);
foreach (var (name, photos) in ranked.Take(top)) bars.Add(Bar(name, photos, total));
if (ranked.Count > top) bars.Add(Bar(restLabel(ranked.Count - top), ranked.Skip(top).Sum(c => c.Photos), total));
return bars;
}
private static BarValue Bar(string label, long photos, long total)
{
var share = Formatting.Percent(total > 0 ? photos / (double)total : 0);
return new BarValue(label, photos, share, Loc.L("Archive.Chart.ShareTip", label, Loc.Plural("Shell.Status.Photos", photos), share));
}
private static string Year(int year) => year.ToString(CultureInfo.InvariantCulture);
}
+130
View File
@@ -0,0 +1,130 @@
using System.Globalization;
using Titano.App.Infrastructure;
using Titano.Core.Archiving;
using Titano.Core.Localization;
using Titano.Core.Model;
namespace Titano.App.Archiving;
public enum TreeNodeKind
{
Archive,
Year,
Sequence,
}
/// <summary>A node of the archive tree: the archive, a capture year, or a sequence.</summary>
public sealed class ArchiveTreeNode
{
private readonly List<ArchiveTreeNode> _children = [];
internal ArchiveTreeNode(TreeNodeKind kind, string key, int depth)
{
Kind = kind;
Key = key;
Depth = depth;
}
public TreeNodeKind Kind { get; }
/// <summary>Stable across rebuilds: the archive id, the year, or the sequence id.</summary>
public string Key { get; }
public int Depth { get; }
public required string Title { get; init; }
/// <summary>"18 sequences · 2.1 TB", "3,600 photos · 72 GB".</summary>
public required string Detail { get; init; }
public Sequence? Sequence { get; init; }
public bool IsExpanded { get; set; }
public IReadOnlyList<ArchiveTreeNode> Children => _children;
public bool HasChildren => _children.Count > 0;
internal void Add(ArchiveTreeNode child) => _children.Add(child);
/// <summary>The sequences this node stands for (itself, or all below it).</summary>
public IEnumerable<Sequence> Sequences() => Sequence is { } own ? [own] : _children.SelectMany(c => c.Sequences());
}
/// <summary>
/// The Archive screen's tree (BRIEF §12.5): the archive with its availability, its capture years (newest first) and
/// their sequences (newest first), flattened into the visible rows of a virtualised list. Undated sequences sit under
/// their own node after the years.
/// </summary>
public sealed class ArchiveTree
{
private ArchiveTree(ArchiveTreeNode root, ArchiveAvailability availability)
{
Root = root;
Availability = availability;
}
public ArchiveTreeNode Root { get; }
public ArchiveAvailability Availability { get; }
public static ArchiveTree Build(Core.Model.Archive archive, ArchiveAvailability availability, IReadOnlyList<Sequence> sequences)
{
var root = new ArchiveTreeNode(TreeNodeKind.Archive, archive.Id.ToString("N"), 0)
{
Title = archive.Name,
Detail = Summary(sequences),
IsExpanded = true,
};
foreach (var year in sequences.GroupBy(s => s.FirstCapture?.Year).OrderByDescending(g => g.Key ?? int.MinValue))
{
var members = year.OrderByDescending(s => s.FirstCapture).ThenBy(s => s.DisplayTitle, StringComparer.CurrentCultureIgnoreCase).ToList();
var node = new ArchiveTreeNode(TreeNodeKind.Year, year.Key?.ToString(CultureInfo.InvariantCulture) ?? "undated", 1)
{
Title = year.Key?.ToString(CultureInfo.InvariantCulture) ?? Loc.L("Archive.Tree.Undated"),
Detail = Summary(members),
};
foreach (var s in members)
{
node.Add(new ArchiveTreeNode(TreeNodeKind.Sequence, s.Id.ToString("N"), 2)
{
Title = s.DisplayTitle,
Detail = Loc.Plural("Shell.Status.Photos", s.FrameCount) + " · " + Formatting.Bytes(s.TotalBytes),
Sequence = s,
});
}
root.Add(node);
}
return new ArchiveTree(root, availability);
}
/// <summary>Rows to show: every node whose ancestors are all expanded, depth first.</summary>
public IReadOnlyList<ArchiveTreeNode> Visible()
{
var rows = new List<ArchiveTreeNode>();
void Walk(ArchiveTreeNode node)
{
rows.Add(node);
if (!node.IsExpanded) return;
foreach (var child in node.Children) Walk(child);
}
Walk(Root);
return rows;
}
/// <summary>Expands the nodes whose keys are given (restoring the state after a refresh).</summary>
public void Expand(IReadOnlySet<string> keys)
{
foreach (var year in Root.Children) year.IsExpanded = keys.Contains(year.Key);
}
/// <summary>Keys of the expanded year nodes.</summary>
public IReadOnlySet<string> ExpandedKeys() => Root.Children.Where(c => c.IsExpanded).Select(c => c.Key).ToHashSet(StringComparer.Ordinal);
/// <summary>The set mass operations act on: the sequences of the selected nodes, each once; all of them when nothing is selected.</summary>
public static IReadOnlyList<Sequence> SetOf(ArchiveTree tree, IEnumerable<ArchiveTreeNode> selected)
{
var chosen = selected.ToList();
var source = chosen.Count == 0 ? tree.Root.Sequences() : chosen.SelectMany(n => n.Sequences());
var seen = new HashSet<Guid>();
return [.. source.Where(s => seen.Add(s.Id))];
}
private static string Summary(IReadOnlyCollection<Sequence> sequences) =>
Loc.Plural("Shell.Status.Sequences", sequences.Count) + " · " + Formatting.Bytes(sequences.Sum(s => s.TotalBytes));
}
@@ -0,0 +1,93 @@
using Titano.App.Infrastructure;
using Titano.App.Jobs;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data.Archiving;
using Titano.Data.Repositories;
namespace Titano.App.Archiving;
/// <summary>A group of identical photos: the copies and where they are; the first one counts as the original.</summary>
public sealed record DuplicateRow(string Title, string Detail, IReadOnlyList<string> Places, Guid SequenceId);
/// <summary>What an orphan line is about, which decides its fix.</summary>
public enum OrphanKind
{
/// <summary>Photos in a sequence folder that its sidecar does not list: fix = index them.</summary>
UnlistedFiles,
/// <summary>Frames whose file is gone: fix = reconcile (flags them missing in sidecar and index).</summary>
MissingFiles,
/// <summary>An index row whose folder has no sidecar any more: fix = remove the row (after confirmation).</summary>
MissingSequence,
/// <summary>A folder with photos the index does not know yet: fix = scan.</summary>
NewFolder,
}
/// <summary>One line of the orphans report and the target of its fix.</summary>
public sealed record OrphanRow(OrphanKind Kind, string Title, string Detail, Guid? SequenceId);
/// <summary>A line of "Recent maintenance": date, operation and outcome.</summary>
public sealed record MaintenanceRow(Guid JobId, string DateText, string Text, string StateText, JobState State);
/// <summary>
/// The Maintenance view's reports (BRIEF §12.5): duplicates across sequences, orphans with their safe fixes, and the
/// recent archive jobs. Nothing here deletes a file; the only removal is of index rows whose sidecar is gone.
/// </summary>
public static class MaintenanceReports
{
/// <summary>Kinds of jobs listed under "Recent maintenance".</summary>
public static readonly IReadOnlyList<JobKind> MaintenanceKinds = [JobKind.Scan, JobKind.Rebuild, JobKind.Verify, JobKind.Maintenance];
public static IReadOnlyList<DuplicateRow> Duplicates(IReadOnlyList<DuplicateGroup> groups, IReadOnlyList<SequenceLocation> locations)
{
var titles = locations.ToDictionary(l => l.Id, l => l.Title ?? l.Folder[(l.Folder.LastIndexOf('/') + 1)..]);
return
[
.. groups.Where(g => g.Frames.Count > 1).Select(g =>
{
var first = g.Frames[0];
var name = first.RelativePath[(first.RelativePath.LastIndexOf('/') + 1)..];
var places = g.Frames.Select(f => Loc.L("Archive.Duplicates.Place", titles.GetValueOrDefault(f.SequenceId, f.RelativePath), f.RelativePath)).ToList();
return new DuplicateRow(name, Loc.Plural("Archive.Duplicates.Copies", g.Frames.Count), places, first.SequenceId);
}),
];
}
public static IReadOnlyList<OrphanRow> Orphans(OrphanReport report, IReadOnlyList<SequenceLocation> locations)
{
var byFolder = locations.ToDictionary(l => l.Folder, StringComparer.Ordinal);
var rows = new List<OrphanRow>();
foreach (var s in report.Sequences)
{
byFolder.TryGetValue(s.Folder, out var location);
var title = location?.Title ?? s.Folder;
if (s.UnindexedFiles.Count > 0)
rows.Add(new OrphanRow(OrphanKind.UnlistedFiles, title, Loc.Plural("Archive.Orphans.Unlisted", s.UnindexedFiles.Count), location?.Id));
if (s.MissingFiles.Count > 0)
rows.Add(new OrphanRow(OrphanKind.MissingFiles, title, Loc.Plural("Archive.Orphans.Missing", s.MissingFiles.Count), location?.Id));
}
foreach (var missing in report.MissingSequences)
rows.Add(new OrphanRow(OrphanKind.MissingSequence, missing.Title ?? missing.Folder, Loc.L("Archive.Orphans.NoSidecar", missing.Folder), missing.Id));
foreach (var folder in report.UnindexedFolders)
rows.Add(new OrphanRow(OrphanKind.NewFolder, folder.Length == 0 ? "/" : folder, Loc.L("Archive.Orphans.NewFolder"), null));
return rows;
}
public static IReadOnlyList<MaintenanceRow> Recent(IEnumerable<Job> jobs, int count) =>
[
.. jobs.OrderByDescending(j => j.Finished ?? j.Started ?? j.Created).Take(count).Select(j =>
{
var when = j.Finished ?? j.Started ?? j.Created;
var text = string.IsNullOrWhiteSpace(j.TargetLabel) ? JobText.Kind(j.Kind) : Loc.L("Archive.Recent.Line", JobText.Kind(j.Kind), j.TargetLabel);
var state = j.State switch
{
JobState.Running when j.ProgressTotal > 0 => Formatting.Percent(j.ProgressDone / (double)j.ProgressTotal),
_ => Loc.L("Jobs.State." + j.State),
};
return new MaintenanceRow(j.Id, Formatting.Date(when), text, state, j.State);
}),
];
}
+82
View File
@@ -0,0 +1,82 @@
using Titano.App.Settings;
using Titano.Core.Archiving;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Core.Naming;
using Titano.Data.Repositories;
namespace Titano.App.Archiving;
/// <summary>What a mass rename changes: the sequence titles (Rename) or the folder layout (Move).</summary>
public enum RenameMode
{
Titles,
Folders,
}
/// <summary>One line of the rename dry run: before → after.</summary>
public sealed record RenameRow(Guid SequenceId, string From, string To);
/// <summary>
/// Mass rename and move of sequences (BRIEF §7, §12.5): the template is checked live, the engine's dry run
/// (<see cref="RenamePlan"/>) is listed line by line, and applying makes exactly those changes.
/// </summary>
public static class MassRename
{
/// <summary>The first problem of a template, localized; null when it can be used.</summary>
public static string? Validate(RenameMode mode, string? template)
{
if (string.IsNullOrWhiteSpace(template)) return Loc.L("Errors.Template.Empty", string.Empty, 1);
if (mode == RenameMode.Folders) return NamingPreview.Validate(template, isFolder: true);
var parsed = PathTemplate.Parse(template);
return parsed.Errors is [var error, ..] ? Loc.L("Errors.Template." + error.Code, error.Token ?? string.Empty, error.Position + 1) : null;
}
/// <summary>The changes of a plan as rows: titles or folders, whichever the mode changes.</summary>
public static IReadOnlyList<RenameRow> Rows(RenamePlan plan, RenameMode mode) =>
[
.. plan.Steps.Select(s => mode == RenameMode.Folders
? new RenameRow(s.SequenceId, s.FromFolder, s.ToFolder)
: new RenameRow(s.SequenceId, s.FromTitle ?? string.Empty, s.ToTitle ?? string.Empty)),
];
/// <summary>"12 of 36 sequences change".</summary>
public static string Summary(RenamePlan plan, int setSize) => Loc.Plural("Archive.Rename.Summary", plan.Steps.Count, setSize);
}
/// <summary>Adding and removing tags on a set of sequences (BRIEF §12.5 Retag).</summary>
public static class Retag
{
/// <summary>"sunset, harbour; Holy grail" → normalized, distinct tags; entries that cannot be tags are left out.</summary>
public static IReadOnlyList<string> Parse(string? text)
{
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
return [.. Split(text).Where(IsValid).Select(TagRepository.Normalize).Where(seen.Add)];
}
/// <summary>The problem of a tag list as one sentence; null when every entry can be a tag.</summary>
public static string? Validate(string? text) => Split(text).All(IsValid) ? null : Loc.L("Archive.Retag.Invalid", TagRepository.MaxLength);
private static IEnumerable<string> Split(string? text) =>
string.IsNullOrWhiteSpace(text) ? [] : text.Split([',', ';'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
private static bool IsValid(string tag) => tag.Length is > 0 and <= TagRepository.MaxLength && !tag.Any(char.IsControl);
/// <summary>The new tag list of one sequence: removals first, then additions not already present.</summary>
public static IReadOnlyList<string> Apply(IReadOnlyList<string> current, IReadOnlyList<string> add, IReadOnlyList<string> remove)
{
var removed = new HashSet<string>(remove, StringComparer.OrdinalIgnoreCase);
var result = current.Where(t => !removed.Contains(t)).ToList();
var present = new HashSet<string>(result, StringComparer.OrdinalIgnoreCase);
result.AddRange(add.Where(present.Add));
return result;
}
/// <summary>Only the sequences whose tags change, with their new tags (the dry run).</summary>
public static IReadOnlyList<(Sequence Sequence, IReadOnlyList<string> Tags)> Changes(IEnumerable<Sequence> sequences, IReadOnlyList<string> add,
IReadOnlyList<string> remove) =>
[
.. sequences.Select(s => (Sequence: s, Tags: Apply(s.Tags, add, remove)))
.Where(c => !c.Tags.SequenceEqual(c.Sequence.Tags, StringComparer.Ordinal)),
];
}