Files
Chronos/src/Titano.App/Import/ImportPlans.cs
T
Claude f7affe7840 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
2026-10-02 17:39:03 +00:00

206 lines
10 KiB
C#

using Titano.App.Infrastructure;
using Titano.Core.Archiving;
using Titano.Core.Import;
using Titano.Core.Localization;
using Titano.Core.Naming;
namespace Titano.App.Import;
/// <summary>Figures of a plan for the Plan panel header and the Import button (Import.html).</summary>
public sealed record PlanTotals(int Sessions, int Photos, int CopyCount, long CopyBytes, int Duplicates, int ImportedBefore, int Problems,
long? FreeAfter, TimeSpan Estimate)
{
public bool HasEnoughSpace => FreeAfter is not < 0;
/// <summary>"3 sessions · 4,812 photos · 96.2 GB · about 12 min".</summary>
public string Text => string.Join(" · ",
Loc.Plural("Import.Plan.Sessions", Sessions),
Loc.Plural("Shell.Status.Photos", Photos),
Formatting.Bytes(CopyBytes),
Loc.L("Import.Plan.About", Formatting.Duration(Estimate)));
/// <summary>"0 duplicates" (already in the archive by hash).</summary>
public string DuplicatesText => Loc.Plural("Import.Plan.Duplicates", Duplicates);
/// <summary>"12 imported before" (same file from this card), or empty.</summary>
public string ImportedBeforeText => ImportedBefore > 0 ? Loc.Plural("Import.Plan.ImportedBefore", ImportedBefore) : string.Empty;
/// <summary>"2.1 TB free after import", "3.2 GB missing", or empty when the volume does not report its space.</summary>
public string SpaceText => FreeAfter switch
{
null => string.Empty,
< 0 => Loc.L("Import.Plan.SpaceMissing", Formatting.Bytes(-FreeAfter.Value)),
_ => Loc.L("Import.Plan.FreeAfter", Formatting.Bytes(FreeAfter.Value)),
};
/// <summary>"Import 4,812 photos".</summary>
public string ImportText => Loc.Plural("Import.Start", CopyCount);
}
/// <summary>One row of the session table: what the planner grouped and where it goes.</summary>
/// <param name="DefaultTitle">Title the sequence gets when the user types none (its folder name).</param>
/// <param name="IsNew">The session starts a new sequence (false: it continues one imported before).</param>
public sealed record PlanSessionRow(int Number, string SessionKey, string? Title, string DefaultTitle, string TimeText, string FramesText,
string SizeText, string CameraText, string TargetText, bool IsNew);
public enum PlanRowKind
{
Session,
File,
}
/// <summary>A line of "Show plan": a session heading or one file and its destination.</summary>
public sealed record PlanDetailRow(PlanRowKind Kind, string Source, string Destination, string ActionText, string SizeText, bool IsSkipped);
/// <summary>Everything "Show plan" lists: every file to its destination, the totals and the conflicts.</summary>
public sealed record PlanDetails(IReadOnlyList<PlanDetailRow> Rows, string TotalsText, IReadOnlyList<string> Conflicts);
/// <summary>
/// Turns an <see cref="ImportPlan"/> into what the Import screen shows (BRIEF §12.4 "Plan before touching disk") and
/// applies the choices that need no new scan of the card: the duplicate choice and session titles.
/// </summary>
public static class ImportPlans
{
/// <summary>Planning speed assumption for the estimate: a UHS-I card read plus the read-back of the copy.</summary>
public const double BytesPerSecond = 80e6;
public const double VerifiedBytesPerSecond = 55e6;
public static TimeSpan Estimate(long bytes, bool verify) =>
TimeSpan.FromSeconds(System.Math.Ceiling(bytes / (verify ? VerifiedBytesPerSecond : BytesPerSecond)));
public static PlanTotals Totals(ImportPlan plan, bool verify) => new(
plan.Sessions.Count,
plan.FileCount,
plan.CopyCount,
plan.CopyBytes,
plan.Items.Count(i => i.ExistingFrameId is not null),
plan.Items.Count(i => i.Action == ImportAction.SkipImported),
plan.Problems.Count,
plan.AvailableBytes is { } free ? free - plan.CopyBytes : null,
Estimate(plan.CopyBytes, verify));
/// <summary>
/// The plan with every photo already in the archive skipped or imported again, as the planner would have decided
/// (BRIEF §13: skip, or import again; never overwrite).
/// </summary>
public static ImportPlan WithDuplicates(ImportPlan plan, DuplicatePolicy policy) => plan with
{
Sessions =
[
.. plan.Sessions.Select(s => s with
{
Items =
[
.. s.Items.Select(i => i.ExistingFrameId is null || i.Action == ImportAction.SkipImported
? i
: i with { Action = policy == DuplicatePolicy.Skip ? ImportAction.SkipInArchive : ImportAction.Copy }),
],
}),
],
};
/// <summary>The plan with the typed session titles (when no template uses <c>{title}</c>, so no name changes).</summary>
public static ImportPlan WithTitles(ImportPlan plan, IReadOnlyDictionary<string, string> titles) => plan with
{
Sessions = [.. plan.Sessions.Select(s => s with { Title = titles.TryGetValue(s.SessionKey, out var t) && !string.IsNullOrWhiteSpace(t) ? t.Trim() : null })],
};
/// <param name="existingFolders">Folders of sequences already in the archive (a session there continues it).</param>
public static IReadOnlyList<PlanSessionRow> Sessions(ImportPlan plan, ImportDestinationKind destination, IReadOnlySet<string> existingFolders) =>
[
.. plan.Sessions.Select(s =>
{
var isNew = !existingFolders.Contains(s.Folder);
var leaf = s.Folder[(s.Folder.LastIndexOf('/') + 1)..];
var target = destination switch
{
ImportDestinationKind.Server => Loc.L("Import.Session.Server"),
ImportDestinationKind.Folder => s.Folder,
_ => Loc.L(isNew ? "Import.Session.New" : "Import.Session.Adds", s.Folder),
};
return new PlanSessionRow(s.Number, s.SessionKey, s.Title, leaf, TimeText(s), FramesText(s), Formatting.Bytes(s.Items.Sum(i => i.Size)),
PathTemplate.CameraName(s.CameraMake, s.CameraModel), target, isNew);
}),
];
/// <summary>"Show plan": every file and where it goes, with the conflicts the plan resolved or reports.</summary>
public static PlanDetails Details(ImportPlan plan, ImportDestinationKind destination, bool verify)
{
var rows = new List<PlanDetailRow>(plan.FileCount + plan.Sessions.Count);
foreach (var s in plan.Sessions)
{
var folder = DestinationFolder(s, destination);
rows.Add(new PlanDetailRow(PlanRowKind.Session, Loc.L("Import.Details.Session", s.Number, TimeText(s)), folder,
Loc.Plural("Shell.Status.Photos", s.Items.Count), Formatting.Bytes(s.Items.Sum(i => i.Size)), false));
foreach (var item in s.Items)
{
rows.Add(new PlanDetailRow(PlanRowKind.File, item.SourcePath, folder + "/" + item.FileName, ActionText(item),
Formatting.Bytes(item.Size), item.Action != ImportAction.Copy));
}
}
var totals = Totals(plan, verify);
var conflicts = new List<string>();
foreach (var problem in plan.Problems) conflicts.Add(Loc.L("Import.Details.Unreadable", problem.RelativePath, problem.Message));
if (totals.Duplicates > 0) conflicts.Add(totals.DuplicatesText);
if (!totals.HasEnoughSpace) conflicts.Add(totals.SpaceText);
var text = string.Join(" · ", new[]
{
Loc.Plural("Import.Details.Files", plan.FileCount),
Loc.L("Import.Details.Copy", Formatting.Count(plan.CopyCount), Formatting.Bytes(plan.CopyBytes)),
totals.ImportedBeforeText,
totals.Duplicates > 0 ? totals.DuplicatesText : string.Empty,
}.Where(t => t.Length > 0));
return new PlanDetails(rows, text, conflicts);
}
/// <summary>The destination of a session as the user will find it: the archive's originals folder, the folder, or the server.</summary>
public static string DestinationFolder(PlannedSession session, ImportDestinationKind destination) => destination switch
{
ImportDestinationKind.Archive => session.Folder + "/" + ArchiveLayout.OriginalsFolder,
ImportDestinationKind.Server => Loc.L("Import.Session.Server"),
_ => session.Folder,
};
/// <summary>"→ 2026/2026-09-28 Canon EOS R5/2026-09-28_18-02-11_0001.CR2": the first file the plan copies.</summary>
public static string? FirstDestination(ImportPlan plan, ImportDestinationKind destination)
{
foreach (var s in plan.Sessions)
{
if (s.Items.FirstOrDefault(i => i.Action == ImportAction.Copy) is { } item)
return destination == ImportDestinationKind.Server ? item.FileName : s.Folder + "/" + item.FileName;
}
return null;
}
private static string ActionText(PlannedItem item) => item.Action switch
{
ImportAction.SkipImported => Loc.L("Import.Action.ImportedBefore"),
ImportAction.SkipInArchive => Loc.L("Import.Action.Duplicate"),
_ when item.ExistingFrameId is not null => Loc.L("Import.Action.Again"),
_ => Loc.L("Import.Action.Copy"),
};
/// <summary>"28/09/2026 · 18:02 → 20:04".</summary>
private static string TimeText(PlannedSession s) =>
Loc.L("Import.Session.Time", Formatting.Date(s.Start), s.Start.ToString("t", Loc.Culture), s.End.ToString("t", Loc.Culture));
/// <summary>"3,600 · 2 s": photos and the median interval between them.</summary>
private static string FramesText(PlannedSession s)
{
var interval = MedianInterval(s.Items);
var count = Formatting.Count(s.Items.Count);
return interval is { } median ? Loc.L("Import.Session.Frames", count, Formatting.Duration(median)) : count;
}
internal static TimeSpan? MedianInterval(IReadOnlyList<PlannedItem> items)
{
if (items.Count < 2) return null;
var gaps = new List<double>(items.Count - 1);
for (var i = 1; i < items.Count; i++) gaps.Add((items[i].CapturedAt - items[i - 1].CapturedAt).TotalSeconds);
gaps.Sort();
var middle = gaps.Count / 2;
var seconds = gaps.Count % 2 == 1 ? gaps[middle] : (gaps[middle - 1] + gaps[middle]) / 2;
return TimeSpan.FromSeconds(System.Math.Max(0, seconds));
}
}