diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx index 1d5c8702..fcb3a77b 100644 --- a/i18n/en/Tooltips.resx +++ b/i18n/en/Tooltips.resx @@ -54,6 +54,43 @@ Collapse navigation to icons Show navigation names Stop the current job · it can be resumed later + Add a folder to watch + Pick files, a folder or a card + Pick one or more photos + Pick a folder or a card; every photo inside is added + Do not connect to this server + Choose the sequence + Close settings + Delete each source file once the server has verified it + Delete the local file only after the server has confirmed its hash; asks before turning on + Titano Server found on this network · click to use it + SHA-256 fingerprint of the server certificate + Leave source files where they are + Bandwidth limit in MB/s; 0 means no limit + Closing the window keeps the uploader running in the tray + Title of the new sequence; leave empty to let the server name it + Your password; only a sign-in token is kept, encrypted for your Windows account + Pause; the queue survives a restart + Space left in your quota on the server + Stop watching this folder; files already uploaded stay on the server + Resume uploading + Try again + Try this file again now + Address of the Titano Server, such as https://nas.local:8443 + Server, sign in, bandwidth, startup, tray + Check the server certificate and sign in + Sign out and forget the saved token + Run when you sign in to Windows + Stop and clear the queue; uploaded files stay on the server + Create one new sequence with a title you type + Add every file to one existing sequence + The server splits the files into sessions and creates the sequences + Remember this certificate; trust it only if the fingerprint matches the one on the server + Your user name on the Titano Server + Checked every {0}; a file is uploaded once it has stopped growing · click to change or remove + The folder cannot be reached; it is checked again every {0} · click to change or remove + Network share; polled every {0} because change notifications are unreliable on SMB · click to change or remove + Check the folder at this interval Close Maximize Minimize diff --git a/i18n/en/Uploader.resx b/i18n/en/Uploader.resx new file mode 100644 index 00000000..4dbacf76 --- /dev/null +++ b/i18n/en/Uploader.resx @@ -0,0 +1,107 @@ + + + text/microsoft-resx + 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 + Add folder + Close + Pause + Resume + Retry + Stop + Titano Uploaderinvariant + All files + Browse… + Files… + Add photos + Folder or card… + Folder or card + Photos + Watch a folder + https://nas.local:8443invariant + Wrong user name or password.long + The server reported an error.long + Enter an address such as https://nas.local:8443.long + This address is not a Titano Server.long + The server did not answer.long + The server certificate was not trusted.long + Found + Password + Server + Sign in + Connect to server + User + Delete after upload + Keep files + Each file is deleted from this PC only after the server has verified its hash.long + Delete source files? + Drop photos, folders or a card herelong + The file changed while it was read.long + The file is no longer there.long + The file could not be read.long + The server refused the file: {0}long + The upload failed; the log has the details.long + Not connected + {0} free of {1} + Limit + MB/sinvariant + Delete after upload + Minimise to tray + Start with Windows + {0:N0} failed + {0:N0} retry + {0:N0} retries + {0:N0} of {1:N0} sent + {0:N0} verified by the server + Done + Nothing queued + {0:N0} file + {0:N0} files + Queue + {0} left + Paused + Waiting for server + Bandwidth + Files + Server + Sign out + Startup + Settings + User + Failed + Hashing + Queued + On server + Uploading + Verified + Connected + Offline + Signed out + Signing in + Target + New + Sequence + Group into sessions + Title + {0:N0} file added + {0:N0} files added + The server certificate changed.long + Choose a sequence first. + No new photos were found there.long + The server ended the session.long + {0:N0} file verified by the serverlong + {0:N0} files verified by the serverlong + Upload complete + Exit + Show + Trust + Cancel + Compare this fingerprint with the one shown on the server.long + Trust this server? + {0}/s + {0} · every {1} + Every {0} + Watch folders + Remove + diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx index ca09ebc5..039162d1 100644 --- a/i18n/it/Tooltips.it.resx +++ b/i18n/it/Tooltips.it.resx @@ -54,6 +54,43 @@ Riduci la navigazione alle icone Mostra i nomi della navigazione Ferma l'attività in corso · potrai riprenderla + Aggiungi una cartella da controllare + Scegli file, una cartella o una scheda + Scegli una o più foto + Scegli una cartella o una scheda; vengono aggiunte tutte le foto contenute + Non connetterti a questo server + Scegli la sequenza + Chiudi le impostazioni + Elimina ogni file originale dopo la verifica del server + Elimina il file locale solo dopo che il server ne ha confermato l'hash; chiede conferma prima di attivarsi + Titano Server trovato in questa rete · fai clic per usarlo + Impronta SHA-256 del certificato del server + Lascia i file originali dove sono + Limite di banda in MB/s; 0 significa nessun limite + Chiudendo la finestra l'uploader resta attivo nell'area di notifica + Titolo della nuova sequenza; lascialo vuoto per farlo scegliere al server + La tua password; viene conservato solo un token di accesso, cifrato per il tuo account Windows + Metti in pausa; la coda sopravvive a un riavvio + Spazio rimasto nella tua quota sul server + Smetti di controllare questa cartella; i file già inviati restano sul server + Riprendi l'invio + Riprova + Riprova subito questo file + Indirizzo del Titano Server, ad esempio https://nas.local:8443 + Server, accesso, banda, avvio, area di notifica + Controlla il certificato del server e accedi + Esci e dimentica il token salvato + Avvia quando accedi a Windows + Ferma e svuota la coda; i file inviati restano sul server + Crea una nuova sequenza con il titolo che scrivi + Aggiungi tutti i file a una sequenza esistente + Il server divide i file in sessioni e crea le sequenze + Ricorda questo certificato; accettalo solo se l'impronta coincide con quella sul server + Il tuo nome utente sul Titano Server + Controllata ogni {0}; un file viene inviato quando smette di crescere · fai clic per modificare o rimuovere + La cartella non è raggiungibile; viene ricontrollata ogni {0} · fai clic per modificare o rimuovere + Condivisione di rete; controllata ogni {0} perché le notifiche di modifica non sono affidabili su SMB · fai clic per modificare o rimuovere + Controlla la cartella con questo intervallo Chiudi Ingrandisci Riduci a icona diff --git a/i18n/it/Uploader.it.resx b/i18n/it/Uploader.it.resx new file mode 100644 index 00000000..e4eb6bb7 --- /dev/null +++ b/i18n/it/Uploader.it.resx @@ -0,0 +1,104 @@ + + + text/microsoft-resx + 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 + Aggiungi cartella + Chiudi + Pausa + Riprendi + Riprova + Ferma + Tutti i file + Sfoglia… + File… + Aggiungi foto + Cartella o scheda… + Cartella o scheda + Foto + Controlla una cartella + Nome utente o password errati. + Il server ha segnalato un errore. + Inserisci un indirizzo come https://nas.local:8443. + Questo indirizzo non è un Titano Server. + Il server non ha risposto. + Il certificato del server non è stato accettato. + Trovati + Password + Server + Accedi + Connetti al server + Utente + Elimina dopo l'invio + Mantieni i file + Ogni file viene eliminato da questo PC solo dopo che il server ne ha verificato l'hash. + Eliminare i file originali? + Trascina qui foto, cartelle o una scheda + Il file è cambiato durante la lettura. + Il file non c'è più. + Impossibile leggere il file. + Il server ha rifiutato il file: {0} + Invio non riuscito; i dettagli sono nel log. + Non connesso + {0} liberi su {1} + Limite + Elimina dopo l'invio + Riduci nell'area notifiche + Avvia con Windows + {0:N0} non riusciti + {0:N0} nuovo tentativo + {0:N0} nuovi tentativi + {0:N0} di {1:N0} inviati + {0:N0} verificati dal server + Completato + Coda vuota + {0:N0} file + {0:N0} file + Coda + mancano {0} + In pausa + In attesa del server + Banda + File + Server + Esci + Avvio + Impostazioni + Utente + Non riuscito + Calcolo hash + In coda + Già sul server + Invio + Verificato + Connesso + Non in linea + Disconnesso + Accesso in corso + Destinazione + Nuova + Sequenza + Raggruppa in sessioni + Titolo + {0:N0} file aggiunto + {0:N0} file aggiunti + Il certificato del server è cambiato. + Scegli prima una sequenza. + Nessuna nuova foto trovata. + Il server ha chiuso la sessione. + {0:N0} file verificato dal server + {0:N0} file verificati dal server + Invio completato + Esci + Mostra + Accetta + Annulla + Confronta questa impronta con quella mostrata sul server. + Accettare questo server? + {0}/s + {0} · ogni {1} + Ogni {0} + Cartelle controllate + Rimuovi + diff --git a/src/Titano.Uploader/App.xaml b/src/Titano.Uploader/App.xaml index 6e70f617..ec3359f9 100644 --- a/src/Titano.Uploader/App.xaml +++ b/src/Titano.Uploader/App.xaml @@ -1,4 +1,5 @@ + xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" + ShutdownMode="OnExplicitShutdown"> diff --git a/src/Titano.Uploader/App.xaml.cs b/src/Titano.Uploader/App.xaml.cs index 67a0cc99..f737a506 100644 --- a/src/Titano.Uploader/App.xaml.cs +++ b/src/Titano.Uploader/App.xaml.cs @@ -1,7 +1,345 @@ +using System.ComponentModel; +using System.Globalization; +using System.IO; using System.Windows; +using System.Windows.Threading; +using Titano.Core.Diagnostics; +using Titano.Core.Localization; +using Titano.Ui.Mvvm; +using Titano.Ui.Theming; +using Titano.Uploader.DesignTime; +using Titano.Uploader.Infrastructure; +using Titano.Uploader.Interop; +using Titano.Uploader.Server; +using Titano.Uploader.Shell; +using Titano.Uploader.Uploads; +using Titano.Uploader.Watching; namespace Titano.Uploader; +/// +/// Titano Uploader (BRIEF §15): one instance per session, logging, language and theme, the persisted queue, the +/// server session, watch folders and the tray icon. --capture <dir> renders screenshots and exits. +/// public partial class App : Application { + private const int TrayShow = 1; + private const int TrayPause = 2; + private const int TrayExit = 3; + + private readonly CoalescingWriter _writer = new(); + private FileLogSink? _log; + private SingleInstance? _instance; + private UploaderEnvironment? _environment; + private UploaderSettings? _settings; + private UploadQueue? _queue; + private ProcessedFileMemory? _memory; + private ServerSession? _session; + private UploadEngine? _engine; + private WatchFolderService? _watch; + private DiscoveryListener? _discovery; + private MainViewModel? _vm; + private Shell.MainWindow? _window; + private TrayIcon? _tray; + private DispatcherTimer? _persist; + private bool _queueDirty; + private bool _exiting; + + protected override void OnStartup(StartupEventArgs e) + { + base.OnStartup(e); + var command = CommandLine.Parse(e.Args); + _environment = UploaderEnvironment.Detect(); + _log = new FileLogSink(_environment.LogDirectory, "uploader"); + Log.SetSink(_log); + Log.Info("app", $"Titano Uploader {typeof(App).Assembly.GetName().Version} starting; data at {_environment.DataDirectory}"); + HookUnhandledExceptions(); + + if (command.CaptureDirectory is { } captureDirectory) + { + RunCapture(captureDirectory); + return; + } + + _instance = SingleInstance.TryAcquire(); + if (_instance is null) + { + SingleInstance.HandOver([.. command.Paths.Select(Absolute).OfType()]); + Log.Info("app", "Another uploader runs in this session; arguments handed over"); + Shutdown(); + return; + } + + _settings = UploaderSettings.Load(_environment.SettingsPath); + ApplyLanguage(_settings.Language); + ThemeManager.Initialize(this, _settings.Theme); + BuildServices(_environment, _settings); + + _instance.Listen(args => Dispatcher.BeginInvoke(() => OnHandOver(args))); + _session!.Start(); + _engine!.Start(); + _vm!.Start(); + _vm.StartWatching(); + UpdateTray(); + UpdateDiscovery(); + if (command.Paths.Count > 0) _ = _vm.EnqueueAsync(command.Paths); + + if (command.StartInTray && _settings.MinimizeToTray) return; + if (command.StartInTray) _window!.WindowState = WindowState.Minimized; + _window!.Show(); + } + + protected override void OnExit(ExitEventArgs e) + { + _persist?.Stop(); + _vm?.Dispose(); + // Cancels transfers; interrupted items are written as queued and resume from the server's chunks. + _engine?.Dispose(); + if (_queue is not null && _environment is not null) + { + Persist(); + _writer.Flush(TimeSpan.FromSeconds(10)); + } + if (_window is not null && _settings is not null) _window.SavePlacement(); + SaveSettings(); + _watch?.Dispose(); + _discovery?.Dispose(); + _session?.Dispose(); + _tray?.Dispose(); + _instance?.Dispose(); + Log.Info("app", "Titano Uploader exiting"); + _log?.Dispose(); + base.OnExit(e); + } + + private void BuildServices(UploaderEnvironment environment, UploaderSettings settings) + { + _queue = new UploadQueue(); + QueueStore.Load(environment.QueuePath, _queue); + _memory = ProcessedFileMemory.Load(environment.WatchMemoryPath); + _session = new ServerSession(settings, SaveSettings); + _engine = new UploadEngine(_queue, _session, () => settings.DeleteAfterUpload); + _watch = new WatchFolderService(_memory, _queue.ContainsPath); + var startup = new RunKeyStartupRegistration(); + startup.Refresh(); + var dialogs = new UploaderDialogs(); + _vm = new MainViewModel(new UploaderServices(settings, SaveSettings, _session, _queue, _engine, startup, dialogs, _watch, _memory, environment.LogDirectory)); + _window = new Shell.MainWindow(_vm, settings); + dialogs.Owner = _window; + MainWindow = _window; + + AsyncRelayCommand.Failed += _vm.ReportError; + _engine.ItemConfirmed += (_, item) => + { + if (item.WatchRoot is { } root) _memory.Add(root, item.Path, item.Size, item.ModifiedUtc); + }; + _watch.FilesReady += _vm.OnWatchFilesReady; + _watch.AvailabilityChanged += _vm.OnWatchAvailabilityChanged; + _queue.Changed += (_, _) => _queueDirty = true; + _vm.UploadsCompleted += OnUploadsCompleted; + _vm.PropertyChanged += OnViewModelChanged; + _window.Closing += OnWindowClosing; + _window.Closed += (_, _) => ExitApplication(); + _window.StateChanged += OnWindowStateChanged; + _persist = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromSeconds(2) }; + _persist.Tick += (_, _) => Persist(); + _persist.Start(); + } + + /// Switches the UI language (BRIEF §16); an unknown code falls back to the OS language. + private static void ApplyLanguage(string? code) + { + CultureInfo requested; + try + { + requested = code is null ? CultureInfo.CurrentUICulture : CultureInfo.GetCultureInfo(code); + } + catch (CultureNotFoundException) + { + requested = CultureInfo.CurrentUICulture; + } + var culture = Languages.BestMatch(requested); + CultureInfo.DefaultThreadCurrentUICulture = culture; + CultureInfo.CurrentUICulture = culture; + Loc.SetCulture(culture); + } + + /// Writes the queue and the watch memory when they changed (every 2 s and at exit). + private void Persist() + { + if (_queue is null || _memory is null || _environment is null) return; + if (_queueDirty) + { + _queueDirty = false; + _writer.Write(_environment.QueuePath, QueueStore.Serialize(_queue)); + } + if (_memory.IsDirty) _writer.Write(_environment.WatchMemoryPath, _memory.Serialize()); + } + + private void SaveSettings() + { + if (_settings is null || _environment is null) return; + try + { + _settings.Save(_environment.SettingsPath); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Warning("app", "Settings not saved", ex); + } + } + + private void OnHandOver(IReadOnlyList paths) + { + ShowWindow(); + if (paths.Count > 0) _ = _vm!.EnqueueAsync(paths); + } + + private void OnViewModelChanged(object? sender, PropertyChangedEventArgs e) + { + switch (e.PropertyName) + { + case nameof(MainViewModel.MinimizeToTray): + UpdateTray(); + break; + case nameof(MainViewModel.IsConnectVisible): + UpdateDiscovery(); + break; + case nameof(MainViewModel.TrayText): + _tray?.SetToolTip(_vm!.TrayText); + break; + } + } + + /// The tray icon exists while "Minimise to tray" is on. + private void UpdateTray() + { + if (_settings!.MinimizeToTray && _tray is null) + { + _tray = new TrayIcon(_vm!.TrayText, TrayMenu, OnTrayCommand, ShowWindow); + } + else if (!_settings.MinimizeToTray && _tray is not null) + { + _tray.Dispose(); + _tray = null; + if (_window is { IsVisible: false }) ShowWindow(); + } + } + + private IReadOnlyList TrayMenu() => + [ + new(TrayShow, Loc.L("Uploader.Tray.Show")), + new(TrayPause, _vm!.PauseLabel), + new(0, null), + new(TrayExit, Loc.L("Uploader.Tray.Exit")), + ]; + + private void OnTrayCommand(int id) + { + switch (id) + { + case TrayShow: + ShowWindow(); + break; + case TrayPause: + _vm!.TogglePause(); + break; + case TrayExit: + ExitApplication(); + break; + } + } + + /// Listens for server beacons only while the sign-in form is shown. + private void UpdateDiscovery() + { + if (_vm!.IsConnectVisible) + { + if (_discovery is not null) return; + _discovery = new DiscoveryListener(); + _discovery.Found += _vm.Connect.AddDiscovered; + _discovery.Start(); + } + else if (_discovery is not null) + { + _discovery.Dispose(); + _discovery = null; + } + } + + private void OnUploadsCompleted(int count) + { + if (_window is { IsVisible: true, WindowState: not WindowState.Minimized }) return; + _tray?.ShowBalloon(Loc.L("Uploader.Tray.Done.Title"), Loc.Plural("Uploader.Tray.Done.Message", count)); + } + + /// Closing keeps the uploader running in the tray when "Minimise to tray" is on. + private void OnWindowClosing(object? sender, CancelEventArgs e) + { + if (_exiting || !_settings!.MinimizeToTray) return; + e.Cancel = true; + _window!.SavePlacement(); + _window.Hide(); + } + + private void OnWindowStateChanged(object? sender, EventArgs e) + { + if (_window is { WindowState: WindowState.Minimized } && _settings!.MinimizeToTray) _window.Hide(); + } + + private void ShowWindow() + { + if (_window is null) return; + _window.Show(); + if (_window.WindowState == WindowState.Minimized) _window.WindowState = WindowState.Normal; + _window.Activate(); + } + + private void ExitApplication() + { + if (_exiting) return; + _exiting = true; + Shutdown(); + } + + private void RunCapture(string directory) + { + ApplyLanguage(null); + ThemeManager.Initialize(this, AppTheme.Dark); + var sample = new SampleData(); + var vm = sample.CreateViewModel(); + var window = new Shell.MainWindow(vm, sample.Settings); + MainWindow = window; + ScreenCapture.Run(window, vm, sample, directory); + } + + private void HookUnhandledExceptions() + { + DispatcherUnhandledException += (_, e) => + { + Log.Error("app", "Unhandled UI exception", e.Exception); + if (_vm is null) return; + _vm.ReportError(e.Exception); + e.Handled = true; + }; + AppDomain.CurrentDomain.UnhandledException += (_, e) => Log.Error("app", "Unhandled exception", e.ExceptionObject as Exception); + TaskScheduler.UnobservedTaskException += (_, e) => + { + Log.Error("app", "Unobserved task exception", e.Exception); + e.SetObserved(); + }; + } + + /// Paths handed to the running instance must not depend on this process's working directory. + private static string? Absolute(string path) + { + try + { + return Path.GetFullPath(path); + } + catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException) + { + return null; + } + } } diff --git a/src/Titano.Uploader/DesignTime/SampleData.cs b/src/Titano.Uploader/DesignTime/SampleData.cs new file mode 100644 index 00000000..62dc5a99 --- /dev/null +++ b/src/Titano.Uploader/DesignTime/SampleData.cs @@ -0,0 +1,171 @@ +using System.ComponentModel; +using System.Globalization; +using System.Runtime.CompilerServices; +using Titano.Protocol; +using Titano.Uploader.Infrastructure; +using Titano.Uploader.Server; +using Titano.Uploader.Shell; +using Titano.Uploader.Uploads; +using Titano.Uploader.Watching; + +namespace Titano.Uploader.DesignTime; + +/// +/// Sample content for --capture screenshots ONLY: a fake signed-in session, a running queue of 4,812 files +/// and two watch folders. Nothing here touches the network, the registry or the user's data files. +/// +public sealed class SampleData +{ + private const int FileCount = 4_812; + private const long FileSize = 20_000_000; + + private readonly SampleSession _session = new(); + private readonly UploadQueue _queue = new(); + private MainViewModel? _vm; + + public UploaderSettings Settings { get; } = new() + { + ServerUrl = "https://nas.local:8443/", + Username = "alberto", + BandwidthLimit = 50, + MinimizeToTray = true, + WatchFolders = + [ + new UploaderSettings.WatchFolderSettings { Path = @"D:\Cam\Roof", IntervalSeconds = 60 }, + new UploaderSettings.WatchFolderSettings { Path = @"\\garage-pi\cam", IntervalSeconds = 300 }, + ], + }; + + /// A view model over in-memory sample services; settings changes are discarded. + public MainViewModel CreateViewModel() + { + var memory = new ProcessedFileMemory(); + _session.BandwidthLimit = Settings.BandwidthLimit; + _vm = new MainViewModel(new UploaderServices( + Settings, () => { }, _session, _queue, new SampleEngine(_queue), new SampleStartup(), new UploaderDialogs(), + new WatchFolderService(memory, _queue.ContainsPath), memory, string.Empty)); + foreach (var w in _vm.WatchFolders) w.IsAvailable = true; + return _vm; + } + + /// First run: no server yet, one server found on the LAN. + public void ShowConnect() + { + _session.SetState(ConnectionState.NotConfigured); + _vm!.Connect.Address = string.Empty; + _vm.Connect.Username = string.Empty; + _vm.Connect.Discovered.Clear(); + _vm.Connect.Discovered.Add(new DiscoveredServer("Studio NAS", "https://192.168.1.20:8443")); + } + + /// Signed in, a card being uploaded at 38 MB/s. + public void ShowQueue() + { + _session.SetState(ConnectionState.Connected); + if (_queue.Items.Count == 0) FillQueue(); + _vm!.Sequences.Clear(); + _vm.Sequences.Add(new SequenceOption(Guid.Empty, "Harbour sunset")); + _vm.SelectedSequence = _vm.Sequences[0]; + _vm.RefreshQueue(); + } + + private void FillQueue() + { + var batch = new UploadBatch { Id = Guid.CreateVersion7(), Mode = UploadTargetMode.Sessions }; + var start = new DateTime(2026, 9, 28, 15, 22, 0); + _queue.Add(batch, Enumerable.Range(0, FileCount).Select(i => + { + var shot = start.AddSeconds(i * 5); + var name = shot.ToString("yyyy-MM-dd_HH-mm-ss", CultureInfo.InvariantCulture) + "_" + (i + 1).ToString("0000", CultureInfo.InvariantCulture) + ".CR2"; + return new QueueEntry(@"E:\DCIM\100CANON\" + name, FileSize, shot.ToUniversalTime(), shot, "1a2b3c4d-20260928-152200", null); + })); + for (var i = 0; i < 2_201; i++) _queue.Items[i].State = i % 200 == 7 ? UploadItemState.Skipped : UploadItemState.Verified; + _queue.Items[1_640].Retries = 1; + _queue.Items[2_201].State = UploadItemState.Uploading; + _queue.Items[2_201].BytesSent = FileSize * 46 / 100; + _queue.Items[2_202].State = UploadItemState.Hashing; + _queue.Fail(_queue.Items[2_203], UploadFailure.FileUnreadable, null, DateTime.UtcNow); + } + + private sealed class SampleSession : IServerSession + { + private ConnectionState _state = ConnectionState.Connected; + + public event PropertyChangedEventHandler? PropertyChanged; + + public event EventHandler? SessionEnded + { + add { } + remove { } + } + + public ConnectionState State => _state; + public string? Address => "https://nas.local:8443/"; + public string? Username => "alberto"; + public long QuotaBytes => 5_000_000_000_000; + public long UsedBytes => 3_100_000_000_000; + public int BandwidthLimit { get; set; } + + public void SetState(ConnectionState state) + { + _state = state; + Raise(nameof(State)); + } + + public Task<(SignInResult Result, string? Fingerprint)> SignInAsync(string address, string username, string password, CancellationToken ct) => + Task.FromResult<(SignInResult, string?)>((SignInResult.Failed, null)); + + public void Trust(string fingerprint) + { + } + + public Task SignOutAsync() => Task.CompletedTask; + + public Task RefreshAsync() => Task.CompletedTask; + + public Task> ListSequencesAsync(CancellationToken ct) => Task.FromResult>([]); + + private void Raise([CallerMemberName] string? name = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); + } + + private sealed class SampleEngine(UploadQueue queue) : IUploadEngine + { + public event PropertyChangedEventHandler? PropertyChanged + { + add { } + remove { } + } + + public event EventHandler? Drained + { + add { } + remove { } + } + + public EngineStatus Status => queue.IsPaused ? EngineStatus.Paused : EngineStatus.Running; + public double BytesPerSecond => 38_000_000; + + public void Pump() + { + } + + public void Pause() => queue.IsPaused = true; + + public void Resume() => queue.IsPaused = false; + + public void StopAndClear() + { + } + + public void Retry(UploadItem item) + { + } + } + + private sealed class SampleStartup : IStartupRegistration + { + public bool IsEnabled { get; private set; } = true; + + public void SetEnabled(bool enabled) => IsEnabled = enabled; + } +} diff --git a/src/Titano.Uploader/Infrastructure/CoalescingWriter.cs b/src/Titano.Uploader/Infrastructure/CoalescingWriter.cs new file mode 100644 index 00000000..31f0cdcc --- /dev/null +++ b/src/Titano.Uploader/Infrastructure/CoalescingWriter.cs @@ -0,0 +1,62 @@ +using System.IO; +using Titano.Core.Diagnostics; +using Titano.Core.IO; + +namespace Titano.Uploader.Infrastructure; + +/// +/// Writes state files off the UI thread with . Only the newest content of each file is kept +/// while a write is in progress, so a slow disk never writes an older snapshot after a newer one. +/// +public sealed class CoalescingWriter +{ + private readonly Lock _gate = new(); + private readonly Dictionary _pending = new(StringComparer.OrdinalIgnoreCase); + private Task _worker = Task.CompletedTask; + private bool _running; + + public void Write(string path, byte[] content) + { + lock (_gate) + { + _pending[path] = content; + if (_running) return; + _running = true; + _worker = Task.Run(Drain); + } + } + + /// Waits for pending writes (at exit). + public void Flush(TimeSpan timeout) + { + Task worker; + lock (_gate) worker = _worker; + if (!worker.Wait(timeout)) Log.Warning("persist", "State files still being written at exit"); + } + + private void Drain() + { + while (true) + { + KeyValuePair next; + lock (_gate) + { + if (_pending.Count == 0) + { + _running = false; + return; + } + next = _pending.First(); + _pending.Remove(next.Key); + } + try + { + AtomicFile.WriteAllBytes(next.Key, next.Value); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Warning("persist", $"{next.Key} not written", ex); + } + } + } +} diff --git a/src/Titano.Uploader/Infrastructure/CommandLine.cs b/src/Titano.Uploader/Infrastructure/CommandLine.cs new file mode 100644 index 00000000..f7df7dc0 --- /dev/null +++ b/src/Titano.Uploader/Infrastructure/CommandLine.cs @@ -0,0 +1,27 @@ +namespace Titano.Uploader.Infrastructure; + +/// +/// Titano.Uploader.exe [--tray] [--capture <dir>] [files or folders…]: paths are enqueued, --tray +/// starts hidden (used by the Run key), --capture renders screenshots and exits. +/// +public sealed record CommandLine(IReadOnlyList Paths, bool StartInTray, string? CaptureDirectory) +{ + public const string TrayOption = "--tray"; + public const string CaptureOption = "--capture"; + + public static CommandLine Parse(IReadOnlyList args) + { + var paths = new List(); + var tray = false; + string? capture = null; + for (var i = 0; i < args.Count; i++) + { + var a = args[i]; + if (a.Equals(TrayOption, StringComparison.OrdinalIgnoreCase)) tray = true; + else if (a.Equals(CaptureOption, StringComparison.OrdinalIgnoreCase)) + capture = i + 1 < args.Count && !args[i + 1].StartsWith("--", StringComparison.Ordinal) ? args[++i] : "screenshots"; + else if (!a.StartsWith("--", StringComparison.Ordinal) && a.Length > 0) paths.Add(a); + } + return new CommandLine(paths, tray, capture); + } +} diff --git a/src/Titano.Uploader/Infrastructure/SingleInstance.cs b/src/Titano.Uploader/Infrastructure/SingleInstance.cs new file mode 100644 index 00000000..1c3c89cf --- /dev/null +++ b/src/Titano.Uploader/Infrastructure/SingleInstance.cs @@ -0,0 +1,98 @@ +using System.Diagnostics; +using System.IO; +using System.IO.Pipes; +using System.Text; +using Titano.Core.Diagnostics; + +namespace Titano.Uploader.Infrastructure; + +/// +/// One uploader per Windows session: a named mutex marks the running instance, and a second launch hands its +/// file arguments over a named pipe (current user only) before exiting. +/// +public sealed class SingleInstance : IDisposable +{ + private const string MutexName = @"Local\Titano.Uploader"; + private const string Header = "TITANO-UPLOADER/1"; + private const int MaxMessageBytes = 1 << 20; + + private readonly Mutex _mutex; + private readonly CancellationTokenSource _stop = new(); + + private SingleInstance(Mutex mutex) => _mutex = mutex; + + private static string PipeName => $"Titano.Uploader.{Process.GetCurrentProcess().SessionId}.{Environment.UserName}"; + + /// The instance guard, or null when another uploader already runs in this session. + public static SingleInstance? TryAcquire() + { + var mutex = new Mutex(initiallyOwned: true, MutexName, out var createdNew); + if (createdNew) return new SingleInstance(mutex); + mutex.Dispose(); + return null; + } + + /// Sends (absolute paths; empty = just show the window) to the running instance. + public static void HandOver(IReadOnlyList args) + { + try + { + using var pipe = new NamedPipeClientStream(".", PipeName, PipeDirection.Out, PipeOptions.CurrentUserOnly); + pipe.Connect(3000); + pipe.Write(Encode(args)); + pipe.Flush(); + } + catch (Exception ex) when (ex is IOException or TimeoutException or UnauthorizedAccessException) + { + Log.Warning("instance", "Could not reach the running uploader", ex); + } + } + + /// Receives messages from later launches; runs on a pool thread. + public void Listen(Action> received) => _ = ListenAsync(received, _stop.Token); + + public void Dispose() + { + _stop.Cancel(); + _mutex.ReleaseMutex(); + _mutex.Dispose(); + _stop.Dispose(); + } + + /// UTF-8: a header line, then one argument per line (paths cannot contain line breaks). + public static byte[] Encode(IReadOnlyList args) => + Encoding.UTF8.GetBytes(Header + "\n" + string.Join("\n", args.Where(a => !a.Contains('\n', StringComparison.Ordinal)))); + + /// Arguments of a message, or null when it is not one of ours. + public static IReadOnlyList? Decode(ReadOnlySpan message) + { + if (message.Length > MaxMessageBytes) return null; + var lines = Encoding.UTF8.GetString(message).Split('\n'); + if (lines[0] != Header) return null; + return [.. lines.Skip(1).Where(l => l.Length > 0)]; + } + + private static async Task ListenAsync(Action> received, CancellationToken ct) + { + while (!ct.IsCancellationRequested) + { + try + { + await using var pipe = new NamedPipeServerStream(PipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, + PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); + await pipe.WaitForConnectionAsync(ct).ConfigureAwait(false); + using var buffer = new MemoryStream(); + await pipe.CopyToAsync(buffer, ct).ConfigureAwait(false); + if (Decode(buffer.GetBuffer().AsSpan(0, (int)buffer.Length)) is { } args) received(args); + } + catch (OperationCanceledException) + { + return; + } + catch (IOException ex) + { + Log.Warning("instance", "Hand-over pipe failed; listening again", ex); + } + } + } +} diff --git a/src/Titano.Uploader/Infrastructure/StartupRegistration.cs b/src/Titano.Uploader/Infrastructure/StartupRegistration.cs new file mode 100644 index 00000000..0953ab73 --- /dev/null +++ b/src/Titano.Uploader/Infrastructure/StartupRegistration.cs @@ -0,0 +1,61 @@ +using System.Security; +using Microsoft.Win32; +using Titano.Core.Diagnostics; + +namespace Titano.Uploader.Infrastructure; + +/// "Start with Windows". +public interface IStartupRegistration +{ + bool IsEnabled { get; } + + void SetEnabled(bool enabled); +} + +/// +/// HKCU\Software\Microsoft\Windows\CurrentVersion\Run value that starts the uploader in the tray at sign-in. +/// The registry stays the source of truth because Task Manager can turn it off. +/// +public sealed class RunKeyStartupRegistration : IStartupRegistration +{ + private const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run"; + private const string ValueName = "Titano Uploader"; + + public bool IsEnabled + { + get + { + try + { + using var key = Registry.CurrentUser.OpenSubKey(RunKey); + return key?.GetValue(ValueName) is string { Length: > 0 }; + } + catch (SecurityException) + { + return false; + } + } + } + + private static string Command => $"\"{Environment.ProcessPath}\" {CommandLine.TrayOption}"; + + public void SetEnabled(bool enabled) + { + try + { + using var key = Registry.CurrentUser.CreateSubKey(RunKey, writable: true); + if (enabled) key.SetValue(ValueName, Command, RegistryValueKind.String); + else key.DeleteValue(ValueName, throwOnMissingValue: false); + } + catch (Exception ex) when (ex is SecurityException or UnauthorizedAccessException) + { + Log.Warning("startup", "Run key not updated", ex); + } + } + + /// Points an existing entry at the current executable (after an update moved it). + public void Refresh() + { + if (IsEnabled) SetEnabled(true); + } +} diff --git a/src/Titano.Uploader/Infrastructure/TokenProtector.cs b/src/Titano.Uploader/Infrastructure/TokenProtector.cs new file mode 100644 index 00000000..d7e9d7b8 --- /dev/null +++ b/src/Titano.Uploader/Infrastructure/TokenProtector.cs @@ -0,0 +1,98 @@ +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; + +namespace Titano.Uploader.Infrastructure; + +/// +/// Encrypts the sign-in token for the current Windows user with DPAPI (CryptProtectData, no machine scope), +/// so uploader.json copied to another account or PC cannot be used. +/// +public static partial class TokenProtector +{ + private const int CryptProtectUiForbidden = 0x1; + + // Ties the blob to this program; other DPAPI consumers of the same user cannot unwrap it by accident. + private static readonly byte[] Entropy = "Titano.Uploader.Token.v1"u8.ToArray(); + + /// Base64 DPAPI blob of . + public static string Protect(string token) + { + var plain = Encoding.UTF8.GetBytes(token); + try + { + return Convert.ToBase64String(Transform(plain, protect: true)); + } + finally + { + CryptographicOperations.ZeroMemory(plain); + } + } + + /// The token, or null when the blob is corrupt or belongs to another user. + public static string? Unprotect(string protectedToken) + { + byte[] blob; + try + { + blob = Convert.FromBase64String(protectedToken); + } + catch (FormatException) + { + return null; + } + try + { + var plain = Transform(blob, protect: false); + var token = Encoding.UTF8.GetString(plain); + CryptographicOperations.ZeroMemory(plain); + return token; + } + catch (CryptographicException) + { + return null; + } + } + + private static unsafe byte[] Transform(byte[] input, bool protect) + { + fixed (byte* inPtr = input) + fixed (byte* entropyPtr = Entropy) + { + var source = new DataBlob { Size = input.Length, Data = (IntPtr)inPtr }; + var entropy = new DataBlob { Size = Entropy.Length, Data = (IntPtr)entropyPtr }; + var ok = protect + ? CryptProtectData(source, null, entropy, IntPtr.Zero, IntPtr.Zero, CryptProtectUiForbidden, out var output) + : CryptUnprotectData(source, IntPtr.Zero, entropy, IntPtr.Zero, IntPtr.Zero, CryptProtectUiForbidden, out output); + if (!ok) throw new CryptographicException(Marshal.GetLastPInvokeError()); + try + { + var result = new byte[output.Size]; + Marshal.Copy(output.Data, result, 0, output.Size); + return result; + } + finally + { + LocalFree(output.Data); + } + } + } + + [StructLayout(LayoutKind.Sequential)] + private struct DataBlob + { + public int Size; + public IntPtr Data; + } + + [LibraryImport("crypt32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool CryptProtectData(in DataBlob dataIn, string? description, in DataBlob entropy, IntPtr reserved, IntPtr prompt, int flags, out DataBlob dataOut); + + [LibraryImport("crypt32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool CryptUnprotectData(in DataBlob dataIn, IntPtr description, in DataBlob entropy, IntPtr reserved, IntPtr prompt, int flags, out DataBlob dataOut); + + [LibraryImport("kernel32.dll")] + private static partial IntPtr LocalFree(IntPtr memory); +} diff --git a/src/Titano.Uploader/Infrastructure/UploaderEnvironment.cs b/src/Titano.Uploader/Infrastructure/UploaderEnvironment.cs new file mode 100644 index 00000000..993a0fdb --- /dev/null +++ b/src/Titano.Uploader/Infrastructure/UploaderEnvironment.cs @@ -0,0 +1,37 @@ +using System.IO; + +namespace Titano.Uploader.Infrastructure; + +/// +/// Where the uploader keeps its files: %LOCALAPPDATA%\Titano (shared with the client), or .\data next +/// to the executable when portable.txt exists — the same rule as the desktop client. +/// +public sealed class UploaderEnvironment +{ + private UploaderEnvironment(string dataDirectory) + { + DataDirectory = dataDirectory; + Directory.CreateDirectory(DataDirectory); + Directory.CreateDirectory(LogDirectory); + } + + public string DataDirectory { get; } + public string LogDirectory => Path.Combine(DataDirectory, "logs"); + + /// Settings, DPAPI-protected token and trusted certificate fingerprints. + public string SettingsPath => Path.Combine(DataDirectory, "uploader.json"); + + /// The persisted upload queue. + public string QueuePath => Path.Combine(DataDirectory, "uploader-queue.json"); + + /// Files of watch folders the server already confirmed. + public string WatchMemoryPath => Path.Combine(DataDirectory, "uploader-watch.json"); + + public static UploaderEnvironment Detect() + { + var exeDir = AppContext.BaseDirectory; + if (File.Exists(Path.Combine(exeDir, "portable.txt"))) return new UploaderEnvironment(Path.Combine(exeDir, "data")); + var local = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + return new UploaderEnvironment(Path.Combine(local, "Titano")); + } +} diff --git a/src/Titano.Uploader/Infrastructure/UploaderSettings.cs b/src/Titano.Uploader/Infrastructure/UploaderSettings.cs new file mode 100644 index 00000000..d1bc3394 --- /dev/null +++ b/src/Titano.Uploader/Infrastructure/UploaderSettings.cs @@ -0,0 +1,77 @@ +using System.IO; +using System.Text.Json; +using System.Text.Json.Serialization; +using Titano.Core.Diagnostics; +using Titano.Core.IO; +using Titano.Ui.Theming; +using Titano.Uploader.Uploads; + +namespace Titano.Uploader.Infrastructure; + +/// +/// uploader.json. The bearer token is stored only DPAPI-protected for the current Windows user +/// (); "Start with Windows" lives in the registry, which stays the source of truth. +/// +public sealed class UploaderSettings +{ + public string? ServerUrl { get; set; } + public string? Username { get; set; } + + /// Base64 of the DPAPI (CurrentUser) blob of the bearer token. + public string? ProtectedToken { get; set; } + + /// SHA-256 fingerprints (XX:XX:…) of self-signed certificates the user trusted (TOFU). + public List TrustedFingerprints { get; set; } = []; + + /// Upload limit in MB/s (decimal megabytes); 0 = unlimited. + public int BandwidthLimit { get; set; } + + public bool MinimizeToTray { get; set; } = true; + public bool DeleteAfterUpload { get; set; } + public UploadTargetMode Target { get; set; } = UploadTargetMode.Sessions; + public Guid? TargetSequenceId { get; set; } + public string? NewSequenceTitle { get; set; } + public List WatchFolders { get; set; } = []; + public string? Language { get; set; } + public AppTheme Theme { get; set; } = AppTheme.Dark; + public WindowPlacement? Window { get; set; } + + public sealed class WatchFolderSettings + { + public string Path { get; set; } = string.Empty; + public int IntervalSeconds { get; set; } = 60; + } + + public sealed class WindowPlacement + { + public double Left { get; set; } + public double Top { get; set; } + public double Width { get; set; } + public double Height { get; set; } + } + + public static UploaderSettings Load(string path) + { + try + { + if (File.Exists(path)) + return JsonSerializer.Deserialize(File.ReadAllBytes(path), UploaderSettingsJson.Default.UploaderSettings) ?? new UploaderSettings(); + } + catch (JsonException ex) + { + // A corrupt settings file must never block startup; defaults apply. + Log.Warning("settings", "uploader.json unreadable; using defaults", ex); + } + catch (IOException ex) + { + Log.Warning("settings", "uploader.json unreadable; using defaults", ex); + } + return new UploaderSettings(); + } + + public void Save(string path) => AtomicFile.WriteAllBytes(path, JsonSerializer.SerializeToUtf8Bytes(this, UploaderSettingsJson.Default.UploaderSettings)); +} + +[JsonSourceGenerationOptions(WriteIndented = true, PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, UseStringEnumConverter = true)] +[JsonSerializable(typeof(UploaderSettings))] +internal sealed partial class UploaderSettingsJson : JsonSerializerContext; diff --git a/src/Titano.Uploader/Interop/FileDialogs.cs b/src/Titano.Uploader/Interop/FileDialogs.cs new file mode 100644 index 00000000..39160398 --- /dev/null +++ b/src/Titano.Uploader/Interop/FileDialogs.cs @@ -0,0 +1,187 @@ +using System.Runtime.InteropServices; + +namespace Titano.Uploader.Interop; + +/// A filter of the Open dialog: display name and patterns such as *.jpg;*.cr2. +public readonly record struct FileFilter(string Name, string Patterns); + +/// +/// The shell's Open dialog through IFileOpenDialog COM (no WinForms): several files at once, or one folder +/// (which also picks a card root such as E:\). +/// +public static class FileDialogs +{ + private const uint FosPickFolders = 0x20; + private const uint FosForceFileSystem = 0x40; + private const uint FosAllowMultiSelect = 0x200; + private const uint FosPathMustExist = 0x800; + private const uint FosFileMustExist = 0x1000; + private const uint SigdnFileSysPath = 0x80058000; + private const int ErrorCancelled = unchecked((int)0x800704C7); + + /// Selected files; empty when cancelled. + public static IReadOnlyList PickFiles(IntPtr owner, string title, IReadOnlyList filters) => + Show(owner, title, FosAllowMultiSelect | FosFileMustExist, filters); + + /// Selected folder; null when cancelled. + public static string? PickFolder(IntPtr owner, string title) => Show(owner, title, FosPickFolders, []).FirstOrDefault(); + + private static List Show(IntPtr owner, string title, uint options, IReadOnlyList filters) + { + var dialog = (IFileOpenDialog)new FileOpenDialogClass(); + try + { + dialog.GetOptions(out var current); + dialog.SetOptions(current | options | FosForceFileSystem | FosPathMustExist); + dialog.SetTitle(title); + if (filters.Count > 0) + { + var specs = filters.Select(f => new FilterSpec { Name = f.Name, Spec = f.Patterns }).ToArray(); + dialog.SetFileTypes((uint)specs.Length, specs); + dialog.SetFileTypeIndex(1); + } + var hr = dialog.Show(owner); + if (hr == ErrorCancelled) return []; + Marshal.ThrowExceptionForHR(hr); + + dialog.GetResults(out var items); + try + { + items.GetCount(out var count); + var paths = new List((int)count); + for (uint i = 0; i < count; i++) + { + items.GetItemAt(i, out var item); + try + { + item.GetDisplayName(SigdnFileSysPath, out var path); + paths.Add(path); + } + finally + { + Marshal.ReleaseComObject(item); + } + } + return paths; + } + finally + { + Marshal.ReleaseComObject(items); + } + } + finally + { + Marshal.ReleaseComObject(dialog); + } + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + private struct FilterSpec + { + [MarshalAs(UnmanagedType.LPWStr)] + public string Name; + + [MarshalAs(UnmanagedType.LPWStr)] + public string Spec; + } + + [ComImport] + [Guid("DC1C5A9C-E88A-4dde-A5A1-60F82A20AEF7")] + private class FileOpenDialogClass; + + // Classic COM interop does not inherit vtables: IModalWindow and IFileDialog members are repeated in order. + [ComImport] + [Guid("d57c7288-d4ad-4768-be02-9d969532d960")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IFileOpenDialog + { + [PreserveSig] + int Show(IntPtr owner); + + void SetFileTypes(uint count, [In, MarshalAs(UnmanagedType.LPArray)] FilterSpec[] filters); + + void SetFileTypeIndex(uint index); + + void GetFileTypeIndex(out uint index); + + void Advise(IntPtr events, out uint cookie); + + void Unadvise(uint cookie); + + void SetOptions(uint options); + + void GetOptions(out uint options); + + void SetDefaultFolder(IShellItem item); + + void SetFolder(IShellItem item); + + void GetFolder(out IShellItem item); + + void GetCurrentSelection(out IShellItem item); + + void SetFileName([MarshalAs(UnmanagedType.LPWStr)] string name); + + void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string name); + + void SetTitle([MarshalAs(UnmanagedType.LPWStr)] string title); + + void SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string text); + + void SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string label); + + void GetResult(out IShellItem item); + + void AddPlace(IShellItem item, int placement); + + void SetDefaultExtension([MarshalAs(UnmanagedType.LPWStr)] string extension); + + void Close(int hr); + + void SetClientGuid(ref Guid guid); + + void ClearClientData(); + + void SetFilter(IntPtr filter); + + void GetResults(out IShellItemArray items); + + void GetSelectedItems(out IShellItemArray items); + } + + [ComImport] + [Guid("43826d1e-e718-42ee-bc55-a1e261c37bfe")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IShellItem + { + void BindToHandler(IntPtr bindContext, ref Guid handler, ref Guid iid, out IntPtr result); + + void GetParent(out IShellItem parent); + + void GetDisplayName(uint form, [MarshalAs(UnmanagedType.LPWStr)] out string name); + + void GetAttributes(uint mask, out uint attributes); + + void Compare(IShellItem other, uint hint, out int order); + } + + [ComImport] + [Guid("b63ea76d-1f85-456f-a19c-48159efa858b")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IShellItemArray + { + void BindToHandler(IntPtr bindContext, ref Guid handler, ref Guid iid, out IntPtr result); + + void GetPropertyStore(int flags, ref Guid iid, out IntPtr store); + + void GetPropertyDescriptionList(IntPtr keyType, ref Guid iid, out IntPtr list); + + void GetAttributes(int flags, uint mask, out uint attributes); + + void GetCount(out uint count); + + void GetItemAt(uint index, out IShellItem item); + + void EnumItems(out IntPtr items); + } +} diff --git a/src/Titano.Uploader/Interop/TrayIcon.cs b/src/Titano.Uploader/Interop/TrayIcon.cs new file mode 100644 index 00000000..e6c52ec6 --- /dev/null +++ b/src/Titano.Uploader/Interop/TrayIcon.cs @@ -0,0 +1,251 @@ +using System.Runtime.InteropServices; +using System.Windows.Interop; +using Titano.Core.Diagnostics; + +namespace Titano.Uploader.Interop; + +/// One entry of the tray menu; an id of 0 is a separator. +public readonly record struct TrayMenuItem(int Id, string? Text); + +/// +/// Notification-area icon through Shell_NotifyIconW: the program icon from the executable's resources, a tooltip, +/// a native context menu and balloons. A hidden window receives the callbacks and re-adds the icon after Explorer restarts. +/// +public sealed unsafe partial class TrayIcon : IDisposable +{ + private const uint NimAdd = 0; + private const uint NimModify = 1; + private const uint NimDelete = 2; + private const uint NifMessage = 0x1; + private const uint NifIcon = 0x2; + private const uint NifTip = 0x4; + private const uint NifInfo = 0x10; + private const uint NiifUser = 0x4; + private const int CallbackMessage = 0x8000 + 1; // WM_APP + 1 + private const int WmContextMenu = 0x007B; + private const int WmLButtonUp = 0x0202; + private const int WmLButtonDblClk = 0x0203; + private const int WmRButtonUp = 0x0205; + private const int NinBalloonUserClick = 0x0405; + private const uint MfString = 0x0; + private const uint MfSeparator = 0x800; + private const uint TpmRightButton = 0x2; + private const uint TpmNoNotify = 0x80; + private const uint TpmReturnCmd = 0x100; + + private readonly HwndSource _window; + private readonly IntPtr _icon; + private readonly bool _ownsIcon; + private readonly uint _taskbarCreated; + private readonly Func> _menu; + private readonly Action _command; + private readonly Action _show; + private string _toolTip; + private bool _added; + + /// Hover text (up to 127 characters). + /// Builds the context menu when it opens. + /// Runs a chosen menu id. + /// Left click or balloon click. + public TrayIcon(string toolTip, Func> menu, Action command, Action show) + { + _toolTip = toolTip; + _menu = menu; + _command = command; + _show = show; + // A hidden top-level window: message-only windows miss the TaskbarCreated broadcast. + _window = new HwndSource(new HwndSourceParameters("TitanoUploaderTray") { Width = 0, Height = 0, WindowStyle = 0 }); + _window.AddHook(WndProc); + _taskbarCreated = RegisterWindowMessageW("TaskbarCreated"); + (_icon, _ownsIcon) = LoadProgramIcon(); + Add(); + } + + public void SetToolTip(string text) + { + _toolTip = text; + var data = NewData(NifTip); + Copy(_toolTip, data.Tip, 128); + Notify(NimModify, &data); + } + + /// Shows a balloon (a toast on Windows 10/11) with the program icon. + public void ShowBalloon(string title, string text) + { + var data = NewData(NifInfo); + Copy(title, data.InfoTitle, 64); + Copy(text, data.Info, 256); + data.InfoFlags = NiifUser; + Notify(NimModify, &data); + } + + public void Dispose() + { + if (_added) + { + var data = NewData(0); + Notify(NimDelete, &data); + _added = false; + } + if (_ownsIcon) DestroyIcon(_icon); + _window.Dispose(); + } + + private void Add() + { + var data = NewData(NifMessage | NifIcon | NifTip); + data.CallbackMessage = CallbackMessage; + data.Icon = _icon; + Copy(_toolTip, data.Tip, 128); + _added = Notify(NimAdd, &data); + } + + private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) + { + if (msg == CallbackMessage) + { + switch ((int)(lParam.ToInt64() & 0xFFFF)) + { + case WmLButtonUp or WmLButtonDblClk or NinBalloonUserClick: + _show(); + break; + case WmRButtonUp or WmContextMenu: + ShowMenu(); + break; + } + handled = true; + } + else if (_taskbarCreated != 0 && msg == (int)_taskbarCreated) + { + Add(); + } + return IntPtr.Zero; + } + + private void ShowMenu() + { + var menu = CreatePopupMenu(); + if (menu == IntPtr.Zero) return; + try + { + foreach (var item in _menu()) + { + if (item.Id == 0 || item.Text is null) AppendMenuW(menu, MfSeparator, 0, null); + else AppendMenuW(menu, MfString, (nuint)item.Id, item.Text); + } + GetCursorPos(out var point); + // Without foreground the menu would not close when the user clicks elsewhere. + SetForegroundWindow(_window.Handle); + var chosen = TrackPopupMenuEx(menu, TpmReturnCmd | TpmRightButton | TpmNoNotify, point.X, point.Y, _window.Handle, IntPtr.Zero); + PostMessageW(_window.Handle, 0, IntPtr.Zero, IntPtr.Zero); + if (chosen != 0) _command(chosen); + } + finally + { + DestroyMenu(menu); + } + } + + private NotifyIconData NewData(uint flags) => new() + { + Size = (uint)sizeof(NotifyIconData), + Window = _window.Handle, + Id = 1, + Flags = flags, + }; + + private static bool Notify(uint message, NotifyIconData* data) + { + if (Shell_NotifyIconW(message, data)) return true; + Log.Info("tray", $"Shell_NotifyIcon({message}) failed"); + return false; + } + + private static void Copy(string text, char* destination, int capacity) + { + var length = Math.Min(text.Length, capacity - 1); + text.AsSpan(0, length).CopyTo(new Span(destination, capacity)); + destination[length] = '\0'; + } + + /// The generated titano-uploader icon embedded in the executable; the stock icon if it cannot be read. + private static (IntPtr Icon, bool Owned) LoadProgramIcon() + { + if (Environment.ProcessPath is { } exe) + { + IntPtr small; + if (ExtractIconExW(exe, 0, null, &small, 1) > 0 && small != IntPtr.Zero) return (small, true); + } + return (LoadIconW(IntPtr.Zero, 32512), false); // IDI_APPLICATION + } + + [StructLayout(LayoutKind.Sequential)] + private struct NotifyIconData + { + public uint Size; + public IntPtr Window; + public uint Id; + public uint Flags; + public uint CallbackMessage; + public IntPtr Icon; + public fixed char Tip[128]; + public uint State; + public uint StateMask; + public fixed char Info[256]; + public uint TimeoutOrVersion; + public fixed char InfoTitle[64]; + public uint InfoFlags; + public Guid Item; + public IntPtr BalloonIcon; + } + + [StructLayout(LayoutKind.Sequential)] + private struct Point + { + public int X; + public int Y; + } + + [LibraryImport("shell32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool Shell_NotifyIconW(uint message, NotifyIconData* data); + + [LibraryImport("shell32.dll", StringMarshalling = StringMarshalling.Utf16)] + private static partial uint ExtractIconExW(string file, int index, IntPtr* large, IntPtr* small, uint count); + + [LibraryImport("user32.dll")] + private static partial IntPtr LoadIconW(IntPtr instance, nint name); + + [LibraryImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool DestroyIcon(IntPtr icon); + + [LibraryImport("user32.dll", StringMarshalling = StringMarshalling.Utf16)] + private static partial uint RegisterWindowMessageW(string name); + + [LibraryImport("user32.dll")] + private static partial IntPtr CreatePopupMenu(); + + [LibraryImport("user32.dll", StringMarshalling = StringMarshalling.Utf16)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool AppendMenuW(IntPtr menu, uint flags, nuint id, string? text); + + [LibraryImport("user32.dll")] + private static partial int TrackPopupMenuEx(IntPtr menu, uint flags, int x, int y, IntPtr window, IntPtr parameters); + + [LibraryImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool DestroyMenu(IntPtr menu); + + [LibraryImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool GetCursorPos(out Point point); + + [LibraryImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool SetForegroundWindow(IntPtr window); + + [LibraryImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool PostMessageW(IntPtr window, int message, IntPtr wParam, IntPtr lParam); +} diff --git a/src/Titano.Uploader/Server/DiscoveryListener.cs b/src/Titano.Uploader/Server/DiscoveryListener.cs new file mode 100644 index 00000000..1796ed3d --- /dev/null +++ b/src/Titano.Uploader/Server/DiscoveryListener.cs @@ -0,0 +1,74 @@ +using System.Net; +using System.Net.Sockets; +using Titano.Core.Diagnostics; +using Titano.Protocol; + +namespace Titano.Uploader.Server; + +/// A Titano Server announced on the LAN. +public sealed record DiscoveredServer(string Name, string Address); + +/// +/// Listens for the server's UDP beacon () while the connect form is open and reports +/// each server once. Beacons are unauthenticated: they only fill the address field, never trust a certificate. +/// +public sealed class DiscoveryListener : IDisposable +{ + private readonly HashSet _seen = new(StringComparer.OrdinalIgnoreCase); + private CancellationTokenSource? _cts; + + /// Raised on the thread that called . + public event Action? Found; + + public void Start() + { + if (_cts is not null) return; + _cts = new CancellationTokenSource(); + var context = SynchronizationContext.Current; + _ = Task.Run(() => ListenAsync(context, _cts.Token)); + } + + public void Dispose() + { + _cts?.Cancel(); + _cts?.Dispose(); + _cts = null; + } + + /// The address the client should use for sent from . + private static string AddressOf(DiscoveryBeacon beacon, IPAddress sender) + { + var host = sender.AddressFamily == AddressFamily.InterNetworkV6 ? "[" + sender + "]" : sender.ToString(); + return beacon.HttpsPort > 0 ? $"https://{host}:{beacon.HttpsPort}" : $"http://{host}:{beacon.HttpPort}"; + } + + private async Task ListenAsync(SynchronizationContext? context, CancellationToken ct) + { + try + { + using var udp = new UdpClient(); + // The desktop client may listen on the same port. + udp.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); + udp.Client.Bind(new IPEndPoint(IPAddress.Any, DiscoveryBeacon.Port)); + while (!ct.IsCancellationRequested) + { + var datagram = await udp.ReceiveAsync(ct).ConfigureAwait(false); + if (DiscoveryBeacon.TryParse(datagram.Buffer) is not { } beacon) continue; + var server = new DiscoveredServer(beacon.Name, AddressOf(beacon, datagram.RemoteEndPoint.Address)); + lock (_seen) + { + if (!_seen.Add(server.Address)) continue; + } + if (context is null) Found?.Invoke(server); + else context.Post(_ => Found?.Invoke(server), null); + } + } + catch (OperationCanceledException) + { + } + catch (SocketException ex) + { + Log.Info("discovery", "LAN discovery unavailable: " + ex.Message); + } + } +} diff --git a/src/Titano.Uploader/Server/ServerAddress.cs b/src/Titano.Uploader/Server/ServerAddress.cs new file mode 100644 index 00000000..6d025400 --- /dev/null +++ b/src/Titano.Uploader/Server/ServerAddress.cs @@ -0,0 +1,21 @@ +namespace Titano.Uploader.Server; + +/// Server addresses as typed in the sign-in form. +public static class ServerAddress +{ + /// + /// Accepts "nas.local:8443" (https assumed) or a full http(s) URL; the result is the API base, ending with "/". + /// + public static bool TryParse(string? text, out Uri uri) + { + uri = null!; + if (string.IsNullOrWhiteSpace(text)) return false; + var trimmed = text.Trim(); + if (!trimmed.Contains("://", StringComparison.Ordinal)) trimmed = "https://" + trimmed; + if (!Uri.TryCreate(trimmed, UriKind.Absolute, out var parsed) || parsed.Scheme is not ("https" or "http") || parsed.Host.Length == 0) return false; + var builder = new UriBuilder(parsed) { Query = string.Empty, Fragment = string.Empty }; + if (!builder.Path.EndsWith('/')) builder.Path += "/"; + uri = builder.Uri; + return true; + } +} diff --git a/src/Titano.Uploader/Server/ServerSession.cs b/src/Titano.Uploader/Server/ServerSession.cs new file mode 100644 index 00000000..7a672483 --- /dev/null +++ b/src/Titano.Uploader/Server/ServerSession.cs @@ -0,0 +1,460 @@ +using System.ComponentModel; +using System.Net; +using System.Net.Http; +using System.Runtime.CompilerServices; +using System.Text.Json; +using Titano.Core.Diagnostics; +using Titano.Protocol; +using Titano.Protocol.Client; +using Titano.Uploader.Infrastructure; +using Titano.Uploader.Uploads; + +namespace Titano.Uploader.Server; + +/// Connection shown in the header. +public enum ConnectionState +{ + /// First run: no server chosen yet. + NotConfigured, + SigningIn, + Connected, + + /// Signed in, but the server cannot be reached; probed every 30 s. + Offline, + + /// A server is known but there is no valid token. + SignedOut, +} + +/// Outcome of the sign-in form. +public enum SignInResult +{ + Success, + InvalidAddress, + Unreachable, + NotTitano, + + /// The certificate is self-signed and unknown: ask the user to trust its fingerprint. + Untrusted, + BadCredentials, + Failed, +} + +/// The server connection as the window sees it. +public interface IServerSession : INotifyPropertyChanged +{ + ConnectionState State { get; } + + /// Server address as the user typed or discovered it. + string? Address { get; } + + string? Username { get; } + + /// Quota in bytes; 0 = unlimited. + long QuotaBytes { get; } + + long UsedBytes { get; } + + /// Upload limit in MB/s; 0 = unlimited. + int BandwidthLimit { get; set; } + + /// Raised when the server ended the session (token rejected or certificate changed). + event EventHandler? SessionEnded; + + /// Signs in; comes with the fingerprint to show. + Task<(SignInResult Result, string? Fingerprint)> SignInAsync(string address, string username, string password, CancellationToken ct); + + /// Remembers a certificate fingerprint the user confirmed (trust on first use). + void Trust(string fingerprint); + + Task SignOutAsync(); + + /// Refreshes the account (quota) when connected. + Task RefreshAsync(); + + Task> ListSequencesAsync(CancellationToken ct); +} + +/// +/// Owns the : sign-in with trust-on-first-use, token restore from DPAPI, offline probing, +/// and the upload transport. Runs on the UI thread. +/// +public sealed class ServerSession : IServerSession, IUploadTransport, IDisposable +{ + private static readonly TimeSpan ProbeInterval = TimeSpan.FromSeconds(30); + + private readonly UploaderSettings _settings; + private readonly Action _saveSettings; + private TitanoClient? _client; + private ConnectionState _state; + private string? _username; + private long _quotaBytes; + private long _usedBytes; + private int _bandwidthLimit; + private CancellationTokenSource? _probe; + + public ServerSession(UploaderSettings settings, Action saveSettings) + { + _settings = settings; + _saveSettings = saveSettings; + _username = settings.Username; + _bandwidthLimit = Math.Max(0, settings.BandwidthLimit); + _state = settings.ServerUrl is null ? ConnectionState.NotConfigured : ConnectionState.SignedOut; + } + + public event PropertyChangedEventHandler? PropertyChanged; + + public event EventHandler? ReadyChanged; + + public event EventHandler? SessionEnded; + + public ConnectionState State + { + get => _state; + private set + { + if (_state == value) return; + var wasReady = IsReady; + _state = value; + OnPropertyChanged(); + if (wasReady != IsReady) ReadyChanged?.Invoke(this, EventArgs.Empty); + } + } + + public bool IsReady => _state == ConnectionState.Connected && _client is not null; + + public string? Address => _settings.ServerUrl; + + public string? Username + { + get => _username; + private set => Set(ref _username, value); + } + + public long QuotaBytes + { + get => _quotaBytes; + private set => Set(ref _quotaBytes, value); + } + + public long UsedBytes + { + get => _usedBytes; + private set => Set(ref _usedBytes, value); + } + + public int BandwidthLimit + { + get => _bandwidthLimit; + set + { + if (!Set(ref _bandwidthLimit, Math.Max(0, value))) return; + ApplyBandwidth(); + } + } + + /// Restores the saved session, if any, in the background. + public void Start() + { + if (_settings.ServerUrl is null || _settings.ProtectedToken is null) return; + var token = TokenProtector.Unprotect(_settings.ProtectedToken); + if (token is null || !ServerAddress.TryParse(_settings.ServerUrl, out var uri)) + { + Log.Warning("session", "Saved token cannot be used; sign in again"); + State = ConnectionState.SignedOut; + return; + } + UseClient(CreateClient(uri)); + _client!.Token = token; + State = ConnectionState.SigningIn; + _ = RefreshAsync(); + } + + public async Task<(SignInResult Result, string? Fingerprint)> SignInAsync(string address, string username, string password, CancellationToken ct) + { + if (!ServerAddress.TryParse(address, out var uri)) return (SignInResult.InvalidAddress, null); + StopProbing(); + var previous = State; + State = ConnectionState.SigningIn; + var client = CreateClient(uri); + try + { + await client.GetInfoAsync(ct); + var login = await client.LoginAsync(username, password, ct); + if (login.Token is null) throw new TitanoApiException(HttpStatusCode.Unauthorized, new ApiError("no_token", "No token issued")); + + _settings.ServerUrl = uri.ToString(); + _settings.Username = login.User.Username; + _settings.ProtectedToken = TokenProtector.Protect(login.Token); + _saveSettings(); + UseClient(client); + OnPropertyChanged(nameof(Address)); + Username = login.User.Username; + SetQuota(login.User); + State = ConnectionState.Connected; + Log.Info("session", $"Signed in to {uri} as {login.User.Username}"); + return (SignInResult.Success, null); + } + catch (Exception ex) + { + client.Dispose(); + State = previous == ConnectionState.SigningIn ? ConnectionState.NotConfigured : previous; + var result = Classify(ex, ct); + if (result == SignInResult.Failed) Log.Warning("session", $"Sign-in to {uri} failed", ex); + return (result, (ex as UntrustedCertificateException)?.Fingerprint); + } + } + + public void Trust(string fingerprint) + { + if (_settings.TrustedFingerprints.Contains(fingerprint, StringComparer.OrdinalIgnoreCase)) return; + _settings.TrustedFingerprints.Add(fingerprint); + _saveSettings(); + Log.Info("session", $"Trusted certificate {fingerprint}"); + } + + public async Task SignOutAsync() + { + StopProbing(); + if (_client is { Token: not null } client) + { + try + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + await client.LogoutAsync(timeout.Token); + } + catch (Exception ex) when (ex is HttpRequestException or TitanoApiException or OperationCanceledException or UntrustedCertificateException) + { + // The token is forgotten locally either way. + Log.Info("session", "Logout not confirmed by the server: " + ex.Message); + } + } + ForgetToken(); + } + + public async Task RefreshAsync() + { + if (_client is not { } client) return; + try + { + var me = await client.MeAsync(); + Username = me.Username; + SetQuota(me); + State = ConnectionState.Connected; + StopProbing(); + } + catch (Exception ex) when (IsServerProblem(ex, CancellationToken.None, out var problem)) + { + OnServerProblem(problem, ex); + } + catch (TitanoApiException ex) + { + Log.Warning("session", "Account refresh failed", ex); + } + } + + public async Task> ListSequencesAsync(CancellationToken ct) + { + if (!IsReady) return []; + var all = new List(); + string? cursor = null; + try + { + // Five pages of 200 cover any realistic choice list. + for (var page = 0; page < 5; page++) + { + var result = await _client!.ListSequencesAsync(cursor: cursor, ct: ct); + all.AddRange(result.Items); + cursor = result.NextCursor; + if (cursor is null) break; + } + } + catch (Exception ex) when (IsServerProblem(ex, ct, out var problem)) + { + OnServerProblem(problem, ex); + } + catch (TitanoApiException ex) + { + Log.Warning("session", "Sequence list unavailable", ex); + } + return all; + } + + // ---------------- IUploadTransport ---------------- + + public async Task<(UploadOutcome Outcome, Guid? FrameId)> UploadAsync(UploadItem item, Guid? sequenceId, string sha256, IProgress progress, CancellationToken ct) + { + var client = _client ?? throw new ServerUnavailableException(ServerProblem.SignedOut); + try + { + var result = await client.UploadFileAsync(item.Path, sequenceId, item.CapturedAt, item.SessionKey, sha256, progress, ct); + // The client reports an existing file as index −1 (or no frame at all). + return result is null || result.Index < 0 ? (UploadOutcome.AlreadyOnServer, result?.FrameId) : (UploadOutcome.Verified, result.FrameId); + } + catch (Exception ex) when (IsServerProblem(ex, ct, out var problem)) + { + OnServerProblem(problem, ex); + throw new ServerUnavailableException(problem, ex); + } + } + + public async Task CreateSequenceAsync(string? title, CancellationToken ct) + { + var client = _client ?? throw new ServerUnavailableException(ServerProblem.SignedOut); + try + { + var created = await client.CreateSequenceAsync(new CreateSequenceRequest(string.IsNullOrWhiteSpace(title) ? null : title.Trim(), null), ct); + Log.Info("session", $"Created sequence {created.Id} \"{created.DisplayTitle}\""); + return created.Id; + } + catch (Exception ex) when (IsServerProblem(ex, ct, out var problem)) + { + OnServerProblem(problem, ex); + throw new ServerUnavailableException(problem, ex); + } + } + + public void Dispose() + { + StopProbing(); + _client?.Dispose(); + } + + // ---------------- Plumbing ---------------- + + private TitanoClient CreateClient(Uri uri) + { + // A fresh pinning per client: the protocol's last-rejected fingerprint must not outlive a trust decision. + var client = new TitanoClient(uri, new CertificatePinning(_settings.TrustedFingerprints), $"Titano Uploader ({Environment.MachineName})"); + client.Bandwidth.BytesPerSecond = _bandwidthLimit * 1_000_000L; + return client; + } + + private void UseClient(TitanoClient client) + { + if (ReferenceEquals(_client, client)) return; + _client?.Dispose(); + _client = client; + } + + private void ApplyBandwidth() + { + if (_client is not null) _client.Bandwidth.BytesPerSecond = _bandwidthLimit * 1_000_000L; + } + + private void SetQuota(UserDto user) + { + QuotaBytes = user.QuotaBytes; + UsedBytes = user.UsedBytes; + } + + private void ForgetToken() + { + if (_client is not null) _client.Token = null; + _settings.ProtectedToken = null; + _saveSettings(); + QuotaBytes = 0; + UsedBytes = 0; + State = _settings.ServerUrl is null ? ConnectionState.NotConfigured : ConnectionState.SignedOut; + } + + private bool IsServerProblem(Exception ex, CancellationToken ct, out ServerProblem problem) + { + problem = ServerProblem.Unreachable; + switch (ex) + { + case TitanoApiException { Status: HttpStatusCode.Unauthorized }: + problem = ServerProblem.SignedOut; + return true; + case TitanoApiException api: + return api.IsTransient; + case UntrustedCertificateException untrusted: + // The pinning remembers its last rejection; once trusted, a later network error can still carry it. + if (!_settings.TrustedFingerprints.Contains(untrusted.Fingerprint, StringComparer.OrdinalIgnoreCase)) + problem = ServerProblem.CertificateChanged; + return true; + case HttpRequestException: + return true; + case OperationCanceledException when !ct.IsCancellationRequested: + return true; // request timeout + default: + return false; + } + } + + private void OnServerProblem(ServerProblem problem, Exception ex) + { + switch (problem) + { + case ServerProblem.SignedOut: + Log.Warning("session", "The server rejected the token; signing out"); + StopProbing(); + ForgetToken(); + SessionEnded?.Invoke(this, problem); + break; + case ServerProblem.CertificateChanged: + // Never upload to a server whose certificate changed: the user must sign in and confirm it again. + Log.Warning("session", "The server certificate changed; sign in again to review it", ex); + StopProbing(); + ForgetToken(); + SessionEnded?.Invoke(this, problem); + break; + default: + if (State != ConnectionState.Offline) Log.Warning("session", "Server unreachable; retrying every 30 s", ex); + State = ConnectionState.Offline; + StartProbing(); + break; + } + } + + private void StartProbing() + { + if (_probe is not null) return; + _probe = new CancellationTokenSource(); + _ = ProbeAsync(_probe.Token); + } + + private void StopProbing() + { + _probe?.Cancel(); + _probe?.Dispose(); + _probe = null; + } + + private async Task ProbeAsync(CancellationToken ct) + { + try + { + while (!ct.IsCancellationRequested && State == ConnectionState.Offline) + { + await Task.Delay(ProbeInterval, ct); + await RefreshAsync(); + } + } + catch (OperationCanceledException) + { + } + } + + private static SignInResult Classify(Exception ex, CancellationToken ct) => ex switch + { + UntrustedCertificateException => SignInResult.Untrusted, + TitanoApiException { Status: HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden } => SignInResult.BadCredentials, + TitanoApiException { Status: HttpStatusCode.NotFound } => SignInResult.NotTitano, + TitanoApiException api when api.IsTransient => SignInResult.Unreachable, + JsonException or NotSupportedException => SignInResult.NotTitano, + HttpRequestException => SignInResult.Unreachable, + OperationCanceledException when !ct.IsCancellationRequested => SignInResult.Unreachable, + _ => SignInResult.Failed, + }; + + private bool Set(ref T field, T value, [CallerMemberName] string? name = null) + { + if (EqualityComparer.Default.Equals(field, value)) return false; + field = value; + OnPropertyChanged(name); + return true; + } + + private void OnPropertyChanged([CallerMemberName] string? name = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); +} diff --git a/src/Titano.Uploader/Shell/ConfirmDialog.xaml b/src/Titano.Uploader/Shell/ConfirmDialog.xaml new file mode 100644 index 00000000..d3eab487 --- /dev/null +++ b/src/Titano.Uploader/Shell/ConfirmDialog.xaml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +