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:
22 files changed
+2258
No files matched your search
@@ -0,0 +1,62 @@
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.Core.Import;
|
||||
using Titano.Core.Localization;
|
||||
|
||||
namespace Titano.App.Import;
|
||||
|
||||
/// <summary>
|
||||
/// What may be done to the card after an import (BRIEF §0.2 rule 8, §12.4, §13). Deleting needs a recorded,
|
||||
/// verified import into this PC's archive and a dry run that re-hashed every card file and its copy; formatting
|
||||
/// needs, on top, a complete verified import and a dry run in which every photo still on the card is safe to delete.
|
||||
/// Ejecting only needs a removable card. Each refusal comes with the sentence the button's tooltip shows.
|
||||
/// </summary>
|
||||
/// <param name="CardPhotos">Photos on the card now (the scanner's count), for the format check.</param>
|
||||
public sealed record CardActions(ImportDestinationKind Destination, bool IsKnownCard, bool IsInserted, bool IsRemovable, ImportOutcome? Outcome,
|
||||
ErasePlan? Erase, int CardPhotos)
|
||||
{
|
||||
/// <summary>The dry run of "Delete imported" may start.</summary>
|
||||
public bool CanCheck => CheckBlocker is null;
|
||||
|
||||
public string? CheckBlocker =>
|
||||
Destination != ImportDestinationKind.Archive ? Loc.L("Import.Blocked.NotArchive")
|
||||
: !IsKnownCard || !IsInserted ? Loc.L("Import.Blocked.NoCard")
|
||||
: Outcome is not { Imported: > 0 } and not { Skipped: > 0 } ? Loc.L("Import.Blocked.NothingImported")
|
||||
: null;
|
||||
|
||||
public bool CanDelete => DeleteBlocker is null;
|
||||
|
||||
public string? DeleteBlocker =>
|
||||
CheckBlocker ?? (Erase is null ? Loc.L("Import.Blocked.NoDryRun") : DeleteCount == 0 ? Loc.L("Import.Blocked.NothingVerified") : null);
|
||||
|
||||
public bool CanFormat => FormatBlocker is null;
|
||||
|
||||
public string? FormatBlocker =>
|
||||
DeleteBlocker
|
||||
?? (Outcome is not { IsComplete: true, Verified: true } ? Loc.L("Import.Blocked.Incomplete")
|
||||
: KeptCount > 0 || DeleteCount < CardPhotos ? Loc.L("Import.Blocked.NotAllVerified")
|
||||
: null);
|
||||
|
||||
public bool CanEject => IsInserted && IsRemovable;
|
||||
|
||||
public int DeleteCount => Erase?.ToDelete.Count() ?? 0;
|
||||
|
||||
public long DeleteBytes => Erase?.ToDelete.Sum(i => i.Candidate.Size) ?? 0;
|
||||
|
||||
public int KeptCount => Erase?.Items.Count(i => i.Verdict != EraseVerdict.Delete) ?? 0;
|
||||
|
||||
/// <summary>"4,812 verified on the card · 96.2 GB · 2 kept": the dry run in one line; empty before it ran.</summary>
|
||||
public string EraseText => Erase is null
|
||||
? string.Empty
|
||||
: string.Join(" · ", new[]
|
||||
{
|
||||
Loc.Plural("Import.Erase.Verified", DeleteCount),
|
||||
Formatting.Bytes(DeleteBytes),
|
||||
KeptCount > 0 ? Loc.Plural("Import.Erase.Kept", KeptCount) : string.Empty,
|
||||
}.Where(t => t.Length > 0));
|
||||
|
||||
/// <summary>Why each kept photo stays on the card ("IMG_0042.CR2 · the archive copy no longer matches").</summary>
|
||||
public IReadOnlyList<string> KeptReasons =>
|
||||
Erase is null ? [] : [.. Erase.Items.Where(i => i.Verdict != EraseVerdict.Delete).Select(i => Loc.L("Import.Erase.Reason", i.Candidate.SourcePath, Verdict(i.Verdict)))];
|
||||
|
||||
public static string Verdict(EraseVerdict verdict) => Loc.L("Import.Erase.Verdict." + verdict);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
using System.Globalization;
|
||||
using Titano.Data.Archiving;
|
||||
|
||||
namespace Titano.App.Import;
|
||||
|
||||
/// <summary>
|
||||
/// A volume the Import screen offers (BRIEF §12.4, §13): a removable volume, or any volume with a <c>DCIM</c> folder.
|
||||
/// Card identity is <c>{serial:X8}-{label}-{capacity}</c>, stable across readers and drive letters.
|
||||
/// </summary>
|
||||
/// <param name="Root">Root with trailing separator, e.g. <c>E:\</c>.</param>
|
||||
public sealed record CardDevice(string Root, string Label, uint SerialNumber, long TotalBytes, long FreeBytes, bool IsRemovable, bool HasDcim)
|
||||
{
|
||||
public string Identity => string.Create(CultureInfo.InvariantCulture, $"{SerialNumber:X8}-{Label}-{TotalBytes}");
|
||||
|
||||
public long UsedBytes => System.Math.Max(0, TotalBytes - FreeBytes);
|
||||
|
||||
public CardVolume ToVolume() => new(Identity, SerialNumber, Label.Length == 0 ? null : Label, TotalBytes);
|
||||
}
|
||||
|
||||
/// <summary>Outcome of a safe removal.</summary>
|
||||
public enum EjectOutcome
|
||||
{
|
||||
Ejected,
|
||||
|
||||
/// <summary>Files on the card are still open; nothing changed.</summary>
|
||||
InUse,
|
||||
|
||||
/// <summary>Not a removable drive, or Windows refused.</summary>
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// <summary>Outcome of the operating system's format dialog (BRIEF §8.6).</summary>
|
||||
public enum FormatOutcome
|
||||
{
|
||||
Formatted,
|
||||
Cancelled,
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Card detection and the two OS actions on a card (BRIEF §8.6, §13): safe removal and the Windows format dialog.
|
||||
/// Events may arrive on any thread.
|
||||
/// </summary>
|
||||
public interface IDeviceMonitor : IDisposable
|
||||
{
|
||||
event Action<CardDevice>? Arrived;
|
||||
|
||||
event Action<CardDevice>? Removed;
|
||||
|
||||
/// <summary>Candidate volumes present now.</summary>
|
||||
IReadOnlyList<CardDevice> Devices { get; }
|
||||
|
||||
/// <summary>Starts watching (idempotent); the first snapshot raises no events.</summary>
|
||||
void Start();
|
||||
|
||||
/// <summary>Locks, dismounts and ejects the volume; blocks for up to a few seconds.</summary>
|
||||
EjectOutcome Eject(CardDevice device);
|
||||
|
||||
/// <summary>Shows the Windows format dialog for the volume; call on the UI thread.</summary>
|
||||
FormatOutcome Format(CardDevice device);
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
using System.Globalization;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Naming;
|
||||
|
||||
namespace Titano.App.Import;
|
||||
|
||||
public enum SourceKind
|
||||
{
|
||||
/// <summary>A card with a DCIM tree, or a remembered card.</summary>
|
||||
Card,
|
||||
|
||||
/// <summary>A removable drive without DCIM: imported as a plain folder tree.</summary>
|
||||
Drive,
|
||||
|
||||
/// <summary>A folder picked with "Folder…".</summary>
|
||||
Folder,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One entry of the Devices list (BRIEF §12.4, §13 card pool): an inserted volume joined with its remembered card, a
|
||||
/// remembered card that is not inserted, or a picked folder. <see cref="Key"/> is the card identity or the folder path.
|
||||
/// </summary>
|
||||
public sealed record ImportSource(string Key, SourceKind Kind, CardDevice? Device, MediaCard? Card, string? FolderPath)
|
||||
{
|
||||
public bool IsInserted => Device is not null || FolderPath is not null;
|
||||
|
||||
public bool IsKnown => Card is not null;
|
||||
|
||||
/// <summary>Where the photos are read from; null for a remembered card that is not inserted.</summary>
|
||||
public string? Root => Device?.Root ?? FolderPath;
|
||||
|
||||
/// <summary>"EOS R5 · card A", the volume label, or the drive.</summary>
|
||||
public string Title => Card?.Nickname is { Length: > 0 } nickname ? nickname
|
||||
: Device is { Label.Length: > 0 } labelled ? labelled.Label
|
||||
: Device?.Root ?? FolderPath ?? Card?.Label ?? string.Empty;
|
||||
|
||||
/// <summary>"E:\ · 128 GB · 96.2 GB used", "no DCIM · 1.8 TB free", "Canon EOS R5 · not inserted".</summary>
|
||||
public string Subtitle => Kind switch
|
||||
{
|
||||
SourceKind.Folder => FolderPath ?? string.Empty,
|
||||
SourceKind.Drive => Loc.L("Import.Device.NoDcim", Device!.Root, Formatting.Bytes(Device.FreeBytes)),
|
||||
_ when Device is not null => Loc.L("Import.Device.Card", Device.Root, Formatting.Bytes(Device.TotalBytes), Formatting.Bytes(Device.UsedBytes)),
|
||||
_ => Loc.L("Import.Device.Away", CameraText(Card) is { Length: > 0 } camera ? camera : Formatting.Bytes(Card!.Capacity)),
|
||||
};
|
||||
|
||||
/// <summary>"Known card", "New card", … for the state dot's tooltip.</summary>
|
||||
public string StateText => Loc.L(Kind switch
|
||||
{
|
||||
SourceKind.Folder => "Import.Device.State.Folder",
|
||||
SourceKind.Drive => "Import.Device.State.Drive",
|
||||
_ when !IsInserted => "Import.Device.State.Away",
|
||||
_ when IsKnown => "Import.Device.State.Known",
|
||||
_ => "Import.Device.State.New",
|
||||
});
|
||||
|
||||
/// <summary>"128 GB · serial 3F2A-9C11 · Canon EOS R5 #0431": the identity line of the profile header.</summary>
|
||||
public string IdentityText
|
||||
{
|
||||
get
|
||||
{
|
||||
var parts = new List<string>();
|
||||
if (Device is not null) parts.Add(Device.Root);
|
||||
var capacity = Device?.TotalBytes ?? Card?.Capacity ?? 0;
|
||||
if (capacity > 0) parts.Add(Formatting.Bytes(capacity));
|
||||
var serial = Device?.SerialNumber ?? Card?.VolumeSerial;
|
||||
if (serial is { } s && Kind != SourceKind.Folder) parts.Add(Loc.L("Import.Device.Serial", SerialText(s)));
|
||||
if (CameraText(Card) is { Length: > 0 } camera) parts.Add(Card?.CameraSerial is { Length: > 0 } body ? Loc.L("Import.Device.Body", camera, body) : camera);
|
||||
return string.Join(" · ", parts);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"3F2A-9C11", as Windows shows a volume serial.</summary>
|
||||
public static string SerialText(uint serial)
|
||||
{
|
||||
var hex = serial.ToString("X8", CultureInfo.InvariantCulture);
|
||||
return hex[..4] + "-" + hex[4..];
|
||||
}
|
||||
|
||||
private static string CameraText(MediaCard? card) => card is null ? string.Empty : PathTemplate.CameraName(card.CameraMake, card.CameraModel);
|
||||
}
|
||||
|
||||
/// <summary>Builds the Devices list: inserted volumes first (in drive order), then remembered cards, then a picked folder.</summary>
|
||||
public static class CardPool
|
||||
{
|
||||
public static IReadOnlyList<ImportSource> Build(IEnumerable<CardDevice> devices, IEnumerable<MediaCard> cards, string? folder)
|
||||
{
|
||||
var known = cards.ToDictionary(c => c.Identity, StringComparer.Ordinal);
|
||||
var list = new List<ImportSource>();
|
||||
foreach (var device in devices.OrderBy(d => d.Root, StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
known.Remove(device.Identity, out var card);
|
||||
var kind = device.HasDcim || card is not null ? SourceKind.Card : SourceKind.Drive;
|
||||
list.Add(new ImportSource(device.Identity, kind, device, card, null));
|
||||
}
|
||||
foreach (var card in known.Values.OrderByDescending(c => c.LastSeen))
|
||||
list.Add(new ImportSource(card.Identity, SourceKind.Card, null, card, null));
|
||||
if (folder is not null) list.Add(new ImportSource(folder, SourceKind.Folder, null, null, folder));
|
||||
return list;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
using Titano.Core.Import;
|
||||
using Titano.Core.Naming;
|
||||
using Titano.Data.Archiving;
|
||||
|
||||
namespace Titano.App.Import;
|
||||
|
||||
/// <summary>Where the photos go (BRIEF §12.4): this PC's archive, a plain folder, or the signed-in server.</summary>
|
||||
public enum ImportDestinationKind
|
||||
{
|
||||
Archive,
|
||||
Folder,
|
||||
Server,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Import form (Import.html): scan, sessions, names, duplicates and after-import choices. Remembered per card as
|
||||
/// its <see cref="CardProfile"/>; a session gap of 0 minutes in a profile means "do not split into sessions".
|
||||
/// </summary>
|
||||
public sealed record ImportChoices
|
||||
{
|
||||
public ImportDestinationKind Destination { get; init; } = ImportDestinationKind.Archive;
|
||||
public string? FolderPath { get; init; }
|
||||
public bool IncludeSubfolders { get; init; } = true;
|
||||
public bool SplitSessions { get; init; } = true;
|
||||
public int GapMinutes { get; init; } = 45;
|
||||
public int MinimumFrames { get; init; } = 8;
|
||||
public bool VerifyCopies { get; init; } = true;
|
||||
public string FolderTemplate { get; init; } = TemplateDefaults.Folder;
|
||||
public string FileTemplate { get; init; } = TemplateDefaults.File;
|
||||
public DuplicatePolicy Duplicates { get; init; } = DuplicatePolicy.Skip;
|
||||
public AfterImport AfterImport { get; init; } = AfterImport.Keep;
|
||||
public bool Eject { get; init; } = true;
|
||||
public bool DeepAnalysis { get; init; } = true;
|
||||
|
||||
/// <summary>A card's remembered choices.</summary>
|
||||
public static ImportChoices FromProfile(CardProfile profile) => new()
|
||||
{
|
||||
IncludeSubfolders = profile.IncludeSubfolders,
|
||||
SplitSessions = profile.SessionGapMinutes > 0,
|
||||
GapMinutes = profile.SessionGapMinutes > 0 ? profile.SessionGapMinutes : new CardProfile().SessionGapMinutes,
|
||||
MinimumFrames = profile.MinimumSessionFrames,
|
||||
VerifyCopies = profile.VerifyCopies,
|
||||
FolderTemplate = profile.FolderTemplate,
|
||||
FileTemplate = profile.FileTemplate,
|
||||
Duplicates = profile.Duplicates,
|
||||
AfterImport = profile.AfterImport,
|
||||
Eject = profile.Eject,
|
||||
DeepAnalysis = profile.DeepAnalysis,
|
||||
};
|
||||
|
||||
public CardProfile ToProfile() => new()
|
||||
{
|
||||
FolderTemplate = FolderTemplate,
|
||||
FileTemplate = FileTemplate,
|
||||
SessionGapMinutes = SplitSessions ? GapMinutes : 0,
|
||||
MinimumSessionFrames = MinimumFrames,
|
||||
IncludeSubfolders = IncludeSubfolders,
|
||||
VerifyCopies = VerifyCopies,
|
||||
Duplicates = Duplicates,
|
||||
AfterImport = AfterImport,
|
||||
Eject = Eject,
|
||||
DeepAnalysis = DeepAnalysis,
|
||||
};
|
||||
|
||||
/// <summary>Planner options; <paramref name="titles"/> are the session titles typed in the plan, by session key.</summary>
|
||||
public ImportOptions ToOptions(IReadOnlyDictionary<string, string>? titles = null) => new()
|
||||
{
|
||||
FolderTemplate = FolderTemplate,
|
||||
FileTemplate = FileTemplate,
|
||||
// Without session splitting every camera body and format stays one session.
|
||||
SessionGap = SplitSessions ? TimeSpan.FromMinutes(System.Math.Max(1, GapMinutes)) : TimeSpan.MaxValue,
|
||||
MinimumSessionFrames = System.Math.Max(1, MinimumFrames),
|
||||
IncludeSubfolders = IncludeSubfolders,
|
||||
VerifyCopies = VerifyCopies,
|
||||
Duplicates = Duplicates,
|
||||
Titles = titles ?? new Dictionary<string, string>(),
|
||||
};
|
||||
|
||||
/// <summary>True when a choice changes which photos form which session or where they go, so the card must be planned again.</summary>
|
||||
public bool NeedsNewPlan(ImportChoices previous) =>
|
||||
previous.Destination != Destination
|
||||
|| !string.Equals(previous.FolderPath, FolderPath, StringComparison.OrdinalIgnoreCase)
|
||||
|| previous.IncludeSubfolders != IncludeSubfolders
|
||||
|| previous.SplitSessions != SplitSessions
|
||||
|| (SplitSessions && previous.GapMinutes != GapMinutes)
|
||||
|| previous.MinimumFrames != MinimumFrames
|
||||
|| previous.FolderTemplate != FolderTemplate
|
||||
|| previous.FileTemplate != FileTemplate;
|
||||
|
||||
/// <summary>Session titles feed the names only when a template uses <c>{title}</c>.</summary>
|
||||
public bool TitlesChangeNames => UsesTitle(FolderTemplate) || UsesTitle(FileTemplate);
|
||||
|
||||
private static bool UsesTitle(string template) => template.Contains("{title", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
using Titano.Core.Import;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Archiving;
|
||||
|
||||
namespace Titano.App.Import;
|
||||
|
||||
/// <summary>Plans an import into one destination (BRIEF §12.4); nothing is written.</summary>
|
||||
public interface IImportDestination
|
||||
{
|
||||
ImportDestinationKind Kind { get; }
|
||||
|
||||
/// <param name="progress">Photos read so far.</param>
|
||||
Task<ImportPlan> PlanAsync(string sourceRoot, ImportOptions options, Guid? cardId, IProgress<int>? progress, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>This PC's archive: the planner knows the card's history, the archive's duplicates and its sequences.</summary>
|
||||
public sealed class ArchiveDestination(ArchiveService archives, Archive archive) : IImportDestination
|
||||
{
|
||||
public Archive Archive { get; } = archive;
|
||||
|
||||
public ImportDestinationKind Kind => ImportDestinationKind.Archive;
|
||||
|
||||
public Task<ImportPlan> PlanAsync(string sourceRoot, ImportOptions options, Guid? cardId, IProgress<int>? progress, CancellationToken cancellationToken) =>
|
||||
archives.PlanImportAsync(Archive.Id, sourceRoot, options, cardId, progress, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A plain folder or the server: nothing is indexed on this PC, so every photo is copied; a folder destination finds
|
||||
/// identical files by name and hash while copying, the server by hash before any byte is sent.
|
||||
/// </summary>
|
||||
public sealed class UnindexedDestination(ImportDestinationKind kind, string root) : IImportDestination
|
||||
{
|
||||
public ImportDestinationKind Kind { get; } = kind;
|
||||
|
||||
/// <summary>The folder, or the local staging folder of server uploads.</summary>
|
||||
public string Root { get; } = root;
|
||||
|
||||
public Task<ImportPlan> PlanAsync(string sourceRoot, ImportOptions options, Guid? cardId, IProgress<int>? progress, CancellationToken cancellationToken)
|
||||
{
|
||||
var problems = new List<ImportProblem>();
|
||||
var files = CardScanner.Find(sourceRoot, options.IncludeSubfolders, cancellationToken);
|
||||
var photos = CardScanner.ReadMetadata(sourceRoot, files, problems, progress, cancellationToken);
|
||||
return ImportPlanner.PlanAsync(sourceRoot, Root, photos, problems, options, NoIndex.Instance, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>No history and no index; folders are reused so a repeated import lands next to the first one.</summary>
|
||||
private sealed class NoIndex : IImportLookup
|
||||
{
|
||||
public static readonly NoIndex Instance = new();
|
||||
|
||||
public Task<bool> WasImportedAsync(CardFile file, CancellationToken cancellationToken) => Task.FromResult(false);
|
||||
|
||||
public Task<IReadOnlyList<ArchiveMatch>> FindCandidatesAsync(long size, DateTime capturedAt, CancellationToken cancellationToken) =>
|
||||
Task.FromResult<IReadOnlyList<ArchiveMatch>>([]);
|
||||
|
||||
public Task<string?> FindSessionFolderAsync(string sessionKey, CancellationToken cancellationToken) => Task.FromResult<string?>(null);
|
||||
|
||||
public bool IsFolderTaken(string folder) => false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A failed photo of an import: where it is on the card and why.</summary>
|
||||
public sealed record ImportFailure(string SourcePath, string Message);
|
||||
|
||||
/// <summary>What an import did (BRIEF §12.4 verification result).</summary>
|
||||
/// <param name="Copied">Copied and committed (verified by read-back when <paramref name="Verified"/>).</param>
|
||||
/// <param name="Duplicates">Copied, but the destination already held the same content.</param>
|
||||
/// <param name="Skipped">Not copied: imported before, or already in the archive.</param>
|
||||
public sealed record ImportOutcome(int Copied, int Duplicates, int Skipped, IReadOnlyList<ImportFailure> Failures, bool Verified)
|
||||
{
|
||||
public bool IsComplete => Failures.Count == 0;
|
||||
|
||||
/// <summary>Photos the destination now holds a verified copy of.</summary>
|
||||
public int Imported => Copied + Duplicates;
|
||||
|
||||
/// <summary>Totals of an executor run (folder or server destination).</summary>
|
||||
public static ImportOutcome From(IEnumerable<ImportItemResult> results, bool verified)
|
||||
{
|
||||
int copied = 0, duplicates = 0, skipped = 0;
|
||||
var failures = new List<ImportFailure>();
|
||||
foreach (var r in results)
|
||||
{
|
||||
switch (r.Status)
|
||||
{
|
||||
case ImportItemStatus.Copied:
|
||||
copied++;
|
||||
break;
|
||||
case ImportItemStatus.Duplicate:
|
||||
duplicates++;
|
||||
break;
|
||||
case ImportItemStatus.Skipped:
|
||||
skipped++;
|
||||
break;
|
||||
default:
|
||||
failures.Add(new ImportFailure(r.Item.SourcePath, r.Error ?? string.Empty));
|
||||
break;
|
||||
}
|
||||
}
|
||||
return new ImportOutcome(copied, duplicates, skipped, failures, verified);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// After an archive import job: every planned copy must now be a frame of the archive (found by size and capture
|
||||
/// time, the planner's own duplicate key); the copy was hashed and read back while the job ran.
|
||||
/// </summary>
|
||||
public static async Task<ImportOutcome> CheckAsync(ImportPlan plan, bool verified, Func<PlannedItem, CancellationToken, Task<bool>> isInArchive,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
int copied = 0, skipped = 0;
|
||||
var failures = new List<ImportFailure>();
|
||||
foreach (var item in plan.Items)
|
||||
{
|
||||
if (item.Action != ImportAction.Copy)
|
||||
{
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
if (await isInArchive(item, cancellationToken).ConfigureAwait(false)) copied++;
|
||||
else failures.Add(new ImportFailure(item.SourcePath, Core.Localization.Loc.L("Import.Result.NotCommitted")));
|
||||
}
|
||||
return new ImportOutcome(copied, 0, skipped, failures, verified);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs a confirmed plan into a folder or the server on this PC (no job handler exists for those destinations): copies
|
||||
/// with hashing and read-back, commits each batch to the sink and collects the per-file results.
|
||||
/// </summary>
|
||||
public static class LocalImport
|
||||
{
|
||||
public static async Task<ImportOutcome> RunAsync(ImportPlan plan, IImportSink sink, bool verify, IProgress<ImportProgress>? progress,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var results = new List<ImportItemResult>(plan.FileCount);
|
||||
await new ImportExecutor(plan, sink).RunAsync(0, verify, batch =>
|
||||
{
|
||||
results.AddRange(batch.Results);
|
||||
progress?.Report(batch.Progress);
|
||||
return ValueTask.CompletedTask;
|
||||
}, p =>
|
||||
{
|
||||
progress?.Report(p);
|
||||
return ValueTask.CompletedTask;
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
return ImportOutcome.From(results, verify);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using System.IO;
|
||||
using Titano.Core.Import;
|
||||
using Titano.Protocol;
|
||||
using Titano.Protocol.Client;
|
||||
|
||||
namespace Titano.App.Import;
|
||||
|
||||
/// <summary>
|
||||
/// Import destination "Server" (BRIEF §12.4, §14.4): each verified copy staged on this PC is uploaded with the
|
||||
/// protocol's resumable chunks and the hash computed while copying; the server checks that hash before it commits the
|
||||
/// frame, and only then does the photo count as imported. Photos of one plan session share its session key, so the
|
||||
/// server files them in one sequence — the same one when an interrupted import is started again. A typed session
|
||||
/// title is set on that sequence once.
|
||||
/// </summary>
|
||||
public sealed class ServerImportSink(TitanoClient client, string stagingDirectory) : IImportSink
|
||||
{
|
||||
private readonly HashSet<Guid> _titled = [];
|
||||
|
||||
public string StagingDirectory { get; } = stagingDirectory;
|
||||
|
||||
public async Task<IReadOnlyList<SinkCommit>> CommitAsync(PlannedSession session, IReadOnlyList<StagedFile> files, CancellationToken cancellationToken)
|
||||
{
|
||||
var results = new List<SinkCommit>(files.Count);
|
||||
foreach (var file in files)
|
||||
{
|
||||
// The server records the uploaded file name as the original name: upload the card's name, not the staging name.
|
||||
var folder = Path.Combine(StagingDirectory, Path.GetFileNameWithoutExtension(file.StagedPath));
|
||||
var named = Path.Combine(folder, Path.GetFileName(file.Item.SourcePath));
|
||||
Directory.CreateDirectory(folder);
|
||||
File.Move(file.StagedPath, named);
|
||||
try
|
||||
{
|
||||
var committed = await client.UploadFileAsync(named, null, file.Item.CapturedAt, session.SessionKey, file.Sha256, null, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
// An upload the server already held reports no position in a sequence.
|
||||
var duplicate = committed is null || committed.Index < 0;
|
||||
results.Add(new SinkCommit(committed?.FrameId, file.Item.FileName, duplicate));
|
||||
if (committed is { Index: >= 0 } && session.Title is { Length: > 0 } title && _titled.Add(committed.SequenceId))
|
||||
await client.UpdateSequenceAsync(committed.SequenceId, new UpdateSequenceRequest(title, null, null, null, null, null), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Our own staged copy; the original stays on the card.
|
||||
File.Delete(named);
|
||||
Directory.Delete(folder);
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user