diff --git a/i18n/en/Import.resx b/i18n/en/Import.resx index 594867fa..4ded1106 100644 --- a/i18n/en/Import.resx +++ b/i18n/en/Import.resx @@ -109,6 +109,8 @@ A photo or its archive copy could not be read.long The destination is full.long The import stopped before the end.long + The photo could not be read or copied.long + Titano was denied access to the photo or its copy.long Retry The server did not accept the photos.long {0} is no longer available.long diff --git a/i18n/it/Import.it.resx b/i18n/it/Import.it.resx index d7f703a7..aa9a3724 100644 --- a/i18n/it/Import.it.resx +++ b/i18n/it/Import.it.resx @@ -107,6 +107,8 @@ Impossibile leggere una foto o la sua copia nell'archivio. La destinazione è piena. L'importazione si è interrotta prima della fine. + Impossibile leggere o copiare la foto. + A Titano è stato negato l'accesso alla foto o alla sua copia. Riprova Il server non ha accettato le foto. {0} non è più disponibile. diff --git a/src/Titano.App/Editor/EditorViewModel.cs b/src/Titano.App/Editor/EditorViewModel.cs index 508c7b37..2e4ca35a 100644 --- a/src/Titano.App/Editor/EditorViewModel.cs +++ b/src/Titano.App/Editor/EditorViewModel.cs @@ -930,14 +930,21 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable if (!_jobs.Concerns(job)) return; _dispatcher.BeginInvoke(() => { - if (_disposed) return; + if (_disposed) + { + // Closed after the Jobs screen left this render's end to it (FollowsRender): said without a read. + if (job is { Kind: JobKind.Render, State: JobState.Done } && _jobs.IsActive(job.Id) && Shell.Jobs.ClaimRenderToast(job.Id)) + AnnounceRender(job, read: false); + return; + } var wasActive = _jobs.IsActive(job.Id); // Progress alone (several times a second on a server) only moves the server job's text and bar. if (_jobs.Track(job)) OnBusyChanged(); else OnServerJobChanged(); LearnAnalysisSpeed(job); if (!wasActive) return; - if (job.State == JobState.Done) _ = ReloadAsync(job.Kind == JobKind.Render ? job : null); + // A render this editor followed to its end is said here, with its output, unless the Jobs screen said it first. + if (job.State == JobState.Done) _ = ReloadAsync(job.Kind == JobKind.Render && Shell.Jobs.ClaimRenderToast(job.Id) ? job : null); else if (IsRemote && job.State is JobState.Failed or JobState.Cancelled) ReportServerJobEnded(job); }); } @@ -1010,23 +1017,43 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable if (job is { Kind: JobKind.DeepAnalyse, State: JobState.Done, ItemsPerSecond: > 0 and var speed }) _analysisSecondsPerFrame = 1 / speed; } - /// Reads the sequence again after a job; a finished render offers its follow-ups (BRIEF §11.5). + /// + /// Reads the sequence again after a job. A finished render whose toast this editor took () + /// is said in any case, also when the editor closed meanwhile: with its output and follow-ups (BRIEF §11.5) once the + /// sequence is read again, without them when that failed. + /// private async Task ReloadAsync(Job? render) { + var reloaded = false; try { await Session.ReloadAsync(); + reloaded = true; } catch (Exception ex) when (ex is System.IO.IOException or System.IO.InvalidDataException or InvalidOperationException or UnauthorizedAccessException - or System.Net.Http.HttpRequestException or Protocol.Client.TitanoApiException or OperationCanceledException) + or System.Net.Http.HttpRequestException or Protocol.Client.TitanoApiException or OperationCanceledException + or Data.DatabaseException) { // A server that does not answer in time cancels the request (OperationCanceledException). Shell.ReportError(ex); - return; } - if (render is null || _disposed) return; - // A server's render stays on the server: nothing to show in Explorer. - var output = Session.Content.Renders.FirstOrDefault(r => render.Started is not { } started || r.Created >= started)?.OutputPath is { Length: > 0 } path + finally + { + if (render is not null) AnnounceRender(render, reloaded); + } + } + + /// + /// This editor follows the render (UI thread): it saw it wait or run and has not seen it end yet, so it will take its + /// toast () when it does. + /// + internal bool FollowsRender(Guid jobId) => !_disposed && _jobs.IsActive(jobId); + + /// "Render finished" with the output file and Show in folder; : the sequence was read again after the render. + private void AnnounceRender(Job render, bool read) + { + // A server's render stays on the server: nothing to show in Explorer. Before a read the renders are the old ones. + var output = read && Session.Content.Renders.FirstOrDefault(r => render.Started is not { } started || r.Created >= started)?.OutputPath is { Length: > 0 } path ? path : null; Shell.ShowToast(new Toast diff --git a/src/Titano.App/Import/ImportDestinations.cs b/src/Titano.App/Import/ImportDestinations.cs index 426541ef..89136bd1 100644 --- a/src/Titano.App/Import/ImportDestinations.cs +++ b/src/Titano.App/Import/ImportDestinations.cs @@ -211,7 +211,8 @@ public sealed record ImportOutcome(int Copied, int Duplicates, int Skipped, IRea /// public static class LocalImport { - public static async Task RunAsync(ImportPlan plan, IImportSink sink, bool verify, IProgress? progress, + /// The card or folder as the Devices list names it (a card that leaves is named in each failure). + public static async Task RunAsync(ImportPlan plan, IImportSink sink, string source, bool verify, IProgress? progress, CancellationToken cancellationToken, ImportSinkReport? report = null) { var results = new List(plan.FileCount); @@ -232,8 +233,7 @@ public static class LocalImport catch (Exception ex) when (!cancellationToken.IsCancellationRequested && Stops(ex)) { Log.Warning("import", $"Import into {plan.DestinationRoot} stopped", ex); - // The server's own sentence (in the user's language) rather than the status line. - stopped = ex is TitanoApiException api ? api.Error.Message : ex.Message; + stopped = ImportFailures.Stop(ex, source); } return ImportOutcome.From(plan, results, verify, report, stopped); } diff --git a/src/Titano.App/Import/ImportFailures.cs b/src/Titano.App/Import/ImportFailures.cs index e648a40a..b1308733 100644 --- a/src/Titano.App/Import/ImportFailures.cs +++ b/src/Titano.App/Import/ImportFailures.cs @@ -1,5 +1,6 @@ using System.IO; using System.Net.Http; +using Titano.App.Shell; using Titano.Core.Archiving; using Titano.Core.Import; using Titano.Core.Localization; @@ -29,6 +30,17 @@ public static class ImportFailures _ => Loc.L("Import.Failed.Other"), }; + /// + /// Why the photos an import into a folder or the server never reached were not copied (): + /// the card left, the destination is full or refuses writing, or the server answered with its own sentence, does + /// not answer (a timeout too) or is no longer trusted. + /// + public static string Stop(Exception ex, string source) => ex switch + { + TitanoApiException or HttpRequestException or UntrustedCertificateException or OperationCanceledException => ErrorText.ForServer(ex), + _ => Import(ex, source), + }; + /// Why the card or folder could not be planned. public static string Plan(Exception ex, string source) => ex switch { diff --git a/src/Titano.App/Import/ServerImportSink.cs b/src/Titano.App/Import/ServerImportSink.cs index f05584fa..311c34fe 100644 --- a/src/Titano.App/Import/ServerImportSink.cs +++ b/src/Titano.App/Import/ServerImportSink.cs @@ -1,5 +1,6 @@ using System.IO; using System.Net; +using Titano.App.Shell; using Titano.Core.Diagnostics; using Titano.Core.Import; using Titano.Protocol; @@ -38,7 +39,7 @@ public sealed class ServerImportSink(TitanoClient client, string stagingDirector ImportOutcome? outcome = null; try { - outcome = await LocalImport.RunAsync(plan, this, verify, events.Forward(progress), cancellationToken, Report).ConfigureAwait(false); + outcome = await LocalImport.RunAsync(plan, this, card, verify, events.Forward(progress), cancellationToken, Report).ConfigureAwait(false); return outcome; } finally @@ -69,8 +70,9 @@ public sealed class ServerImportSink(TitanoClient client, string stagingDirector } catch (TitanoApiException ex) when (IsRefusal(ex)) { - // The executor has no failed commit: the refusal travels in the report, which turns this result into a failure. - Report.Rejected[file.Item.SourcePath] = ex.Error.Message; + // The executor has no failed commit: the refusal travels in the report, which turns this result into a failure. The + // server words its refusal in the client's language; one without words reads as the catalog's sentence. + Report.Rejected[file.Item.SourcePath] = ErrorText.ForServer(ex); results.Add(new SinkCommit(null, file.Item.FileName, Duplicate: false)); } finally diff --git a/src/Titano.App/Sections/ArchiveViewModel.cs b/src/Titano.App/Sections/ArchiveViewModel.cs index e5b9e3c4..30ab9f78 100644 --- a/src/Titano.App/Sections/ArchiveViewModel.cs +++ b/src/Titano.App/Sections/ArchiveViewModel.cs @@ -135,19 +135,7 @@ public sealed class ArchiveViewModel : SectionViewModel _archive = value; _duplicates = null; _orphans = null; - if (other) - { - // Until the picked archive is read (IsRead), nothing of the previous one stays actionable: no tree to take - // a set from, no availability to allow a scan, no figures for the rebuild dialog or the health fixes, no - // search results. The tooltips say the archive is being read. - _search?.Cancel(); - _tree = null; - _stats = null; - _health = []; - RebuildRows(); - OnPropertyChanged(string.Empty); - CommandManager.InvalidateRequerySuggested(); - } + if (other) ForgetRead(); _ = LoadAsync(); } } @@ -430,8 +418,11 @@ public sealed class ArchiveViewModel : SectionViewModel { AttachJobEvents(); Archives = await db.Archives.ListAsync(); - _archive = _archive is { } current ? Archives.FirstOrDefault(a => a.Id == current.Id) : null; + var shown = _archive; + _archive = shown is { } current ? Archives.FirstOrDefault(a => a.Id == current.Id) : null; _archive ??= CurrentArchive.Pick(Archives, Services.Settings.LastArchivePath); + // The archive shown is gone from the index: another one (or none) takes its place, without its figures. + if (shown is not null && _archive?.Id != shown.Id) ForgetRead(); if (_archive is not { } archive) return; var root = archive.RootPath; var availability = await Task.Run(() => ArchiveVolume.Probe(new ArchivePaths(root))); @@ -459,6 +450,37 @@ public sealed class ArchiveViewModel : SectionViewModel } } + /// + /// Another archive is shown: until it is read (IsRead), nothing of the previous one stays actionable or on screen. No + /// tree to take a set from, no availability to allow a scan, no figures for the rebuild dialog or the health fixes, + /// no search results, and none of its tiles, charts, last scan, recent runs or rail badge under the new archive's + /// name, which a slow or failed read would leave there. The tooltips say the archive is being read. + /// + private void ForgetRead() + { + // Picking A, then B, then A again before B's read ends must not find A "read" with none of its figures. + _readId = null; + _search?.Cancel(); + _duplicates = null; + _orphans = null; + _tree = null; + _sequenceIds = []; + _stats = null; + _withoutProxies = 0; + _health = []; + _tiles = []; + _months = []; + _storage = []; + _cameras = []; + _formats = []; + _recent = []; + _lastScanText = string.Empty; + Badge = 0; + RebuildRows(); + OnPropertyChanged(string.Empty); + CommandManager.InvalidateRequerySuggested(); + } + /// Opens the rebuild dialog (BRIEF §12.5) and counts, off the UI thread, the sidecars the rebuild will read. public async Task OpenRebuildDialogAsync() { diff --git a/src/Titano.App/Sections/ImportViewModel.cs b/src/Titano.App/Sections/ImportViewModel.cs index 96d76ba1..fcc45e58 100644 --- a/src/Titano.App/Sections/ImportViewModel.cs +++ b/src/Titano.App/Sections/ImportViewModel.cs @@ -1166,7 +1166,8 @@ public sealed class ImportViewModel : SectionViewModel var progress = new Progress(ShowProgress); ImportOutcome outcome; if (choices.Destination == ImportDestinationKind.Folder) - outcome = await Task.Run(() => LocalImport.RunAsync(plan, new FolderImportSink(choices.FolderPath!), choices.VerifyCopies, progress, cts.Token), cts.Token); + outcome = await Task.Run(() => LocalImport.RunAsync(plan, new FolderImportSink(choices.FolderPath!), source.Title, choices.VerifyCopies, progress, + cts.Token), cts.Token); else if (Services.Server.Flow is { Address: { } address, Token: { } token }) outcome = await RunServerAsync(plan, choices, source.Title, address, token, progress, cts.Token); else @@ -1304,7 +1305,7 @@ public sealed class ImportViewModel : SectionViewModel catch (DatabaseException ex) { Log.Warning("import", "The import could not be checked against the index", ex); - return ImportOutcome.From(plan, [], verify, stopped: ex.Message); + return ImportOutcome.From(plan, [], verify, stopped: ArchiveFailures.Cause(ex)); } } diff --git a/src/Titano.App/Sections/JobsViewModel.cs b/src/Titano.App/Sections/JobsViewModel.cs index fff2a7fb..1aa9de27 100644 --- a/src/Titano.App/Sections/JobsViewModel.cs +++ b/src/Titano.App/Sections/JobsViewModel.cs @@ -3,6 +3,7 @@ using System.IO; using System.Windows.Input; using Titano.App.Infrastructure; using Titano.App.Jobs; +using Titano.App.Library; using Titano.App.Settings; using Titano.App.Shell; using Titano.Core.Diagnostics; @@ -63,6 +64,10 @@ public sealed class JobsViewModel : SectionViewModel private readonly Dictionary _rows = []; private readonly HashSet _unseenFailures = []; private readonly JobEndings _endings = new(); + + /// Finished renders whose toast was taken (). + private readonly HashSet _renderToasts = []; + private readonly JobActions _actions; private CoalescingThrottle? _throttle; private IJobQueue? _queue; @@ -250,10 +255,20 @@ public sealed class JobsViewModel : SectionViewModel if (job.State != JobState.Failed) _unseenFailures.Remove(job.Id); else if (before != JobState.Failed && !IsSelected) _unseenFailures.Add(job.Id); var notice = JobNotices.For(before, job); - if (notice == JobNotice.Done && EditorAnnounces(job)) return; + // A flush can take the end before the editor that follows the render has seen it: the editor says it, with its output. + if (notice == JobNotice.Done && job.Kind == JobKind.Render + && (Shell.Sequence.Editor?.FollowsRender(job.Id) == true || !ClaimRenderToast(job.Id))) return; _endings.Add(notice, job); } + /// + /// Takes the toast of a finished render, which is said once (UI thread): true for the first caller only, which then + /// raises it. The editor of the render's sequence takes it when it sees the render end, and says it with the output + /// file even when the sequence cannot be read again or the editor closed meanwhile; a render the editor did not + /// follow is said here. + /// + internal bool ClaimRenderToast(Guid jobId) => _renderToasts.Add(jobId); + /// /// The toast of a job that ended, with one action (BRIEF §12.1, §0.2 rule 6). Several endings at once (a batch /// finished, or failed together) say how many and lead to this screen. Clicking the Windows notification of a @@ -311,11 +326,6 @@ public sealed class JobsViewModel : SectionViewModel }; } - /// A finished render of the sequence open in the editor: the editor says it, with its output file. - private bool EditorAnnounces(Job job) => - job is { Kind: JobKind.Render, State: JobState.Done } && Shell.Sequence.Editor is { IsRemote: false } editor - && job.TargetIds.Contains(editor.Session.Content.Sequence.Id); - /// A job changed state (any thread; tests feed it too): buffered until the next flush. internal void OnJobChanged(Job job) { @@ -403,13 +413,41 @@ public sealed class JobsViewModel : SectionViewModel SyncRows(); } - /// Opens what a job worked on inside Titano: its sequence in the editor, or the Archive screen. + /// + /// Opens what a job worked on inside Titano: its sequence in the editor; several sequences (a deep analysis of a + /// Library selection) in the Library, every one of them selected; else the Archive screen. A job over more sequences + /// than a Library page holds (a maintenance run over a whole archive) opens the Library as it is: looking each one + /// up, then reading page after page to select them all, would hold the screen. + /// internal async Task OpenTargetAsync(Job job) { var db = Shell.Services.Database; if (db is null || job.TargetIds.Count == 0) return; - if (await db.Sequences.GetAsync(job.TargetIds[0]) is { } sequence) Shell.OpenSequence(sequence.Id); - else Shell.Navigate(SectionKey.Archive); + var targets = job.TargetIds.Distinct().ToList(); + if (targets.Count > LibraryPager.DefaultPageSize) + { + Shell.Navigate(SectionKey.Library); + return; + } + // Each one is looked up: an id no longer in the index would have the Library read every page in search of it. + var sequences = new List(targets.Count); + foreach (var id in targets) + { + if (await db.Sequences.GetAsync(id) is { } sequence) sequences.Add(sequence.Id); + } + switch (sequences.Count) + { + case 0: + Shell.Navigate(SectionKey.Archive); + break; + case 1: + Shell.OpenSequence(sequences[0]); + break; + default: + Shell.Navigate(SectionKey.Library); + await Shell.Library.ShowSelectedAsync(sequences); + break; + } } /// Shows the folder of what a job worked on in Explorer. diff --git a/src/Titano.App/Sections/LibraryViewModel.cs b/src/Titano.App/Sections/LibraryViewModel.cs index 7fc70225..1a65e73e 100644 --- a/src/Titano.App/Sections/LibraryViewModel.cs +++ b/src/Titano.App/Sections/LibraryViewModel.cs @@ -71,6 +71,10 @@ public sealed class LibraryViewModel : SectionViewModel private bool _isLoading; private bool _hasLoaded; private bool _suppressReload; + + /// Many cards change selection at once (): the selection is counted once after them. + private bool _bulkSelect; + private int _layoutIndex; private SequenceItem? _selected; private int _selectionCount; @@ -581,6 +585,52 @@ public sealed class LibraryViewModel : SectionViewModel RaiseMass(); } + /// + /// Shows the sequences of selected, under the mass actions bar (Open on a job over several + /// sequences). Search and filters go when one of them would be hidden or is still being applied, pages are read until + /// each is listed, and the first comes into sight. Ids not in the index are left out. + /// + public async Task ShowSelectedAsync(IReadOnlyCollection ids) + { + if (_pager is null) return; + var wanted = ids.ToHashSet(); + if (_searchDelay.IsEnabled || _pager.IsLoading || !Lists(wanted)) + { + ResetFilters(); + await ReloadAsync(); + while (!Lists(wanted) && _pager is { HasMore: true }) + { + var listed = Items.Count; + await LoadMoreAsync(); + if (Items.Count == listed) break; + } + } + SelectOnly(item => wanted.Contains(item.Sequence.Id)); + if (Items.FirstOrDefault(i => i.IsSelected) is { } first) ScrollRequested?.Invoke(first); + } + + /// + /// Selects exactly the cards picks. The selection, its summary and the mass actions' + /// tooltips are worked out once at the end: once per card, each over every card, a whole archive would hold the screen. + /// + private void SelectOnly(Func chosen) + { + _bulkSelect = true; + try + { + foreach (var item in Items) + { + var selected = chosen(item); + if (item.IsSelected != selected) item.IsSelected = selected; + } + } + finally + { + _bulkSelect = false; + } + OnSelectionChanged(); + } + /// Opens Tags on the selection (capture, tests). public void OpenRetag() => OpenRetag(Targets(MassAction.Tag)); @@ -850,6 +900,13 @@ public sealed class LibraryViewModel : SectionViewModel } private void ClearFilters() + { + ResetFilters(); + Reload(); + } + + /// Search and filters back to "any", without reading the list again. + private void ResetFilters() { _suppressReload = true; _searchDelay.Stop(); @@ -863,9 +920,11 @@ public sealed class LibraryViewModel : SectionViewModel _timelineMonth = null; _scrollToMonth = false; _suppressReload = false; - Reload(); } + /// Every sequence of is in the list on screen. + private bool Lists(HashSet ids) => ids.IsSubsetOf(Items.Select(i => i.Sequence.Id)); + /// Shows a saved view: its search, filters and sort, at once. private void Apply(SavedView view) { @@ -920,15 +979,11 @@ public sealed class LibraryViewModel : SectionViewModel await LoadViewsAsync(); } - private void ClearSelection() - { - foreach (var item in Items) item.IsSelected = false; - OnSelectionChanged(); - } + private void ClearSelection() => SelectOnly(_ => false); private void OnItemChanged(object? sender, PropertyChangedEventArgs e) { - if (e.PropertyName == nameof(SequenceItem.IsSelected)) OnSelectionChanged(); + if (e.PropertyName == nameof(SequenceItem.IsSelected) && !_bulkSelect) OnSelectionChanged(); } private void RaiseState() diff --git a/src/Titano.App/Sections/SequenceViewModel.cs b/src/Titano.App/Sections/SequenceViewModel.cs index 8e7f1393..9f52f821 100644 --- a/src/Titano.App/Sections/SequenceViewModel.cs +++ b/src/Titano.App/Sections/SequenceViewModel.cs @@ -142,6 +142,13 @@ public sealed class SequenceViewModel : SectionViewModel await editor.DisposeAsync(); } + /// Shows , which the caller opened over a source of its own (tests), as the open sequence. + internal void Attach(EditorViewModel editor) + { + _openId = editor.Session.Content.Sequence.Id; + Editor = editor; + } + public override void Dispose() { Shell.PropertyChanged -= OnShellChanged; diff --git a/src/Titano.App/Shell/ErrorText.cs b/src/Titano.App/Shell/ErrorText.cs index 52fbaaee..5421b8a7 100644 --- a/src/Titano.App/Shell/ErrorText.cs +++ b/src/Titano.App/Shell/ErrorText.cs @@ -1,4 +1,5 @@ using System.IO; +using System.Net; using System.Net.Http; using System.Reflection; using Titano.Core.Archiving; @@ -7,6 +8,7 @@ using Titano.Core.Localization; using Titano.Core.Render; using Titano.Data.Archiving; using Titano.Data.Sync; +using Titano.Protocol; using Titano.Protocol.Client; namespace Titano.App.Shell; @@ -21,8 +23,9 @@ public static class ErrorText public static string For(Exception ex) => Describe(Unwrap(ex)) ?? Loc.L("Errors.Unexpected"); /// - /// A request to the signed-in server failed: the server's own sentence when it answered, else that it does not answer - /// (refused, timed out, dropped) or that its certificate is no longer trusted. + /// A request to the signed-in server failed: the server's own sentence when it answered, else what the reply's status + /// means (a proxy in front of it), that it does not answer (refused, timed out, dropped) or that its certificate is no + /// longer trusted. /// public static string ForServer(Exception ex) { @@ -40,11 +43,28 @@ public static class ErrorText LeaseUnavailableException or ArchiveOfflineException or NewerFormatException or ImportSourceUnavailableException or CopyVerificationException or StaleRenamePlanException or SyncConflictChangedException => ex.Message, // The server words its errors in the client's language (Accept-Language). - TitanoApiException api when !string.IsNullOrWhiteSpace(api.Error.Message) => api.Error.Message, + TitanoApiException api when FromServer(api.Error) => api.Error.Message, + // Any other reply (a reverse proxy's 502 page while the server restarts, its 413 for a large body, a bare 500) holds + // only the HTTP reason phrase, in English: say what its status means. + TitanoApiException api => api.Status switch + { + HttpStatusCode.RequestEntityTooLarge => Loc.L("Server.Error.TooLarge"), + HttpStatusCode.TooManyRequests => Loc.L("Server.Error.RateLimited"), + _ when api.IsTransient => Loc.L("Server.Error.Unreachable"), + >= HttpStatusCode.InternalServerError => Loc.L("Server.Error.Internal"), + _ => null, + }, RenderException render => Loc.Get(render.ReasonKey, Loc.Culture) is null ? null : Loc.L(render.ReasonKey, [.. render.Args]), _ => null, }; + /// + /// An error the server wrote as its JSON, with its own sentence. TitanoClient codes any other reply + /// http_<status> with the reason phrase as its message, and JSON of another shape has no code. + /// + private static bool FromServer(ApiError error) => + error.Code is { } code && !code.StartsWith("http_", StringComparison.Ordinal) && !string.IsNullOrWhiteSpace(error.Message); + /// Awaited tasks and reflection wrap the real failure in one layer or more. private static Exception Unwrap(Exception ex) { diff --git a/src/Titano.Core/Import/CardScanner.cs b/src/Titano.Core/Import/CardScanner.cs index 603f5958..8c2270cb 100644 --- a/src/Titano.Core/Import/CardScanner.cs +++ b/src/Titano.Core/Import/CardScanner.cs @@ -62,7 +62,10 @@ public static class CardScanner return files; } - /// Reads light metadata of every file; unreadable files become . + /// + /// Reads light metadata of every file; unreadable files become , each with one localized + /// sentence (the system's text goes to the log only). + /// public static IReadOnlyList ReadMetadata(string root, IReadOnlyList files, List problems, IProgress? progress = null, CancellationToken cancellationToken = default) { @@ -78,7 +81,7 @@ public static class CardScanner catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { Log.Warning("import", $"Cannot read {file.RelativePath}", ex); - problems.Add(new ImportProblem(file.RelativePath, ex.Message)); + problems.Add(new ImportProblem(file.RelativePath, ImportExecutor.FailureText(ex))); } progress?.Report(i + 1); } diff --git a/src/Titano.Core/Import/ImportExecutor.cs b/src/Titano.Core/Import/ImportExecutor.cs index 3a8c0728..5a7f166e 100644 --- a/src/Titano.Core/Import/ImportExecutor.cs +++ b/src/Titano.Core/Import/ImportExecutor.cs @@ -10,6 +10,9 @@ public sealed class ImportSourceUnavailableException(string root, Exception? inn public string Root { get; } = root; } +/// A card file is gone or has another size than when the plan was made: that photo fails, the import goes on. +internal sealed class ImportSourceChangedException(string path) : IOException(Loc.L("Archive.Error.SourceChanged", path)); + /// A verified copy waiting in the sink's staging folder. public sealed record StagedFile(PlannedItem Item, string StagedPath, string Sha256); @@ -59,6 +62,8 @@ public sealed record ImportBatch(IReadOnlyList Results, int Ne public sealed class ImportExecutor(ImportPlan plan, IImportSink sink) { private const int BatchSize = 32; + private const int DiskFull = unchecked((int)0x80070070); + private const int HandleDiskFull = unchecked((int)0x80070027); /// Number of plan items already done (the last recorded). /// Called after each batch; record the results, then checkpoint . @@ -119,7 +124,7 @@ public sealed class ImportExecutor(ImportPlan plan, IImportSink sink) try { if (new FileInfo(source) is not { Exists: true } info || info.Length != item.Size) - throw new IOException(Loc.L("Archive.Error.SourceChanged", item.SourcePath)); + throw new ImportSourceChangedException(item.SourcePath); var sha = await VerifiedCopy.CopyAsync(source, target, verify, read => bytesDone += read, cancellationToken).ConfigureAwait(false); staged.Add(new StagedFile(item, target, sha)); stagedSession = session; @@ -133,13 +138,27 @@ public sealed class ImportExecutor(ImportPlan plan, IImportSink sink) } Log.Warning("import", $"Copy of {item.SourcePath} failed", ex); failed++; - results.Add(new ImportItemResult(session, item, ImportItemStatus.Failed, null, null, ex.Message)); + results.Add(new ImportItemResult(session, item, ImportItemStatus.Failed, null, null, FailureText(ex))); } } await FlushAsync().ConfigureAwait(false); return Snapshot(null); } + /// + /// Why one photo was not copied, as one localized sentence (BRIEF §0.2 rule 6): the Import screen lists it beside the + /// photo and the import job writes it to its log. The executor's own checks say what they found; the operating + /// system's text, technical English, goes to the application log only. + /// + internal static string FailureText(Exception ex) => ex switch + { + // Already one localized sentence each. + ImportSourceChangedException or CopyVerificationException => ex.Message, + IOException { HResult: DiskFull or HandleDiskFull } => Loc.L("Import.Failed.Full"), + UnauthorizedAccessException => Loc.L("Import.Failed.PhotoAccess"), + _ => Loc.L("Import.Failed.Photo"), + }; + private static void DeleteLeftover(string staged) { // Staged files are this import's own copies of card files; the originals stay on the card. diff --git a/tests/Titano.App.Tests/Archive/ArchiveScreenSmokeTests.cs b/tests/Titano.App.Tests/Archive/ArchiveScreenSmokeTests.cs index 54984448..ead7f59f 100644 --- a/tests/Titano.App.Tests/Archive/ArchiveScreenSmokeTests.cs +++ b/tests/Titano.App.Tests/Archive/ArchiveScreenSmokeTests.cs @@ -182,17 +182,38 @@ public sealed class ArchiveScreenSmokeTests var archive = app.Shell.Archive; await ArchiveScenes.ShowAsync(app.Shell, "overview"); Assert.Contains(archive.TreeRows, r => r.Node.Kind == TreeNodeKind.Sequence); + Assert.NotEmpty(archive.Tiles); + Assert.NotEmpty(archive.CameraBars); + var first = archive.SelectedArchive!; var second = await app.Services.Archives!.CreateAsync(Path.Combine(app.Services.Environment.DataDirectory, "second-archive"), "Second"); var reading = archive.LoadAsync(); archive.SelectedArchive = second; Assert.Empty(archive.TreeRows); + // None of the first archive's figures stays on screen under the picked one's name while it is read (or if its read fails). + Assert.Empty(archive.Tiles); + Assert.Empty(archive.MonthRows); + Assert.Empty(archive.StorageBars); + Assert.Empty(archive.CameraBars); + Assert.Empty(archive.FormatBars); + Assert.Empty(archive.Recent); + Assert.False(archive.HasRecent); + Assert.Equal(string.Empty, archive.LastScanText); + Assert.Equal(0, archive.Badge, "the rail badge counts the picked archive's health, which is not read yet"); Assert.False(archive.AnalyseSetCommand.CanExecute(null), "nothing of the first archive can be acted on while the picked one is read"); Assert.False(archive.ScanCommand.CanExecute(null), "the picked archive is not known to be online yet"); Assert.Equal(Loc.L("Archive.Blocked.Reading"), archive.ScanToolTip, "not yet read is not offline"); Assert.False(archive.RebuildCommand.CanExecute(null), "the rebuild dialog waits for the picked archive's own state and figures"); Assert.Null(await archive.OpenRebuildDialogAsync()); Assert.Empty(archive.Health); + // Back to the first archive before the picked one is read: it was read before, but none of its figures is left. + archive.SelectedArchive = first; + Assert.Empty(archive.TreeRows); + Assert.False(archive.RebuildCommand.CanExecute(null), "the first archive is not read again yet"); + Assert.False(archive.ScanCommand.CanExecute(null)); + Assert.Equal(Loc.L("Archive.Blocked.Reading"), archive.ScanToolTip); + Assert.Null(await archive.OpenRebuildDialogAsync()); + archive.SelectedArchive = second; await reading; Assert.Equal(second.Id, archive.SelectedArchive!.Id); diff --git a/tests/Titano.App.Tests/Editor/EditorFixture.cs b/tests/Titano.App.Tests/Editor/EditorFixture.cs index 8fb39b85..2099ebd1 100644 --- a/tests/Titano.App.Tests/Editor/EditorFixture.cs +++ b/tests/Titano.App.Tests/Editor/EditorFixture.cs @@ -111,7 +111,15 @@ internal sealed class FakeSequenceSource(SyntheticSequence sequence, SequenceCon /// Awaited by every decode (tests of cancellation). public Task DecodeGate { get; set; } = Task.CompletedTask; - public Task LoadAsync(CancellationToken cancellationToken) => Task.FromResult(Content with { Project = Stored }); + /// Thrown by the next load (the sequence read again after a job). + public Exception? FailNextLoad { get; set; } + + public Task LoadAsync(CancellationToken cancellationToken) + { + if (FailNextLoad is not { } failure) return Task.FromResult(Content with { Project = Stored }); + FailNextLoad = null; + return Task.FromException(failure); + } public async ValueTask DecodeAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken) { diff --git a/tests/Titano.App.Tests/Import/ImportFailuresTests.cs b/tests/Titano.App.Tests/Import/ImportFailuresTests.cs index 79d47c92..8c1d5094 100644 --- a/tests/Titano.App.Tests/Import/ImportFailuresTests.cs +++ b/tests/Titano.App.Tests/Import/ImportFailuresTests.cs @@ -31,6 +31,24 @@ public sealed class ImportFailuresTests Assert.Equal("The import stopped before the end.", ImportFailures.Import(new InvalidDataException("Bad sidecar. Second sentence."), Card)); } + [Test] + public void TheCopiesAStoppedImportNeverReachedSayWhyInOneSentence() + { + const string Card = "EOS R5 · card A"; + Assert.Equal("EOS R5 · card A is no longer available.", ImportFailures.Stop(new ImportSourceUnavailableException(@"E:\"), Card)); + Assert.Equal("The destination is full.", ImportFailures.Stop(new IOException("There is not enough space on the disk.", unchecked((int)0x80070070)), Card)); + Assert.Equal("Titano may not write to the destination.", ImportFailures.Stop(new UnauthorizedAccessException(@"Access to D:\Shoots is denied."), Card)); + Assert.Equal("The import stopped before the end.", ImportFailures.Stop(new IOException("The specified network name is no longer available."), Card)); + // The server's own sentence, else why it could not be asked. + Assert.Equal("Sign in again", + ImportFailures.Stop(new TitanoApiException(HttpStatusCode.Unauthorized, new ApiError("unauthorized", "Sign in again", null)), Card)); + Assert.Equal(Loc.L("Server.Error.Unreachable"), ImportFailures.Stop(new HttpRequestException("An error occurred while sending the request."), Card)); + // A reverse proxy answered while the server restarted: its reason phrase is English, never the server's sentence. + Assert.Equal(Loc.L("Server.Error.Unreachable"), ImportFailures.Stop(new TitanoApiException(HttpStatusCode.BadGateway, new ApiError("http_502", "Bad Gateway")), Card)); + Assert.Equal(Loc.L("Server.Error.Unreachable"), ImportFailures.Stop(new TaskCanceledException("The operation was canceled."), Card)); + Assert.Equal(Loc.L("Server.Error.Untrusted"), ImportFailures.Stop(new UntrustedCertificateException("AB:CD"), Card)); + } + [Test] public void APlanningFailureNamesTheSource() { diff --git a/tests/Titano.App.Tests/Import/ImportFlowTests.cs b/tests/Titano.App.Tests/Import/ImportFlowTests.cs index a8289519..f4ff7778 100644 --- a/tests/Titano.App.Tests/Import/ImportFlowTests.cs +++ b/tests/Titano.App.Tests/Import/ImportFlowTests.cs @@ -1,5 +1,6 @@ using System.Globalization; using System.IO; +using System.Net.Http; using Titano.App.Import; using Titano.Core.Import; using Titano.Core.Localization; @@ -111,7 +112,7 @@ public sealed class ImportFlowTests(TestContext context) Assert.Equal(16, plan.CopyCount); var reports = new List(); - var outcome = await LocalImport.RunAsync(plan, new FolderImportSink(target), verify: true, new Progress(reports), context.Cancellation); + var outcome = await LocalImport.RunAsync(plan, new FolderImportSink(target), "EOS R5 · card A", verify: true, new Progress(reports), context.Cancellation); Assert.Equal(16, outcome.Copied); Assert.True(outcome.IsComplete); Assert.True(outcome.Verified); @@ -120,7 +121,7 @@ public sealed class ImportFlowTests(TestContext context) Assert.FileExists(Path.Combine(target, folder, name)); var again = await LocalImport.RunAsync(await destination.PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation), - new FolderImportSink(target), verify: true, null, context.Cancellation); + new FolderImportSink(target), "EOS R5 · card A", verify: true, null, context.Cancellation); Assert.Equal(0, again.Copied); Assert.Equal(16, again.Duplicates); Assert.False(new CardActions(ImportDestinationKind.Folder, false, true, true, outcome, null, null).CanCheck); @@ -164,6 +165,21 @@ public sealed class ImportFlowTests(TestContext context) outcome.Failures); } + [Test] + public async Task ARunTheServerStopsListsEveryPhotoLeftWithASentenceNotTheExceptionText() + { + Loc.SetCulture(CultureInfo.GetCultureInfo("en")); + var card = Card(context.CreateTempDirectory("card"), 8, Start); + var staging = context.CreateTempDirectory("staging"); + var plan = await new UnindexedDestination(ImportDestinationKind.Server, staging).PlanAsync(card, new ImportChoices().ToOptions(), null, null, + context.Cancellation); + + var outcome = await LocalImport.RunAsync(plan, new UnreachableSink(staging), "EOS R5 · card A", verify: true, null, context.Cancellation); + Assert.Equal(0, outcome.Imported); + Assert.Equal(8, outcome.Failures.Count); + Assert.True(outcome.Failures.All(f => f.Message == Loc.L("Server.Error.Unreachable")), "the stop reason is the catalog's, never the exception's text"); + } + private async Task WaitDoneAsync(TitanoDatabase db, Guid jobId) { var until = DateTime.UtcNow.AddSeconds(60); @@ -177,6 +193,15 @@ public sealed class ImportFlowTests(TestContext context) Assert.Fail("The import job did not finish"); } + /// A server destination whose connection is gone: every commit fails as the HTTP stack reports it. + private sealed class UnreachableSink(string staging) : IImportSink + { + public string StagingDirectory { get; } = staging; + + public Task> CommitAsync(PlannedSession session, IReadOnlyList files, CancellationToken cancellationToken) => + throw new HttpRequestException("An error occurred while sending the request."); + } + /// Collects reports synchronously (System.Progress posts to the thread pool). private sealed class Progress(List into) : IProgress { diff --git a/tests/Titano.App.Tests/Import/ServerImportSinkTests.cs b/tests/Titano.App.Tests/Import/ServerImportSinkTests.cs index b957ad21..ff65c7ad 100644 --- a/tests/Titano.App.Tests/Import/ServerImportSinkTests.cs +++ b/tests/Titano.App.Tests/Import/ServerImportSinkTests.cs @@ -27,7 +27,7 @@ public sealed class ServerImportSinkTests(TestContext context) var plan = await new UnindexedDestination(ImportDestinationKind.Server, staging).PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation); plan = plan with { Sessions = [plan.Sessions[0] with { Title = "Harbour sunset" }, .. plan.Sessions.Skip(1)] }; - var outcome = await LocalImport.RunAsync(plan, new ServerImportSink(client, staging), verify: true, null, context.Cancellation); + var outcome = await LocalImport.RunAsync(plan, new ServerImportSink(client, staging), "EOS R5 · card A", verify: true, null, context.Cancellation); Assert.Equal(16, outcome.Copied); Assert.True(outcome.IsComplete); @@ -55,10 +55,10 @@ public sealed class ServerImportSinkTests(TestContext context) using var client = new TitanoClient(new Uri("https://nas.local:8443/"), new CertificatePinning([]), "tests", server) { Token = "t" }; var destination = new UnindexedDestination(ImportDestinationKind.Server, staging); var plan = await destination.PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation); - await LocalImport.RunAsync(plan, new ServerImportSink(client, staging), verify: true, null, context.Cancellation); + await LocalImport.RunAsync(plan, new ServerImportSink(client, staging), "EOS R5 · card A", verify: true, null, context.Cancellation); var chunks = server.ChunkCount; - var again = await LocalImport.RunAsync(plan, new ServerImportSink(client, staging), verify: true, null, context.Cancellation); + var again = await LocalImport.RunAsync(plan, new ServerImportSink(client, staging), "EOS R5 · card A", verify: true, null, context.Cancellation); Assert.Equal(0, again.Copied); Assert.Equal(8, again.Duplicates); Assert.Equal(chunks, server.ChunkCount); @@ -74,13 +74,29 @@ public sealed class ServerImportSinkTests(TestContext context) var plan = await new UnindexedDestination(ImportDestinationKind.Server, staging).PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation); var sink = new ServerImportSink(client, staging); - var outcome = await LocalImport.RunAsync(plan, sink, true, null, context.Cancellation, sink.Report); + var outcome = await LocalImport.RunAsync(plan, sink, "EOS R5 · card A", true, null, context.Cancellation, sink.Report); Assert.Equal(7, outcome.Copied); Assert.Equal(7, server.Committed.Count); Assert.Equal(new ImportFailure("DCIM/100CANON/IMG_0003.JPG", "Hash mismatch"), outcome.Failures.Single()); Assert.Empty(Directory.EnumerateFileSystemEntries(staging)); } + [Test] + public async Task AFileAProxyRefusesIsListedWithTheCatalogsSentence() + { + var card = Card(context.CreateTempDirectory("card"), 8, Start); + var staging = context.CreateTempDirectory("staging"); + var server = new FakeUploadServer(chunkSize: 4096) { ProxyRefusesFile = "IMG_0005.JPG" }; + using var client = new TitanoClient(new Uri("https://nas.local:8443/"), new CertificatePinning([]), "tests", server) { Token = "t" }; + var plan = await new UnindexedDestination(ImportDestinationKind.Server, staging).PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation); + var sink = new ServerImportSink(client, staging); + + var outcome = await LocalImport.RunAsync(plan, sink, "EOS R5 · card A", true, null, context.Cancellation, sink.Report); + Assert.Equal(7, outcome.Copied); + // The proxy's page says "Request Entity Too Large" in English: the photo reads the catalog's sentence instead. + Assert.Equal(new ImportFailure("DCIM/100CANON/IMG_0005.JPG", Titano.Core.Localization.Loc.L("Server.Error.TooLarge")), outcome.Failures.Single()); + } + [Test] public async Task ALostSignInStopsTheImportAndKeepsWhatWasUploaded() { @@ -91,7 +107,7 @@ public sealed class ServerImportSinkTests(TestContext context) var plan = await new UnindexedDestination(ImportDestinationKind.Server, staging).PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation); var sink = new ServerImportSink(client, staging); - var outcome = await LocalImport.RunAsync(plan, sink, true, null, context.Cancellation, sink.Report); + var outcome = await LocalImport.RunAsync(plan, sink, "EOS R5 · card A", true, null, context.Cancellation, sink.Report); Assert.Equal(3, outcome.Copied, "the uploads the server committed before the sign-in was lost"); Assert.Equal(5, outcome.Failures.Count); Assert.Equal("Sign in again", outcome.Failures[0].Message, "the server's sentence"); @@ -231,6 +247,9 @@ public sealed class ServerImportSinkTests(TestContext context) /// Flip a byte of every chunk of this file (a damaged transfer). public string? CorruptFile { get; init; } + /// A reverse proxy in front of the server refuses the chunks of this file: 413 with its own HTML page. + public string? ProxyRefusesFile { get; init; } + /// Answer 401 to new uploads once this many were committed (the sign-in expired). public int? SignedOutAfter { get; init; } @@ -276,6 +295,13 @@ public sealed class ServerImportSinkTests(TestContext context) if (request.Method == HttpMethod.Put && path is ["api", "v1", "uploads", var id, "chunks", var n]) { var upload = _open[Guid.Parse(id)]; + if (upload.FileName == ProxyRefusesFile) + { + return new HttpResponseMessage(HttpStatusCode.RequestEntityTooLarge) + { + Content = new StringContent("

