Titano: time-lapse ecosystem (client, server, uploader) — in progress #1

Merged
Alby96 merged 204 commits from claude/keen-knuth-uhxv8w into main 2026-10-02 16:29:53 +02:00
6 changed files with 115 additions and 45 deletions
Showing only changes of commit 9fd7ac0d36 - Show all commits

No files matched your search

+1
View File
@@ -4,6 +4,7 @@
<resheader name="version"><value>2.0</value></resheader>
<resheader name="reader"><value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
<resheader name="writer"><value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
<data name="Errors.Archive.Open" xml:space="preserve"><value>The archive could not be opened.</value><comment>long</comment></data>
<data name="Errors.Number.Range" xml:space="preserve"><value>Enter a whole number from {0} to {1}.</value></data>
<data name="Errors.Path.Empty" xml:space="preserve"><value>Enter a folder.</value></data>
<data name="Errors.Path.Invalid" xml:space="preserve"><value>This is not a valid folder path.</value></data>
+1
View File
@@ -4,6 +4,7 @@
<resheader name="version"><value>2.0</value></resheader>
<resheader name="reader"><value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
<resheader name="writer"><value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
<data name="Errors.Archive.Open" xml:space="preserve"><value>Impossibile aprire l'archivio.</value></data>
<data name="Errors.Number.Range" xml:space="preserve"><value>Inserisci un numero intero da {0} a {1}.</value></data>
<data name="Errors.Path.Empty" xml:space="preserve"><value>Inserisci una cartella.</value></data>
<data name="Errors.Path.Invalid" xml:space="preserve"><value>Questo non è un percorso di cartella valido.</value></data>
+69 -21
View File
@@ -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;
/// <summary>
/// Composition root of local mode (BRIEF §4.4): the SQLite index under the data folder (migrated on open), the one
/// <see cref="JobEngine"/> of this PC with the handlers of <see cref="CreateJobHandlers"/>, 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 <see cref="JobEngine"/> of this PC with the handlers of
/// <see cref="CreateJobHandlers"/>, 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 <see cref="ScanInterval"/> (BRIEF §7: polling, no file-system watchers).
/// </summary>
/// <remarks>
/// Integration points (one place each):
/// <list type="bullet">
/// <item><see cref="CreateJobHandlers"/> — register the archive handlers (scan, rebuild, verify, adopt, …) and the
/// render handler here.</item>
/// <item><see cref="ArchiveSetup"/> — replace <see cref="LocalArchiveSetup"/> with the archive engine's
/// implementation (it receives the first-run choices: create a local archive, adopt a folder).</item>
/// </list>
/// </remarks>
public sealed class AppServices : IAsyncDisposable
{
public static readonly TimeSpan ScanInterval = TimeSpan.FromMinutes(10);
private static readonly Lazy<HttpClient> Http = new(() => new HttpClient { Timeout = TimeSpan.FromSeconds(20) });
private readonly CancellationTokenSource _stopping = new();
private readonly Dictionary<Guid, Guid> _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; }
/// <summary>First-run archive actions; replaced by the integrator with the archive engine's implementation.</summary>
/// <summary>First-run and Library archive actions.</summary>
public IArchiveSetup ArchiveSetup { get; set; }
/// <summary>The archive engine; null until the index is open.</summary>
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<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "0.0.0";
/// <summary>
/// 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).
/// </summary>
/// <summary>The job handlers of this PC's engine — the single registration list; a kind without a handler stays
/// queued (it is never claimed here).</summary>
public static IReadOnlyList<IJobHandler> CreateJobHandlers(AppServices services) =>
[
];
services.Archives?.CreateJobHandlers() ?? [];
/// <summary>Queues a scan of <paramref name="archive"/> unless one is already waiting or running.</summary>
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);
}
/// <summary>Uses an already open index (capture, tests) instead of opening one; sample data keeps the engine stopped.</summary>
@@ -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();
}
/// <summary>Reopens the last archive (relinking a moved one, finishing interrupted renames) and rescans it periodically.</summary>
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 });
+41 -20
View File
@@ -1,12 +1,11 @@
using System.IO;
using Titano.Core.Diagnostics;
using Titano.Data.Archiving;
namespace Titano.App.Infrastructure;
/// <summary>
/// First-run archive choices (BRIEF §12.1): create a local archive or adopt an existing folder tree. The
/// integrator replaces <see cref="LocalArchiveSetup"/> with an implementation backed by the archive engine (folder
/// layout, index, adopt job); see <see cref="AppServices"/>.
/// First-run and Library archive choices (BRIEF §12.1): create a local archive or adopt an existing folder tree.
/// </summary>
public interface IArchiveSetup
{
@@ -17,27 +16,49 @@ public interface IArchiveSetup
Task AdoptAsync(string folder, CancellationToken cancellationToken = default);
}
/// <summary>Until the archive engine is connected: remembers the chosen root in the settings and nothing else.</summary>
public sealed class LocalArchiveSetup(AppSettings settings, Action save) : IArchiveSetup
/// <summary>
/// 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.
/// </summary>
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}");
}
}
/// <summary>Runs an archive action from the UI; a failure becomes a toast instead of an unhandled exception.</summary>
public static class ArchiveActions
{
public static async Task<bool> TryAsync(Shell.ShellViewModel shell, Func<IArchiveSetup, Task> 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;
}
}
}
+1 -2
View File
@@ -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();
}
/// <summary>Writes the selected rows as CSV (UTF-8, invariant numbers) into a chosen folder.</summary>
+2 -2
View File
@@ -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;