using System.IO; using System.Windows.Input; using Titano.App.Infrastructure; using Titano.App.Shell; using Titano.Core.Diagnostics; using Titano.Core.Import; using Titano.Core.Localization; using Titano.Core.Model; using Titano.Data; using Titano.Data.Archiving; using Titano.Ui.Controls; using Titano.Ui.Mvvm; namespace Titano.App.Import; /// /// The end of an import (BRIEF §12.4, §13): the verification result and the after-import actions — check the card /// (dry run: every card file and its archive copy hashed again), delete the verified photos or format the card /// (each after a confirmation, never by default), eject, open in the Library. decides /// what is allowed and why not; a card that leaves needs a new check, and formatting refuses a card that changed /// since its check. /// public sealed class ImportResultViewModel : LocalizedViewModel { private const int ListedFailures = 100; private const int ListedOther = 8; private readonly ShellViewModel _shell; private readonly ImportPlan _plan; private readonly ImportChoices _choices; private readonly Core.Model.Archive? _archive; private readonly MediaCard? _card; private CardDevice? _device; private CardActions _actions; private bool _isBusy; private string? _busyText; public ImportResultViewModel(ShellViewModel shell, ImportPlan plan, ImportOutcome outcome, ImportChoices choices, Core.Model.Archive? archive, MediaCard? card, CardDevice? device) { _shell = shell; _plan = plan; _choices = choices; _archive = archive; _card = card; _device = device; Outcome = outcome; _actions = new CardActions(choices.Destination, card is not null, device is not null, device?.IsRemovable == true, outcome, null, null); Failures = [.. outcome.Failures.Take(ListedFailures).Select(f => Loc.L("Import.Result.Failure", BidiText.Ltr(f.SourcePath), f.Message))]; CheckCommand = new AsyncRelayCommand(CheckAsync, () => _actions.CanCheck && !_isBusy); DeleteCommand = new AsyncRelayCommand(DeleteAsync, () => _actions.CanDelete && !_isBusy); FormatCommand = new AsyncRelayCommand(FormatAsync, () => _actions.CanFormat && !_isBusy); EjectCommand = new AsyncRelayCommand(EjectAsync, () => _actions.CanEject && !_isBusy); OpenLibraryCommand = new AsyncRelayCommand(async () => { await _shell.Library.RefreshAsync(); _shell.Navigate(SectionKey.Library); }); } public ImportOutcome Outcome { get; } public CardActions Actions { get => _actions; private set { _actions = value; OnAllPropertiesChanged(); CommandManager.InvalidateRequerySuggested(); } } public ICommand CheckCommand { get; } public ICommand DeleteCommand { get; } public ICommand FormatCommand { get; } public ICommand EjectCommand { get; } public ICommand OpenLibraryCommand { get; } /// "4,812 copied and verified", "4,800 copied · 12 failed". public string ResultText => Outcome.IsComplete ? Loc.Plural(Outcome.Verified ? "Import.Result.Verified" : "Import.Result.Copied", Outcome.Imported) : Loc.L("Import.Result.Partial", Formatting.Count(Outcome.Imported), Formatting.Count(Outcome.Failures.Count)); /// "12 skipped · 3 already there", or empty. public string DetailText => string.Join(" · ", new[] { Outcome.Skipped > 0 ? Loc.Plural("Import.Result.Skipped", Outcome.Skipped) : string.Empty, Outcome.Duplicates > 0 ? Loc.Plural("Import.Result.AlreadyThere", Outcome.Duplicates) : string.Empty, }.Where(t => t.Length > 0)); public bool IsComplete => Outcome.IsComplete; public StatusKind ResultKind => Outcome.IsComplete ? StatusKind.Done : StatusKind.Warning; public IReadOnlyList Failures { get; } public bool HasFailures => Failures.Count > 0; /// The profile chose "Delete imported": the dry run and the delete button are offered. public bool OffersDelete => _choices.AfterImport == AfterImport.DeleteImported; /// The profile chose "Format card". public bool OffersFormat => _choices.AfterImport == AfterImport.FormatCard; public bool OffersCheck => OffersDelete || OffersFormat; public bool IsBusy { get => _isBusy; private set { if (Set(ref _isBusy, value)) CommandManager.InvalidateRequerySuggested(); } } /// "Checking 1,240 photos" while the dry run hashes. public string? BusyText { get => _busyText; private set => Set(ref _busyText, value); } public string EraseText => _actions.EraseText; public IReadOnlyList KeptReasons => _actions.KeptReasons; public string CheckToolTip => _actions.CheckBlocker ?? Loc.L("Tooltips.Import.Check"); /// "Delete 4,812 photos…" once the card was checked; "Delete photos…" before. public string DeleteText => _actions.Erase is null ? Loc.L("Import.Erase.DeletePlain") : Loc.Plural("Import.Erase.Delete", _actions.DeleteCount); public string DeleteToolTip => _actions.DeleteBlocker ?? Loc.L("Tooltips.Import.Delete"); public string FormatToolTip => _actions.FormatBlocker ?? Loc.L("Tooltips.Import.Format"); public string EjectToolTip => _actions.CanEject ? Loc.L("Tooltips.Import.Eject") : Loc.L("Import.Blocked.NotRemovable"); /// /// The card is listed again, left, or came back (Devices list); actions follow. A card that left may come back /// changed (photos shot meanwhile), so its dry run no longer counts: a new check is needed. /// public void SetDevice(CardDevice? device) { var same = device is not null && _device is not null && device.Identity == _device.Identity && device.Root == _device.Root; _device = device; Actions = _actions with { IsInserted = device is not null, IsRemovable = device?.IsRemovable == true, Erase = same ? _actions.Erase : null, Card = same ? _actions.Card : null, }; } /// Shows a dry run computed elsewhere (capture, tests). public void ShowErase(ErasePlan erase, CardSnapshot card) => Actions = _actions with { Erase = erase, Card = card }; /// Ejects when the profile asks for it and nothing more is to be done on the card. public async Task AutoEjectAsync() { if (_choices.Eject && _choices.AfterImport == AfterImport.Keep && Outcome.IsComplete && _actions.CanEject) await EjectAsync(); } private async Task CheckAsync() { if (_shell.Services.Archives is not { } archives || _archive is null || _card is null || _device is null) return; var device = _device; IsBusy = true; try { var progress = new Progress(n => BusyText = Loc.Plural("Import.Erase.Checking", n)); var (erase, snapshot) = await Task.Run(async () => { // Listed before hashing: formatting later compares the card with this list. var card = CardSnapshot.Take(device.Root, device.Identity); return (await archives.PlanCardEraseAsync(_archive.Id, _card.Id, device.Root, progress).ConfigureAwait(false), card); }); if (_device == device) ShowErase(erase, snapshot); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException) { Log.Warning("import", "Card check failed", ex); _shell.Notify(Loc.L("Import.Toast.CheckFailed"), ex.Message); } finally { BusyText = null; IsBusy = false; } } private async Task DeleteAsync() { if (_actions.Erase is not { } erase) return; var confirmed = _shell.Services.Dialogs.Confirm(new ConfirmRequest { Heading = Loc.Plural("Import.Confirm.DeleteHeading", _actions.DeleteCount), Message = Loc.L("Import.Confirm.DeleteMessage"), SafeText = Loc.L("Import.Confirm.Keep"), SafeToolTip = Loc.L("Tooltips.Import.KeepCard"), ActionText = Loc.L("Import.Confirm.Delete"), ActionToolTip = Loc.L("Tooltips.Import.Delete"), IsDestructive = true, }); if (!confirmed) return; IsBusy = true; try { var result = await Task.Run(() => CardEraser.Execute(erase)); _shell.Notify(Loc.Plural("Import.Toast.Deleted", result.Deleted), result.Kept.Count > 0 ? Loc.Plural("Import.Erase.Kept", result.Kept.Count) : null); // The card changed: a new dry run is needed before anything else is deleted. Actions = _actions with { Erase = null, Card = null }; } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { Log.Warning("import", "Deleting imported photos failed", ex); _shell.Notify(Loc.L("Import.Toast.DeleteFailed"), ex.Message); } finally { IsBusy = false; } if (_choices.Eject && _actions.CanEject) await EjectAsync(); } private async Task FormatAsync() { if (_device is not { } device || _actions.Card is not { } checkedCard) return; var name = _card?.Nickname ?? device.Label; var notImported = _actions.NotImported; var confirmed = _shell.Services.Dialogs.Confirm(new ConfirmRequest { Heading = Loc.L("Import.Confirm.FormatHeading", name), Message = notImported.Count == 0 ? Loc.Plural("Import.Confirm.FormatMessage", _actions.DeleteCount) : Loc.Plural("Import.Confirm.FormatMessage", _actions.DeleteCount) + " " + Loc.Plural("Import.Confirm.FormatOther", notImported.Count), Detail = notImported.Count == 0 ? null : OtherFilesDetail(notImported), DetailToolTip = Loc.L("Tooltips.Import.NotImported"), SafeText = Loc.L("Import.Confirm.Keep"), SafeToolTip = Loc.L("Tooltips.Import.KeepCard"), ActionText = Loc.L("Import.Confirm.Format"), ActionToolTip = Loc.L("Tooltips.Import.FormatConfirm"), IsDestructive = true, TypedConfirmation = name, TypedPrompt = Loc.L("Import.Confirm.TypeName"), }); if (!confirmed) return; // Right before formatting: the same card, holding exactly what was checked (BRIEF §0.2 rule 8). IsBusy = true; bool unchanged; try { var present = _shell.Services.Devices.Devices.FirstOrDefault(d => d.Identity == device.Identity && d.Root == device.Root); unchanged = present is not null && checkedCard.IsUnchanged(await Task.Run(() => CardSnapshot.Take(present.Root, present.Identity))); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { Log.Warning("import", "The card could not be listed before formatting", ex); unchanged = false; } finally { IsBusy = false; } if (!unchanged) { Actions = _actions with { Erase = null, Card = null }; _shell.Notify(Loc.L("Import.Toast.CardChanged", name), Loc.L("Import.Blocked.NoDryRun")); return; } var outcome = _shell.Services.Devices.Format(device); if (outcome == FormatOutcome.Formatted) Actions = _actions with { Erase = null, Card = null }; if (outcome != FormatOutcome.Cancelled) _shell.Notify(Loc.L("Import.Toast.Format." + outcome, name)); } /// The first files that were never imported, one per line. private static string OtherFilesDetail(IReadOnlyList files) { var shown = files.Take(ListedOther).ToList(); if (files.Count > ListedOther) shown.Add("…"); return string.Join(Environment.NewLine, shown); } private async Task EjectAsync() { if (_device is not { } device) return; IsBusy = true; try { var outcome = await Task.Run(() => _shell.Services.Devices.Eject(device)); _shell.Notify(Loc.L("Import.Toast.Eject." + outcome, _card?.Nickname ?? device.Label)); if (outcome == EjectOutcome.Ejected) SetDevice(null); } finally { IsBusy = false; } } }