fix(app): import gates, partial results and plan editing after review

- a card that leaves needs a new check; formatting re-lists the card and refuses
  one that changed since its check; files that are not photos are named in the
  format confirmation
- an import never stays stuck in Running; Retry never resumes an older job
- server imports list refused files and keep what was uploaded when stopped
- the archive result matches each copy to its job's record and shows the job's
  own error per file
- refreshing devices keeps typed titles and choices; titles lock while copying
- three destination names, merge and split of sessions, camera profiles shared
  by the cards of a camera, photo counts and a new-card toast
- disabled controls say why; keyboard focus follows the nickname field and
  Show plan (Esc closes it); label column fits longer languages
- capture states for insertion, running, failed and a new card

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-03 10:44:22 +00:00
1 parent 5aa5edab57
commit 29c82eba5c
27 files changed
+1286 -285

No files matched your search

+293 -69
View File
@@ -43,10 +43,11 @@ public sealed record ProfileSource(string Name, ICommand Command);
/// <summary>
/// Card and folder import (BRIEF §12.4, §13, Import.html): the card pool, the remembered profile of the selected
/// card, the destination (this PC's archive, a folder, or the signed-in server), the plan before anything is
/// copied (sessions with editable titles, duplicates, space, "Show plan"), the hash-verified import itself (a job
/// for the archive, run here for a folder or the server), its verification result and the after-import actions.
/// Inserted cards raise a toast; a known card with automatic import starts with its profile.
/// card (its own, or its camera's shared profile), the destination (this PC's archive, a folder, or the signed-in
/// server), the plan before anything is copied (sessions with editable titles, merges and splits, duplicates, space,
/// "Show plan"), the hash-verified import itself (a job for the archive, run here for a folder or the server), its
/// verification result and the after-import actions. Inserted cards raise a toast; a known card with automatic
/// import starts with its profile.
/// </summary>
public sealed class ImportViewModel : SectionViewModel
{
@@ -54,6 +55,9 @@ public sealed class ImportViewModel : SectionViewModel
private readonly DispatcherTimer _planDelay;
private readonly Dictionary<string, string> _titles = new(StringComparer.Ordinal);
private readonly HashSet<string> _splits = new(StringComparer.Ordinal);
private readonly HashSet<string> _merges = new(StringComparer.Ordinal);
private readonly Dictionary<string, CardContents> _contents = new(StringComparer.Ordinal);
private IReadOnlyList<MediaCard> _cards = [];
private ImportSource? _selected;
private string? _folderSource;
@@ -76,6 +80,9 @@ public sealed class ImportViewModel : SectionViewModel
private string? _errorText;
private Guid? _jobId;
private string? _jobSourceKey;
private Guid? _jobCardId;
private CameraProfile? _camera;
private bool _followsCamera;
private bool _jobEventsAttached;
private bool _loaded;
private string? _autoStartKey;
@@ -115,10 +122,12 @@ public sealed class ImportViewModel : SectionViewModel
field.Commit();
});
RenameCommand = new RelayCommand(() => IsRenaming = true, () => CanEditProfile);
FollowCameraCommand = new AsyncRelayCommand(() => SetFollowsCameraAsync(!_followsCamera), () => CanFollowCamera);
ForgetCommand = new AsyncRelayCommand(ForgetCardAsync, () => CanEditProfile);
ShowPlanCommand = new RelayCommand(() => Details = _plan is null ? null : ImportPlans.Details(_plan, _choices.Destination, _choices.VerifyCopies),
() => _plan is not null);
CloseDetailsCommand = new RelayCommand(() => Details = null);
SplitCommand = new RelayCommand(p => Split((PlanDetailRow)p!), p => _phase == ImportPhase.Ready && p is PlanDetailRow { CanSplit: true });
StartCommand = new AsyncRelayCommand(StartAsync, () => StartBlocker is null);
CancelCommand = new AsyncRelayCommand(CancelAsync, () => _phase == ImportPhase.Running);
NewImportCommand = new RelayCommand(() =>
@@ -156,6 +165,9 @@ public sealed class ImportViewModel : SectionViewModel
public ICommand RefreshCommand { get; }
public ICommand PickFolderCommand { get; }
/// <summary>The source of a running import stays selected.</summary>
public bool CanChangeSource => _phase != ImportPhase.Running;
/// <summary>Start the import with the card's profile as soon as this card is inserted (per card, BRIEF §12.4).</summary>
public bool AutoImport
{
@@ -197,6 +209,21 @@ public sealed class ImportViewModel : SectionViewModel
/// <summary>A remembered card's profile can be edited, except while its import runs.</summary>
public bool CanEditProfile => _selected?.Card is not null && _phase != ImportPhase.Running;
public string EditToolTip => _selected?.Card is null ? Loc.L("Import.Blocked.EditNeedsCard")
: _phase == ImportPhase.Running ? Loc.L("Import.Blocked.Copying")
: Loc.L("Tooltips.Import.Edit");
/// <summary>The card imports with its camera's shared profile (BRIEF §13); changes made here apply to every card that follows it.</summary>
public bool FollowsCamera => _followsCamera;
public bool CanFollowCamera => CanEditProfile && _selected?.Card?.CameraModel is not null;
public string FollowCameraToolTip => !CanEditProfile ? EditToolTip
: _selected?.Card?.CameraModel is null ? Loc.L("Import.Blocked.CameraUnknown")
: Loc.L("Tooltips.Import.FollowCamera", PathTemplate.CameraName(_selected.Card.CameraMake, _selected.Card.CameraModel));
public ICommand FollowCameraCommand { get; }
public IReadOnlyList<ProfileSource> OtherCards =>
[
.. _cards.Where(c => c.Id != _selected?.Card?.Id)
@@ -292,16 +319,10 @@ public sealed class ImportViewModel : SectionViewModel
/// <summary>The view tells which template field the "{ }" menu writes into.</summary>
public void SetActiveTemplate(bool folder) => _activeTemplateIsFolder = folder;
/// <summary>"→ 2026/2026-09-28 Canon EOS R5/2026-09-28_18-02-11_0001.CR2".</summary>
public string NamePreview
{
get
{
var first = _plan is null ? null : ImportPlans.FirstDestination(_plan, _choices.Destination);
first ??= NamingPreview.FirstNames(_choices.FolderTemplate, _choices.FileTemplate).FirstOrDefault();
return first is null ? string.Empty : Loc.L("Import.Names.Preview", first);
}
}
/// <summary>The first three names the plan copies to, or the templates' sample names before a plan (BRIEF §7.1).</summary>
public string NamePreview => ImportPlans.NamePreview(_plan is { CopyCount: > 0 } plan
? ImportPlans.FirstDestinations(plan, _choices.Destination)
: NamingPreview.FirstNames(_choices.FolderTemplate, _choices.FileTemplate));
public bool SkipDuplicates
{
@@ -363,6 +384,12 @@ public sealed class ImportViewModel : SectionViewModel
/// <summary>Card actions only exist for a card imported into this PC's archive.</summary>
public bool CardActionsApply => _choices.Destination == ImportDestinationKind.Archive && _selected?.Kind == SourceKind.Card;
public string DeleteChoiceToolTip => CardActionsApply ? Loc.L("Tooltips.Import.DeleteChoice") : Loc.L("Import.Blocked.CardActions");
public string FormatChoiceToolTip => CardActionsApply ? Loc.L("Tooltips.Import.FormatChoice") : Loc.L("Import.Blocked.CardActions");
public string DeepToolTip => IsArchiveDestination ? Loc.L("Tooltips.Import.Deep") : Loc.L("Import.Blocked.DeepNeedsArchive");
// ---------------- Plan ----------------
public ImportPhase Phase
@@ -371,6 +398,7 @@ public sealed class ImportViewModel : SectionViewModel
private set
{
if (!Set(ref _phase, value)) return;
foreach (var row in Sessions) row.IsEditable = value != ImportPhase.Running;
OnPropertyChanged(string.Empty);
CommandManager.InvalidateRequerySuggested();
}
@@ -380,7 +408,11 @@ public sealed class ImportViewModel : SectionViewModel
public ImportPlan? Plan => _plan;
public bool IsBusyPlanning => _phase == ImportPhase.Planning;
public bool IsFormEnabled => _phase != ImportPhase.Running;
/// <summary>The form is fixed while copying, and behind "Show plan" while it is open.</summary>
public bool IsFormEnabled => _phase != ImportPhase.Running && _details is null;
public bool IsPlanPanelEnabled => _details is null;
public bool HasPlan => _plan is not null && _phase is ImportPhase.Ready or ImportPhase.Running;
public bool IsRunning => _phase == ImportPhase.Running;
public bool IsDone => _phase == ImportPhase.Done;
@@ -406,7 +438,10 @@ public sealed class ImportViewModel : SectionViewModel
get => _details;
private set
{
if (Set(ref _details, value)) OnPropertyChanged(nameof(IsDetailsOpen));
if (!Set(ref _details, value)) return;
OnPropertyChanged(nameof(IsDetailsOpen));
OnPropertyChanged(nameof(IsFormEnabled));
OnPropertyChanged(nameof(IsPlanPanelEnabled));
}
}
@@ -415,6 +450,9 @@ public sealed class ImportViewModel : SectionViewModel
public ICommand ShowPlanCommand { get; }
public ICommand CloseDetailsCommand { get; }
/// <summary>"Split here" on a file of "Show plan": a new session starts at that photo.</summary>
public ICommand SplitCommand { get; }
// ---------------- Start, progress, result ----------------
public ICommand StartCommand { get; }
@@ -463,7 +501,10 @@ public sealed class ImportViewModel : SectionViewModel
_ = RefreshSourcesAsync();
}
/// <summary>Lists the devices and remembered cards again, keeping the selection.</summary>
/// <summary>
/// Lists the devices and remembered cards again, keeping the selection and what was typed for it; the selected card
/// that leaves or comes back is planned again, unless its import runs or ended (its result and resume stay).
/// </summary>
public async Task RefreshSourcesAsync()
{
try
@@ -478,28 +519,44 @@ public sealed class ImportViewModel : SectionViewModel
{
Log.Warning("import", "Card list unavailable", ex);
}
var key = _selected?.Key;
await ListContentsAsync();
var previous = _selected;
var pool = Rebuild();
var again = pool.FirstOrDefault(s => s.Key == key) ?? pool.FirstOrDefault(s => s.IsInserted && s.Kind == SourceKind.Card);
// The card of a running, failed or finished import may leave and come back: its import, result and resume stay.
var keepsImport = again is not null && again.Key == key && _phase is ImportPhase.Running or ImportPhase.Failed or ImportPhase.Done;
if (Equals(again, _selected) || keepsImport)
if (previous is not null && pool.FirstOrDefault(s => s.Key == previous.Key) is { } again)
{
_selected = again;
_result?.SetDevice(again?.Device);
_result?.SetDevice(again.Device);
_ = LoadIdentityAsync();
OnPropertyChanged(string.Empty);
if (again.Root != previous.Root && _phase is not (ImportPhase.Running or ImportPhase.Failed or ImportPhase.Done)) Replan();
return;
}
else
_selected = pool.FirstOrDefault(s => s.IsInserted && s.Kind == SourceKind.Card);
OnSourceChanged();
}
/// <summary>Counts the photos of newly inserted cards (a directory walk, off the UI thread); a card that left is forgotten.</summary>
private async Task ListContentsAsync()
{
var devices = Services.Devices.Devices;
foreach (var gone in _contents.Keys.Where(k => devices.All(d => d.Identity != k)).ToList()) _contents.Remove(gone);
foreach (var device in devices.Where(d => d.HasDcim && !_contents.ContainsKey(d.Identity)))
{
_selected = again;
OnSourceChanged();
try
{
_contents[device.Identity] = await Task.Run(() => CardContents.Read(device.Root));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("import", $"Cannot list {device.Root}", ex);
}
}
}
/// <summary>Lists inserted devices, remembered cards and the picked folder again.</summary>
private IReadOnlyList<ImportSource> Rebuild()
{
var pool = CardPool.Build(Services.Devices.Devices, _cards, _folderSource);
var pool = CardPool.Build(Services.Devices.Devices, _cards, _folderSource, _contents);
_refreshing = true;
try
{
@@ -530,6 +587,17 @@ public sealed class ImportViewModel : SectionViewModel
return _result!;
}
/// <summary>Shows the plan's import copying, at <paramref name="progress"/>, without running it (capture).</summary>
public void ShowRunning(ImportProgress progress)
{
Details = null;
Phase = ImportPhase.Running;
ShowProgress(progress);
}
/// <summary>Shows an import that stopped with <paramref name="message"/>, without running it (capture).</summary>
public void ShowFailed(string message) => Fail(message);
public override void Dispose()
{
_planDelay.Stop();
@@ -550,19 +618,39 @@ public sealed class ImportViewModel : SectionViewModel
{
_isRenaming = false;
_titles.Clear();
_splits.Clear();
_merges.Clear();
_jobId = null;
_jobSourceKey = null;
_jobCardId = null;
Details = null;
Result = null;
Nickname.Load(_selected?.Card?.Nickname ?? string.Empty);
_planning = SelectAsync();
}
/// <summary>Loads the selected source's settings — the card's own, its camera's shared profile, or the defaults — and plans it.</summary>
private async Task SelectAsync()
{
var key = _selected?.Key;
var camera = _selected?.Card is { } selected ? await FindCameraAsync(selected.CameraMake, selected.CameraModel) : null;
// A refresh may have replaced the record meanwhile; another source may have been chosen.
if (_selected?.Key != key) return;
var card = _selected?.Card;
// A card that has a camera but no saved settings takes the camera profile now; one seen for the first time
// takes it once its first plan names the camera (InheritedProfile).
// A card seen for the first time takes its camera's profile once its first plan names the camera (InheritCameraAsync).
_profileResolved = _selected?.Kind != SourceKind.Card || card is { ProfileJson.Length: > 0 } || card?.CameraModel is not null;
LoadChoices(card is { ProfileJson.Length: > 0 } ? ImportService.ProfileOf(card)
: card is not null && CameraProfiles.Find(card.CameraMake, card.CameraModel, _cards.Where(c => c.Id != card.Id)) is { } camera ? camera
: DefaultProfile());
var resolved = card is null ? new ResolvedProfile(DefaultProfile(), false) : CameraProfiles.Resolve(card, camera, DefaultProfile());
if (card is not null && camera is not null && resolved.FollowsCamera) await FollowCameraAsync(card, camera);
else
{
_camera = camera;
_followsCamera = false;
LoadChoices(resolved.Profile);
}
_ = LoadIdentityAsync();
OnPropertyChanged(string.Empty);
Replan();
await _planning;
}
/// <summary>A new card starts from the archive's templates and the brief's defaults.</summary>
@@ -584,6 +672,61 @@ public sealed class ImportViewModel : SectionViewModel
Choices = loaded;
}
private async Task<CameraProfile?> FindCameraAsync(string? make, string? model)
{
if (model is null || Services.Database is not { } db) return null;
try
{
return await new CameraProfileStore(db).FindAsync(make, model);
}
catch (DatabaseException ex)
{
Log.Warning("import", "Camera profile unavailable", ex);
return null;
}
}
/// <summary>Joins or leaves the camera's shared profile; a card that leaves keeps the settings it has now as its own.</summary>
private async Task SetFollowsCameraAsync(bool follow)
{
if (_selected?.Card is not { CameraModel: { } model } card || Services.Database is not { } db || Services.Archives is not { } archives) return;
try
{
var store = new CameraProfileStore(db);
var camera = await store.FindAsync(card.CameraMake, model) ?? new CameraProfile(card.CameraMake, model, _choices.ToProfile(), []);
camera = follow ? camera.With(card.Id) : camera.Without(card.Id);
await store.SaveAsync(camera);
_camera = camera;
_followsCamera = follow;
if (follow) LoadChoices(camera.Profile);
else await ReplaceCardAsync(await archives.Imports.SaveCardAsync(card.Id, card.Nickname, _choices.ToProfile(), card.AutoImport));
OnPropertyChanged(string.Empty);
}
catch (DatabaseException ex)
{
Shell.ReportError(ex);
}
}
/// <summary>Remembers the settings an import starts with: on the card, and on its camera's profile when the card follows it.</summary>
private async Task SaveProfileAsync(MediaCard card, ImportChoices choices)
{
if (Services.Archives is not { } archives || Services.Database is not { } db) return;
try
{
await archives.Imports.SaveCardAsync(card.Id, card.Nickname, choices.ToProfile(), card.AutoImport);
if (_followsCamera && card.CameraModel is { } model)
{
var camera = (_camera ?? new CameraProfile(card.CameraMake, model, choices.ToProfile(), [])) with { Profile = choices.ToProfile() };
await new CameraProfileStore(db).SaveAsync(_camera = camera.With(card.Id));
}
}
catch (DatabaseException ex)
{
Log.Warning("import", "The card profile was not saved", ex);
}
}
private async Task LoadIdentityAsync()
{
var text = _selected?.IdentityText ?? string.Empty;
@@ -654,6 +797,18 @@ public sealed class ImportViewModel : SectionViewModel
_ = RefreshAndSelectAsync(folder);
}
/// <summary>
/// Archive manager "Adopt folder › Copy into the layout" (BRIEF §12.5): the folder becomes the source and this PC's
/// archive the destination; the plan shows where every photo goes before anything is copied.
/// </summary>
public async Task ImportFolderAsync(string folder)
{
if (_phase == ImportPhase.Running) return;
_folderSource = folder;
if (CanUseArchive) _choices = _choices with { Destination = ImportDestinationKind.Archive };
await RefreshAndSelectAsync(folder);
}
private async Task RefreshAndSelectAsync(string key)
{
await RefreshSourcesAsync();
@@ -725,7 +880,7 @@ public sealed class ImportViewModel : SectionViewModel
{
if (!cts.IsCancellationRequested) SetStatus(ImportPhase.Planning, Loc.Plural("Import.Status.ReadingCount", n));
});
var options = _choices.ToOptions(_titles);
var options = _choices.ToOptions(_titles, _splits, _merges);
var cardId = _selected.Kind == SourceKind.Card ? await RegisteredCardIdAsync() : null;
try
{
@@ -736,7 +891,8 @@ public sealed class ImportViewModel : SectionViewModel
if (cts.IsCancellationRequested) return;
_existingFolders = folders;
_rawPlan = plan;
if (InheritedProfile(plan) is { } camera) LoadChoices(camera);
await InheritCameraAsync(plan);
if (cts.IsCancellationRequested) return;
ApplyPlan();
SetStatus(ImportPhase.Ready, null);
// An inherited profile that groups or names differently plans again first.
@@ -756,12 +912,44 @@ public sealed class ImportViewModel : SectionViewModel
}
}
/// <summary>The camera profile of a card seen for the first time, once its first plan names the camera (BRIEF §13).</summary>
private CardProfile? InheritedProfile(ImportPlan plan)
/// <summary>
/// A card seen for the first time: its first plan names the camera (and the index now records it); a camera with a
/// shared profile gives the card its settings (BRIEF §13), which may group or name differently and plan again.
/// </summary>
private async Task InheritCameraAsync(ImportPlan plan)
{
if (_profileResolved || _selected?.Card is not { } card) return null;
if (_profileResolved || _selected?.Card is not { } card || Services.Database is not { } db) return;
_profileResolved = true;
return plan.Sessions is [var first, ..] ? CameraProfiles.Find(first.CameraMake, first.CameraModel, _cards.Where(c => c.Id != card.Id)) : null;
if (plan.Sessions is not [var first, ..]) return;
try
{
// An archive plan recorded the card's camera; keep the screen's copy of the card in step with the index.
if (await db.MediaCards.GetAsync(card.Id) is { } saved) await ReplaceCardAsync(saved);
}
catch (DatabaseException ex)
{
Log.Warning("import", "The card could not be read again", ex);
}
var make = _selected?.Card?.CameraMake ?? first.CameraMake;
var model = _selected?.Card?.CameraModel ?? first.CameraModel;
if (await FindCameraAsync(make, model) is { } camera && _selected?.Card?.Id == card.Id) await FollowCameraAsync(card, camera);
}
/// <summary>The card takes its camera's shared profile and is recorded among the cards that follow it.</summary>
private async Task FollowCameraAsync(MediaCard card, CameraProfile camera)
{
_camera = camera.With(card.Id);
_followsCamera = true;
LoadChoices(camera.Profile);
if (camera.Follows(card.Id) || Services.Database is not { } db) return;
try
{
await new CameraProfileStore(db).SaveAsync(_camera);
}
catch (DatabaseException ex)
{
Log.Warning("import", "The camera profile was not saved", ex);
}
}
/// <summary>The selected card's id, registering an inserted card on first sight.</summary>
@@ -791,10 +979,11 @@ public sealed class ImportViewModel : SectionViewModel
_plan = _choices.TitlesChangeNames ? plan : ImportPlans.WithTitles(plan, _titles);
_totals = ImportPlans.Totals(_plan, _choices.VerifyCopies);
var rows = ImportPlans.Sessions(_plan, _choices.Destination, _existingFolders);
if (!rows.Select(r => r.SessionKey).SequenceEqual(Sessions.Select(s => s.Row.SessionKey)))
// Typed titles do not rebuild the rows (the field being typed in stays); anything else the planner changed does.
if (!rows.Select(r => r with { Title = null }).SequenceEqual(Sessions.Select(s => s.Row with { Title = null })))
{
Sessions.Clear();
foreach (var row in rows) Sessions.Add(new ImportSessionRowViewModel(row, OnTitleChanged));
foreach (var row in rows) Sessions.Add(new ImportSessionRowViewModel(row, OnTitleChanged, Merge) { IsEditable = _phase != ImportPhase.Running });
}
OnPropertyChanged(string.Empty);
CommandManager.InvalidateRequerySuggested();
@@ -808,6 +997,23 @@ public sealed class ImportViewModel : SectionViewModel
else ApplyPlan();
}
/// <summary>Joins a session to the earlier one of the same camera and format (BRIEF §13: merge in the plan).</summary>
private void Merge(PlanSessionRow row)
{
_splits.Remove(row.FirstPath);
_merges.Add(row.FirstPath);
Replan();
}
/// <summary>Starts a new session at a photo of "Show plan" (BRIEF §13: split in the plan).</summary>
private void Split(PlanDetailRow row)
{
_merges.Remove(row.Source);
_splits.Add(row.Source);
Details = null;
Replan();
}
private void SetStatus(ImportPhase phase, string? text)
{
_statusText = text;
@@ -821,32 +1027,25 @@ public sealed class ImportViewModel : SectionViewModel
{
if (_plan is not { } plan || _selected is not { Root: { } root } source) return;
var choices = _choices;
if (source.Card is { } card && Services.Archives is { } archives)
{
try
{
await archives.Imports.SaveCardAsync(card.Id, card.Nickname, choices.ToProfile(), card.AutoImport);
}
catch (DatabaseException ex)
{
Log.Warning("import", "The card profile was not saved", ex);
}
}
// A new import: an earlier failed job of this screen is no longer what Retry resumes.
_jobId = null;
_jobCardId = null;
_jobSourceKey = source.Key;
if (source.Card is { } card) await SaveProfileAsync(card, choices);
Details = null;
ErrorText = null;
Progress = 0;
ProgressText = Loc.L("Import.Progress.Starting");
_jobSourceKey = source.Key;
Phase = ImportPhase.Running;
if (choices.Destination == ImportDestinationKind.Archive)
{
await StartJobAsync(plan, choices, source);
return;
}
var cts = _runCts = new CancellationTokenSource();
var progress = new Progress<ImportProgress>(ShowProgress);
try
{
if (choices.Destination == ImportDestinationKind.Archive)
{
await StartJobAsync(plan, choices, source, cts.Token);
return;
}
var progress = new Progress<ImportProgress>(ShowProgress);
var outcome = choices.Destination == ImportDestinationKind.Folder
? await Task.Run(() => LocalImport.RunAsync(plan, new FolderImportSink(choices.FolderPath!), choices.VerifyCopies, progress, cts.Token), cts.Token)
: await RunServerAsync(plan, choices, progress, cts.Token);
@@ -856,8 +1055,9 @@ public sealed class ImportViewModel : SectionViewModel
{
Fail(Loc.L("Import.Status.Cancelled"));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or TitanoApiException or HttpRequestException or UntrustedCertificateException)
catch (Exception ex)
{
// Whatever stopped it, the screen leaves Running: the form, the sources and Retry come back.
Log.Warning("import", $"Import of {root} failed", ex);
Fail(ex.Message);
}
@@ -871,16 +1071,29 @@ public sealed class ImportViewModel : SectionViewModel
using var client = new TitanoClient(address, new CertificatePinning(Services.Server.Fingerprints), $"Titano ({Environment.MachineName})") { Token = token };
try
{
return await Task.Run(() => LocalImport.RunAsync(plan, new ServerImportSink(client, staging), choices.VerifyCopies, progress, ct), ct);
var sink = new ServerImportSink(client, staging);
return await Task.Run(() => LocalImport.RunAsync(plan, sink, choices.VerifyCopies, progress, ct, sink.Report), ct);
}
finally
{
// Our own staging folder: verified copies not uploaded yet stay on the card.
if (Directory.Exists(staging)) Directory.Delete(staging, recursive: true);
DeleteStaging(staging);
}
}
private async Task StartJobAsync(ImportPlan plan, ImportChoices choices, ImportSource source)
/// <summary>Our own staging folder: verified copies not uploaded yet stay on the card, so a leftover is only disk space.</summary>
private static void DeleteStaging(string staging)
{
try
{
if (Directory.Exists(staging)) Directory.Delete(staging, recursive: true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("import", $"Staging folder {staging} left behind", ex);
}
}
private async Task StartJobAsync(ImportPlan plan, ImportChoices choices, ImportSource source, CancellationToken cancelled)
{
if (Services.Engine is not { } engine || _archive is not { } archive)
{
@@ -891,6 +1104,9 @@ public sealed class ImportViewModel : SectionViewModel
var cardId = source.Kind == SourceKind.Card ? source.Card?.Id ?? await RegisteredCardIdAsync() : null;
var job = await engine.EnqueueAsync(ArchiveJobs.Import(archive, plan, cardId, choices.VerifyCopies));
_jobId = job.Id;
_jobCardId = cardId;
// Cancel pressed while the job was being queued.
if (cancelled.IsCancellationRequested && Services.Jobs is { } jobs) await jobs.CancelAsync(job.Id);
Shell.Notify(Loc.L("Import.Toast.Started", source.Title), plan.CopyCount > 0 ? _totals?.Text : null, Loc.L("Shell.Nav.Jobs"),
Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs));
}
@@ -926,6 +1142,7 @@ public sealed class ImportViewModel : SectionViewModel
case JobState.Done:
_jobId = null;
var outcome = await VerifyAsync(plan, job);
_jobCardId = null;
Finish(plan, outcome);
await QueueDeepAnalysisAsync(plan);
break;
@@ -942,14 +1159,21 @@ public sealed class ImportViewModel : SectionViewModel
}
}
/// <summary>Every planned copy must be a frame of the archive now (BRIEF §12.4 verification result).</summary>
/// <summary>Every planned copy must be a frame of the archive now, matched through the job's own records (BRIEF §12.4 verification result).</summary>
private async Task<ImportOutcome> VerifyAsync(ImportPlan plan, Job job)
{
if (Services.Database is not { } db || _archive is not { } archive) return new ImportOutcome(0, 0, 0, [], false);
var verify = _choices.VerifyCopies;
return await Task.Run(() => ImportOutcome.CheckAsync(plan, verify,
async (item, ct) => (await db.Frames.FindBySizeAndCaptureAsync(archive.Id, item.Size, item.CapturedAt, ct).ConfigureAwait(false)).Count > 0,
CancellationToken.None));
var cardId = _jobCardId;
try
{
return await Task.Run(() => ArchiveImportCheck.CheckAsync(db, archive.Id, plan, job, cardId, verify, CancellationToken.None));
}
catch (DatabaseException ex)
{
Log.Warning("import", "The import could not be checked against the index", ex);
return ImportOutcome.From(plan, [], verify, stopped: ex.Message);
}
}
/// <summary>
@@ -1061,8 +1285,8 @@ public sealed class ImportViewModel : SectionViewModel
}
Shell.ShowToast(new Toast
{
Title = Loc.L("Import.Toast.Inserted", source.Title),
Message = source.Subtitle,
Title = Loc.L(source.IsKnown ? "Import.Toast.Inserted" : "Import.Toast.NewCard", source.Title),
Message = source.ToastText,
ActionText = Loc.L("Import.Toast.Import"),
ActionToolTip = Loc.L("Tooltips.Import.OpenCard"),
ActionCommand = new RelayCommand(() =>