diff --git a/i18n/en/Errors.resx b/i18n/en/Errors.resx index 2c90ab45..a57f5095 100644 --- a/i18n/en/Errors.resx +++ b/i18n/en/Errors.resx @@ -4,6 +4,7 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + The archive could not be opened.long Enter a whole number from {0} to {1}. Enter a folder. This is not a valid folder path. diff --git a/i18n/it/Errors.it.resx b/i18n/it/Errors.it.resx index 44442694..d3b8318d 100644 --- a/i18n/it/Errors.it.resx +++ b/i18n/it/Errors.it.resx @@ -4,6 +4,7 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Impossibile aprire l'archivio. Inserisci un numero intero da {0} a {1}. Inserisci una cartella. Questo non è un percorso di cartella valido. diff --git a/src/Titano.App/Infrastructure/AppServices.cs b/src/Titano.App/Infrastructure/AppServices.cs index 7e000a70..f366bf3e 100644 --- a/src/Titano.App/Infrastructure/AppServices.cs +++ b/src/Titano.App/Infrastructure/AppServices.cs @@ -1,3 +1,4 @@ +using System.IO; using System.Net.Http; using System.Reflection; using Titano.App.About; @@ -5,30 +6,32 @@ using Titano.App.Jobs; using Titano.App.Library; using Titano.App.Server; using Titano.App.Settings; +using Titano.Core.Archiving; using Titano.Core.Diagnostics; +using Titano.Core.Imaging.Decoders; +using Titano.Core.Model; +using Titano.Core.Windows.Wic; using Titano.Data; +using Titano.Data.Archiving; using Titano.Data.Jobs; namespace Titano.App.Infrastructure; /// -/// Composition root of local mode (BRIEF §4.4): the SQLite index under the data folder (migrated on open), the one -/// of this PC with the handlers of , thumbnails, the server -/// session, the encoder inventory, the update check and the archive setup. Started after the window shows, stopped -/// when the app exits. +/// Composition root of local mode (BRIEF §4.4): the SQLite index under the data folder (migrated on open), the +/// archive engine (WIC first, then managed decoders), the one of this PC with the handlers of +/// , thumbnails, the server session, the encoder inventory and the update check. +/// Started after the window shows, stopped when the app exits. The last archive is reopened at start and rescanned +/// every (BRIEF §7: polling, no file-system watchers). /// -/// -/// Integration points (one place each): -/// -/// — register the archive handlers (scan, rebuild, verify, adopt, …) and the -/// render handler here. -/// — replace with the archive engine's -/// implementation (it receives the first-run choices: create a local archive, adopt a folder). -/// -/// public sealed class AppServices : IAsyncDisposable { + public static readonly TimeSpan ScanInterval = TimeSpan.FromMinutes(10); + private static readonly Lazy Http = new(() => new HttpClient { Timeout = TimeSpan.FromSeconds(20) }); + private readonly CancellationTokenSource _stopping = new(); + private readonly Dictionary _scans = []; + private Task _polling = Task.CompletedTask; public AppServices(AppEnvironment environment, AppSettings settings, Action saveSettings, IAppDialogs dialogs) { @@ -36,7 +39,7 @@ public sealed class AppServices : IAsyncDisposable Settings = settings; SaveSettingsAction = saveSettings; Dialogs = dialogs; - ArchiveSetup = new LocalArchiveSetup(settings, saveSettings); + ArchiveSetup = new EngineArchiveSetup(this); Server = new ServerSession(settings, saveSettings, new TitanoServerApiFactory(), new DpapiTokenProtector()); Encoders = new MediaFoundationInventory(); CheckForUpdateAsync = ct => UpdateCheck.FetchAsync(Http.Value, ProductLinks.LatestReleaseApi, VersionText, ct); @@ -48,9 +51,12 @@ public sealed class AppServices : IAsyncDisposable private Action SaveSettingsAction { get; } - /// First-run archive actions; replaced by the integrator with the archive engine's implementation. + /// First-run and Library archive actions. public IArchiveSetup ArchiveSetup { get; set; } + /// The archive engine; null until the index is open. + public ArchiveService? Archives { get; private set; } + public ServerSession Server { get; set; } public IEncoderInventory Encoders { get; set; } @@ -77,13 +83,27 @@ public sealed class AppServices : IAsyncDisposable public static string VersionText { get; } = typeof(AppServices).Assembly.GetCustomAttribute()?.InformationalVersion ?? "0.0.0"; - /// - /// The job handlers of this PC's engine — the single registration list. The integrator adds the archive - /// handlers and the render handler here; a kind without a handler stays queued (it is never claimed here). - /// + /// The job handlers of this PC's engine — the single registration list; a kind without a handler stays + /// queued (it is never claimed here). public static IReadOnlyList CreateJobHandlers(AppServices services) => - [ - ]; + services.Archives?.CreateJobHandlers() ?? []; + + /// Queues a scan of unless one is already waiting or running. + public async Task QueueScanAsync(Archive archive, bool full, CancellationToken ct = default) + { + if (Engine is null || Database is null) return; + Guid previous; + lock (_scans) + { + _scans.TryGetValue(archive.Id, out previous); + } + if (previous != Guid.Empty && await Database.Jobs.GetAsync(previous, ct) is { State: JobState.Queued or JobState.Running }) return; + var job = await Engine.EnqueueAsync(ArchiveJobs.Scan(archive, full), cancellationToken: ct); + lock (_scans) + { + _scans[archive.Id] = job.Id; + } + } public void SaveSettings() => SaveSettingsAction(); @@ -103,6 +123,7 @@ public sealed class AppServices : IAsyncDisposable } await StartJobsAsync(Database, startEngine: true, ct); Thumbnails = new ThumbnailService(Database, Settings.ThumbnailMemoryItems); + if (Settings.LastArchivePath is { Length: > 0 } root) _polling = PollAsync(root, _stopping.Token); } /// Uses an already open index (capture, tests) instead of opening one; sample data keeps the engine stopped. @@ -115,6 +136,9 @@ public sealed class AppServices : IAsyncDisposable public async ValueTask DisposeAsync() { + await _stopping.CancelAsync(); + await _polling; + _stopping.Dispose(); (Jobs as IDisposable)?.Dispose(); if (Engine is not null) await Engine.DisposeAsync(); Thumbnails?.Dispose(); @@ -122,8 +146,32 @@ public sealed class AppServices : IAsyncDisposable if (Database is not null) await Database.DisposeAsync(); } + /// Reopens the last archive (relinking a moved one, finishing interrupted renames) and rescans it periodically. + private async Task PollAsync(string root, CancellationToken ct) + { + try + { + if (Archives is null) return; + var archive = await Task.Run(() => Archives.OpenAsync(root, ct), ct); + using var timer = new PeriodicTimer(ScanInterval); + do + { + if (ArchiveService.GetAvailability(archive) == ArchiveAvailability.Online) await QueueScanAsync(archive, full: false, ct); + } + while (await timer.WaitForNextTickAsync(ct)); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException) + { + Log.Warning("archive", $"The archive at {root} could not be opened", ex); + } + } + private async Task StartJobsAsync(TitanoDatabase database, bool startEngine, CancellationToken ct) { + Archives = new ArchiveService(database, new ArchiveServiceOptions { Decoder = DecoderFactory.CreateClient(new WicDecoderProvider()) }); var handlers = CreateJobHandlers(this); var kinds = handlers.Select(h => h.Kind).Distinct().ToArray(); Engine = new JobEngine(database, handlers, new JobEngineOptions { WorkerId = WorkerId, Kinds = kinds }); diff --git a/src/Titano.App/Infrastructure/ArchiveSetup.cs b/src/Titano.App/Infrastructure/ArchiveSetup.cs index 92975647..15b3672c 100644 --- a/src/Titano.App/Infrastructure/ArchiveSetup.cs +++ b/src/Titano.App/Infrastructure/ArchiveSetup.cs @@ -1,12 +1,11 @@ using System.IO; using Titano.Core.Diagnostics; +using Titano.Data.Archiving; namespace Titano.App.Infrastructure; /// -/// First-run archive choices (BRIEF §12.1): create a local archive or adopt an existing folder tree. The -/// integrator replaces with an implementation backed by the archive engine (folder -/// layout, index, adopt job); see . +/// First-run and Library archive choices (BRIEF §12.1): create a local archive or adopt an existing folder tree. /// public interface IArchiveSetup { @@ -17,27 +16,49 @@ public interface IArchiveSetup Task AdoptAsync(string folder, CancellationToken cancellationToken = default); } -/// Until the archive engine is connected: remembers the chosen root in the settings and nothing else. -public sealed class LocalArchiveSetup(AppSettings settings, Action save) : IArchiveSetup +/// +/// Creates or adopts the archive through the archive engine (originals stay where they are), remembers it as the +/// archive to open at start and queues a full scan that indexes its sequences. +/// +public sealed class EngineArchiveSetup(AppServices services) : IArchiveSetup { - public Task CreateAsync(string root, CancellationToken cancellationToken = default) - { - Remember(root); - Log.Info("archive", $"Local archive root set to {root}"); - return Task.CompletedTask; - } + public Task CreateAsync(string root, CancellationToken cancellationToken = default) => OpenAsync(root, cancellationToken); - public Task AdoptAsync(string folder, CancellationToken cancellationToken = default) - { - Remember(folder); - Log.Info("archive", $"Adopted folder recorded: {folder}"); - return Task.CompletedTask; - } + public Task AdoptAsync(string folder, CancellationToken cancellationToken = default) => OpenAsync(folder, cancellationToken); - private void Remember(string path) + private async Task OpenAsync(string path, CancellationToken cancellationToken) { - settings.LastArchivePath = Path.GetFullPath(path); - save(); + var archives = services.Archives ?? throw new InvalidOperationException("The index is not open.", services.OpenError); + var root = Path.GetFullPath(path); + var archive = await Task.Run(async () => + { + Directory.CreateDirectory(root); + return await archives.AdoptAsync(root, null, cancellationToken).ConfigureAwait(false); + }, cancellationToken); + services.Settings.LastArchivePath = root; + services.SaveSettings(); + await services.QueueScanAsync(archive, full: true, cancellationToken); + Log.Info("archive", $"Archive {archive.Name} ready at {root}"); + } +} + +/// Runs an archive action from the UI; a failure becomes a toast instead of an unhandled exception. +public static class ArchiveActions +{ + public static async Task TryAsync(Shell.ShellViewModel shell, Func action) + { + try + { + await action(shell.Services.ArchiveSetup); + return true; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException or InvalidDataException + or Data.DatabaseException) + { + Log.Error("archive", "Archive action failed", ex); + shell.Notify(Core.Localization.Loc.L("Errors.Archive.Open"), ex.Message); + return false; + } } } diff --git a/src/Titano.App/Sections/LibraryViewModel.cs b/src/Titano.App/Sections/LibraryViewModel.cs index dd45491d..f1072311 100644 --- a/src/Titano.App/Sections/LibraryViewModel.cs +++ b/src/Titano.App/Sections/LibraryViewModel.cs @@ -538,8 +538,7 @@ public sealed class LibraryViewModel : SectionViewModel { var folder = Shell.Services.Dialogs.PickFolder(Loc.L("Library.Adopt.Title")); if (folder is null) return; - await Shell.Services.ArchiveSetup.AdoptAsync(folder); - await RefreshAsync(); + if (await ArchiveActions.TryAsync(Shell, s => s.AdoptAsync(folder))) await RefreshAsync(); } /// Writes the selected rows as CSV (UTF-8, invariant numbers) into a chosen folder. diff --git a/src/Titano.App/Sections/WelcomeViewModel.cs b/src/Titano.App/Sections/WelcomeViewModel.cs index 91a727b5..c5fcf375 100644 --- a/src/Titano.App/Sections/WelcomeViewModel.cs +++ b/src/Titano.App/Sections/WelcomeViewModel.cs @@ -207,11 +207,11 @@ public sealed class WelcomeViewModel : LocalizedViewModel _shell.Notify(problem); return; } - await _shell.Services.ArchiveSetup.CreateAsync(LocalRoot); + if (!await ArchiveActions.TryAsync(_shell, s => s.CreateAsync(LocalRoot))) return; break; case WelcomeChoice.AdoptFolder: if (_adoptFolder is null && !PickAdoptFolder()) return; - await _shell.Services.ArchiveSetup.AdoptAsync(_adoptFolder!); + if (!await ArchiveActions.TryAsync(_shell, s => s.AdoptAsync(_adoptFolder!))) return; break; case WelcomeChoice.Server: if (FoundServer is { } server) _shell.Server.Address = server.Address;