feat(app): Import and Archive manager screens with capture scenes and resources
Import (cards and folders): the card pool with remembered profiles and the nickname field for new cards, the form (destination, scan, sessions, names with live preview and tokens, duplicates, after-import choices), the plan panel with editable session titles, Show plan, the archive import job or the folder/server run with progress, the verification result and the after-import actions (dry run, delete, format through the Windows dialog, eject, open in Library), card-insertion toasts, automatic import into the archive and resume after re-insertion. Deep analysis after import is queued with ProcessingJobs at background priority. Archive manager: archive picker, tree with availability, figure tiles and charts, mass operations on the selected set, scan/rebuild (dialog)/verify/ duplicates/orphans/adopt/maintenance as jobs, and the maintenance view with index health, recent runs and the duplicate and orphan reports with safe fixes. --capture renders import-<state> and archive-<view> from a simulated card and sample reports; en and it resources for both screens. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
31 files changed
+4531
-28
No files matched your search
@@ -1,9 +1,621 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using System.IO;
|
||||
using System.Windows.Input;
|
||||
using Titano.App.Archiving;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.App.Jobs;
|
||||
using Titano.App.Shell;
|
||||
using Titano.Core.Archiving;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.IO;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data;
|
||||
using Titano.Data.Archiving;
|
||||
using Titano.Data.Archiving.Jobs;
|
||||
using Titano.Data.Processing;
|
||||
using Titano.Data.Repositories;
|
||||
using Titano.Ui.Mvvm;
|
||||
using Titano.Ui.Visuals;
|
||||
|
||||
namespace Titano.App.Sections;
|
||||
|
||||
/// <summary>Archive manager (BRIEF §12.5).</summary>
|
||||
public sealed class ArchiveViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.Archive, "Icon.Archive")
|
||||
/// <summary>
|
||||
/// Archive manager (BRIEF §12.5, Archive.html): the archive's tree (years, sequences) with its availability, its
|
||||
/// figures and charts, mass operations on the selected set (analyse, proxies, thumbnails, verify, rename, move,
|
||||
/// retag, CSV), and the operations on the whole archive as jobs (scan, rebuild with its dialog, verify,
|
||||
/// maintenance), plus the maintenance view: index health, duplicates and orphans with safe fixes, recent runs.
|
||||
/// </summary>
|
||||
public sealed class ArchiveViewModel : SectionViewModel
|
||||
{
|
||||
public ShellViewModel Shell { get; } = shell;
|
||||
private const int RecentCount = 6;
|
||||
private const int PageSize = 1000;
|
||||
|
||||
private readonly HashSet<ArchiveTreeNode> _selection = [];
|
||||
private IReadOnlyList<Core.Model.Archive> _archives = [];
|
||||
private Core.Model.Archive? _archive;
|
||||
private ArchiveAvailability _availability = ArchiveAvailability.Offline;
|
||||
private ArchiveStats? _stats;
|
||||
private ArchiveTree? _tree;
|
||||
private int _viewIndex;
|
||||
private bool _loaded;
|
||||
private Task _load = Task.CompletedTask;
|
||||
private bool _jobEvents;
|
||||
private string _lastScanText = string.Empty;
|
||||
private ArchiveDialogViewModel? _dialog;
|
||||
private IReadOnlyList<ArchiveTile> _tiles = [];
|
||||
private IReadOnlyList<ChartRow> _months = [];
|
||||
private IReadOnlyList<ChartItem> _storage = [];
|
||||
private IReadOnlyList<ChartItem> _cameras = [];
|
||||
private IReadOnlyList<ChartItem> _formats = [];
|
||||
private IReadOnlyList<HealthLineViewModel> _health = [];
|
||||
private IReadOnlyList<MaintenanceRow> _recent = [];
|
||||
private IReadOnlyList<DuplicateRowViewModel>? _duplicates;
|
||||
private IReadOnlyList<OrphanRowViewModel>? _orphans;
|
||||
private bool _findingDuplicates;
|
||||
private bool _findingOrphans;
|
||||
|
||||
public ArchiveViewModel(ShellViewModel shell)
|
||||
: base(SectionKey.Archive, "Icon.Archive")
|
||||
{
|
||||
Shell = shell;
|
||||
ScanCommand = new AsyncRelayCommand(() => QueueAsync(a => ArchiveJobs.Scan(a)), IsOnline);
|
||||
RebuildCommand = new AsyncRelayCommand(() => OpenRebuildDialogAsync(), () => _archive is not null);
|
||||
VerifyCommand = new AsyncRelayCommand(() => QueueAsync(a => ArchiveJobs.Verify(a)), IsOnline);
|
||||
AdoptCommand = new AsyncRelayCommand(AdoptAsync);
|
||||
MaintenanceCommand = new AsyncRelayCommand(() => QueueAsync(a => ArchiveJobs.Maintenance(a)), IsOnline);
|
||||
MaintenanceDryRunCommand = new AsyncRelayCommand(() => QueueAsync(a => ArchiveJobs.Maintenance(a, dryRun: true)), () => _archive is not null);
|
||||
RebuildProxiesCommand = new AsyncRelayCommand(() => QueueSetAsync(ids => ArchiveJobs.Proxies(ids, SetLabel(), force: true), All()), IsOnline);
|
||||
RelinkCommand = new AsyncRelayCommand(RelinkAsync);
|
||||
HistoryCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Jobs));
|
||||
|
||||
AnalyseSetCommand = new AsyncRelayCommand(() => QueueSetAsync(ids => ProcessingJobs.DeepAnalysis(ids, SetLabel()), Set()), HasSet);
|
||||
ProxiesSetCommand = new AsyncRelayCommand(() => QueueSetAsync(ids => ArchiveJobs.Proxies(ids, SetLabel()), Set()), HasSet);
|
||||
ThumbnailsSetCommand = new AsyncRelayCommand(() => QueueSetAsync(ids => ArchiveJobs.Thumbnails(ids, SetLabel()), Set()), HasSet);
|
||||
VerifySetCommand = new AsyncRelayCommand(() => QueueSetAsync(ids => ArchiveJobs.Verify(_archive!, ids), Set()), HasSet);
|
||||
RenameSetCommand = new RelayCommand(() => OpenRename(RenameMode.Titles), () => HasSet() && IsOnline());
|
||||
MoveSetCommand = new RelayCommand(() => OpenRename(RenameMode.Folders), () => HasSet() && IsOnline());
|
||||
RetagSetCommand = new RelayCommand(OpenRetag, () => HasSet() && IsOnline());
|
||||
ExportSetCommand = new AsyncRelayCommand(ExportAsync, HasSet);
|
||||
|
||||
FindDuplicatesCommand = new AsyncRelayCommand(FindDuplicatesAsync, () => _archive is not null && !_findingDuplicates);
|
||||
FindOrphansCommand = new AsyncRelayCommand(FindOrphansAsync, () => IsOnline() && !_findingOrphans);
|
||||
MarkDuplicatesCommand = new AsyncRelayCommand(() => QueueAsync(a => ArchiveJobs.Maintenance(a)), IsOnline);
|
||||
}
|
||||
|
||||
public ShellViewModel Shell { get; }
|
||||
|
||||
private AppServices Services => Shell.Services;
|
||||
|
||||
// ---------------- Toolbar ----------------
|
||||
|
||||
public IReadOnlyList<Core.Model.Archive> Archives { get => _archives; private set => Set(ref _archives, value); }
|
||||
|
||||
public Core.Model.Archive? SelectedArchive
|
||||
{
|
||||
get => _archive;
|
||||
set
|
||||
{
|
||||
if (value is null || value == _archive) return;
|
||||
_archive = value;
|
||||
_duplicates = null;
|
||||
_orphans = null;
|
||||
_ = LoadAsync();
|
||||
}
|
||||
}
|
||||
|
||||
public bool HasArchive => _archive is not null;
|
||||
|
||||
public string ArchiveToolTip => _archive is null ? Loc.L("Tooltips.Archive.Pick") : Loc.L("Tooltips.Archive.PickRoot", _archive.RootPath);
|
||||
|
||||
/// <summary>0 = overview (tree and figures), 1 = maintenance.</summary>
|
||||
public int ViewIndex
|
||||
{
|
||||
get => _viewIndex;
|
||||
set
|
||||
{
|
||||
if (!Set(ref _viewIndex, value)) return;
|
||||
OnPropertyChanged(nameof(IsOverview));
|
||||
OnPropertyChanged(nameof(IsMaintenance));
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsOverview => HasArchive && _viewIndex == 0;
|
||||
public bool IsMaintenance => HasArchive && _viewIndex == 1;
|
||||
|
||||
/// <summary>"Last scan 29/09/2026 07:12 · 14 min".</summary>
|
||||
public string LastScanText { get => _lastScanText; private set => Set(ref _lastScanText, value); }
|
||||
|
||||
public ICommand ScanCommand { get; }
|
||||
public ICommand RebuildCommand { get; }
|
||||
public ICommand VerifyCommand { get; }
|
||||
public ICommand AdoptCommand { get; }
|
||||
public ICommand MaintenanceCommand { get; }
|
||||
public ICommand MaintenanceDryRunCommand { get; }
|
||||
public ICommand RebuildProxiesCommand { get; }
|
||||
public ICommand RelinkCommand { get; }
|
||||
public ICommand HistoryCommand { get; }
|
||||
|
||||
// ---------------- Overview ----------------
|
||||
|
||||
public ObservableCollection<ArchiveTreeRowViewModel> TreeRows { get; } = [];
|
||||
|
||||
public IReadOnlyList<ArchiveTile> Tiles { get => _tiles; private set => Set(ref _tiles, value); }
|
||||
public IReadOnlyList<ChartRow> MonthRows { get => _months; private set => Set(ref _months, value); }
|
||||
public IReadOnlyList<string> MonthLabels => ArchiveFigures.MonthLabels();
|
||||
public IReadOnlyList<ChartItem> StorageBars { get => _storage; private set => Set(ref _storage, value); }
|
||||
public IReadOnlyList<ChartItem> CameraBars { get => _cameras; private set => Set(ref _cameras, value); }
|
||||
public IReadOnlyList<ChartItem> FormatBars { get => _formats; private set => Set(ref _formats, value); }
|
||||
|
||||
/// <summary>Photos per month in the culture's digits.</summary>
|
||||
public Func<double, string> CountFormatter { get; } = v => Formatting.Count((long)v);
|
||||
|
||||
/// <summary>"412 sequences · all", "36 sequences · 2025", "Harbour sunset".</summary>
|
||||
public string SetText
|
||||
{
|
||||
get
|
||||
{
|
||||
var set = Set();
|
||||
if (_selection.Count == 0 || _selection.Any(n => n.Kind == TreeNodeKind.Archive)) return Loc.Plural("Archive.Set.All", set.Count);
|
||||
return set.Count == 1 ? set[0].DisplayTitle : Loc.Plural("Shell.Status.Sequences", set.Count);
|
||||
}
|
||||
}
|
||||
|
||||
public ICommand AnalyseSetCommand { get; }
|
||||
public ICommand ProxiesSetCommand { get; }
|
||||
public ICommand ThumbnailsSetCommand { get; }
|
||||
public ICommand VerifySetCommand { get; }
|
||||
public ICommand RenameSetCommand { get; }
|
||||
public ICommand MoveSetCommand { get; }
|
||||
public ICommand RetagSetCommand { get; }
|
||||
public ICommand ExportSetCommand { get; }
|
||||
|
||||
/// <summary>The view reports the selected tree rows.</summary>
|
||||
public void SetSelection(IEnumerable<ArchiveTreeRowViewModel> rows)
|
||||
{
|
||||
_selection.Clear();
|
||||
foreach (var row in rows) _selection.Add(row.Node);
|
||||
OnPropertyChanged(nameof(SetText));
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
|
||||
// ---------------- Maintenance view ----------------
|
||||
|
||||
public IReadOnlyList<HealthLineViewModel> Health { get => _health; private set => Set(ref _health, value); }
|
||||
public IReadOnlyList<MaintenanceRow> Recent { get => _recent; private set => Set(ref _recent, value); }
|
||||
|
||||
public IReadOnlyList<DuplicateRowViewModel>? Duplicates
|
||||
{
|
||||
get => _duplicates;
|
||||
private set
|
||||
{
|
||||
if (Set(ref _duplicates, value)) OnPropertyChanged(nameof(DuplicatesText));
|
||||
}
|
||||
}
|
||||
|
||||
public IReadOnlyList<OrphanRowViewModel>? Orphans
|
||||
{
|
||||
get => _orphans;
|
||||
private set
|
||||
{
|
||||
if (Set(ref _orphans, value)) OnPropertyChanged(nameof(OrphansText));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"3 groups", "None found", or empty before the first search.</summary>
|
||||
public string DuplicatesText => _findingDuplicates ? Loc.L("Archive.Find.Searching")
|
||||
: _duplicates is null ? string.Empty
|
||||
: _duplicates.Count == 0 ? Loc.L("Archive.Find.None")
|
||||
: Loc.Plural("Archive.Duplicates.Groups", _duplicates.Count);
|
||||
|
||||
public string OrphansText => _findingOrphans ? Loc.L("Archive.Find.Searching")
|
||||
: _orphans is null ? string.Empty
|
||||
: _orphans.Count == 0 ? Loc.L("Archive.Find.None")
|
||||
: Loc.Plural("Archive.Orphans.Count", _orphans.Count);
|
||||
|
||||
public ICommand FindDuplicatesCommand { get; }
|
||||
public ICommand FindOrphansCommand { get; }
|
||||
public ICommand MarkDuplicatesCommand { get; }
|
||||
|
||||
// ---------------- Dialogs ----------------
|
||||
|
||||
/// <summary>The open in-window dialog (rebuild, rename, retag); null when none.</summary>
|
||||
public ArchiveDialogViewModel? Dialog
|
||||
{
|
||||
get => _dialog;
|
||||
private set
|
||||
{
|
||||
if (Set(ref _dialog, value)) OnPropertyChanged(nameof(IsDialogOpen));
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsDialogOpen => _dialog is not null;
|
||||
|
||||
public bool IsEmpty => _loaded && _archive is null;
|
||||
|
||||
// ---------------- Lifecycle ----------------
|
||||
|
||||
protected override void OnActivated()
|
||||
{
|
||||
if (_loaded) return;
|
||||
_ = LoadAsync();
|
||||
}
|
||||
|
||||
/// <summary>Reads archives, figures, tree, health and recent maintenance of the selected archive; joins a read in progress.</summary>
|
||||
public Task LoadAsync() => _load.IsCompleted ? _load = ReadAsync() : _load;
|
||||
|
||||
private async Task ReadAsync()
|
||||
{
|
||||
if (Services.Database is not { } db) return;
|
||||
try
|
||||
{
|
||||
AttachJobEvents();
|
||||
Archives = await db.Archives.ListAsync();
|
||||
_archive = _archive is { } current ? Archives.FirstOrDefault(a => a.Id == current.Id) : null;
|
||||
_archive ??= CurrentArchive.Pick(Archives, Services.Settings.LastArchivePath);
|
||||
if (_archive is not { } archive) return;
|
||||
var root = archive.RootPath;
|
||||
_availability = await Task.Run(() => ArchiveVolume.Probe(new ArchivePaths(root)));
|
||||
_stats = await db.Sequences.GetStatsAsync(archive.Id);
|
||||
var sequences = await ListSequencesAsync(db, archive.Id);
|
||||
var withoutProxies = await db.Sequences.CountAsync(new SequenceQuery { ArchiveId = archive.Id, WithoutStatus = SequenceStatus.ProxiesBuilt });
|
||||
ShowFigures(_stats, withoutProxies);
|
||||
ShowTree(ArchiveTree.Build(archive, _availability, sequences));
|
||||
await LoadRecentAsync(db, archive);
|
||||
}
|
||||
catch (DatabaseException ex)
|
||||
{
|
||||
Log.Warning("archive", "Archive figures unavailable", ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_loaded = true;
|
||||
OnPropertyChanged(string.Empty);
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Opens the rebuild dialog (BRIEF §12.5) and counts, off the UI thread, the sidecars the rebuild will read.</summary>
|
||||
public async Task<RebuildDialogViewModel?> OpenRebuildDialogAsync()
|
||||
{
|
||||
if (_archive is not { } archive || Services.Engine is not { } engine) return null;
|
||||
var dialog = new RebuildDialogViewModel(archive, _availability, _stats?.Sequences ?? 0, async () =>
|
||||
{
|
||||
var request = ArchiveJobs.Rebuild(archive);
|
||||
await engine.EnqueueAsync(request);
|
||||
Queued(request.Kind, archive.Name);
|
||||
}, CloseDialog);
|
||||
Dialog = dialog;
|
||||
await dialog.CountAsync();
|
||||
return dialog;
|
||||
}
|
||||
|
||||
/// <summary>Shows reports computed elsewhere (capture).</summary>
|
||||
public void ShowReports(IReadOnlyList<DuplicateGroup> duplicates, OrphanReport orphans, IReadOnlyList<SequenceLocation> locations)
|
||||
{
|
||||
Duplicates = DuplicateRows(duplicates, locations);
|
||||
Orphans = OrphanRows(orphans, locations);
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
if (_jobEvents && Services.Jobs is { } jobs) jobs.JobChanged -= OnJobChanged;
|
||||
_dialog?.Dispose();
|
||||
base.Dispose();
|
||||
}
|
||||
|
||||
private static async Task<List<Sequence>> ListSequencesAsync(TitanoDatabase db, Guid archiveId)
|
||||
{
|
||||
var all = new List<Sequence>();
|
||||
string? cursor = null;
|
||||
do
|
||||
{
|
||||
var page = await db.Sequences.ListAsync(new SequenceQuery { ArchiveId = archiveId, Sort = SequenceSort.Newest, Limit = PageSize, Cursor = cursor });
|
||||
all.AddRange(page.Items);
|
||||
cursor = page.NextCursor;
|
||||
}
|
||||
while (cursor is not null);
|
||||
return all;
|
||||
}
|
||||
|
||||
private void ShowFigures(ArchiveStats stats, int withoutProxies)
|
||||
{
|
||||
Tiles = ArchiveFigures.Tiles(stats);
|
||||
MonthRows = [.. ArchiveFigures.PhotosPerMonth(stats, DateTime.Today).Select(r => new ChartRow(r.Label, r.Values, r.ToolTips))];
|
||||
StorageBars = Bars(ArchiveFigures.StorageByYear(stats));
|
||||
CameraBars = Bars(ArchiveFigures.ByCamera(stats));
|
||||
FormatBars = Bars(ArchiveFigures.ByFormat(stats));
|
||||
Health =
|
||||
[
|
||||
.. ArchiveFigures.Health(stats, withoutProxies).Select(line => new HealthLineViewModel(line, line.Action switch
|
||||
{
|
||||
HealthAction.Verify => new AsyncRelayCommand(() => QueueStatusAsync(SequenceStatus.Verified, ids => ArchiveJobs.Verify(_archive!, ids))),
|
||||
HealthAction.Proxies => new AsyncRelayCommand(() => QueueStatusAsync(SequenceStatus.ProxiesBuilt, ids => ArchiveJobs.Proxies(ids, CountLabel(ids)))),
|
||||
HealthAction.Analyse => new AsyncRelayCommand(() => QueueStatusAsync(SequenceStatus.AnalyzedLight, ids => ProcessingJobs.LightAnalysis(ids, CountLabel(ids)))),
|
||||
HealthAction.Duplicates => FindDuplicatesCommand,
|
||||
HealthAction.Orphans => FindOrphansCommand,
|
||||
_ => null,
|
||||
})),
|
||||
];
|
||||
}
|
||||
|
||||
private static IReadOnlyList<ChartItem> Bars(IReadOnlyList<BarValue> values) =>
|
||||
[.. values.Select(v => new ChartItem(v.Label, v.Value, v.ValueText, v.ToolTip))];
|
||||
|
||||
private void ShowTree(ArchiveTree tree)
|
||||
{
|
||||
var expanded = _tree?.ExpandedKeys();
|
||||
if (expanded is not null) tree.Expand(expanded);
|
||||
else if (tree.Root.Children.Count > 0) tree.Root.Children[0].IsExpanded = true;
|
||||
_tree = tree;
|
||||
_selection.Clear();
|
||||
RebuildRows();
|
||||
}
|
||||
|
||||
private void RebuildRows()
|
||||
{
|
||||
TreeRows.Clear();
|
||||
if (_tree is null) return;
|
||||
foreach (var node in _tree.Visible()) TreeRows.Add(new ArchiveTreeRowViewModel(node, _tree.Availability, Toggle));
|
||||
OnPropertyChanged(nameof(SetText));
|
||||
}
|
||||
|
||||
private void Toggle(ArchiveTreeNode node)
|
||||
{
|
||||
if (node.Kind == TreeNodeKind.Archive) return;
|
||||
node.IsExpanded = !node.IsExpanded;
|
||||
RebuildRows();
|
||||
}
|
||||
|
||||
private async Task LoadRecentAsync(TitanoDatabase db, Core.Model.Archive archive)
|
||||
{
|
||||
var jobs = new List<Job>();
|
||||
foreach (var kind in MaintenanceReports.MaintenanceKinds)
|
||||
jobs.AddRange((await db.Jobs.ListAsync(null, kind, RecentCount)).Items.Where(j => j.TargetIds.Contains(archive.Id)));
|
||||
Recent = MaintenanceReports.Recent(jobs, RecentCount);
|
||||
var scan = jobs.Where(j => j.Kind == JobKind.Scan && j is { State: JobState.Done, Finished: not null, Started: not null })
|
||||
.MaxBy(j => j.Finished);
|
||||
LastScanText = scan is { Started: { } started, Finished: { } finished }
|
||||
? Loc.L("Archive.LastScan", Formatting.Date(finished) + " " + Formatting.TimeOfDay(finished), Formatting.Duration(finished - started))
|
||||
: string.Empty;
|
||||
}
|
||||
|
||||
private void AttachJobEvents()
|
||||
{
|
||||
if (_jobEvents || Services.Jobs is not { } jobs) return;
|
||||
jobs.JobChanged += OnJobChanged;
|
||||
_jobEvents = true;
|
||||
}
|
||||
|
||||
/// <summary>A finished archive job changes the figures: read them again.</summary>
|
||||
private void OnJobChanged(Job job)
|
||||
{
|
||||
if (job.State is not (JobState.Done or JobState.Failed) || _archive is null) return;
|
||||
if (job.Kind is not (JobKind.Scan or JobKind.Rebuild or JobKind.Verify or JobKind.Maintenance or JobKind.Import or JobKind.Proxies or JobKind.Thumbs
|
||||
or JobKind.LightAnalyse or JobKind.DeepAnalyse)) return;
|
||||
System.Windows.Application.Current?.Dispatcher.BeginInvoke(() =>
|
||||
{
|
||||
if (IsSelected) _ = LoadAsync();
|
||||
else _loaded = false;
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------- Actions ----------------
|
||||
|
||||
private bool IsOnline() => _archive is not null && _availability == ArchiveAvailability.Online;
|
||||
|
||||
private bool HasSet() => _archive is not null && _tree is not null && Set().Count > 0;
|
||||
|
||||
private IReadOnlyList<Sequence> Set() => _tree is null ? [] : ArchiveTree.SetOf(_tree, _selection);
|
||||
|
||||
private IReadOnlyList<Sequence> All() => _tree is null ? [] : ArchiveTree.SetOf(_tree, []);
|
||||
|
||||
private string SetLabel() => SetText;
|
||||
|
||||
private async Task QueueAsync(Func<Core.Model.Archive, ArchiveJobRequest> build)
|
||||
{
|
||||
if (Services.Engine is not { } engine || _archive is not { } archive) return;
|
||||
var request = build(archive);
|
||||
await engine.EnqueueAsync(request);
|
||||
Queued(request.Kind, request.Label ?? archive.Name);
|
||||
}
|
||||
|
||||
private async Task QueueSetAsync(Func<IReadOnlyList<Guid>, ArchiveJobRequest> build, IReadOnlyList<Sequence> set)
|
||||
{
|
||||
if (Services.Engine is not { } engine || set.Count == 0) return;
|
||||
var request = build([.. set.Select(s => s.Id)]);
|
||||
await engine.EnqueueAsync(request);
|
||||
Queued(request.Kind, request.Label ?? SetLabel());
|
||||
}
|
||||
|
||||
/// <summary>Health fixes act on the sequences that miss a status (never verified, no proxies).</summary>
|
||||
private async Task QueueStatusAsync(SequenceStatus missing, Func<IReadOnlyList<Guid>, ArchiveJobRequest> build)
|
||||
{
|
||||
if (Services.Database is not { } db || _archive is not { } archive) return;
|
||||
var page = await db.Sequences.ListAsync(new SequenceQuery { ArchiveId = archive.Id, WithoutStatus = missing, Limit = PageSize });
|
||||
await QueueSetAsync(build, page.Items);
|
||||
}
|
||||
|
||||
private static string CountLabel(IReadOnlyList<Guid> ids) => Loc.Plural("Shell.Status.Sequences", ids.Count);
|
||||
|
||||
private void Queued(JobKind kind, string label) =>
|
||||
Shell.Notify(Loc.L("Library.Queued", JobText.Kind(kind), label), actionText: Loc.L("Shell.Nav.Jobs"), actionToolTip: Loc.L("Tooltips.Nav.Jobs"),
|
||||
action: () => Shell.Navigate(SectionKey.Jobs));
|
||||
|
||||
private void OpenRename(RenameMode mode)
|
||||
{
|
||||
if (Services.Archives is not { } archives || _archive is not { } archive) return;
|
||||
var dialog = new RenameDialogViewModel(mode, archives, archive, Set(), Applied, CloseDialog);
|
||||
Dialog = dialog;
|
||||
_ = dialog.PlanAsync();
|
||||
}
|
||||
|
||||
private void OpenRetag()
|
||||
{
|
||||
if (Services.Archives is not { } archives) return;
|
||||
Dialog = new RetagDialogViewModel(archives, Set(), Applied, CloseDialog);
|
||||
}
|
||||
|
||||
private async Task Applied(int changed)
|
||||
{
|
||||
Shell.Notify(Loc.Plural("Archive.Applied", changed));
|
||||
await LoadAsync();
|
||||
await Shell.Library.RefreshAsync();
|
||||
}
|
||||
|
||||
private void CloseDialog()
|
||||
{
|
||||
_dialog?.Dispose();
|
||||
Dialog = null;
|
||||
}
|
||||
|
||||
private async Task AdoptAsync()
|
||||
{
|
||||
var folder = Services.Dialogs.PickFolder(Loc.L("Library.Adopt.Title"));
|
||||
if (folder is null) return;
|
||||
if (await ArchiveActions.TryAsync(Shell, s => s.AdoptAsync(folder)))
|
||||
{
|
||||
_archive = null;
|
||||
await LoadAsync();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A moved archive keeps its id: opening it at the new root relinks every sequence (BRIEF §12.5 Move archive).</summary>
|
||||
private async Task RelinkAsync()
|
||||
{
|
||||
if (Services.Archives is not { } archives) return;
|
||||
var folder = Services.Dialogs.PickFolder(Loc.L("Archive.Relink.Title"));
|
||||
if (folder is null) return;
|
||||
try
|
||||
{
|
||||
var archive = await Task.Run(() => archives.OpenAsync(folder));
|
||||
Services.Settings.LastArchivePath = archive.RootPath;
|
||||
Services.SaveSettings();
|
||||
_archive = archive;
|
||||
await Services.QueueScanAsync(archive, full: false);
|
||||
Shell.Notify(Loc.L("Archive.Relink.Done", archive.Name), archive.RootPath);
|
||||
await LoadAsync();
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException)
|
||||
{
|
||||
Log.Warning("archive", $"Relinking {folder} failed", ex);
|
||||
Shell.Notify(Loc.L("Archive.Relink.Failed"), ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ExportAsync()
|
||||
{
|
||||
var set = Set();
|
||||
var folder = Services.Dialogs.PickFolder(Loc.L("Library.Export.Title"));
|
||||
if (folder is null || set.Count == 0) return;
|
||||
var path = Path.Combine(folder, $"Titano sequences {DateTime.Now:yyyy-MM-dd HHmm}.csv");
|
||||
var csv = LibraryViewModel.Csv(set);
|
||||
await Task.Run(() => AtomicFile.WriteAllText(path, csv));
|
||||
Shell.Notify(Loc.L("Library.Export.Done"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"),
|
||||
() => ShellActions.Reveal(path));
|
||||
}
|
||||
|
||||
private async Task FindDuplicatesAsync()
|
||||
{
|
||||
if (Services.Archives is not { } archives || Services.Database is not { } db || _archive is not { } archive) return;
|
||||
ViewIndex = 1;
|
||||
_findingDuplicates = true;
|
||||
OnPropertyChanged(nameof(DuplicatesText));
|
||||
try
|
||||
{
|
||||
var groups = await Task.Run(() => archives.FindDuplicatesAsync(archive.Id));
|
||||
Duplicates = DuplicateRows(groups, await db.Sequences.ListLocationsAsync(archive.Id));
|
||||
}
|
||||
catch (DatabaseException ex)
|
||||
{
|
||||
Shell.ReportError(ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_findingDuplicates = false;
|
||||
OnPropertyChanged(nameof(DuplicatesText));
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task FindOrphansAsync()
|
||||
{
|
||||
if (Services.Archives is not { } archives || Services.Database is not { } db || _archive is not { } archive) return;
|
||||
ViewIndex = 1;
|
||||
_findingOrphans = true;
|
||||
OnPropertyChanged(nameof(OrphansText));
|
||||
try
|
||||
{
|
||||
var report = await Task.Run(() => archives.FindOrphansAsync(archive.Id));
|
||||
Orphans = OrphanRows(report, await db.Sequences.ListLocationsAsync(archive.Id));
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or ArchiveOfflineException or DatabaseException)
|
||||
{
|
||||
Log.Warning("archive", "Orphan search failed", ex);
|
||||
Shell.Notify(Loc.L("Archive.Orphans.Failed"), ex.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_findingOrphans = false;
|
||||
OnPropertyChanged(nameof(OrphansText));
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
}
|
||||
|
||||
private IReadOnlyList<DuplicateRowViewModel> DuplicateRows(IReadOnlyList<DuplicateGroup> groups, IReadOnlyList<SequenceLocation> locations) =>
|
||||
[
|
||||
.. MaintenanceReports.Duplicates(groups, locations).Select(row => new DuplicateRowViewModel(row,
|
||||
new RelayCommand(() => Shell.OpenSequence(row.SequenceId)),
|
||||
new RelayCommand(() =>
|
||||
{
|
||||
if (_archive is { } archive && locations.FirstOrDefault(l => l.Id == row.SequenceId) is { } location)
|
||||
ShellActions.Reveal(new ArchivePaths(archive.RootPath).Sequence(location.Folder).Folder);
|
||||
}))),
|
||||
];
|
||||
|
||||
private IReadOnlyList<OrphanRowViewModel> OrphanRows(OrphanReport report, IReadOnlyList<SequenceLocation> locations) =>
|
||||
[.. MaintenanceReports.Orphans(report, locations).Select(row => new OrphanRowViewModel(row, new AsyncRelayCommand(() => FixAsync(row))))];
|
||||
|
||||
/// <summary>The safe fix of an orphan line; removing an index row asks first (its sidecar is gone, its files are not touched).</summary>
|
||||
private async Task FixAsync(OrphanRow row)
|
||||
{
|
||||
if (Services.Archives is not { } archives || _archive is not { } archive) return;
|
||||
try
|
||||
{
|
||||
switch (row.Kind)
|
||||
{
|
||||
case OrphanKind.UnlistedFiles or OrphanKind.MissingFiles when row.SequenceId is { } id:
|
||||
await Task.Run(() => archives.ReconcileAsync(id));
|
||||
break;
|
||||
case OrphanKind.MissingSequence when row.SequenceId is { } id:
|
||||
var confirmed = Services.Dialogs.Confirm(new ConfirmRequest
|
||||
{
|
||||
Heading = Loc.L("Archive.Confirm.RemoveHeading", row.Title),
|
||||
Message = Loc.L("Archive.Confirm.RemoveMessage"),
|
||||
SafeText = Loc.L("Archive.Confirm.Keep"),
|
||||
SafeToolTip = Loc.L("Tooltips.Archive.KeepRow"),
|
||||
ActionText = Loc.L("Archive.Confirm.Remove"),
|
||||
ActionToolTip = Loc.L("Tooltips.Archive.Orphans.MissingSequence"),
|
||||
IsDestructive = true,
|
||||
});
|
||||
if (!confirmed) return;
|
||||
await Task.Run(() => archives.RemoveMissingSequencesAsync(archive.Id, [id]));
|
||||
break;
|
||||
case OrphanKind.NewFolder:
|
||||
await Services.QueueScanAsync(archive, full: false);
|
||||
Queued(JobKind.Scan, archive.Name);
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
Orphans = Orphans?.Where(o => o.Row != row).ToList();
|
||||
await LoadAsync();
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or ArchiveOfflineException or DatabaseException
|
||||
or ArgumentException)
|
||||
{
|
||||
Log.Warning("archive", $"Fixing {row.Title} failed", ex);
|
||||
Shell.Notify(Loc.L("Archive.Orphans.FixFailed"), ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user