merge: desktop section fixes (V-0, V-12, V-13, V-14)

Merge branch fix2/desktop-sections into the verification branch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-12 16:56:44 +00:00
commit acd51baa31
23 files changed
+609 -75

No files matched your search

+2
View File
@@ -109,6 +109,8 @@
<data name="Import.Failed.CheckRead" xml:space="preserve"><value>A photo or its archive copy could not be read.</value><comment>long</comment></data> <data name="Import.Failed.CheckRead" xml:space="preserve"><value>A photo or its archive copy could not be read.</value><comment>long</comment></data>
<data name="Import.Failed.Full" xml:space="preserve"><value>The destination is full.</value><comment>long</comment></data> <data name="Import.Failed.Full" xml:space="preserve"><value>The destination is full.</value><comment>long</comment></data>
<data name="Import.Failed.Other" xml:space="preserve"><value>The import stopped before the end.</value><comment>long</comment></data> <data name="Import.Failed.Other" xml:space="preserve"><value>The import stopped before the end.</value><comment>long</comment></data>
<data name="Import.Failed.Photo" xml:space="preserve"><value>The photo could not be read or copied.</value><comment>long</comment></data>
<data name="Import.Failed.PhotoAccess" xml:space="preserve"><value>Titano was denied access to the photo or its copy.</value><comment>long</comment></data>
<data name="Import.Failed.Retry" xml:space="preserve"><value>Retry</value></data> <data name="Import.Failed.Retry" xml:space="preserve"><value>Retry</value></data>
<data name="Import.Failed.Server" xml:space="preserve"><value>The server did not accept the photos.</value><comment>long</comment></data> <data name="Import.Failed.Server" xml:space="preserve"><value>The server did not accept the photos.</value><comment>long</comment></data>
<data name="Import.Failed.SourceGone" xml:space="preserve"><value>{0} is no longer available.</value><comment>long</comment></data> <data name="Import.Failed.SourceGone" xml:space="preserve"><value>{0} is no longer available.</value><comment>long</comment></data>
+2
View File
@@ -107,6 +107,8 @@
<data name="Import.Failed.CheckRead" xml:space="preserve"><value>Impossibile leggere una foto o la sua copia nell'archivio.</value></data> <data name="Import.Failed.CheckRead" xml:space="preserve"><value>Impossibile leggere una foto o la sua copia nell'archivio.</value></data>
<data name="Import.Failed.Full" xml:space="preserve"><value>La destinazione è piena.</value></data> <data name="Import.Failed.Full" xml:space="preserve"><value>La destinazione è piena.</value></data>
<data name="Import.Failed.Other" xml:space="preserve"><value>L'importazione si è interrotta prima della fine.</value></data> <data name="Import.Failed.Other" xml:space="preserve"><value>L'importazione si è interrotta prima della fine.</value></data>
<data name="Import.Failed.Photo" xml:space="preserve"><value>Impossibile leggere o copiare la foto.</value></data>
<data name="Import.Failed.PhotoAccess" xml:space="preserve"><value>A Titano è stato negato l'accesso alla foto o alla sua copia.</value></data>
<data name="Import.Failed.Retry" xml:space="preserve"><value>Riprova</value></data> <data name="Import.Failed.Retry" xml:space="preserve"><value>Riprova</value></data>
<data name="Import.Failed.Server" xml:space="preserve"><value>Il server non ha accettato le foto.</value></data> <data name="Import.Failed.Server" xml:space="preserve"><value>Il server non ha accettato le foto.</value></data>
<data name="Import.Failed.SourceGone" xml:space="preserve"><value>{0} non è più disponibile.</value></data> <data name="Import.Failed.SourceGone" xml:space="preserve"><value>{0} non è più disponibile.</value></data>
+35 -8
View File
@@ -930,14 +930,21 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
if (!_jobs.Concerns(job)) return; if (!_jobs.Concerns(job)) return;
_dispatcher.BeginInvoke(() => _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); var wasActive = _jobs.IsActive(job.Id);
// Progress alone (several times a second on a server) only moves the server job's text and bar. // Progress alone (several times a second on a server) only moves the server job's text and bar.
if (_jobs.Track(job)) OnBusyChanged(); if (_jobs.Track(job)) OnBusyChanged();
else OnServerJobChanged(); else OnServerJobChanged();
LearnAnalysisSpeed(job); LearnAnalysisSpeed(job);
if (!wasActive) return; 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); 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; if (job is { Kind: JobKind.DeepAnalyse, State: JobState.Done, ItemsPerSecond: > 0 and var speed }) _analysisSecondsPerFrame = 1 / speed;
} }
/// <summary>Reads the sequence again after a job; a finished render offers its follow-ups (BRIEF §11.5).</summary> /// <summary>
/// Reads the sequence again after a job. A finished render whose toast this editor took (<see cref="Sections.JobsViewModel.ClaimRenderToast"/>)
/// 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.
/// </summary>
private async Task ReloadAsync(Job? render) private async Task ReloadAsync(Job? render)
{ {
var reloaded = false;
try try
{ {
await Session.ReloadAsync(); await Session.ReloadAsync();
reloaded = true;
} }
catch (Exception ex) when (ex is System.IO.IOException or System.IO.InvalidDataException or InvalidOperationException or UnauthorizedAccessException 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). // A server that does not answer in time cancels the request (OperationCanceledException).
Shell.ReportError(ex); Shell.ReportError(ex);
return;
} }
if (render is null || _disposed) return; finally
// 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 if (render is not null) AnnounceRender(render, reloaded);
}
}
/// <summary>
/// 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 (<see cref="Sections.JobsViewModel.ClaimRenderToast"/>) when it does.
/// </summary>
internal bool FollowsRender(Guid jobId) => !_disposed && _jobs.IsActive(jobId);
/// <summary>"Render finished" with the output file and Show in folder; <paramref name="read"/>: the sequence was read again after the render.</summary>
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 ? path
: null; : null;
Shell.ShowToast(new Toast Shell.ShowToast(new Toast
+3 -3
View File
@@ -211,7 +211,8 @@ public sealed record ImportOutcome(int Copied, int Duplicates, int Skipped, IRea
/// </summary> /// </summary>
public static class LocalImport public static class LocalImport
{ {
public static async Task<ImportOutcome> RunAsync(ImportPlan plan, IImportSink sink, bool verify, IProgress<ImportProgress>? progress, /// <param name="source">The card or folder as the Devices list names it (a card that leaves is named in each failure).</param>
public static async Task<ImportOutcome> RunAsync(ImportPlan plan, IImportSink sink, string source, bool verify, IProgress<ImportProgress>? progress,
CancellationToken cancellationToken, ImportSinkReport? report = null) CancellationToken cancellationToken, ImportSinkReport? report = null)
{ {
var results = new List<ImportItemResult>(plan.FileCount); var results = new List<ImportItemResult>(plan.FileCount);
@@ -232,8 +233,7 @@ public static class LocalImport
catch (Exception ex) when (!cancellationToken.IsCancellationRequested && Stops(ex)) catch (Exception ex) when (!cancellationToken.IsCancellationRequested && Stops(ex))
{ {
Log.Warning("import", $"Import into {plan.DestinationRoot} stopped", 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 = ImportFailures.Stop(ex, source);
stopped = ex is TitanoApiException api ? api.Error.Message : ex.Message;
} }
return ImportOutcome.From(plan, results, verify, report, stopped); return ImportOutcome.From(plan, results, verify, report, stopped);
} }
+12
View File
@@ -1,5 +1,6 @@
using System.IO; using System.IO;
using System.Net.Http; using System.Net.Http;
using Titano.App.Shell;
using Titano.Core.Archiving; using Titano.Core.Archiving;
using Titano.Core.Import; using Titano.Core.Import;
using Titano.Core.Localization; using Titano.Core.Localization;
@@ -29,6 +30,17 @@ public static class ImportFailures
_ => Loc.L("Import.Failed.Other"), _ => Loc.L("Import.Failed.Other"),
}; };
/// <summary>
/// Why the photos an import into a folder or the server never reached were not copied (<see cref="LocalImport"/>):
/// 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.
/// </summary>
public static string Stop(Exception ex, string source) => ex switch
{
TitanoApiException or HttpRequestException or UntrustedCertificateException or OperationCanceledException => ErrorText.ForServer(ex),
_ => Import(ex, source),
};
/// <summary>Why the card or folder could not be planned.</summary> /// <summary>Why the card or folder could not be planned.</summary>
public static string Plan(Exception ex, string source) => ex switch public static string Plan(Exception ex, string source) => ex switch
{ {
+5 -3
View File
@@ -1,5 +1,6 @@
using System.IO; using System.IO;
using System.Net; using System.Net;
using Titano.App.Shell;
using Titano.Core.Diagnostics; using Titano.Core.Diagnostics;
using Titano.Core.Import; using Titano.Core.Import;
using Titano.Protocol; using Titano.Protocol;
@@ -38,7 +39,7 @@ public sealed class ServerImportSink(TitanoClient client, string stagingDirector
ImportOutcome? outcome = null; ImportOutcome? outcome = null;
try 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; return outcome;
} }
finally finally
@@ -69,8 +70,9 @@ public sealed class ServerImportSink(TitanoClient client, string stagingDirector
} }
catch (TitanoApiException ex) when (IsRefusal(ex)) 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. // The executor has no failed commit: the refusal travels in the report, which turns this result into a failure. The
Report.Rejected[file.Item.SourcePath] = ex.Error.Message; // 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)); results.Add(new SinkCommit(null, file.Item.FileName, Duplicate: false));
} }
finally finally
+36 -14
View File
@@ -135,19 +135,7 @@ public sealed class ArchiveViewModel : SectionViewModel
_archive = value; _archive = value;
_duplicates = null; _duplicates = null;
_orphans = null; _orphans = null;
if (other) if (other) ForgetRead();
{
// 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();
}
_ = LoadAsync(); _ = LoadAsync();
} }
} }
@@ -430,8 +418,11 @@ public sealed class ArchiveViewModel : SectionViewModel
{ {
AttachJobEvents(); AttachJobEvents();
Archives = await db.Archives.ListAsync(); 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); _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; if (_archive is not { } archive) return;
var root = archive.RootPath; var root = archive.RootPath;
var availability = await Task.Run(() => ArchiveVolume.Probe(new ArchivePaths(root))); var availability = await Task.Run(() => ArchiveVolume.Probe(new ArchivePaths(root)));
@@ -459,6 +450,37 @@ public sealed class ArchiveViewModel : SectionViewModel
} }
} }
/// <summary>
/// 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.
/// </summary>
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();
}
/// <summary>Opens the rebuild dialog (BRIEF §12.5) and counts, off the UI thread, the sidecars the rebuild will read.</summary> /// <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() public async Task<RebuildDialogViewModel?> OpenRebuildDialogAsync()
{ {
+3 -2
View File
@@ -1166,7 +1166,8 @@ public sealed class ImportViewModel : SectionViewModel
var progress = new Progress<ImportProgress>(ShowProgress); var progress = new Progress<ImportProgress>(ShowProgress);
ImportOutcome outcome; ImportOutcome outcome;
if (choices.Destination == ImportDestinationKind.Folder) 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 }) else if (Services.Server.Flow is { Address: { } address, Token: { } token })
outcome = await RunServerAsync(plan, choices, source.Title, address, token, progress, cts.Token); outcome = await RunServerAsync(plan, choices, source.Title, address, token, progress, cts.Token);
else else
@@ -1304,7 +1305,7 @@ public sealed class ImportViewModel : SectionViewModel
catch (DatabaseException ex) catch (DatabaseException ex)
{ {
Log.Warning("import", "The import could not be checked against the index", 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));
} }
} }
+47 -9
View File
@@ -3,6 +3,7 @@ using System.IO;
using System.Windows.Input; using System.Windows.Input;
using Titano.App.Infrastructure; using Titano.App.Infrastructure;
using Titano.App.Jobs; using Titano.App.Jobs;
using Titano.App.Library;
using Titano.App.Settings; using Titano.App.Settings;
using Titano.App.Shell; using Titano.App.Shell;
using Titano.Core.Diagnostics; using Titano.Core.Diagnostics;
@@ -63,6 +64,10 @@ public sealed class JobsViewModel : SectionViewModel
private readonly Dictionary<Guid, JobRowViewModel> _rows = []; private readonly Dictionary<Guid, JobRowViewModel> _rows = [];
private readonly HashSet<Guid> _unseenFailures = []; private readonly HashSet<Guid> _unseenFailures = [];
private readonly JobEndings _endings = new(); private readonly JobEndings _endings = new();
/// <summary>Finished renders whose toast was taken (<see cref="ClaimRenderToast"/>).</summary>
private readonly HashSet<Guid> _renderToasts = [];
private readonly JobActions _actions; private readonly JobActions _actions;
private CoalescingThrottle? _throttle; private CoalescingThrottle? _throttle;
private IJobQueue? _queue; private IJobQueue? _queue;
@@ -250,10 +255,20 @@ public sealed class JobsViewModel : SectionViewModel
if (job.State != JobState.Failed) _unseenFailures.Remove(job.Id); if (job.State != JobState.Failed) _unseenFailures.Remove(job.Id);
else if (before != JobState.Failed && !IsSelected) _unseenFailures.Add(job.Id); else if (before != JobState.Failed && !IsSelected) _unseenFailures.Add(job.Id);
var notice = JobNotices.For(before, job); 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); _endings.Add(notice, job);
} }
/// <summary>
/// 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.
/// </summary>
internal bool ClaimRenderToast(Guid jobId) => _renderToasts.Add(jobId);
/// <summary> /// <summary>
/// The toast of a job that ended, with one action (BRIEF §12.1, §0.2 rule 6). Several endings at once (a batch /// 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 /// 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
}; };
} }
/// <summary>A finished render of the sequence open in the editor: the editor says it, with its output file.</summary>
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);
/// <summary>A job changed state (any thread; tests feed it too): buffered until the next flush.</summary> /// <summary>A job changed state (any thread; tests feed it too): buffered until the next flush.</summary>
internal void OnJobChanged(Job job) internal void OnJobChanged(Job job)
{ {
@@ -403,13 +413,41 @@ public sealed class JobsViewModel : SectionViewModel
SyncRows(); SyncRows();
} }
/// <summary>Opens what a job worked on inside Titano: its sequence in the editor, or the Archive screen.</summary> /// <summary>
/// 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.
/// </summary>
internal async Task OpenTargetAsync(Job job) internal async Task OpenTargetAsync(Job job)
{ {
var db = Shell.Services.Database; var db = Shell.Services.Database;
if (db is null || job.TargetIds.Count == 0) return; if (db is null || job.TargetIds.Count == 0) return;
if (await db.Sequences.GetAsync(job.TargetIds[0]) is { } sequence) Shell.OpenSequence(sequence.Id); var targets = job.TargetIds.Distinct().ToList();
else Shell.Navigate(SectionKey.Archive); 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<Guid>(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;
}
} }
/// <summary>Shows the folder of what a job worked on in Explorer.</summary> /// <summary>Shows the folder of what a job worked on in Explorer.</summary>
+62 -7
View File
@@ -71,6 +71,10 @@ public sealed class LibraryViewModel : SectionViewModel
private bool _isLoading; private bool _isLoading;
private bool _hasLoaded; private bool _hasLoaded;
private bool _suppressReload; private bool _suppressReload;
/// <summary>Many cards change selection at once (<see cref="SelectOnly"/>): the selection is counted once after them.</summary>
private bool _bulkSelect;
private int _layoutIndex; private int _layoutIndex;
private SequenceItem? _selected; private SequenceItem? _selected;
private int _selectionCount; private int _selectionCount;
@@ -581,6 +585,52 @@ public sealed class LibraryViewModel : SectionViewModel
RaiseMass(); RaiseMass();
} }
/// <summary>
/// Shows the sequences of <paramref name="ids"/> 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.
/// </summary>
public async Task ShowSelectedAsync(IReadOnlyCollection<Guid> 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);
}
/// <summary>
/// Selects exactly the cards <paramref name="chosen"/> 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.
/// </summary>
private void SelectOnly(Func<SequenceItem, bool> chosen)
{
_bulkSelect = true;
try
{
foreach (var item in Items)
{
var selected = chosen(item);
if (item.IsSelected != selected) item.IsSelected = selected;
}
}
finally
{
_bulkSelect = false;
}
OnSelectionChanged();
}
/// <summary>Opens Tags on the selection (capture, tests).</summary> /// <summary>Opens Tags on the selection (capture, tests).</summary>
public void OpenRetag() => OpenRetag(Targets(MassAction.Tag)); public void OpenRetag() => OpenRetag(Targets(MassAction.Tag));
@@ -850,6 +900,13 @@ public sealed class LibraryViewModel : SectionViewModel
} }
private void ClearFilters() private void ClearFilters()
{
ResetFilters();
Reload();
}
/// <summary>Search and filters back to "any", without reading the list again.</summary>
private void ResetFilters()
{ {
_suppressReload = true; _suppressReload = true;
_searchDelay.Stop(); _searchDelay.Stop();
@@ -863,9 +920,11 @@ public sealed class LibraryViewModel : SectionViewModel
_timelineMonth = null; _timelineMonth = null;
_scrollToMonth = false; _scrollToMonth = false;
_suppressReload = false; _suppressReload = false;
Reload();
} }
/// <summary>Every sequence of <paramref name="ids"/> is in the list on screen.</summary>
private bool Lists(HashSet<Guid> ids) => ids.IsSubsetOf(Items.Select(i => i.Sequence.Id));
/// <summary>Shows a saved view: its search, filters and sort, at once.</summary> /// <summary>Shows a saved view: its search, filters and sort, at once.</summary>
private void Apply(SavedView view) private void Apply(SavedView view)
{ {
@@ -920,15 +979,11 @@ public sealed class LibraryViewModel : SectionViewModel
await LoadViewsAsync(); await LoadViewsAsync();
} }
private void ClearSelection() private void ClearSelection() => SelectOnly(_ => false);
{
foreach (var item in Items) item.IsSelected = false;
OnSelectionChanged();
}
private void OnItemChanged(object? sender, PropertyChangedEventArgs e) 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() private void RaiseState()
@@ -142,6 +142,13 @@ public sealed class SequenceViewModel : SectionViewModel
await editor.DisposeAsync(); await editor.DisposeAsync();
} }
/// <summary>Shows <paramref name="editor"/>, which the caller opened over a source of its own (tests), as the open sequence.</summary>
internal void Attach(EditorViewModel editor)
{
_openId = editor.Session.Content.Sequence.Id;
Editor = editor;
}
public override void Dispose() public override void Dispose()
{ {
Shell.PropertyChanged -= OnShellChanged; Shell.PropertyChanged -= OnShellChanged;
+23 -3
View File
@@ -1,4 +1,5 @@
using System.IO; using System.IO;
using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Reflection; using System.Reflection;
using Titano.Core.Archiving; using Titano.Core.Archiving;
@@ -7,6 +8,7 @@ using Titano.Core.Localization;
using Titano.Core.Render; using Titano.Core.Render;
using Titano.Data.Archiving; using Titano.Data.Archiving;
using Titano.Data.Sync; using Titano.Data.Sync;
using Titano.Protocol;
using Titano.Protocol.Client; using Titano.Protocol.Client;
namespace Titano.App.Shell; 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"); public static string For(Exception ex) => Describe(Unwrap(ex)) ?? Loc.L("Errors.Unexpected");
/// <summary> /// <summary>
/// A request to the signed-in server failed: the server's own sentence when it answered, else that it does not answer /// A request to the signed-in server failed: the server's own sentence when it answered, else what the reply's status
/// (refused, timed out, dropped) or that its certificate is no longer trusted. /// means (a proxy in front of it), that it does not answer (refused, timed out, dropped) or that its certificate is no
/// longer trusted.
/// </summary> /// </summary>
public static string ForServer(Exception ex) public static string ForServer(Exception ex)
{ {
@@ -40,11 +43,28 @@ public static class ErrorText
LeaseUnavailableException or ArchiveOfflineException or NewerFormatException or ImportSourceUnavailableException LeaseUnavailableException or ArchiveOfflineException or NewerFormatException or ImportSourceUnavailableException
or CopyVerificationException or StaleRenamePlanException or SyncConflictChangedException => ex.Message, or CopyVerificationException or StaleRenamePlanException or SyncConflictChangedException => ex.Message,
// The server words its errors in the client's language (Accept-Language). // 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]), RenderException render => Loc.Get(render.ReasonKey, Loc.Culture) is null ? null : Loc.L(render.ReasonKey, [.. render.Args]),
_ => null, _ => null,
}; };
/// <summary>
/// An error the server wrote as its JSON, with its own sentence. <c>TitanoClient</c> codes any other reply
/// <c>http_&lt;status&gt;</c> with the reason phrase as its message, and JSON of another shape has no code.
/// </summary>
private static bool FromServer(ApiError error) =>
error.Code is { } code && !code.StartsWith("http_", StringComparison.Ordinal) && !string.IsNullOrWhiteSpace(error.Message);
/// <summary>Awaited tasks and reflection wrap the real failure in one layer or more.</summary> /// <summary>Awaited tasks and reflection wrap the real failure in one layer or more.</summary>
private static Exception Unwrap(Exception ex) private static Exception Unwrap(Exception ex)
{ {
+5 -2
View File
@@ -62,7 +62,10 @@ public static class CardScanner
return files; return files;
} }
/// <summary>Reads light metadata of every file; unreadable files become <paramref name="problems"/>.</summary> /// <summary>
/// Reads light metadata of every file; unreadable files become <paramref name="problems"/>, each with one localized
/// sentence (the system's text goes to the log only).
/// </summary>
public static IReadOnlyList<CardPhoto> ReadMetadata(string root, IReadOnlyList<CardFile> files, List<ImportProblem> problems, public static IReadOnlyList<CardPhoto> ReadMetadata(string root, IReadOnlyList<CardFile> files, List<ImportProblem> problems,
IProgress<int>? progress = null, CancellationToken cancellationToken = default) IProgress<int>? progress = null, CancellationToken cancellationToken = default)
{ {
@@ -78,7 +81,7 @@ public static class CardScanner
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{ {
Log.Warning("import", $"Cannot read {file.RelativePath}", ex); 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); progress?.Report(i + 1);
} }
+21 -2
View File
@@ -10,6 +10,9 @@ public sealed class ImportSourceUnavailableException(string root, Exception? inn
public string Root { get; } = root; public string Root { get; } = root;
} }
/// <summary>A card file is gone or has another size than when the plan was made: that photo fails, the import goes on.</summary>
internal sealed class ImportSourceChangedException(string path) : IOException(Loc.L("Archive.Error.SourceChanged", path));
/// <summary>A verified copy waiting in the sink's staging folder.</summary> /// <summary>A verified copy waiting in the sink's staging folder.</summary>
public sealed record StagedFile(PlannedItem Item, string StagedPath, string Sha256); public sealed record StagedFile(PlannedItem Item, string StagedPath, string Sha256);
@@ -59,6 +62,8 @@ public sealed record ImportBatch(IReadOnlyList<ImportItemResult> Results, int Ne
public sealed class ImportExecutor(ImportPlan plan, IImportSink sink) public sealed class ImportExecutor(ImportPlan plan, IImportSink sink)
{ {
private const int BatchSize = 32; private const int BatchSize = 32;
private const int DiskFull = unchecked((int)0x80070070);
private const int HandleDiskFull = unchecked((int)0x80070027);
/// <param name="startAt">Number of plan items already done (the last <see cref="ImportBatch.NextItem"/> recorded).</param> /// <param name="startAt">Number of plan items already done (the last <see cref="ImportBatch.NextItem"/> recorded).</param>
/// <param name="committed">Called after each batch; record the results, then checkpoint <see cref="ImportBatch.NextItem"/>.</param> /// <param name="committed">Called after each batch; record the results, then checkpoint <see cref="ImportBatch.NextItem"/>.</param>
@@ -119,7 +124,7 @@ public sealed class ImportExecutor(ImportPlan plan, IImportSink sink)
try try
{ {
if (new FileInfo(source) is not { Exists: true } info || info.Length != item.Size) 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); var sha = await VerifiedCopy.CopyAsync(source, target, verify, read => bytesDone += read, cancellationToken).ConfigureAwait(false);
staged.Add(new StagedFile(item, target, sha)); staged.Add(new StagedFile(item, target, sha));
stagedSession = session; stagedSession = session;
@@ -133,13 +138,27 @@ public sealed class ImportExecutor(ImportPlan plan, IImportSink sink)
} }
Log.Warning("import", $"Copy of {item.SourcePath} failed", ex); Log.Warning("import", $"Copy of {item.SourcePath} failed", ex);
failed++; 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); await FlushAsync().ConfigureAwait(false);
return Snapshot(null); return Snapshot(null);
} }
/// <summary>
/// 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.
/// </summary>
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) private static void DeleteLeftover(string staged)
{ {
// Staged files are this import's own copies of card files; the originals stay on the card. // Staged files are this import's own copies of card files; the originals stay on the card.
@@ -182,17 +182,38 @@ public sealed class ArchiveScreenSmokeTests
var archive = app.Shell.Archive; var archive = app.Shell.Archive;
await ArchiveScenes.ShowAsync(app.Shell, "overview"); await ArchiveScenes.ShowAsync(app.Shell, "overview");
Assert.Contains(archive.TreeRows, r => r.Node.Kind == TreeNodeKind.Sequence); 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 second = await app.Services.Archives!.CreateAsync(Path.Combine(app.Services.Environment.DataDirectory, "second-archive"), "Second");
var reading = archive.LoadAsync(); var reading = archive.LoadAsync();
archive.SelectedArchive = second; archive.SelectedArchive = second;
Assert.Empty(archive.TreeRows); 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.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.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.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.False(archive.RebuildCommand.CanExecute(null), "the rebuild dialog waits for the picked archive's own state and figures");
Assert.Null(await archive.OpenRebuildDialogAsync()); Assert.Null(await archive.OpenRebuildDialogAsync());
Assert.Empty(archive.Health); 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; await reading;
Assert.Equal(second.Id, archive.SelectedArchive!.Id); Assert.Equal(second.Id, archive.SelectedArchive!.Id);
@@ -111,7 +111,15 @@ internal sealed class FakeSequenceSource(SyntheticSequence sequence, SequenceCon
/// <summary>Awaited by every decode (tests of cancellation).</summary> /// <summary>Awaited by every decode (tests of cancellation).</summary>
public Task DecodeGate { get; set; } = Task.CompletedTask; public Task DecodeGate { get; set; } = Task.CompletedTask;
public Task<SequenceContent> LoadAsync(CancellationToken cancellationToken) => Task.FromResult(Content with { Project = Stored }); /// <summary>Thrown by the next load (the sequence read again after a job).</summary>
public Exception? FailNextLoad { get; set; }
public Task<SequenceContent> LoadAsync(CancellationToken cancellationToken)
{
if (FailNextLoad is not { } failure) return Task.FromResult(Content with { Project = Stored });
FailNextLoad = null;
return Task.FromException<SequenceContent>(failure);
}
public async ValueTask<ImageBuffer?> DecodeAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken) public async ValueTask<ImageBuffer?> DecodeAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken)
{ {
@@ -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)); 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] [Test]
public void APlanningFailureNamesTheSource() public void APlanningFailureNamesTheSource()
{ {
@@ -1,5 +1,6 @@
using System.Globalization; using System.Globalization;
using System.IO; using System.IO;
using System.Net.Http;
using Titano.App.Import; using Titano.App.Import;
using Titano.Core.Import; using Titano.Core.Import;
using Titano.Core.Localization; using Titano.Core.Localization;
@@ -111,7 +112,7 @@ public sealed class ImportFlowTests(TestContext context)
Assert.Equal(16, plan.CopyCount); Assert.Equal(16, plan.CopyCount);
var reports = new List<ImportProgress>(); var reports = new List<ImportProgress>();
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.Equal(16, outcome.Copied);
Assert.True(outcome.IsComplete); Assert.True(outcome.IsComplete);
Assert.True(outcome.Verified); Assert.True(outcome.Verified);
@@ -120,7 +121,7 @@ public sealed class ImportFlowTests(TestContext context)
Assert.FileExists(Path.Combine(target, folder, name)); Assert.FileExists(Path.Combine(target, folder, name));
var again = await LocalImport.RunAsync(await destination.PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation), 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(0, again.Copied);
Assert.Equal(16, again.Duplicates); Assert.Equal(16, again.Duplicates);
Assert.False(new CardActions(ImportDestinationKind.Folder, false, true, true, outcome, null, null).CanCheck); 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); 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) private async Task WaitDoneAsync(TitanoDatabase db, Guid jobId)
{ {
var until = DateTime.UtcNow.AddSeconds(60); var until = DateTime.UtcNow.AddSeconds(60);
@@ -177,6 +193,15 @@ public sealed class ImportFlowTests(TestContext context)
Assert.Fail("The import job did not finish"); Assert.Fail("The import job did not finish");
} }
/// <summary>A server destination whose connection is gone: every commit fails as the HTTP stack reports it.</summary>
private sealed class UnreachableSink(string staging) : IImportSink
{
public string StagingDirectory { get; } = staging;
public Task<IReadOnlyList<SinkCommit>> CommitAsync(PlannedSession session, IReadOnlyList<StagedFile> files, CancellationToken cancellationToken) =>
throw new HttpRequestException("An error occurred while sending the request.");
}
/// <summary>Collects reports synchronously (System.Progress posts to the thread pool).</summary> /// <summary>Collects reports synchronously (System.Progress posts to the thread pool).</summary>
private sealed class Progress(List<ImportProgress> into) : IProgress<ImportProgress> private sealed class Progress(List<ImportProgress> into) : IProgress<ImportProgress>
{ {
@@ -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); 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)] }; 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.Equal(16, outcome.Copied);
Assert.True(outcome.IsComplete); 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" }; 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 destination = new UnindexedDestination(ImportDestinationKind.Server, staging);
var plan = await destination.PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation); 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 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(0, again.Copied);
Assert.Equal(8, again.Duplicates); Assert.Equal(8, again.Duplicates);
Assert.Equal(chunks, server.ChunkCount); 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 plan = await new UnindexedDestination(ImportDestinationKind.Server, staging).PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation);
var sink = new ServerImportSink(client, staging); 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, outcome.Copied);
Assert.Equal(7, server.Committed.Count); Assert.Equal(7, server.Committed.Count);
Assert.Equal(new ImportFailure("DCIM/100CANON/IMG_0003.JPG", "Hash mismatch"), outcome.Failures.Single()); Assert.Equal(new ImportFailure("DCIM/100CANON/IMG_0003.JPG", "Hash mismatch"), outcome.Failures.Single());
Assert.Empty(Directory.EnumerateFileSystemEntries(staging)); 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] [Test]
public async Task ALostSignInStopsTheImportAndKeepsWhatWasUploaded() 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 plan = await new UnindexedDestination(ImportDestinationKind.Server, staging).PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation);
var sink = new ServerImportSink(client, staging); 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(3, outcome.Copied, "the uploads the server committed before the sign-in was lost");
Assert.Equal(5, outcome.Failures.Count); Assert.Equal(5, outcome.Failures.Count);
Assert.Equal("Sign in again", outcome.Failures[0].Message, "the server's sentence"); Assert.Equal("Sign in again", outcome.Failures[0].Message, "the server's sentence");
@@ -231,6 +247,9 @@ public sealed class ServerImportSinkTests(TestContext context)
/// <summary>Flip a byte of every chunk of this file (a damaged transfer).</summary> /// <summary>Flip a byte of every chunk of this file (a damaged transfer).</summary>
public string? CorruptFile { get; init; } public string? CorruptFile { get; init; }
/// <summary>A reverse proxy in front of the server refuses the chunks of this file: 413 with its own HTML page.</summary>
public string? ProxyRefusesFile { get; init; }
/// <summary>Answer 401 to new uploads once this many were committed (the sign-in expired).</summary> /// <summary>Answer 401 to new uploads once this many were committed (the sign-in expired).</summary>
public int? SignedOutAfter { get; init; } 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]) if (request.Method == HttpMethod.Put && path is ["api", "v1", "uploads", var id, "chunks", var n])
{ {
var upload = _open[Guid.Parse(id)]; var upload = _open[Guid.Parse(id)];
if (upload.FileName == ProxyRefusesFile)
{
return new HttpResponseMessage(HttpStatusCode.RequestEntityTooLarge)
{
Content = new StringContent("<html><body><h1>413 Request Entity Too Large</h1></body></html>", System.Text.Encoding.UTF8, "text/html"),
};
}
var bytes = await request.Content!.ReadAsByteArrayAsync(cancellationToken); var bytes = await request.Content!.ReadAsByteArrayAsync(cancellationToken);
if (upload.FileName == CorruptFile) bytes[0] ^= 0xFF; if (upload.FileName == CorruptFile) bytes[0] ^= 0xFF;
upload.Parts[int.Parse(n, System.Globalization.CultureInfo.InvariantCulture)] = bytes; upload.Parts[int.Parse(n, System.Globalization.CultureInfo.InvariantCulture)] = bytes;
@@ -30,7 +30,27 @@ public sealed class ErrorTextTests
// Failures that already carry a catalog sentence keep it. // 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(@"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 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] [Test]
@@ -1,11 +1,16 @@
using System.IO;
using System.Windows; using System.Windows;
using System.Windows.Controls; using System.Windows.Controls;
using System.Windows.Input; using System.Windows.Input;
using System.Windows.Shell; using System.Windows.Shell;
using Titano.App.Editor;
using Titano.App.Infrastructure; using Titano.App.Infrastructure;
using Titano.App.Library;
using Titano.App.Sections; using Titano.App.Sections;
using Titano.App.Settings; using Titano.App.Settings;
using Titano.App.Shell; using Titano.App.Shell;
using Titano.App.Tests.Editor;
using Titano.Core.Export;
using Titano.Core.Localization; using Titano.Core.Localization;
using Titano.Core.Model; using Titano.Core.Model;
using Titano.Data.Repositories; using Titano.Data.Repositories;
@@ -133,26 +138,40 @@ public sealed class ShellNotificationTests
Assert.Equal(badge, jobs.Badge); Assert.Equal(badge, jobs.Badge);
Assert.NotEqual(TaskbarItemProgressState.Error, shell.TaskbarState); Assert.NotEqual(TaskbarItemProgressState.Error, shell.TaskbarState);
// The editor announces the renders of its own sequence, with their output: the shell says nothing then. // The editor says the renders it followed to their end, with their output: the shell says nothing then. It says them
var id = await app.Sample.FillEditorAsync(); // also when the sequence cannot be read again (that error is said too), without Show in folder then.
shell.OpenSequence(id); var content = EditorFixture.Content(EditorFixture.Sunset);
await shell.Sequence.OpenAsync(id); var source = new FakeSequenceSource(EditorFixture.Sunset, content);
Assert.NotNull(shell.Sequence.Editor); 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(); 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()); var other = Job(JobKind.Render, JobState.Running, Guid.CreateVersion7());
jobs.OnJobChanged(other); jobs.OnJobChanged(other);
jobs.Flush(); jobs.Flush();
jobs.OnJobChanged(other with { State = JobState.Done }); jobs.OnJobChanged(other with { State = JobState.Done });
jobs.Flush(); jobs.Flush();
Assert.Equal(1, raised.Count(t => t.Title == Loc.L("Shell.Job.Done"))); 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. // Server › Upload all: the batch speaks once, when its last upload ends.
raised.Clear(); raised.Clear();
@@ -380,6 +399,137 @@ public sealed class ShellNotificationTests
Assert.Equal(shell.Archive.Health.Count(h => !h.IsOk), shell.Archive.Badge); Assert.Equal(shell.Archive.Health.Count(h => !h.IsOk), shell.Archive.Badge);
}); });
/// <summary>
/// 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.
/// </summary>
[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<Toast>();
shell.PendingToasts.CollectionChanged += (_, e) => raised.AddRange(e.NewItems?.Cast<Toast>() ?? []);
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");
}
});
/// <summary>
/// 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.
/// </summary>
[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<Guid> 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<Guid>();
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();
});
/// <summary>Lets the dispatcher run what was posted to it (the editor's job events and reload) until <paramref name="done"/> holds.</summary>
private static async Task UntilAsync(Func<bool> done)
{
for (var i = 0; i < 250 && !done(); i++) await Task.Delay(20);
}
/// <summary>The Jobs screen read its first page (it would set the job bar and the badge again).</summary> /// <summary>The Jobs screen read its first page (it would set the job bar and the badge again).</summary>
private static async Task JobsLoadedAsync(ShellViewModel shell) private static async Task JobsLoadedAsync(ShellViewModel shell)
{ {
@@ -1,5 +1,6 @@
using Titano.Core.Archiving; using Titano.Core.Archiving;
using Titano.Core.Import; using Titano.Core.Import;
using Titano.Core.Localization;
using Titano.Core.Tests.Archiving; using Titano.Core.Tests.Archiving;
using Titano.Testing; using Titano.Testing;
using static Titano.Core.Tests.Import.ImportTestKit; using static Titano.Core.Tests.Import.ImportTestKit;
@@ -141,6 +142,41 @@ public sealed class ImportExecutorTests(TestContext context)
Assert.Equal(19, final.Copied); Assert.Equal(19, final.Copied);
Assert.Equal(1, final.Failed); Assert.Equal(1, final.Failed);
Assert.Equal(plan.Sessions[0].Items[5].SourcePath, failed.Single().Item.SourcePath); 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<ImportItemResult>();
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] [Test]
@@ -1,5 +1,6 @@
using Titano.Core.Archiving; using Titano.Core.Archiving;
using Titano.Core.Import; using Titano.Core.Import;
using Titano.Core.Localization;
using Titano.Core.Tests.Archiving; using Titano.Core.Tests.Archiving;
using Titano.Testing; using Titano.Testing;
using static Titano.Core.Tests.Import.ImportTestKit; using static Titano.Core.Tests.Import.ImportTestKit;
@@ -35,6 +36,25 @@ public sealed class ImportPlannerTests(TestContext context)
Assert.Empty(plan.Problems); 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<ImportProblem>();
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] [Test]
public async Task AFlatFolderIncludesSubfoldersOnlyWhenAsked() public async Task AFlatFolderIncludesSubfoldersOnlyWhenAsked()
{ {