diff --git a/i18n/en/Archive.resx b/i18n/en/Archive.resx index c80e69b4..5b0fcf17 100644 --- a/i18n/en/Archive.resx +++ b/i18n/en/Archive.resx @@ -17,6 +17,7 @@ Nothing would change.long The archive must be online and writable.long Wait for the dry run.long + Wait until the archive is read.long A search is running; cancel it or wait.long By camera By format diff --git a/i18n/it/Archive.it.resx b/i18n/it/Archive.it.resx index d5250039..cbc765d4 100644 --- a/i18n/it/Archive.it.resx +++ b/i18n/it/Archive.it.resx @@ -17,6 +17,7 @@ Non cambierebbe nulla. L'archivio deve essere raggiungibile e scrivibile. Attendi la simulazione. + Attendi la lettura dell'archivio. Una ricerca è in corso: annullala o attendi. Per fotocamera Per formato diff --git a/src/Titano.App/Editor/EditorException.cs b/src/Titano.App/Editor/EditorException.cs new file mode 100644 index 00000000..dfbfc8a6 --- /dev/null +++ b/src/Titano.App/Editor/EditorException.cs @@ -0,0 +1,11 @@ +using System.IO; + +namespace Titano.App.Editor; + +/// +/// A sequence the editor could not read or store, for a reason the editor words itself in one localized sentence (the +/// sequence is gone, its project cannot be read, the account may not change it, the settings kept changing elsewhere, +/// the frames changed on the server). A toast shows as it is (BRIEF §0.2 rule 6); any +/// other failure is mapped to a catalog sentence by its cause. +/// +public class EditorException(string message, Exception? innerException = null) : IOException(message, innerException); diff --git a/src/Titano.App/Editor/EditorViewModel.cs b/src/Titano.App/Editor/EditorViewModel.cs index 9bcece09..508c7b37 100644 --- a/src/Titano.App/Editor/EditorViewModel.cs +++ b/src/Titano.App/Editor/EditorViewModel.cs @@ -832,12 +832,13 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable /// /// The first failure of a run of failed saves (they are retried until one succeeds); Retry tries at once. Why it - /// failed is one localized sentence (BRIEF §0.2 rule 6); the exception's own text is in the log. + /// failed is one localized sentence (BRIEF §0.2 rule 6): the editor's own (frames changed, changed elsewhere, gone, + /// unreadable, not allowed), else the cause on the server or in the archive; the exception's own text is in the log. /// private void OnSaveFailed(Exception ex) => Shell.ShowToast(new Toast { Title = Loc.L("Editor.Save.Failed"), - Message = Session.IsRemote ? ErrorText.ForServer(ex) : ArchiveFailures.Cause(ex), + Message = ex is EditorException ? ex.Message : Session.IsRemote ? ErrorText.ForServer(ex) : ArchiveFailures.Cause(ex), IsError = true, ActionText = Loc.L("Editor.Save.Retry"), ActionToolTip = Loc.L("Tooltips.Editor.Save.Retry"), diff --git a/src/Titano.App/Editor/ISequenceSource.cs b/src/Titano.App/Editor/ISequenceSource.cs index d13125a3..00e089a2 100644 --- a/src/Titano.App/Editor/ISequenceSource.cs +++ b/src/Titano.App/Editor/ISequenceSource.cs @@ -41,7 +41,7 @@ public interface ISequenceSource : IAsyncDisposable event Action? JobChanged; /// Everything the editor shows of the sequence; read off the UI thread. - /// The project cannot be read (corrupt, or written by a newer Titano). + /// The sequence is gone, or its project cannot be read (corrupt, or written by a newer Titano). Task LoadAsync(CancellationToken cancellationToken); /// @@ -55,6 +55,7 @@ public interface ISequenceSource : IAsyncDisposable /// change made meanwhile by someone else is kept where this edit left the value alone (). /// Returns the stored project. /// + /// The editor's own reason the project was not stored, worded for the user. Task SaveProjectAsync(ProjectSettings project, ProjectSettings basis, CancellationToken cancellationToken); /// Queues an analysis or render job for the sequence; returns the job id. diff --git a/src/Titano.App/Editor/LocalSequenceSource.cs b/src/Titano.App/Editor/LocalSequenceSource.cs index 6395d6be..d688228f 100644 --- a/src/Titano.App/Editor/LocalSequenceSource.cs +++ b/src/Titano.App/Editor/LocalSequenceSource.cs @@ -146,7 +146,7 @@ public sealed class LocalSequenceSource : ISequenceSource throw Missing(); // The settings moved in the index meanwhile (server API): merge again on top of them; the file follows the next write. case SequenceEditOutcome.Conflict when attempt == SaveAttempts: - throw new IOException(Loc.L("Editor.Error.SaveConflict")); + throw new EditorException(Loc.L("Editor.Error.SaveConflict")); } } }, cancellationToken); @@ -175,7 +175,7 @@ public sealed class LocalSequenceSource : ISequenceSource } /// The settings in force: the index copy, else project.json, else defaults. - /// The settings are not a project or come from a newer Titano. + /// The settings are not a project or come from a newer Titano. internal static ProjectSettings ReadProject(Sequence sequence, SequencePaths folder) { var json = sequence.SettingsJson ?? (File.Exists(folder.ProjectPath) ? File.ReadAllText(folder.ProjectPath) : null); @@ -184,9 +184,9 @@ public sealed class LocalSequenceSource : ISequenceSource { return ProjectSettings.FromJson(json); } - catch (JsonException ex) + catch (Exception ex) when (ex is JsonException or InvalidDataException) { - throw new InvalidDataException(Loc.L("Editor.Error.Project"), ex); + throw new EditorException(Loc.L("Editor.Error.Project"), ex); } } @@ -212,5 +212,5 @@ public sealed class LocalSequenceSource : ISequenceSource private void OnJobChanged(Job job) => JobChanged?.Invoke(job); - private static InvalidOperationException Missing() => new(Loc.L("Editor.Error.Missing")); + private static EditorException Missing() => new(Loc.L("Editor.Error.Missing")); } diff --git a/src/Titano.App/Editor/RemoteSequenceSource.cs b/src/Titano.App/Editor/RemoteSequenceSource.cs index c245b805..2eddef12 100644 --- a/src/Titano.App/Editor/RemoteSequenceSource.cs +++ b/src/Titano.App/Editor/RemoteSequenceSource.cs @@ -145,7 +145,7 @@ public sealed class RemoteSequenceSource : ISequenceSource var merged = changedThere ? ProjectMerge.Merge(basis, project, stored) : project; if (ProjectMerge.SameValues(merged, stored)) return merged; if (IsOutdated) throw new ProxiesOutdatedException(Loc.L("Editor.Error.FramesChanged")); - if (_noEditRight) throw new InvalidOperationException(Loc.L("Editor.Error.RemoteReadOnly")); + if (_noEditRight) throw new EditorException(Loc.L("Editor.Error.RemoteReadOnly")); if (changedThere && ProjectMerge.Conflicts(basis, project, stored) is { Count: > 0 } conflicts) throw new ProjectConflictException(Loc.L("Editor.Error.SaveConflict"), stored, conflicts); var hero = merged.HeroFrame == stored.HeroFrame ? (Guid?)null : HeroFrameId(merged); @@ -159,7 +159,7 @@ public sealed class RemoteSequenceSource : ISequenceSource catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.Conflict) { // Changed on the server since this editor read it: merge again on top of the server's settings. - if (attempt == SaveAttempts) throw new IOException(Loc.L("Editor.Error.SaveConflict"), ex); + if (attempt == SaveAttempts) throw new EditorException(Loc.L("Editor.Error.SaveConflict"), ex); var manifest = await Call(() => _api.GetManifestAsync(Id, cancellationToken)); if (!SameFrames(manifest)) throw Outdated(); Volatile.Write(ref _stored, new Stored(Parse(manifest.SettingsJson), manifest.SettingsVersion)); @@ -359,7 +359,7 @@ public sealed class RemoteSequenceSource : ISequenceSource private Guid HeroFrameId(ProjectSettings project) => project.HeroFrame is { } hero && (uint)hero < (uint)_remote.Frames.Count ? _remote.Frames[hero].Id : Guid.Empty; - /// The settings are not a project or come from a newer Titano. + /// The settings are not a project or come from a newer Titano. private static ProjectSettings Parse(string? json) { if (string.IsNullOrWhiteSpace(json)) return new ProjectSettings(); @@ -367,9 +367,9 @@ public sealed class RemoteSequenceSource : ISequenceSource { return ProjectSettings.FromJson(json); } - catch (JsonException ex) + catch (Exception ex) when (ex is JsonException or InvalidDataException) { - throw new InvalidDataException(Loc.L("Editor.Error.Project"), ex); + throw new EditorException(Loc.L("Editor.Error.Project"), ex); } } @@ -398,7 +398,7 @@ public sealed class RemoteSequenceSource : ISequenceSource } catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound) { - throw new InvalidOperationException(Loc.L("Editor.Error.Missing"), ex); + throw new EditorException(Loc.L("Editor.Error.Missing"), ex); } } @@ -423,4 +423,4 @@ public sealed class ProjectConflictException(string message, ProjectSettings ser /// The proxies of a server sequence are for frames the server no longer has (added or removed since they were fetched): /// they must be fetched again before the sequence can be edited. /// -public sealed class ProxiesOutdatedException(string message) : IOException(message); +public sealed class ProxiesOutdatedException(string message) : EditorException(message); diff --git a/src/Titano.App/Library/LibraryActions.cs b/src/Titano.App/Library/LibraryActions.cs index e12c27ed..ae108c17 100644 --- a/src/Titano.App/Library/LibraryActions.cs +++ b/src/Titano.App/Library/LibraryActions.cs @@ -211,7 +211,8 @@ public sealed class LibraryActions(ShellViewModel shell) await client.CreateJobAsync(request); shell.Notify(Loc.L("Library.QueuedServer", JobText.Kind(kind), label)); } - catch (Exception ex) when (ex is TitanoApiException or HttpRequestException or IOException or TaskCanceledException) + // A certificate the server changed since sign-in is refused by the pin, not by the network (UntrustedCertificateException). + catch (Exception ex) when (ex is TitanoApiException or HttpRequestException or IOException or TaskCanceledException or UntrustedCertificateException) { Log.Warning("library", $"Posting a {kind} job to {address} failed", ex); shell.Notify(Loc.L("Library.Post.Failed"), ErrorText.ForServer(ex), isError: true); diff --git a/src/Titano.App/Sections/ArchiveViewModel.cs b/src/Titano.App/Sections/ArchiveViewModel.cs index c8b39f37..f3a9100d 100644 --- a/src/Titano.App/Sections/ArchiveViewModel.cs +++ b/src/Titano.App/Sections/ArchiveViewModel.cs @@ -46,6 +46,10 @@ public sealed class ArchiveViewModel : SectionViewModel private IReadOnlyList _archives = []; private Core.Model.Archive? _archive; private ArchiveAvailability _availability = ArchiveAvailability.Offline; + + /// The archive whose availability, figures and tree were read last: until it is the picked one, nothing acts on them. + private Guid? _readId; + private ArchiveStats? _stats; private int _withoutProxies; private ArchiveTree? _tree; @@ -79,7 +83,7 @@ public sealed class ArchiveViewModel : SectionViewModel _ = LoadAsync(); }; ScanCommand = new AsyncRelayCommand(() => QueueAsync(a => ArchiveJobs.Scan(a)), IsOnline); - RebuildCommand = new AsyncRelayCommand(() => OpenRebuildDialogAsync(), () => _archive is not null); + RebuildCommand = new AsyncRelayCommand(() => OpenRebuildDialogAsync(), IsRead); VerifyCommand = new AsyncRelayCommand(() => QueueAsync(a => ArchiveJobs.Verify(a)), IsOnline); AdoptCommand = new AsyncRelayCommand(AdoptAsync); CopyFolderCommand = new RelayCommand(CopyFolder, () => _archive is not null); @@ -128,11 +132,15 @@ public sealed class ArchiveViewModel : SectionViewModel _orphans = null; if (other) { - // Until the picked archive is read, nothing of the previous one stays actionable: no tree to take a set - // from, no availability to allow a scan. + // 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; - _availability = ArchiveAvailability.Offline; + _stats = null; + _health = []; RebuildRows(); + OnPropertyChanged(string.Empty); CommandManager.InvalidateRequerySuggested(); } _ = LoadAsync(); @@ -425,6 +433,7 @@ public sealed class ArchiveViewModel : SectionViewModel if (!IsShowing(archive)) return; _availability = availability; _stats = stats; + _readId = archive.Id; ShowFigures(stats, withoutProxies); ShowTree(ArchiveTree.Build(archive, availability, sequences)); await LoadRecentAsync(db, archive); @@ -444,7 +453,7 @@ public sealed class ArchiveViewModel : SectionViewModel /// Opens the rebuild dialog (BRIEF §12.5) and counts, off the UI thread, the sidecars the rebuild will read. public async Task OpenRebuildDialogAsync() { - if (_archive is not { } archive || Services.Engine is not { } engine) return null; + if (_archive is not { } archive || !IsRead() || Services.Engine is not { } engine) return null; var dialog = new RebuildDialogViewModel(archive, _availability, _stats?.Sequences ?? 0, async () => { var request = ArchiveJobs.Rebuild(archive); @@ -649,13 +658,19 @@ public sealed class ArchiveViewModel : SectionViewModel // ---------------- Actions ---------------- - private bool IsOnline() => _archive is not null && _availability == ArchiveAvailability.Online; + private bool IsOnline() => IsRead() && _availability == ArchiveAvailability.Online; + + /// The picked archive's availability and figures are known (a slow volume is probed for seconds). + private bool IsRead() => _archive is { } archive && _readId == archive.Id; /// The archive a read started with is still the one picked. private bool IsShowing(Core.Model.Archive archive) => _archive?.Id == archive.Id; /// A command's tooltip, or why it is disabled: these commands write to the archive or read all of it. - private string WhenOnline(string key) => _archive is null || IsOnline() ? Loc.L(key) : Loc.L("Archive.Blocked.NotOnline"); + private string WhenOnline(string key) => + _archive is null || IsOnline() ? Loc.L(key) + : !IsRead() ? Loc.L("Archive.Blocked.Reading") + : Loc.L("Archive.Blocked.NotOnline"); private bool HasSet() => _archive is not null && _tree is not null && Set().Count > 0; @@ -853,7 +868,10 @@ public sealed class ArchiveViewModel : SectionViewModel try { var groups = await Task.Run(() => archives.FindDuplicatesAsync(archive.Id, search.Token), search.Token); - Duplicates = DuplicateRows(groups, await db.Sequences.ListLocationsAsync(archive.Id, search.Token)); + var locations = await db.Sequences.ListLocationsAsync(archive.Id, search.Token); + // Picking another archive cancels the search; one that ended just then is not the picked archive's. + if (!IsShowing(archive)) return; + Duplicates = DuplicateRows(groups, locations); Log.Info("archive", $"Duplicates search in {archive.RootPath}: {groups.Count} group(s)"); } catch (OperationCanceledException) when (search.IsCancellationRequested) @@ -881,7 +899,9 @@ public sealed class ArchiveViewModel : SectionViewModel try { var report = await Task.Run(() => archives.FindOrphansAsync(archive.Id, search.Token), search.Token); - Orphans = OrphanRows(report, await db.Sequences.ListLocationsAsync(archive.Id, search.Token)); + var locations = await db.Sequences.ListLocationsAsync(archive.Id, search.Token); + if (!IsShowing(archive)) return; + Orphans = OrphanRows(report, locations); Log.Info("archive", $"Orphans search in {archive.RootPath}: {report.UnindexedFiles} unlisted, {report.MissingFiles} missing, " + $"{report.MissingSequences.Count} rows without sidecar, {report.UnindexedFolders.Count} new folders"); } diff --git a/tests/Titano.App.Tests/Archive/ArchiveScreenSmokeTests.cs b/tests/Titano.App.Tests/Archive/ArchiveScreenSmokeTests.cs index 9230c40b..54984448 100644 --- a/tests/Titano.App.Tests/Archive/ArchiveScreenSmokeTests.cs +++ b/tests/Titano.App.Tests/Archive/ArchiveScreenSmokeTests.cs @@ -189,6 +189,10 @@ public sealed class ArchiveScreenSmokeTests Assert.Empty(archive.TreeRows); 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); await reading; Assert.Equal(second.Id, archive.SelectedArchive!.Id); @@ -196,6 +200,13 @@ public sealed class ArchiveScreenSmokeTests Assert.True(archive.TreeRows[0].IsArchive); Assert.False(archive.TreeRows.Any(r => r.Node.Kind == TreeNodeKind.Sequence), "the tree is the picked, empty archive's"); Assert.True(archive.ScanCommand.CanExecute(null), "the picked archive was probed: it is online"); + Assert.Equal(Loc.L("Tooltips.Archive.Scan"), archive.ScanToolTip); + Assert.True(archive.RebuildCommand.CanExecute(null)); + var rebuild = Assert.NotNull(await archive.OpenRebuildDialogAsync()); + Assert.Equal(second.Id, rebuild.Archive.Id); + Assert.Equal(ArchiveAvailability.Online, rebuild.Availability, "the dialog shows the picked archive's availability"); + Assert.Equal(0, rebuild.Indexed, "and its own index, not the first archive's"); + rebuild.CloseCommand.Execute(null); }); [Test] diff --git a/tests/Titano.App.Tests/Editor/EditorSmokeTests.cs b/tests/Titano.App.Tests/Editor/EditorSmokeTests.cs index b5afc462..70ccf97b 100644 --- a/tests/Titano.App.Tests/Editor/EditorSmokeTests.cs +++ b/tests/Titano.App.Tests/Editor/EditorSmokeTests.cs @@ -1,5 +1,6 @@ using System.Collections.Specialized; using System.Globalization; +using System.IO; using System.Net.Http; using System.Windows; using System.Windows.Controls; @@ -255,6 +256,7 @@ public sealed class EditorSmokeTests } // A failed save says why in one localized sentence (BRIEF §0.2 rule 6); the exception's own text stays in the log. + // The editor's own reasons keep their sentence (they are I/O failures too, which would read "does not answer"). var toasts = new List(); NotifyCollectionChangedEventHandler collect = (_, e) => toasts.AddRange(e.NewItems?.OfType() ?? []); shell.PendingToasts.CollectionChanged += collect; @@ -264,6 +266,10 @@ public sealed class EditorSmokeTests { (true, new HttpRequestException("No such host is known."), "Server.Error.Unreachable"), (false, new UnauthorizedAccessException(@"Access to the path 'D:\Archive\.titano\sequence.json' is denied."), "Archive.Failed.Access"), + (true, new ProxiesOutdatedException(Loc.L("Editor.Error.FramesChanged")), "Editor.Error.FramesChanged"), + (true, new EditorException(Loc.L("Editor.Error.RemoteReadOnly")), "Editor.Error.RemoteReadOnly"), + (false, new EditorException(Loc.L("Editor.Error.SaveConflict")), "Editor.Error.SaveConflict"), + (false, new EditorException(Loc.L("Editor.Error.Project"), new InvalidDataException("project.json version 9 is newer")), "Editor.Error.Project"), }) { toasts.Clear(); diff --git a/tests/Titano.App.Tests/Editor/ProjectStoreTests.cs b/tests/Titano.App.Tests/Editor/ProjectStoreTests.cs index 448c8e1d..ab55c4a9 100644 --- a/tests/Titano.App.Tests/Editor/ProjectStoreTests.cs +++ b/tests/Titano.App.Tests/Editor/ProjectStoreTests.cs @@ -4,6 +4,7 @@ using Titano.Core.Archiving; using Titano.Core.Codecs.Jpeg; using Titano.Core.Imaging; using Titano.Core.Imaging.Decoders; +using Titano.Core.Localization; using Titano.Core.Metadata; using Titano.Core.Model; using Titano.Core.Project; @@ -147,7 +148,8 @@ public sealed class ProjectStoreTests(TestContext context) new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) }); var content = await source.LoadAsync(context.Cancellation); Assert.True(await db.Sequences.DeleteAsync(sequenceId)); - await Assert.ThrowsAsync(() => source.SaveProjectAsync(content.Project with { HeroFrame = 1 }, content.Project, context.Cancellation)); + var gone = await Assert.ThrowsAsync(() => source.SaveProjectAsync(content.Project with { HeroFrame = 1 }, content.Project, context.Cancellation)); + Assert.Equal(Loc.L("Editor.Error.Missing"), gone.Message, "the toast shows the editor's own sentence"); } } @@ -178,8 +180,15 @@ public sealed class ProjectStoreTests(TestContext context) var path = Path.Combine(root, "Synthetic", ".titano", "project.json"); File.WriteAllText(path, "{ not json"); await using var source = new LocalSequenceSource(db, sequenceId, DecoderFactory.CreateClient(null), null); - await Assert.ThrowsAsync(() => source.LoadAsync(context.Cancellation)); + var unreadable = await Assert.ThrowsAsync(() => source.LoadAsync(context.Cancellation)); + Assert.Equal(Loc.L("Editor.Error.Project"), unreadable.Message); Assert.Equal("{ not json", File.ReadAllText(path)); + + // A project written by a newer Titano reads the same, not as the parser's English sentence. + var newer = $"{{\"version\":{ProjectSettings.CurrentVersion + 1}}}"; + File.WriteAllText(path, newer); + Assert.Equal(Loc.L("Editor.Error.Project"), (await Assert.ThrowsAsync(() => source.LoadAsync(context.Cancellation))).Message); + Assert.Equal(newer, File.ReadAllText(path)); } } diff --git a/tests/Titano.App.Tests/Editor/RemoteSequenceSourceTests.cs b/tests/Titano.App.Tests/Editor/RemoteSequenceSourceTests.cs index 2daeb97a..1ef3ec8a 100644 --- a/tests/Titano.App.Tests/Editor/RemoteSequenceSourceTests.cs +++ b/tests/Titano.App.Tests/Editor/RemoteSequenceSourceTests.cs @@ -5,6 +5,7 @@ using Titano.Core.Codecs.Jpeg; using Titano.Core.Diagnostics.Synthetic; using Titano.Core.Imaging; using Titano.Core.Imaging.Decoders; +using Titano.Core.Localization; using Titano.Core.Model; using Titano.Core.Project; using Titano.Data.Processing; @@ -229,7 +230,8 @@ public sealed class RemoteSequenceSourceTests(TestContext context) return (theirs with { Camera = theirs.Camera with { OffsetX = offset } }).ToJson(); }); } - await Assert.ThrowsAsync(() => source.SaveProjectAsync(content.Project with { HeroFrame = 2 }, content.Project, context.Cancellation)); + var conflict = await Assert.ThrowsAsync(() => source.SaveProjectAsync(content.Project with { HeroFrame = 2 }, content.Project, context.Cancellation)); + Assert.Equal(Loc.L("Editor.Error.SaveConflict"), conflict.Message, "the toast shows the editor's own sentence"); Assert.False(api.Edits.Any(e => e.Accepted)); } } @@ -268,8 +270,9 @@ public sealed class RemoteSequenceSourceTests(TestContext context) } // The source refuses a change as well; the same project is no change. - await Assert.ThrowsAsync(() => + var refused = await Assert.ThrowsAsync(() => source.SaveProjectAsync(content.Project with { HeroFrame = 1 }, content.Project, context.Cancellation)); + Assert.Equal(Loc.L("Editor.Error.RemoteReadOnly"), refused.Message); Assert.True(ProjectMerge.SameValues(content.Project, await source.SaveProjectAsync(content.Project, content.Project, context.Cancellation))); Assert.Empty(api.Edits); } @@ -366,8 +369,9 @@ public sealed class RemoteSequenceSourceTests(TestContext context) { var content = await source.LoadAsync(context.Cancellation); api.Gone = true; - await Assert.ThrowsAsync(() => source.LoadAsync(context.Cancellation)); - await Assert.ThrowsAsync(() => source.SaveProjectAsync(content.Project with { HeroFrame = 1 }, content.Project, context.Cancellation)); + Assert.Equal(Loc.L("Editor.Error.Missing"), (await Assert.ThrowsAsync(() => source.LoadAsync(context.Cancellation))).Message); + var gone = await Assert.ThrowsAsync(() => source.SaveProjectAsync(content.Project with { HeroFrame = 1 }, content.Project, context.Cancellation)); + Assert.Equal(Loc.L("Editor.Error.Missing"), gone.Message); } } diff --git a/tests/Titano.App.Tests/Library/LibraryScreenSmokeTests.cs b/tests/Titano.App.Tests/Library/LibraryScreenSmokeTests.cs index 56bc15f1..90c693b2 100644 --- a/tests/Titano.App.Tests/Library/LibraryScreenSmokeTests.cs +++ b/tests/Titano.App.Tests/Library/LibraryScreenSmokeTests.cs @@ -1,3 +1,4 @@ +using System.Collections.Specialized; using System.Windows; using System.Windows.Controls; using System.Windows.Input; @@ -9,7 +10,9 @@ using Titano.App.Sections; using Titano.App.Shell; using Titano.App.Tests.Windows; using Titano.Core.Localization; +using Titano.Core.Model; using Titano.Testing; +using Titano.Ui.Controls; using Titano.Ui.Visuals; namespace Titano.App.Tests.Library; @@ -180,6 +183,46 @@ public sealed class LibraryScreenSmokeTests static string Readout(LibraryViewModel library) => library.TimelineBands[0].ToolTips!.First(t => !string.IsNullOrEmpty(t))!; }); + /// + /// A remote card's Analyse posted to a server whose certificate changed since sign-in: the pin refuses it before + /// anything is sent, and the error toast says so (it used to escape the action unreported). + /// + [Test] + public Task APostRefusedByThePinnedCertificateSaysSo() => ScreenHost.RunAsync(async () => + { + using var server = new UntrustedTlsEndpoint(); + await using var app = await ScreenSmokeTests.SampleApp.StartAsync(); + await app.Sample.FillAsync(); + app.Services.Settings.ServerUrl = server.Address.ToString(); + await app.Shell.Services.Server.RestoreAsync(); + var actions = new LibraryActions(app.Shell); + Assert.True(actions.CanPost, "signed in to the endpoint (the sample's own certificate was trusted at sign-in)"); + + var toasts = new List(); + NotifyCollectionChangedEventHandler collect = (_, e) => toasts.AddRange(e.NewItems?.OfType() ?? []); + app.Shell.PendingToasts.CollectionChanged += collect; + try + { + var remote = new Sequence + { + Id = Guid.CreateVersion7(), + ArchiveId = Guid.Empty, + Folder = "Harbour", + Title = "Harbour sunset", + Origin = SequenceOrigin.Server, + SyncState = SyncState.RemoteOnly, + }; + await actions.AnalyseAsync([remote]); + } + finally + { + app.Shell.PendingToasts.CollectionChanged -= collect; + } + var toast = Assert.Contains(toasts, t => t.Title == Loc.L("Library.Post.Failed")); + Assert.Equal(Loc.L("Server.Error.Untrusted"), toast.Message); + Assert.True(toast.IsError); + }); + private static void Press(UIElement target, Key key) => target.RaiseEvent(new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual(target)!, 0, key) { RoutedEvent = Keyboard.KeyDownEvent }); diff --git a/tests/Titano.App.Tests/Library/UntrustedTlsEndpoint.cs b/tests/Titano.App.Tests/Library/UntrustedTlsEndpoint.cs new file mode 100644 index 00000000..fe2348eb --- /dev/null +++ b/tests/Titano.App.Tests/Library/UntrustedTlsEndpoint.cs @@ -0,0 +1,78 @@ +using System.IO; +using System.Net; +using System.Net.Security; +using System.Net.Sockets; +using System.Security.Authentication; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; + +namespace Titano.App.Tests.Library; + +/// +/// A TLS endpoint on loopback with a self-signed certificate no client trusted (a server whose certificate changed since +/// sign-in): the client's pinning refuses every handshake, so nothing is ever sent. +/// +internal sealed class UntrustedTlsEndpoint : IDisposable +{ + private readonly TcpListener _listener = new(IPAddress.Loopback, 0); + private readonly X509Certificate2 _certificate; + private readonly CancellationTokenSource _stop = new(); + private readonly Task _accepting; + + public UntrustedTlsEndpoint() + { + using var key = RSA.Create(2048); + var request = new CertificateRequest("CN=127.0.0.1", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + using var created = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1)); + // Schannel serves only a certificate whose key it can open: a PKCS #12 round trip gives it one. + _certificate = X509CertificateLoader.LoadPkcs12(created.Export(X509ContentType.Pkcs12), null); + _listener.Start(); + _accepting = Task.Run(AcceptAsync); + } + + public Uri Address => new($"https://127.0.0.1:{((IPEndPoint)_listener.LocalEndpoint).Port}/"); + + public void Dispose() + { + _stop.Cancel(); + _listener.Stop(); + try + { + _accepting.Wait(TimeSpan.FromSeconds(5)); + } + catch (AggregateException) + { + // The loop ends with the listener; how it ended does not matter. + } + _certificate.Dispose(); + _stop.Dispose(); + } + + private async Task AcceptAsync() + { + while (!_stop.IsCancellationRequested) + { + TcpClient client; + try + { + client = await _listener.AcceptTcpClientAsync(_stop.Token); + } + catch (Exception ex) when (ex is OperationCanceledException or SocketException or ObjectDisposedException) + { + return; + } + using (client) + { + try + { + await using var tls = new SslStream(client.GetStream()); + await tls.AuthenticateAsServerAsync(new SslServerAuthenticationOptions { ServerCertificate = _certificate }, _stop.Token); + } + catch (Exception ex) when (ex is AuthenticationException or IOException or OperationCanceledException or SocketException) + { + // The client refused the certificate: the handshake ends here, as intended. + } + } + } + } +}