413 Request Entity Too Large

", System.Text.Encoding.UTF8, "text/html"), + }; + } var bytes = await request.Content!.ReadAsByteArrayAsync(cancellationToken); if (upload.FileName == CorruptFile) bytes[0] ^= 0xFF; upload.Parts[int.Parse(n, System.Globalization.CultureInfo.InvariantCulture)] = bytes; diff --git a/tests/Titano.App.Tests/Infrastructure/ErrorTextTests.cs b/tests/Titano.App.Tests/Infrastructure/ErrorTextTests.cs index a5759983..7832bf0d 100644 --- a/tests/Titano.App.Tests/Infrastructure/ErrorTextTests.cs +++ b/tests/Titano.App.Tests/Infrastructure/ErrorTextTests.cs @@ -30,7 +30,27 @@ public sealed class ErrorTextTests // Failures that already carry a catalog sentence keep it. Assert.Equal(@"The archive D:\Shoots is offline.", ErrorText.ForServer(new ArchiveOfflineException(@"D:\Shoots", ArchiveAvailability.Offline))); Assert.Equal("Something went wrong.", ErrorText.ForServer(new InvalidOperationException("Sequence contains no elements"))); - Assert.Equal("Something went wrong.", ErrorText.ForServer(new TitanoApiException(HttpStatusCode.BadGateway, new ApiError("bad_gateway", " ", null)))); + Assert.Equal("Something went wrong.", ErrorText.ForServer(new TitanoApiException(HttpStatusCode.Conflict, new ApiError("conflict", " ", null)))); + Assert.Equal(Unreachable, ErrorText.ForServer(new TitanoApiException(HttpStatusCode.BadGateway, new ApiError("bad_gateway", " ", null)))); + } + + [Test] + public void AReplyThatIsNotTheServersOwnSaysWhatItsStatusMeans() + { + // A reverse proxy answers for the server (the NAS setup): its page is no Titano JSON, so TitanoClient keeps only + // the reason phrase, in English, which never reaches the screen. + static TitanoApiException Proxy(HttpStatusCode status, string reason) => new(status, new ApiError("http_" + (int)status, reason)); + const string Unreachable = "The server does not answer; check the address and the network."; + Assert.Equal(Unreachable, ErrorText.ForServer(Proxy(HttpStatusCode.BadGateway, "Bad Gateway"))); + Assert.Equal(Unreachable, ErrorText.ForServer(Proxy(HttpStatusCode.ServiceUnavailable, "Service Unavailable"))); + Assert.Equal(Unreachable, ErrorText.ForServer(Proxy(HttpStatusCode.GatewayTimeout, "Gateway Timeout"))); + Assert.Equal(Unreachable, ErrorText.For(Proxy(HttpStatusCode.BadGateway, "Bad Gateway"))); + Assert.Equal("The request is larger than the server accepts.", ErrorText.ForServer(Proxy(HttpStatusCode.RequestEntityTooLarge, "Request Entity Too Large"))); + Assert.Equal("Too many attempts; wait a minute and try again.", ErrorText.ForServer(Proxy(HttpStatusCode.TooManyRequests, "Too Many Requests"))); + Assert.Equal("Unexpected server error; try again.", ErrorText.ForServer(Proxy(HttpStatusCode.InternalServerError, "Internal Server Error"))); + Assert.Equal("Something went wrong.", ErrorText.ForServer(Proxy(HttpStatusCode.NotFound, "Not Found"))); + // JSON of another shape has no code: its message is not the server's either. + Assert.Equal(Unreachable, ErrorText.ForServer(new TitanoApiException(HttpStatusCode.BadGateway, new ApiError(null!, "upstream connect error")))); } [Test] diff --git a/tests/Titano.App.Tests/Windows/ShellNotificationTests.cs b/tests/Titano.App.Tests/Windows/ShellNotificationTests.cs index 11b19f09..e5bcc36e 100644 --- a/tests/Titano.App.Tests/Windows/ShellNotificationTests.cs +++ b/tests/Titano.App.Tests/Windows/ShellNotificationTests.cs @@ -1,11 +1,16 @@ +using System.IO; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Shell; +using Titano.App.Editor; using Titano.App.Infrastructure; +using Titano.App.Library; using Titano.App.Sections; using Titano.App.Settings; using Titano.App.Shell; +using Titano.App.Tests.Editor; +using Titano.Core.Export; using Titano.Core.Localization; using Titano.Core.Model; using Titano.Data.Repositories; @@ -133,26 +138,40 @@ public sealed class ShellNotificationTests Assert.Equal(badge, jobs.Badge); Assert.NotEqual(TaskbarItemProgressState.Error, shell.TaskbarState); - // The editor announces the renders of its own sequence, with their output: the shell says nothing then. - var id = await app.Sample.FillEditorAsync(); - shell.OpenSequence(id); - await shell.Sequence.OpenAsync(id); - Assert.NotNull(shell.Sequence.Editor); + // The editor says the renders it followed to their end, with their output: the shell says nothing then. It says them + // also when the sequence cannot be read again (that error is said too), without Show in folder then. + var content = EditorFixture.Content(EditorFixture.Sunset); + var source = new FakeSequenceSource(EditorFixture.Sunset, content); + var editor = new EditorViewModel(shell, new EditorSession(source, content, []), [], EncoderHost.Client); + await using (editor) + { + foreach (var readable in new[] { true, false }) + { + raised.Clear(); + var render = Job(JobKind.Render, JobState.Running, content.Sequence.Id); + source.Report(render); + jobs.OnJobChanged(render); + await UntilAsync(() => editor.IsBusy); + jobs.Flush(); + if (!readable) source.FailNextLoad = new IOException("The specified network name is no longer available."); + source.Report(render with { State = JobState.Done }); + jobs.OnJobChanged(render with { State = JobState.Done }); + await UntilAsync(() => raised.Any(t => t.Title == Loc.L("Editor.Render.Done"))); + jobs.Flush(); + var finished = Assert.Contains(raised, t => t.Title == Loc.L("Editor.Render.Done")); + Assert.False(raised.Any(t => t.Title == Loc.L("Shell.Job.Done")), "the editor's own render toast is not doubled"); + Assert.Equal(readable ? 0 : 1, raised.Count(t => t.IsError), "a failed read is said beside the render's end"); + if (!readable) Assert.Null(finished.ActionCommand, "without the sequence read again, there is no output to show"); + } + } + // A render the editor did not follow (of another sequence) is the shell's to announce. raised.Clear(); - var render = Job(JobKind.Render, JobState.Running, id); - jobs.OnJobChanged(render); - jobs.Flush(); - jobs.OnJobChanged(render with { State = JobState.Done }); - jobs.Flush(); - Assert.False(raised.Any(t => t.Title == Loc.L("Shell.Job.Done")), "the editor's own render toast is not doubled"); - // A render of another sequence is the shell's to announce. var other = Job(JobKind.Render, JobState.Running, Guid.CreateVersion7()); jobs.OnJobChanged(other); jobs.Flush(); jobs.OnJobChanged(other with { State = JobState.Done }); jobs.Flush(); Assert.Equal(1, raised.Count(t => t.Title == Loc.L("Shell.Job.Done"))); - await shell.Sequence.CloseAsync(); // Server › Upload all: the batch speaks once, when its last upload ends. raised.Clear(); @@ -380,6 +399,137 @@ public sealed class ShellNotificationTests Assert.Equal(shell.Archive.Health.Count(h => !h.IsOk), shell.Archive.Badge); }); + /// + /// The Jobs screen's flush can take a render's end before the editor that followed the render has seen it: it leaves + /// the toast to the editor, which says it once with its output, and once without it when it closed in between. + /// + [Test] + public Task TheEditorSaysTheRenderItFollowedAlsoWhenTheJobsScreenSeesItsEndFirst() => ScreenHost.RunAsync(async () => + { + await using var app = await ScreenSmokeTests.SampleApp.StartAsync(); + var shell = app.Shell; + shell.CompleteWelcome(); + await JobsLoadedAsync(shell); + var jobs = shell.Jobs; + var raised = new List(); + shell.PendingToasts.CollectionChanged += (_, e) => raised.AddRange(e.NewItems?.Cast() ?? []); + var content = EditorFixture.Content(EditorFixture.Sunset); + var source = new FakeSequenceSource(EditorFixture.Sunset, content); + var editor = new EditorViewModel(shell, new EditorSession(source, content, []), [], EncoderHost.Client); + shell.Sequence.Attach(editor); + + foreach (var closes in new[] { false, true }) + { + raised.Clear(); + var render = Job(JobKind.Render, JobState.Running, content.Sequence.Id); + source.Report(render); + jobs.OnJobChanged(render); + await UntilAsync(() => editor.FollowsRender(render.Id)); + jobs.Flush(); + + // The end reaches the Jobs screen first; the editor's own callback runs after its flush. + jobs.OnJobChanged(render with { State = JobState.Done }); + jobs.Flush(); + Assert.False(raised.Any(t => t.Title == Loc.L("Shell.Job.Done")), "the Jobs screen leaves the end of a followed render to the editor"); + source.Report(render with { State = JobState.Done }); + if (closes) + { + await shell.Sequence.CloseAsync(); + Assert.Null(shell.Sequence.Editor); + } + await UntilAsync(() => raised.Any(t => t.Title == Loc.L("Editor.Render.Done"))); + jobs.Flush(); + var finished = Assert.Contains(raised, t => t.Title == Loc.L("Editor.Render.Done")); + Assert.Equal(1, raised.Count(t => t.Title == Loc.L("Editor.Render.Done")), "said once"); + Assert.False(raised.Any(t => t.Title == Loc.L("Shell.Job.Done")), "and never by the Jobs screen as well"); + if (closes) Assert.Null(finished.ActionCommand, "a closed editor does not read the sequence again for the output"); + } + }); + + /// + /// Open on a job that worked on several sequences (a deep analysis of a Library selection) shows every one of them + /// selected in the Library: also those a search hides, whether it is still pending or applied, and those beyond the + /// pages read so far. A job over more sequences than a page leaves the Library as it is; a job on an archive opens + /// the Archive screen. + /// + [Test] + public Task OpenOnAJobOverSeveralSequencesSelectsThemAllInTheLibrary() => ScreenHost.RunAsync(async () => + { + await using var app = await ScreenSmokeTests.SampleApp.StartAsync(); + var shell = app.Shell; + shell.CompleteWelcome(); + await app.Sample.FillAsync(); + var db = Assert.NotNull(shell.Services.Database); + var library = shell.Library; + await library.RefreshAsync(); + var ids = (await db.Sequences.ListAsync(new SequenceQuery { Sort = SequenceSort.Oldest, Limit = 3 })).Items.Select(s => s.Id).ToList(); + Assert.Count(3, ids); + bool Listed(Guid id) => library.Items.Any(i => i.Sequence.Id == id); + Job Analysis(IReadOnlyList targets) => + Job(JobKind.DeepAnalyse, JobState.Done, targets[0]) with { TargetIds = targets, TargetLabel = Loc.Plural("Library.Selection.Count", targets.Count) }; + + // A search still waiting to apply. + library.SearchText = "no such sequence"; + await shell.Jobs.OpenTargetAsync(Analysis(ids)); + Assert.Equal(SectionKey.Library, shell.Current.Key); + Assert.Equal(string.Empty, library.SearchText, "the search that hid them is cleared"); + Assert.Equal(ids.Count, library.SelectionCount, "every sequence the job worked on, not only the first"); + Assert.SequenceEqual(ids.Order(), library.SelectedItems().Select(i => i.Sequence.Id).Order()); + + // A search applied: the list no longer holds them. + library.SearchText = "no such sequence"; + await UntilAsync(() => !ids.Any(Listed)); + Assert.False(ids.Any(Listed), "the search hides them"); + await shell.Jobs.OpenTargetAsync(Analysis(ids)); + Assert.Equal(string.Empty, library.SearchText); + Assert.SequenceEqual(ids.Order(), library.SelectedItems().Select(i => i.Sequence.Id).Order()); + + // More sequences than a page: those beyond the first page are read until each is listed. + var archiveId = Assert.NotNull(await db.Sequences.GetAsync(ids[0])).ArchiveId; + var bulk = new List(); + for (var i = 0; i < LibraryPager.DefaultPageSize + 10; i++) + { + var sequence = new Sequence + { + Id = Guid.CreateVersion7(), + ArchiveId = archiveId, + Folder = $"2021/2021-03-01 Bulk {i:000}", + Title = $"Bulk {i:000}", + FirstCapture = new DateTime(2021, 3, 1).AddHours(i), + LastCapture = new DateTime(2021, 3, 1).AddHours(i + 1), + FrameCount = 10, + UpdatedAt = DateTimeOffset.UtcNow, + }; + await db.Sequences.UpsertAsync(sequence); + bulk.Add(sequence.Id); + } + await library.RefreshAsync(); + var beyond = bulk.Where(id => !Listed(id)).Take(3).ToList(); + Assert.Count(3, beyond); + await shell.Jobs.OpenTargetAsync(Analysis(beyond)); + Assert.Greater(library.Items.Count, LibraryPager.DefaultPageSize, "the next pages were read"); + Assert.SequenceEqual(beyond.Order(), library.SelectedItems().Select(i => i.Sequence.Id).Order()); + + // A job over more sequences than a page (a maintenance run over the archive) opens the Library as it is. + shell.Navigate(SectionKey.Jobs); + library.SearchText = "Bulk"; + await shell.Jobs.OpenTargetAsync(Analysis(bulk)); + Assert.Equal(SectionKey.Library, shell.Current.Key); + Assert.Equal("Bulk", library.SearchText, "its search is not cleared"); + Assert.SequenceEqual(beyond.Order(), library.SelectedItems().Select(i => i.Sequence.Id).Order(), "nor its selection replaced"); + + await shell.Jobs.OpenTargetAsync(Job(JobKind.Verify, JobState.Done, Guid.CreateVersion7())); + Assert.Equal(SectionKey.Archive, shell.Current.Key); + // The Archive screen reads its figures when it opens: let that end before the app closes. + await shell.Archive.LoadAsync(); + }); + + /// Lets the dispatcher run what was posted to it (the editor's job events and reload) until holds. + private static async Task UntilAsync(Func done) + { + for (var i = 0; i < 250 && !done(); i++) await Task.Delay(20); + } + /// The Jobs screen read its first page (it would set the job bar and the badge again). private static async Task JobsLoadedAsync(ShellViewModel shell) { diff --git a/tests/Titano.Core.Tests/Import/ImportExecutorTests.cs b/tests/Titano.Core.Tests/Import/ImportExecutorTests.cs index 8fdb8f4d..1d1c2d39 100644 --- a/tests/Titano.Core.Tests/Import/ImportExecutorTests.cs +++ b/tests/Titano.Core.Tests/Import/ImportExecutorTests.cs @@ -1,5 +1,6 @@ using Titano.Core.Archiving; using Titano.Core.Import; +using Titano.Core.Localization; using Titano.Core.Tests.Archiving; using Titano.Testing; using static Titano.Core.Tests.Import.ImportTestKit; @@ -141,6 +142,41 @@ public sealed class ImportExecutorTests(TestContext context) Assert.Equal(19, final.Copied); Assert.Equal(1, final.Failed); Assert.Equal(plan.Sessions[0].Items[5].SourcePath, failed.Single().Item.SourcePath); + Assert.Equal(Loc.L("Archive.Error.SourceChanged", plan.Sessions[0].Items[5].SourcePath), failed.Single().Error); + } + + [Test] + public async Task ACopyTheSystemRefusesFailsAloneWithACatalogSentence() + { + var card = Card(10); + var destination = context.CreateTempDirectory("dest"); + var plan = await PlanAsync(card, destination); + var sink = new FolderImportSink(destination); + // A folder squats the staging name of the fourth copy: creating that copy fails with the system's own text. + var item = plan.Sessions[0].Items[3]; + Directory.CreateDirectory(Path.Combine(sink.StagingDirectory, $"{plan.Id:N}-{3:D6}{Path.GetExtension(item.FileName)}")); + var failed = new List(); + var final = await RunAsync(plan, sink, committed: b => + { + failed.AddRange(b.Results.Where(r => r.Status == ImportItemStatus.Failed)); + return ValueTask.CompletedTask; + }); + Assert.Equal(9, final.Copied); + Assert.Equal(item.SourcePath, failed.Single().Item.SourcePath); + Assert.Contains(failed.Single().Error, new[] { Loc.L("Import.Failed.Photo"), Loc.L("Import.Failed.PhotoAccess") }); + } + + [Test] + public void AFailedCopySaysWhyInOneLocalizedSentence() + { + Assert.Equal(Loc.L("Import.Failed.Full"), ImportExecutor.FailureText(new IOException("There is not enough space on the disk.", unchecked((int)0x80070070)))); + Assert.Equal(Loc.L("Import.Failed.Full"), ImportExecutor.FailureText(new IOException("The disk is full.", unchecked((int)0x80070027)))); + Assert.Equal(Loc.L("Import.Failed.PhotoAccess"), ImportExecutor.FailureText(new UnauthorizedAccessException(@"Access to the path 'E:\DCIM\IMG_0001.CR3' is denied."))); + Assert.Equal(Loc.L("Import.Failed.Photo"), ImportExecutor.FailureText(new IOException("The semaphore timeout period has expired."))); + Assert.Equal(Loc.L("Import.Failed.Photo"), ImportExecutor.FailureText(new FileNotFoundException(@"Could not find file 'E:\DCIM\IMG_0001.CR3'."))); + // The executor's own checks are one sentence each already. + Assert.Equal(Loc.L("Archive.Error.CopyMismatch", "IMG_0001.CR3"), ImportExecutor.FailureText(new CopyVerificationException("/staging/IMG_0001.CR3"))); + Assert.Equal(Loc.L("Archive.Error.SourceChanged", "DCIM/IMG_0001.CR3"), ImportExecutor.FailureText(new ImportSourceChangedException("DCIM/IMG_0001.CR3"))); } [Test] diff --git a/tests/Titano.Core.Tests/Import/ImportPlannerTests.cs b/tests/Titano.Core.Tests/Import/ImportPlannerTests.cs index ad45c26e..c61cbdb4 100644 --- a/tests/Titano.Core.Tests/Import/ImportPlannerTests.cs +++ b/tests/Titano.Core.Tests/Import/ImportPlannerTests.cs @@ -1,5 +1,6 @@ using Titano.Core.Archiving; using Titano.Core.Import; +using Titano.Core.Localization; using Titano.Core.Tests.Archiving; using Titano.Testing; using static Titano.Core.Tests.Import.ImportTestKit; @@ -35,6 +36,25 @@ public sealed class ImportPlannerTests(TestContext context) Assert.Empty(plan.Problems); } + [Test] + public void AFileThatCannotBeReadIsAProblemWithOneLocalizedSentence() + { + var card = context.CreateTempDirectory("card"); + TestPhotos.WriteSeries(Path.Combine(card, "DCIM", "100CANON"), Start, 3, Interval); + var files = CardScanner.Find(card, includeSubfolders: true); + // A photo leaves the card between listing and reading; another name is a folder the system refuses to read as a file. + File.Delete(Path.Combine(card, files[1].RelativePath)); + Directory.CreateDirectory(Path.Combine(card, "DCIM", "100CANON", "IMG_9999.JPG")); + var problems = new List(); + + var photos = CardScanner.ReadMetadata(card, [.. files, new CardFile("DCIM/100CANON/IMG_9999.JPG", 0, Start)], problems); + Assert.Equal(2, photos.Count); + Assert.SequenceEqual([files[1].RelativePath, "DCIM/100CANON/IMG_9999.JPG"], problems.Select(p => p.RelativePath)); + Assert.Equal(Loc.L("Import.Failed.Photo"), problems[0].Message); + Assert.Contains(problems[1].Message, new[] { Loc.L("Import.Failed.Photo"), Loc.L("Import.Failed.PhotoAccess") }); + Assert.False(problems.Any(p => p.Message.Contains(card, StringComparison.Ordinal)), "the system's text, with the card's path, stays in the log"); + } + [Test] public async Task AFlatFolderIncludesSubfoldersOnlyWhenAsked() {