merge: desktop settings fixes (V-4, V-6, V-7, V-30, V-31, V-32, V-34, ENG-08)

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-12 16:54:07 +00:00
commit 78190476be
34 files changed
+1132 -171

No files matched your search

+1 -1
View File
@@ -92,7 +92,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S
| Host | Composition root | What it runs |
|---|---|---|
| Titano (desktop) | `App/Infrastructure/AppServices` | SQLite index in `%LOCALAPPDATA%\Titano` (or `.\data` when portable); `ArchiveService` with WIC first, then managed decoders; `ProcessingService` with Media Foundation, then managed encoders; one `JobEngine` with the handlers of both; thumbnails; `ServerSession`; `SyncHost` while signed in (sync engine and agent, upload and download handlers, metered hold, editors of server sequences); the render node while opted in and signed in; update check and download (`About/UpdateCheck`, `About/UpdateDownload`, `About/UpdateFlow`: the setup, or the portable zip for a portable copy, verified against `SHA256SUMS`, resumable, cancellable, failing after 60 s without data); diagnostics bundle; daily index backups and the restore staged in Settings › Advanced (`DatabaseBackups`) |
| Titano (desktop) | `App/Infrastructure/AppServices` | SQLite index in `%LOCALAPPDATA%\Titano` (or `.\data` when portable, unless the copy is in a OneDrive folder); `ArchiveService` with WIC first, then managed decoders; `ProcessingService` with Media Foundation, then managed encoders; one `JobEngine` with the handlers of both; thumbnails; `ServerSession`; `SyncHost` while signed in (sync engine and agent, upload and download handlers, metered hold, editors of server sequences); the render node while opted in and signed in; update check and download (`About/UpdateCheck`, `About/UpdateDownload`, `About/UpdateFlow`: the setup, or the portable zip for a portable copy, verified against `SHA256SUMS`, resumable, cancellable, failing after 60 s without data); diagnostics bundle; daily index backups and the restore staged in Settings › Advanced (`DatabaseBackups`) |
| Titano Server | `Server/Hosting/ServerHost.Build` | Options from `server.json` + `TITANO_*`; PostgreSQL (or SQLite on Windows); `ArchiveModule` then `ProcessingModule` register job handler providers; `JobEngineHost` (renders only managed formats and MP4 jobs no render node can take, BRIEF §14.7); `RenderNodeService`/`RenderNodeMonitor`; `UploadService`; `EventHub` (WebSocket); embedded admin panel; LAN discovery beacon; Windows service host; daily backups of an SQLite index (`DatabaseBackupService`) |
| Titano Uploader | `Uploader/App.xaml.cs` | `TitanoClient`, persisted queue, watch folders; no database |
| Titano Setup | `Setup/Program` | TPK1 payload extraction, registry, shortcuts, file types named in setup's language, silent mode, uninstaller; only what starts a program its log or payload lists is changed: Windows services of those programs stopped once the programs have closed, started again (also after a failure) or deleted through the Service Control Manager (an elevated `/SERVICES … /NAMES` step when needed), sign-in entries of those programs moved to the program an upgrade renamed or removed, shared shortcuts handed to the product that keeps the program; the Server only for all users inside Program Files; "Remove my data" limited to the programs no other installed product uses |
+3
View File
@@ -8,9 +8,12 @@
<data name="Settings.Advanced.BackupDone" xml:space="preserve"><value>Index backed up</value></data>
<data name="Settings.Advanced.BackupNow" xml:space="preserve"><value>Back up now</value></data>
<data name="Settings.Advanced.DataFolder" xml:space="preserve"><value>Data folder</value></data>
<data name="Settings.Advanced.DataInOneDrive" xml:space="preserve"><value>Data inside OneDrive</value></data>
<data name="Settings.Advanced.DataOutsideOneDrive" xml:space="preserve"><value>Data kept outside OneDrive</value><comment>long</comment></data>
<data name="Settings.Advanced.Diagnostics" xml:space="preserve"><value>Diagnostics</value></data>
<data name="Settings.Advanced.DiagnosticsDone" xml:space="preserve"><value>Diagnostics bundle saved</value></data>
<data name="Settings.Advanced.DiagnosticsTitle" xml:space="preserve"><value>Save the diagnostics bundle to</value></data>
<data name="Settings.Advanced.EarlierData" xml:space="preserve"><value>Earlier data unused</value></data>
<data name="Settings.Advanced.ExportBundle" xml:space="preserve"><value>Export bundle</value></data>
<data name="Settings.Advanced.Logs" xml:space="preserve"><value>Logs</value></data>
<data name="Settings.Advanced.NoBackups" xml:space="preserve"><value>No backups yet</value></data>
+2
View File
@@ -528,10 +528,12 @@
<data name="Tooltips.Settings.ClearCache" xml:space="preserve"><value>Delete the cache contents now</value></data>
<data name="Tooltips.Settings.ClearCacheAsk" xml:space="preserve"><value>Delete spilled frames and cached thumbnails; asks first</value></data>
<data name="Tooltips.Settings.DataFolder" xml:space="preserve"><value>Database, settings, logs and caches of this PC</value></data>
<data name="Tooltips.Settings.DataInOneDrive" xml:space="preserve"><value>Open the data folder in Explorer. OneDrive synchronises it, which can damage the index: exclude it from syncing</value></data>
<data name="Tooltips.Settings.DeepAfterImport" xml:space="preserve"><value>New cards and folders queue a deep analysis of what they import, in the background; each card can change it</value></data>
<data name="Tooltips.Settings.DeepAfterScan" xml:space="preserve"><value>Sequences a scan finds (adopted folders, new sidecars) also get a deep analysis, in the background</value></data>
<data name="Tooltips.Settings.DefaultServer" xml:space="preserve"><value>Server Titano connects to at start; changing it signs out · Enter applies, Esc reverts</value></data>
<data name="Tooltips.Settings.Diagnostics" xml:space="preserve"><value>Zip the logs, a system and codec report, settings and recent failed jobs into a folder you choose; passwords, tokens and photos are left out</value></data>
<data name="Tooltips.Settings.EarlierData" xml:space="preserve"><value>Open the data this portable copy kept beside it before it ran from OneDrive. Titano no longer uses it and leaves it as it is</value></data>
<data name="Tooltips.Settings.Export" xml:space="preserve"><value>Save every setting as JSON, without the session token</value></data>
<data name="Tooltips.Settings.FileTemplate" xml:space="preserve"><value>File name of each frame, for example {date}_{time}_{n:0000}; the extension is added · Enter applies, Esc reverts</value></data>
<data name="Tooltips.Settings.FolderTemplate" xml:space="preserve"><value>Archive folders, for example {year}/{date} {camera}; a slash starts a subfolder · Enter applies, Esc reverts</value></data>
+3
View File
@@ -8,9 +8,12 @@
<data name="Settings.Advanced.BackupDone" xml:space="preserve"><value>Copia dell'indice salvata</value></data>
<data name="Settings.Advanced.BackupNow" xml:space="preserve"><value>Salva una copia</value></data>
<data name="Settings.Advanced.DataFolder" xml:space="preserve"><value>Cartella dati</value></data>
<data name="Settings.Advanced.DataInOneDrive" xml:space="preserve"><value>Dati dentro OneDrive</value></data>
<data name="Settings.Advanced.DataOutsideOneDrive" xml:space="preserve"><value>Dati tenuti fuori da OneDrive</value></data>
<data name="Settings.Advanced.Diagnostics" xml:space="preserve"><value>Diagnostica</value></data>
<data name="Settings.Advanced.DiagnosticsDone" xml:space="preserve"><value>Pacchetto diagnostico salvato</value></data>
<data name="Settings.Advanced.DiagnosticsTitle" xml:space="preserve"><value>Salva il pacchetto in</value></data>
<data name="Settings.Advanced.EarlierData" xml:space="preserve"><value>Dati precedenti inutilizzati</value></data>
<data name="Settings.Advanced.ExportBundle" xml:space="preserve"><value>Esporta pacchetto</value></data>
<data name="Settings.Advanced.Logs" xml:space="preserve"><value>Log</value></data>
<data name="Settings.Advanced.NoBackups" xml:space="preserve"><value>Ancora nessuna copia</value></data>
+2
View File
@@ -528,10 +528,12 @@
<data name="Tooltips.Settings.ClearCache" xml:space="preserve"><value>Elimina adesso il contenuto della cache</value></data>
<data name="Tooltips.Settings.ClearCacheAsk" xml:space="preserve"><value>Elimina fotogrammi temporanei e miniature in cache; prima chiede conferma</value></data>
<data name="Tooltips.Settings.DataFolder" xml:space="preserve"><value>Database, impostazioni, log e cache di questo PC</value></data>
<data name="Tooltips.Settings.DataInOneDrive" xml:space="preserve"><value>Apri la cartella dati in Esplora file. OneDrive la sincronizza e così può danneggiare l'indice: escludila dalla sincronizzazione</value></data>
<data name="Tooltips.Settings.DeepAfterImport" xml:space="preserve"><value>Schede e cartelle nuove accodano l'analisi profonda di ciò che importano, in background; ogni scheda può cambiarlo</value></data>
<data name="Tooltips.Settings.DeepAfterScan" xml:space="preserve"><value>Anche le sequenze trovate da una scansione (cartelle adottate, nuovi sidecar) ricevono l'analisi profonda, in background</value></data>
<data name="Tooltips.Settings.DefaultServer" xml:space="preserve"><value>Server a cui Titano si connette all'avvio; cambiarlo chiude l'accesso · Invio applica, Esc annulla</value></data>
<data name="Tooltips.Settings.Diagnostics" xml:space="preserve"><value>Comprime log, rapporto su sistema e codec, impostazioni e attività fallite di recente in una cartella a tua scelta; password, token e foto restano fuori</value></data>
<data name="Tooltips.Settings.EarlierData" xml:space="preserve"><value>Apri i dati che questa copia portatile teneva accanto a sé prima di trovarsi in OneDrive. Titano non li usa più e li lascia com'erano</value></data>
<data name="Tooltips.Settings.Export" xml:space="preserve"><value>Salva tutte le impostazioni in JSON, senza il token di sessione</value></data>
<data name="Tooltips.Settings.FileTemplate" xml:space="preserve"><value>Nome del file di ogni fotogramma, ad esempio {date}_{time}_{n:0000}; l'estensione viene aggiunta · Invio applica, Esc annulla</value></data>
<data name="Tooltips.Settings.FolderTemplate" xml:space="preserve"><value>Cartelle dell'archivio, ad esempio {year}/{date} {camera}; la barra crea una sottocartella · Invio applica, Esc annulla</value></data>
+4
View File
@@ -45,6 +45,10 @@ public partial class App : Application
// Capture runs in CI: mirror the log to stderr so failures are visible in the job output.
Log.SetSink(capture ? new TeeLogSink(_log, new StderrLogSink()) : _log);
Log.Info("app", $"Titano {AppServices.VersionText} starting; data at {Environment.DataDirectory}");
// Settings tells the user once the window is up.
if (Environment.PortableSyncRoot is { } portableIn) Log.Warning("app", $"This portable copy runs in the OneDrive folder {portableIn}: its data is kept outside it");
if (Environment.EarlierPortableData is { } earlier) Log.Warning("app", $"The data this portable copy kept in {earlier} before is left there and no longer used");
if (Environment.SyncedFolder is { } synced) Log.Warning("app", $"The data folder lies in the OneDrive folder {synced}: synchronisation may damage the index");
var projectFile = capture ? null : ProjectFileArgument(e.Args);
if (!capture)
+29 -11
View File
@@ -1,18 +1,26 @@
using System.IO;
using Titano.Core.Windows.Shell;
namespace Titano.App.Infrastructure;
/// <summary>
/// Where the client keeps its data (BRIEF §6.2): <c>%LOCALAPPDATA%\Titano</c>, or <c>.\data</c> next to the
/// executable when <c>portable.txt</c> exists. Never inside Documents/OneDrive (SQLite corrupts in synced folders).
/// Where the client keeps its data (BRIEF §6.2, <see cref="AppPaths"/>): <c>%LOCALAPPDATA%\Titano</c>, or <c>.\data</c>
/// next to the executable when <c>portable.txt</c> exists. Never inside a folder OneDrive synchronises (SQLite corrupts
/// there): a portable copy in one keeps its data in <c>%LOCALAPPDATA%\Titano</c>, and Settings tells the user so
/// (<see cref="PortableSyncRoot"/>, <see cref="EarlierPortableData"/>). When that folder itself lies in one, nowhere
/// is safe: Titano starts all the same and Settings warns (<see cref="SyncedFolder"/>).
/// </summary>
public sealed class AppEnvironment
{
private AppEnvironment(string dataDirectory, bool portable, bool isCapture)
private AppEnvironment(string dataDirectory, bool portable, bool isCapture, string? syncedFolder = null, string? portableSyncRoot = null,
string? earlierPortableData = null)
{
DataDirectory = dataDirectory;
IsPortable = portable;
IsCapture = isCapture;
SyncedFolder = syncedFolder;
PortableSyncRoot = portableSyncRoot;
EarlierPortableData = earlierPortableData;
Directory.CreateDirectory(DataDirectory);
Directory.CreateDirectory(LogDirectory);
Directory.CreateDirectory(CacheDirectory);
@@ -24,19 +32,29 @@ public sealed class AppEnvironment
/// <summary>A throw-away environment for <c>--capture</c>: nothing of the user's data is read or written.</summary>
public bool IsCapture { get; }
/// <summary>The OneDrive folder <see cref="DataDirectory"/> itself lies in, where the index may be damaged; null when it is safe.</summary>
public string? SyncedFolder { get; }
/// <summary>The OneDrive folder this portable copy runs from; its data is in <c>%LOCALAPPDATA%\Titano</c> instead of <c>.\data</c>. Null otherwise.</summary>
public string? PortableSyncRoot { get; }
/// <summary>The <c>.\data</c> folder this portable copy used before it ran from OneDrive, left as it was; null when there is none.</summary>
public string? EarlierPortableData { get; }
public string LogDirectory => Path.Combine(DataDirectory, "logs");
public string CacheDirectory => Path.Combine(DataDirectory, "cache");
public string BackupDirectory => Path.Combine(DataDirectory, "backups");
public string DatabasePath => Path.Combine(DataDirectory, "titano.db");
public string SettingsPath => Path.Combine(DataDirectory, "settings.json");
public string DatabasePath => Path.Combine(DataDirectory, AppPaths.DatabaseFileName);
public string SettingsPath => Path.Combine(DataDirectory, AppPaths.SettingsFileName);
public static AppEnvironment Detect()
/// <summary>The environment of this process: its executable's folder and the user's OneDrive folders decide.</summary>
public static AppEnvironment Detect() => From(AppPaths.Resolve());
/// <summary>The environment at <paramref name="paths"/> (its folders are created).</summary>
public static AppEnvironment From(AppPaths paths)
{
var exeDir = AppContext.BaseDirectory;
if (File.Exists(Path.Combine(exeDir, "portable.txt")))
return new AppEnvironment(Path.Combine(exeDir, "data"), portable: true, isCapture: false);
var local = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
return new AppEnvironment(Path.Combine(local, "Titano"), portable: false, isCapture: false);
ArgumentNullException.ThrowIfNull(paths);
return new(paths.DataRoot, paths.IsPortable, isCapture: false, paths.SyncedFolder, paths.PortableSyncRoot, paths.EarlierPortableData);
}
/// <summary>A fresh temporary data folder for screenshots and smoke tests; delete it with <see cref="DeleteCaptureData"/>.</summary>
+75 -20
View File
@@ -3,6 +3,7 @@ using System.IO;
using System.Net.Http;
using System.Reflection;
using Titano.App.About;
using Titano.App.Archiving;
using Titano.App.Import;
using Titano.App.Jobs;
using Titano.App.Library;
@@ -32,13 +33,13 @@ namespace Titano.App.Infrastructure;
/// managed encoders), the one <see cref="JobEngine"/> of this PC with the handlers of <see cref="CreateJobHandlers"/>,
/// thumbnails, the server session, the render node, the encoder and format inventories, the update check and the sync
/// with the signed-in server (<see cref="SyncHost"/>). Started after the window shows, stopped when the app exits. The
/// last archive is reopened at start and rescanned every <see cref="ScanInterval"/> (Settings › Archive; BRIEF §7:
/// polling, no file-system watchers). Jobs follow Settings › Rendering and Analysis from the next one on (memory
/// budget, quality profile, analysis parameters through <see cref="ProcessingTuning"/>; parallelism as the engine's
/// workers). The render node runs while the user offers this PC (<see cref="AppSettings.RenderNodeOptIn"/>) and a
/// server session is open (never in capture mode). Renders and the render node use hardware encoders as Settings ›
/// Rendering allows (<see cref="AllowsHardware(HardwarePreference, string)"/>). Disposal never needs the UI thread,
/// which waits for it.
/// archive at Settings › Archive's folder is reopened at start and rescanned every <see cref="ScanInterval"/>, as is one
/// chosen later (BRIEF §7: polling, no file-system watchers). Jobs follow Settings › Rendering and Analysis from the
/// next one on (memory budget, quality profile, analysis parameters through <see cref="ProcessingTuning"/>; parallelism
/// as the engine's workers). The render node runs while the user offers this PC (<see cref="AppSettings.RenderNodeOptIn"/>)
/// and a server session is open (never in capture mode). Renders and the render node use hardware encoders as
/// Settings › Rendering allows (<see cref="AllowsHardware(HardwarePreference, string)"/>). Disposal never needs the UI
/// thread, which waits for it.
/// </summary>
public sealed class AppServices : IAsyncDisposable
{
@@ -228,7 +229,7 @@ public sealed class AppServices : IAsyncDisposable
Devices.Start();
var database = Database;
_backups = Task.Run(() => DatabaseBackups.RunDailyAsync(database, Environment.BackupDirectory, null, _stopping.Token));
if (Settings.LastArchivePath is { Length: > 0 } root) _polling = PollAsync(root, _stopping.Token);
_polling = PollAsync(_stopping.Token);
}
/// <summary>Uses an already open index (capture, tests) instead of opening one; sample data keeps the engine stopped.</summary>
@@ -258,35 +259,89 @@ public sealed class AppServices : IAsyncDisposable
if (Database is not null) await Database.DisposeAsync().ConfigureAwait(false);
}
/// <summary>Reopens the last archive (relinking a moved one, finishing interrupted renames) and rescans it periodically,
/// off the UI thread (disposal waits for it there).</summary>
private async Task PollAsync(string root, CancellationToken ct)
/// <summary>The period of the rescans while they run (Settings › Archive › Rescan every); null before the index opens.</summary>
internal TimeSpan? PollingPeriod => _pollTimer?.Period;
/// <summary>
/// One rescan of the polling, off the UI thread: the archive the Import and Archive screens work on
/// (<see cref="CurrentArchive"/>, the one at Settings › Archive's folder) first takes the settings another process
/// sharing it wrote into its archive.json (also on a read-only share), then gets an incremental scan while it is
/// online. Returns that archive; null when the index holds none.
/// </summary>
internal Task<Archive?> RescanAsync(CancellationToken ct = default) => Task.Run(async () =>
{
if (Database is not { } db || Archives is not { } archives) return null;
var archive = CurrentArchive.Pick(await db.Archives.ListAsync(ct).ConfigureAwait(false), Settings.LastArchivePath);
if (archive is null) return null;
var availability = ArchiveService.GetAvailability(archive);
if (availability != ArchiveAvailability.Offline) await archives.RefreshSettingsAsync(archive.Id, ct).ConfigureAwait(false);
if (availability == ArchiveAvailability.Online) await QueueScanAsync(archive, full: false, ct).ConfigureAwait(false);
return archive;
}, ct);
/// <summary>
/// Rescans the archive now and every <see cref="ScanInterval"/> (<see cref="RescanAsync"/>) until the app exits, which
/// waits for it on the UI thread. Each rescan follows the archive folder: one chosen on the first run, in Settings or
/// by a relink is rescanned from the next tick on, the one before no longer. The archive at the folder of the start is
/// first reopened (a moved one relinked, interrupted renames finished), at each tick until its archive.json is there
/// (an unplugged drive), unless the folder changed meanwhile: whatever changed it opened the new archive.
/// </summary>
private async Task PollAsync(CancellationToken ct)
{
var reopen = Settings.LastArchivePath is { Length: > 0 } start ? start : null;
// Settings › Archive changes the period of this timer (ApplyJobSettings).
using var timer = _pollTimer = new PeriodicTimer(ScanInterval);
try
{
if (Archives is null) return;
var archive = await Task.Run(() => Archives.OpenAsync(root, ct), ct).ConfigureAwait(false);
// Settings › Archive changes the period of this timer (ApplyJobSettings).
using var timer = _pollTimer = new PeriodicTimer(ScanInterval);
do
{
if (ArchiveService.GetAvailability(archive) == ArchiveAvailability.Online) await QueueScanAsync(archive, full: false, ct).ConfigureAwait(false);
if (reopen is not null
&& (!string.Equals(reopen, Settings.LastArchivePath, StringComparison.OrdinalIgnoreCase) || await ReopenAsync(reopen, ct).ConfigureAwait(false)))
reopen = null;
try
{
await RescanAsync(ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException or ArgumentException)
{
// The next tick tries again (a share that dropped, an archive removed from the index meanwhile).
Log.Warning("archive", "The archive could not be rescanned", ex);
}
}
while (await timer.WaitForNextTickAsync(ct).ConfigureAwait(false));
}
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);
}
finally
{
_pollTimer = null;
}
}
/// <summary>
/// Registers the archive at <paramref name="root"/> again as at open; false while its archive.json is not there. A
/// damaged or newer one is not tried again: the archive the index holds at the folder is still rescanned.
/// </summary>
private async Task<bool> ReopenAsync(string root, CancellationToken ct)
{
if (Archives is not { } archives) return true;
try
{
return await Task.Run(async () =>
{
if (!File.Exists(new ArchivePaths(root).ManifestPath)) return false;
await archives.OpenAsync(root, ct).ConfigureAwait(false);
return true;
}, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException or NewerFormatException)
{
Log.Warning("archive", $"The archive at {root} could not be opened", ex);
return true;
}
}
/// <summary>
/// A restore staged in Settings › Advanced replaces the index file before the index is opened, so it also recovers an
/// index that no longer opens (<see cref="StagedRestore"/>).
@@ -20,37 +20,48 @@ public interface IStartWithWindows
/// <summary>
/// <c>HKCU\Software\Microsoft\Windows\CurrentVersion\Run</c> value that starts Titano minimised at sign-in, so inserted
/// cards are noticed (BRIEF §12.4) without a window in the way. The registry stays the source of truth because Task
/// Manager can turn it off. There is one value for every copy of Titano: a copy shows it as on only when it starts
/// that copy, and never takes it over or removes it unless the user ticks or unticks the box there. The uninstaller
/// removes it with the Uploader's when it starts a program of the folder it removes.
/// Manager can turn it off: an entry it turned off (<see cref="StartupApproval"/>) shows as off, and ticking the box
/// turns it on again. There is one value for every copy of Titano: a copy shows it as on only when it starts that
/// copy, and never takes it over or removes it unless the user ticks or unticks the box there. The uninstaller removes
/// it with the Uploader's when it starts a program of the folder it removes.
/// </summary>
public sealed class RunKeyStartWithWindows(string? executable = null) : IStartWithWindows
/// <param name="executable">This copy's program; the running one by default.</param>
/// <param name="root">The registry hive holding the entries; <c>HKEY_CURRENT_USER</c> by default (tests pass a scratch key).</param>
public sealed class RunKeyStartWithWindows(string? executable = null, RegistryKey? root = null) : IStartWithWindows
{
/// <summary>Starts the main window minimised on the taskbar.</summary>
public const string MinimizedOption = "--minimized";
private readonly string? _executable = executable ?? Environment.ProcessPath;
private readonly RegistryKey _root = root ?? Registry.CurrentUser;
public bool IsEnabled => StartupCommand.Starts(Read(), _executable);
/// <summary>The entry starts this copy and Task Manager has not turned it off.</summary>
public bool IsEnabled => StartupCommand.Starts(Read(), _executable) && !StartupApproval.IsTurnedOff(ReadApproval());
public void SetEnabled(bool enabled)
{
if (_executable is null) return;
try
if (_executable is not { } executable) return;
Update(key =>
{
using var key = Registry.CurrentUser.CreateSubKey(StartupCommand.RunKey, writable: true);
if (enabled) key.SetValue(StartupCommand.ClientValue, StartupCommand.Format(_executable, MinimizedOption), RegistryValueKind.String);
else if (StartupCommand.Starts(key.GetValue(StartupCommand.ClientValue) as string, _executable)) key.DeleteValue(StartupCommand.ClientValue, throwOnMissingValue: false);
}
catch (Exception ex) when (ex is SecurityException or UnauthorizedAccessException or IOException)
{
Log.Warning("startup", "Run key not updated", ex);
}
if (enabled)
{
key.SetValue(StartupCommand.ClientValue, StartupCommand.Format(executable, MinimizedOption), RegistryValueKind.String);
// Task Manager's "Disable" outlives a new command: ticking the box undoes it.
DeleteApproval();
}
else if (StartupCommand.Starts(key.GetValue(StartupCommand.ClientValue) as string, executable))
{
key.DeleteValue(StartupCommand.ClientValue, throwOnMissingValue: false);
DeleteApproval();
}
});
}
/// <summary>The command follows a renamed program; an entry Task Manager turned off stays off.</summary>
public void Refresh()
{
if (Follows(Read(), _executable, File.Exists)) SetEnabled(true);
if (_executable is { } executable && Follows(Read(), executable, File.Exists))
Update(key => key.SetValue(StartupCommand.ClientValue, StartupCommand.Format(executable, MinimizedOption), RegistryValueKind.String));
}
/// <summary>
@@ -65,11 +76,11 @@ public sealed class RunKeyStartWithWindows(string? executable = null) : IStartWi
&& string.Equals(StartupCommand.Folder(command), folder, StringComparison.OrdinalIgnoreCase);
}
private static string? Read()
private string? Read()
{
try
{
using var key = Registry.CurrentUser.OpenSubKey(StartupCommand.RunKey);
using var key = _root.OpenSubKey(StartupCommand.RunKey);
return key?.GetValue(StartupCommand.ClientValue) as string;
}
catch (Exception ex) when (ex is SecurityException or IOException)
@@ -77,6 +88,39 @@ public sealed class RunKeyStartWithWindows(string? executable = null) : IStartWi
return null;
}
}
/// <summary>Task Manager's switch for the entry; null when it never touched it.</summary>
private byte[]? ReadApproval()
{
try
{
using var key = _root.OpenSubKey(StartupApproval.RunKey);
return key?.GetValue(StartupCommand.ClientValue) as byte[];
}
catch (Exception ex) when (ex is SecurityException or IOException)
{
return null;
}
}
private void DeleteApproval()
{
using var key = _root.OpenSubKey(StartupApproval.RunKey, writable: true);
key?.DeleteValue(StartupCommand.ClientValue, throwOnMissingValue: false);
}
private void Update(Action<RegistryKey> change)
{
try
{
using var key = _root.CreateSubKey(StartupCommand.RunKey, writable: true);
change(key);
}
catch (Exception ex) when (ex is SecurityException or UnauthorizedAccessException or IOException)
{
Log.Warning("startup", "Run key not updated", ex);
}
}
}
/// <summary>Screenshots, tests and portable copies (which leave nothing in the registry) never touch the user's sign-in programs.</summary>
+120 -37
View File
@@ -45,6 +45,12 @@ public sealed class SettingsViewModel : SectionViewModel
private bool _isTesting;
private CancellationTokenSource? _selfTest;
private Archive? _archive;
/// <summary>
/// The open of the archive at the folder chosen last (<see cref="RetargetArchiveAsync"/>), with the archive it found
/// there: edits of the Archive rows made meanwhile wait for it (<see cref="ArchiveAtFolderAsync"/>).
/// </summary>
private Task<Archive?> _retarget = Task.FromResult<Archive?>(null);
private bool _isDetectingFormats;
private IReadOnlyList<BackupOption> _backups = [];
private BackupOption? _selectedBackup;
@@ -82,7 +88,7 @@ public sealed class SettingsViewModel : SectionViewModel
_s.LastArchivePath = v.Length == 0 ? null : Path.GetFullPath(v);
Save();
UpdateArchiveFree();
_ = RetargetArchiveAsync();
_retarget = RetargetArchiveAsync();
}, () => Loc.L("Tooltips.Settings.ArchiveRoot"));
FolderTemplate = new EditableField(_s.FolderTemplate, v => NamingPreview.Validate(v, isFolder: true), v =>
{
@@ -307,6 +313,9 @@ public sealed class SettingsViewModel : SectionViewModel
/// <summary>Where "Start with Windows" is kept (the Run key); screenshots, tests and portable copies keep it in memory.</summary>
internal IStartWithWindows Startup { get; set; }
/// <summary>The latest archive folder change: done once the rows show what the folder holds (tests wait for it).</summary>
internal Task ArchiveRetarget => _retarget;
/// <summary>A portable copy leaves nothing in the registry (BRIEF §6.2): it offers no Startup row.</summary>
public bool ShowsStartup => !Shell.Services.Environment.IsPortable;
@@ -770,7 +779,8 @@ public sealed class SettingsViewModel : SectionViewModel
/// <summary>
/// Loads what needs the services (certificates, cache usage, the open archive's settings), follows the server session,
/// applies "Background priority" while Titano is in front and says how a restore staged before this start went.
/// applies "Background priority" while Titano is in front and says how a restore staged before this start went, and
/// where the data of a portable copy in a OneDrive folder went.
/// </summary>
public void Attach()
{
@@ -798,6 +808,18 @@ public sealed class SettingsViewModel : SectionViewModel
Shell.Notify(Loc.L("Settings.Advanced.RestoreFailed"), Loc.L("Errors.Backup.Deferred"), isError: true);
break;
}
// BRIEF §6.2: a portable copy in a folder OneDrive synchronises keeps its data in this user's folder instead, and
// leaves the data it kept beside it before where it is. Only a user folder that is itself synchronised is unsafe.
var environment = Shell.Services.Environment;
if (environment.SyncedFolder is not null)
Shell.Notify(Loc.L("Settings.Advanced.DataInOneDrive"), Formatting.LeftToRight(DataFolder), Loc.L("Common.Open"),
Loc.L("Tooltips.Settings.DataInOneDrive"), () => ShellActions.Reveal(DataFolder), isError: true);
else if (environment.PortableSyncRoot is not null)
Shell.Notify(Loc.L("Settings.Advanced.DataOutsideOneDrive"), Formatting.LeftToRight(DataFolder), Loc.L("Common.Open"),
Loc.L("Tooltips.Settings.OpenDataFolder"), () => ShellActions.Reveal(DataFolder));
if (environment.EarlierPortableData is { } earlier)
Shell.Notify(Loc.L("Settings.Advanced.EarlierData"), Formatting.LeftToRight(earlier), Loc.L("Common.Open"),
Loc.L("Tooltips.Settings.EarlierData"), () => ShellActions.Reveal(earlier));
Startup.Refresh();
}
@@ -868,33 +890,48 @@ public sealed class SettingsViewModel : SectionViewModel
/// <summary>
/// Takes the archive and server values other screens set (opening an archive, connecting), unless the field holds an
/// edit not committed yet.
/// edit not committed yet, and the sign-in entry as Task Manager may have left it.
/// </summary>
private void ReloadShared()
{
if (!ArchiveRoot.IsDirty) ArchiveRoot.Load(_s.LastArchivePath ?? string.Empty);
if (!DefaultServer.IsDirty) DefaultServer.Load(ServerAddress.Display(_s.ServerUrl));
OnPropertyChanged(nameof(StartWithWindows));
UpdateArchiveFree();
_ = LoadArchiveAsync();
if (_page == SettingsPage.Advanced) LoadBackups();
}
/// <summary>
/// Shows the open archive's own templates, proxy size and thumbnail size (its archive.json; the index's while it is
/// offline) unless a field holds an edit; they also become the defaults of new archives. The open archive is the one
/// at the archive folder of this PC, never another one of the index: with none registered there, the rows edit only
/// this PC's defaults.
/// Shows the open archive's own templates, proxy size and thumbnail size unless a field holds an edit; they also become
/// the defaults of new archives. They come from its archive.json, which also brings the index up to a change another
/// process sharing the archive made, so imports follow it too. While the file cannot be read (offline), the templates
/// and proxy size are the index's and the thumbnail size stays this PC's: only the file knows the archive's. The open
/// archive is the one at the archive folder of this PC, never another one of the index: with no folder, or none
/// registered there, the rows edit only this PC's defaults. Returns that archive (null for none).
/// </summary>
private async Task LoadArchiveAsync()
private Task<Archive?> LoadArchiveAsync() => LoadArchiveAsync(_s.LastArchivePath);
/// <summary>
/// <see cref="LoadArchiveAsync()"/> for the archive folder <paramref name="root"/>, which a folder change may have
/// replaced meanwhile: the rows are then left to the folder chosen since, and the archive registered at
/// <paramref name="root"/> is still returned, so edits made for that folder reach it.
/// </summary>
private async Task<Archive?> LoadArchiveAsync(string? root)
{
if (Shell.Services.Database is not { } db || Shell.Services.Archives is not { } archives) return;
if (Shell.Services.Database is not { } db || Shell.Services.Archives is not { } archives) return null;
Archive? archive = null;
try
{
var registered = await db.Archives.ListAsync();
var archive = _s.LastArchivePath is { Length: > 0 } root ? CurrentArchive.At(registered, root) : CurrentArchive.Pick(registered, null);
archive = root is { Length: > 0 } ? CurrentArchive.At(registered, root) : null;
if (!IsArchiveFolder(root)) return archive;
_archive = archive;
if (archive is null) return;
var settings = await Task.Run(() => archives.GetSettingsAsync(archive.Id));
if (archive is null) return null;
var settings = await Task.Run(() => archives.RefreshSettingsAsync(archive.Id))
?? new ArchiveSettings(archive.Name, new LayoutTemplates { Folder = archive.FolderTemplate, File = archive.FileTemplate },
new ProxyPolicy { LongEdge = archive.ProxyLongEdge }, new ThumbnailPolicy { LongEdge = _s.ThumbnailLongEdge });
if (!IsArchiveFolder(root)) return archive;
if (!FolderTemplate.IsDirty) FolderTemplate.Load(settings.Templates.Folder);
if (!FileTemplate.IsDirty) FileTemplate.Load(settings.Templates.File);
var changed = _s.FolderTemplate != settings.Templates.Folder || _s.FileTemplate != settings.Templates.File
@@ -915,20 +952,46 @@ public sealed class SettingsViewModel : SectionViewModel
{
Log.Warning("settings", "The open archive's settings could not be read", ex);
}
return archive;
}
/// <summary>Whether <paramref name="root"/> is still this PC's archive folder (the one the rows show).</summary>
private bool IsArchiveFolder(string? root) => string.Equals(root, _s.LastArchivePath, StringComparison.Ordinal);
/// <summary>
/// The archive an Archive row edits, as the folder was when the row was edited (<paramref name="retarget"/>, the
/// latest folder change then): the open one, or, while the archive at that folder is still opening or once another
/// folder has been chosen, the one found there (null for none), so the edit is neither lost nor sent to a folder
/// chosen later.
/// </summary>
private async Task<Archive?> ArchiveAtFolderAsync(Task<Archive?> retarget)
{
if (retarget.IsCompleted && retarget == _retarget) return _archive;
// Its failures were told already; only the archive it found matters here.
await ((Task)retarget).ConfigureAwait(ConfigureAwaitOptions.ContinueOnCapturedContext | ConfigureAwaitOptions.SuppressThrowing);
return retarget.IsCompletedSuccessfully ? retarget.Result : null;
}
/// <summary>
/// Writes one Archive row into the open archive's archive.json and index through the archive engine (BRIEF §7). When
/// that fails (offline, read-only, busy) the user hears why and the rows show the archive's values again.
/// that fails (offline, read-only, busy) the user hears why and the rows show the archive's values again. An edit made
/// while the archive at a folder just chosen is opening waits for it, then goes to that archive (or stays this PC's
/// default when there is none), instead of being lost. <paramref name="retarget"/> is the folder change the edit was
/// made after, the latest one by default.
/// </summary>
private async Task UpdateArchiveAsync(Func<ArchiveSettings, ArchiveSettings> edit)
private async Task UpdateArchiveAsync(Func<ArchiveSettings, ArchiveSettings> edit, Task<Archive?>? retarget = null)
{
if (_archive is not { } archive || Shell.Services.Archives is not { } archives) return;
retarget ??= _retarget;
var waited = !retarget.IsCompleted;
if (await ArchiveAtFolderAsync(retarget) is not { } archive || Shell.Services.Archives is not { } archives) return;
try
{
var updated = await Task.Run(() => archives.UpdateSettingsAsync(archive.Id, edit));
// The archive folder may have changed meanwhile: the rows then belong to another archive.
if (_archive?.Id == updated.Id) _archive = updated;
// The open showed the archive's values over the edit: unless another folder was chosen since, the rows (and
// this PC's defaults) take what it holds now.
if (waited && _retarget == retarget) await LoadArchiveAsync();
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or InvalidDataException or NewerFormatException
or DatabaseException)
@@ -939,36 +1002,42 @@ public sealed class SettingsViewModel : SectionViewModel
}
}
/// <summary>Every archive row into the open archive: Archive › Reset section, after the user confirmed it for that archive.</summary>
private Task PushArchiveSettingsAsync() => UpdateArchiveAsync(a => a with
/// <summary>
/// Every archive row into the archive found after <paramref name="retarget"/>: Archive › Reset section, after the user
/// confirmed it for that archive.
/// </summary>
private Task PushArchiveSettingsAsync(Task<Archive?> retarget) => UpdateArchiveAsync(a => a with
{
Templates = a.Templates with { Folder = _s.FolderTemplate, File = _s.FileTemplate },
Proxies = a.Proxies with { LongEdge = _s.ProxyLongEdge },
Thumbnails = a.Thumbnails with { LongEdge = _s.ThumbnailLongEdge },
});
}, retarget);
/// <summary>
/// The archive folder changed: an archive already there is registered as at start (relinked when it moved) and given
/// its rescan, and the rows show its settings; any other folder leaves them with this PC's defaults for new archives.
/// Later edits never reach the archive shown before.
/// Later edits never reach the archive shown before. Returns the archive registered at that folder (null for none),
/// even when another folder has been chosen since: edits made for this one go there.
/// </summary>
private async Task RetargetArchiveAsync()
private async Task<Archive?> RetargetArchiveAsync()
{
_archive = null;
if (_s.LastArchivePath is { } root && Shell.Services.Archives is { } archives)
var root = _s.LastArchivePath;
if (root is not null && Shell.Services.Archives is { } archives)
{
try
{
var opened = await Task.Run(async () => File.Exists(new ArchivePaths(root).ManifestPath) ? await archives.OpenAsync(root) : null);
if (opened is not null) await Shell.Services.QueueScanAsync(opened, full: false);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException)
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or NewerFormatException
or DatabaseException)
{
Log.Warning("settings", $"The archive at {root} could not be opened", ex);
Shell.Notify(Loc.L("Errors.Archive.Open"), ArchiveActions.Cause(ex), isError: true);
}
}
await LoadArchiveAsync();
return await LoadArchiveAsync(root);
}
/// <summary>
@@ -1306,19 +1375,8 @@ public sealed class SettingsViewModel : SectionViewModel
UiLanguage.Apply(null);
break;
case SettingsPage.Archive:
// The rows are the open archive's own: resetting them changes it for everyone sharing it, so only when confirmed.
var open = _archive;
if (open is not null && !ConfirmArchiveReset(open)) return;
_s.FolderTemplate = defaults.FolderTemplate;
_s.FileTemplate = defaults.FileTemplate;
_s.ProxyLongEdge = defaults.ProxyLongEdge;
_s.ThumbnailLongEdge = defaults.ThumbnailLongEdge;
_s.ScanIntervalMinutes = defaults.ScanIntervalMinutes;
FolderTemplate.Load(_s.FolderTemplate);
FileTemplate.Load(_s.FileTemplate);
UpdatePreview();
if (open is not null) _ = PushArchiveSettingsAsync();
break;
_ = ResetArchiveAsync(defaults);
return;
case SettingsPage.Import:
_s.ImportSessionGapMinutes = defaults.ImportSessionGapMinutes;
_s.ImportMinimumFrames = defaults.ImportMinimumFrames;
@@ -1367,6 +1425,31 @@ public sealed class SettingsViewModel : SectionViewModel
Shell.Server.Refresh();
}
/// <summary>
/// Archive › Reset section. The rows are the open archive's own: resetting them changes it for everyone sharing it, so
/// only when confirmed. The archive at a folder just chosen is opened first, so the question names it and the reset
/// reaches it instead of being undone when it opens.
/// </summary>
private async Task ResetArchiveAsync(AppSettings defaults)
{
var retarget = _retarget;
var open = await ArchiveAtFolderAsync(retarget);
if (open is not null && !ConfirmArchiveReset(open)) return;
_s.FolderTemplate = defaults.FolderTemplate;
_s.FileTemplate = defaults.FileTemplate;
_s.ProxyLongEdge = defaults.ProxyLongEdge;
_s.ThumbnailLongEdge = defaults.ThumbnailLongEdge;
_s.ScanIntervalMinutes = defaults.ScanIntervalMinutes;
FolderTemplate.Load(_s.FolderTemplate);
FileTemplate.Load(_s.FileTemplate);
UpdatePreview();
Save();
OnAllPropertiesChanged();
if (open is not null) await PushArchiveSettingsAsync(retarget);
// Another folder was chosen while this one's archive opened: the rows show what that folder's archive holds again.
if (retarget != _retarget) await LoadArchiveAsync();
}
private void LoadImportFields()
{
SessionGap.Load(_s.ImportSessionGapMinutes.ToString(CultureInfo.CurrentCulture));
@@ -1484,7 +1567,7 @@ public sealed class SettingsViewModel : SectionViewModel
ApplyAll(imported);
// Settings of a PC never rewrite the shared archive.json: the imported templates and sizes are the defaults of new
// archives, and the rows show the own settings of the archive at the (possibly imported) archive folder.
_ = RetargetArchiveAsync();
_retarget = RetargetArchiveAsync();
Shell.Notify(Loc.L("Settings.Import.Done"));
}
+34 -14
View File
@@ -1,22 +1,30 @@
using Titano.Core.IO;
namespace Titano.Core.Windows.Shell;
/// <summary>
/// Where the desktop programs keep their data (BRIEF §6.2): <c>%LOCALAPPDATA%\Titano</c>, or <c>.\data</c> next to the
/// executable in portable mode. SQLite corrupts inside synchronised folders, so a data root under OneDrive is
/// reported by <see cref="SyncedFolder"/> and refused by <see cref="CreateDirectories"/>.
/// Where the desktop programs keep their data (BRIEF §6.2, <see cref="DataLocation"/>): <c>%LOCALAPPDATA%\Titano</c>, or
/// <c>.\data</c> next to the executable in portable mode. SQLite corrupts inside synchronised folders, so a portable
/// copy in a OneDrive folder keeps its data in <c>%LOCALAPPDATA%\Titano</c> instead (<see cref="PortableSyncRoot"/>
/// names that folder to tell the user, <see cref="EarlierPortableData"/> the data it kept there before), and a data
/// root still under OneDrive is reported by <see cref="SyncedFolder"/> and refused by <see cref="CreateDirectories"/>.
/// </summary>
public sealed class AppPaths
{
public const string ProductFolderName = "Titano";
public const string ProductFolderName = DataLocation.ProductFolderName;
public const string DatabaseFileName = "titano.db";
public const string SettingsFileName = "settings.json";
private AppPaths(string dataRoot, bool isPortable, string? syncedFolder)
private AppPaths(DataLocation location, string? earlierPortableData)
{
DataRoot = dataRoot;
IsPortable = isPortable;
SyncedFolder = syncedFolder;
DataRoot = location.Root;
IsPortable = location.IsPortable;
SyncedFolder = location.SyncedFolder;
PortableSyncRoot = location.PortableSyncRoot;
EarlierPortableData = earlierPortableData;
}
/// <summary>A portable copy, also when its data had to go to <c>%LOCALAPPDATA%\Titano</c>.</summary>
public bool IsPortable { get; }
public string DataRoot { get; }
@@ -34,6 +42,15 @@ public sealed class AppPaths
public bool IsInSyncedFolder => SyncedFolder is not null;
/// <summary>The OneDrive sync root a portable copy runs from, whose data is in <c>%LOCALAPPDATA%\Titano</c> instead; null otherwise.</summary>
public string? PortableSyncRoot { get; }
/// <summary>
/// The <c>.\data</c> folder of a portable copy now in a OneDrive folder when it still holds the index or the settings
/// of an earlier start: nothing moves or deletes it, and the user is told where it is. Null otherwise.
/// </summary>
public string? EarlierPortableData { get; }
/// <summary>Paths for this process: the executable's folder decides portable mode.</summary>
public static AppPaths Resolve() => Resolve(AppContext.BaseDirectory, KnownFolders.LocalAppData);
@@ -41,13 +58,16 @@ public sealed class AppPaths
public static AppPaths Resolve(string applicationDirectory, string localAppData) =>
Resolve(applicationDirectory, localAppData, OneDriveFolders.SyncRoots());
internal static AppPaths Resolve(string applicationDirectory, string localAppData, IReadOnlyList<string> syncRoots)
/// <summary>Paths for an executable in <paramref name="applicationDirectory"/>, checked against <paramref name="syncRoots"/>.</summary>
public static AppPaths Resolve(string applicationDirectory, string localAppData, IReadOnlyCollection<string> syncRoots)
{
var portable = PortableMode.IsEnabled(applicationDirectory);
var root = Path.GetFullPath(portable
? Path.Combine(applicationDirectory, PortableMode.DataFolderName)
: Path.Combine(localAppData, ProductFolderName));
return new AppPaths(root, portable, OneDriveFolders.Containing(root, syncRoots));
var location = DataLocation.Choose(applicationDirectory, PortableMode.IsEnabled(applicationDirectory), localAppData, syncRoots);
var beside = Path.GetFullPath(Path.Combine(applicationDirectory, PortableMode.DataFolderName));
var earlier = location.PortableSyncRoot is not null
&& (File.Exists(Path.Combine(beside, DatabaseFileName)) || File.Exists(Path.Combine(beside, SettingsFileName)))
? beside
: null;
return new AppPaths(location, earlier);
}
/// <summary>Creates the data, logs, cache and thumbnails folders.</summary>
@@ -1,4 +1,6 @@
using System.Security;
using Microsoft.Win32;
using Titano.Core.IO;
namespace Titano.Core.Windows.Shell;
@@ -10,34 +12,34 @@ public static class OneDriveFolders
/// <summary>
/// Sync roots from the OneDrive environment variables and <c>HKCU\Software\Microsoft\OneDrive\Accounts\*\UserFolder</c>,
/// as full paths without a trailing separator, distinct (case-insensitive).
/// as full paths without a trailing separator, distinct (case-insensitive). An account key that cannot be read is
/// skipped: the programs start all the same.
/// </summary>
public static IReadOnlyList<string> SyncRoots()
{
var roots = new List<string>();
foreach (var variable in EnvironmentVariables) Add(roots, Environment.GetEnvironmentVariable(variable));
using var accounts = Registry.CurrentUser.OpenSubKey(AccountsKey);
if (accounts is not null)
try
{
foreach (var name in accounts.GetSubKeyNames())
using var accounts = Registry.CurrentUser.OpenSubKey(AccountsKey);
if (accounts is not null)
{
using var account = accounts.OpenSubKey(name);
Add(roots, account?.GetValue("UserFolder") as string);
foreach (var name in accounts.GetSubKeyNames())
{
using var account = accounts.OpenSubKey(name);
Add(roots, account?.GetValue("UserFolder") as string);
}
}
}
catch (Exception ex) when (ex is SecurityException or IOException or UnauthorizedAccessException)
{
// The environment variables name the usual roots.
}
return roots;
}
/// <summary>The sync root that contains <paramref name="path"/>, or null. Both are expected to be full paths.</summary>
public static string? Containing(string path, IEnumerable<string> syncRoots) => syncRoots.FirstOrDefault(root => IsUnder(path, root));
/// <summary>True when <paramref name="path"/> equals <paramref name="root"/> or lies below it (whole path segments, case-insensitive).</summary>
internal static bool IsUnder(string path, string root)
{
var trimmedRoot = root.TrimEnd('\\', '/');
if (trimmedRoot.Length == 0 || !path.StartsWith(trimmedRoot, StringComparison.OrdinalIgnoreCase)) return false;
return path.Length == trimmedRoot.Length || path[trimmedRoot.Length] is '\\' or '/';
}
public static string? Containing(string path, IEnumerable<string> syncRoots) => DataLocation.SyncRootOf(path, syncRoots);
private static void Add(List<string> roots, string? candidate)
{
@@ -1,10 +1,12 @@
using Titano.Core.IO;
namespace Titano.Core.Windows.Shell;
/// <summary>Portable mode (BRIEF §6.2): a <c>portable.txt</c> next to the executable keeps all data under <c>.\data\</c>.</summary>
public static class PortableMode
{
public const string MarkerFileName = "portable.txt";
public const string DataFolderName = "data";
public const string DataFolderName = DataLocation.PortableFolderName;
public static bool IsEnabled(string applicationDirectory) => File.Exists(Path.Combine(applicationDirectory, MarkerFileName));
}
+52
View File
@@ -0,0 +1,52 @@
namespace Titano.Core.IO;
/// <summary>
/// Where the desktop client keeps its data (BRIEF §6.2): the per-user folder (<c>%LOCALAPPDATA%\Titano</c>), or
/// <c>.\data</c> next to the executable of a portable copy (a <c>portable.txt</c> beside it). SQLite corrupts inside
/// synchronised folders, so a portable copy in a folder OneDrive synchronises (a OneDrive folder, or a Desktop or
/// Documents folder moved into one) keeps its data in the per-user folder instead, and <see cref="PortableSyncRoot"/>
/// says so, to tell the user. Paths are full paths; a folder lies in a sync root when its whole leading segments are
/// that root's, ignoring case as Windows does.
/// </summary>
/// <param name="Root">The data folder.</param>
/// <param name="IsPortable">The copy is portable, also when its data had to go to the per-user folder.</param>
/// <param name="SyncedFolder">The sync root that contains <paramref name="Root"/> itself; null when the data is safe there.</param>
/// <param name="PortableSyncRoot">The sync root a portable copy runs from, whose data went to the per-user folder instead; null otherwise.</param>
public sealed record DataLocation(string Root, bool IsPortable, string? SyncedFolder, string? PortableSyncRoot)
{
/// <summary>The data folder's name under the user's local application data.</summary>
public const string ProductFolderName = "Titano";
/// <summary>The data folder's name next to a portable copy's executable.</summary>
public const string PortableFolderName = "data";
/// <summary>
/// The data folder of a copy in <paramref name="applicationDirectory"/> (<paramref name="portable"/> when it has a
/// <c>portable.txt</c>), given the user's local application data and the OneDrive sync roots.
/// </summary>
public static DataLocation Choose(string applicationDirectory, bool portable, string localAppData, IReadOnlyCollection<string> syncRoots)
{
ArgumentNullException.ThrowIfNull(applicationDirectory);
ArgumentNullException.ThrowIfNull(localAppData);
ArgumentNullException.ThrowIfNull(syncRoots);
var perUser = Path.GetFullPath(Path.Combine(localAppData, ProductFolderName));
if (!portable) return new DataLocation(perUser, false, SyncRootOf(perUser, syncRoots), null);
var beside = Path.GetFullPath(Path.Combine(applicationDirectory, PortableFolderName));
return SyncRootOf(beside, syncRoots) is { } synced
? new DataLocation(perUser, true, SyncRootOf(perUser, syncRoots), synced)
: new DataLocation(beside, true, null, null);
}
/// <summary>The sync root that contains <paramref name="path"/>, or null.</summary>
public static string? SyncRootOf(string path, IEnumerable<string> syncRoots) => syncRoots.FirstOrDefault(root => IsUnder(path, root));
/// <summary>True when <paramref name="path"/> equals <paramref name="root"/> or lies below it (whole path segments, case-insensitive).</summary>
public static bool IsUnder(string path, string root)
{
ArgumentNullException.ThrowIfNull(path);
ArgumentNullException.ThrowIfNull(root);
var trimmedRoot = root.TrimEnd('\\', '/');
if (trimmedRoot.Length == 0 || !path.StartsWith(trimmedRoot, StringComparison.OrdinalIgnoreCase)) return false;
return path.Length == trimmedRoot.Length || path[trimmedRoot.Length] is '\\' or '/';
}
}
+16
View File
@@ -0,0 +1,16 @@
namespace Titano.Core.IO;
/// <summary>
/// Whether Windows runs a sign-in entry (<see cref="StartupCommand"/>). Task Manager's Startup tab and Settings › Apps ›
/// Startup turn an entry off without touching its Run value: they write a binary value of the same name under
/// <see cref="RunKey"/> whose first byte is odd while the entry is off (0x03) and even once it is on again (0x02). An
/// entry without that value is on. Rewriting the Run value leaves it as it is, so turning an entry back on means
/// removing it.
/// </summary>
public static class StartupApproval
{
public const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run";
/// <summary>The entry is turned off according to its StartupApproved <paramref name="state"/> (null when it has none).</summary>
public static bool IsTurnedOff(byte[]? state) => state is { Length: > 0 } && (state[0] & 1) != 0;
}
+54 -9
View File
@@ -147,17 +147,31 @@ public sealed class ArchiveService : IJobHandlerProvider
public async Task<ArchiveSettings> GetSettingsAsync(Guid archiveId, CancellationToken cancellationToken = default)
{
var archive = await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false);
var paths = new ArchivePaths(archive.RootPath);
try
return TryReadManifest(archive) is { } manifest
? ArchiveSettings.Of(manifest)
: new ArchiveSettings(archive.Name, new LayoutTemplates { Folder = archive.FolderTemplate, File = archive.FileTemplate },
new ProxyPolicy { LongEdge = archive.ProxyLongEdge }, new ThumbnailPolicy());
}
/// <summary>
/// The settings in the archive's <c>archive.json</c>, with its index row brought up to them when another process
/// sharing the archive changed the file (a server's admin panel, another PC's Settings): imports and uploads take their
/// templates and proxy size from that row. Null while the file cannot be read (offline, damaged, newer, of another
/// archive): the row stays as it is, and only <see cref="GetSettingsAsync"/>'s stand-ins are known.
/// </summary>
public async Task<ArchiveSettings?> RefreshSettingsAsync(Guid archiveId, CancellationToken cancellationToken = default)
{
var archive = await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false);
if (TryReadManifest(archive) is not { } manifest) return null;
var settings = ArchiveSettings.Of(manifest);
if (!settings.IsRegisteredIn(archive))
{
if (File.Exists(paths.ManifestPath)) return ArchiveSettings.Of(ManifestStore.ReadArchive(paths.ManifestPath));
// Read without the settings lease, as at open: an edit made meanwhile writes its own row, and the next refresh
// settles a file that changes again.
await RegisterAsync(new ArchivePaths(archive.RootPath), manifest, cancellationToken).ConfigureAwait(false);
Log.Info("archive", $"Settings of {archive.RootPath} changed elsewhere: {manifest.LayoutTemplates.Folder} · {manifest.LayoutTemplates.File}, proxies {manifest.ProxyPolicy.LongEdge}");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
{
Log.Warning("archive", $"The settings of {paths.Root} cannot be read; the index's are used", ex);
}
return new ArchiveSettings(archive.Name, new LayoutTemplates { Folder = archive.FolderTemplate, File = archive.FileTemplate },
new ProxyPolicy { LongEdge = archive.ProxyLongEdge }, new ThumbnailPolicy());
return settings;
}
/// <summary>
@@ -325,6 +339,29 @@ public sealed class ArchiveService : IJobHandlerProvider
return archive;
}
/// <summary>
/// The archive's <c>archive.json</c>; null (logged) while it cannot be read, when a newer Titano wrote it (this one
/// would drop what it does not know) or when it belongs to another archive.
/// </summary>
private static ArchiveManifest? TryReadManifest(Archive archive)
{
var paths = new ArchivePaths(archive.RootPath);
try
{
if (!File.Exists(paths.ManifestPath)) return null;
var manifest = ManifestStore.ReadArchive(paths.ManifestPath);
if (manifest.SchemaVersion > ArchiveManifest.CurrentSchemaVersion)
Log.Warning("archive", $"{paths.ManifestPath} has schema version {manifest.SchemaVersion}, newer than this Titano's; the index's settings are used");
else if (manifest.Id == archive.Id) return manifest;
else Log.Warning("archive", $"{paths.ManifestPath} belongs to archive {manifest.Id}, not {archive.Id}; the index's settings are used");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
{
Log.Warning("archive", $"The settings of {paths.Root} cannot be read; the index's are used", ex);
}
return null;
}
private async Task<Archive> LoadArchiveAsync(Guid archiveId, CancellationToken cancellationToken) =>
await _db.Archives.GetAsync(archiveId, cancellationToken).ConfigureAwait(false) ?? throw new ArgumentException($"Unknown archive {archiveId}.", nameof(archiveId));
@@ -349,6 +386,14 @@ public sealed record ArchiveSettings(string Name, LayoutTemplates Templates, Pro
public static ArchiveSettings Of(ArchiveManifest manifest) => new(manifest.Name, manifest.LayoutTemplates, manifest.ProxyPolicy, manifest.ThumbnailPolicy);
/// <summary>Whether the index row <paramref name="archive"/> holds these settings (all it keeps: not the thumbnail policy).</summary>
public bool IsRegisteredIn(Archive archive)
{
ArgumentNullException.ThrowIfNull(archive);
return Name == archive.Name && Templates.Folder == archive.FolderTemplate && Templates.File == archive.FileTemplate
&& Proxies.LongEdge == archive.ProxyLongEdge;
}
/// <summary>The first invalid field by its API name (<c>name</c>, <c>folderTemplate</c>, <c>fileTemplate</c>,
/// <c>proxyLongEdge</c>, <c>thumbnailLongEdge</c>); null when every field is valid.</summary>
public string? Problem()
+3 -1
View File
@@ -19,7 +19,9 @@ public static class ArchiveEndpoints
public static void Map(RouteGroupBuilder api)
{
var archive = api.MapGroup("/archive").Requires(Permissions.ManageArchive);
archive.MapGet("/settings", (ServerArchive a) => Results.Json(Settings(a.Current), ProtocolJson.Default.ArchiveSettingsDto));
// The form saves every field: it starts from what archive.json holds now, also a desktop's change since the last poll.
archive.MapGet("/settings", async (HttpContext c, ServerArchive a, TitanoDatabase db, [FromServices] ArchiveService? archives) =>
Results.Json(Settings(archives is null ? a.Current : await a.RefreshAsync(archives, db, c.RequestAborted)), ProtocolJson.Default.ArchiveSettingsDto));
archive.MapPut("/settings", UpdateAsync);
archive.MapGet("/stats", async (HttpContext c, TitanoDatabase db, ServerArchive a) =>
Results.Json(await StatsAsync(db, a, c.RequestAborted), ProtocolJson.Default.ArchiveStatsDto));
+5 -2
View File
@@ -10,9 +10,11 @@ namespace Titano.Server.Storage;
/// Polls the archive (BRIEF §7: by modification time and size, no file-system watchers): an incremental scan at start
/// and every <see cref="Interval"/> while the archive is online, so photos already in an adopted folder and sequences
/// another writer adds (a desktop sharing the archive, files copied in by hand) are indexed without an administrator's
/// rescan. A scan or rebuild of the archive that is waiting, running or paused is not queued again.
/// rescan. Settings such a writer changed in archive.json reach the index first, so uploads and the admin panel follow
/// them. A scan or rebuild of the archive that is waiting, running or paused is not queued again.
/// </summary>
public sealed class ArchivePolling(TitanoDatabase db, ServerArchive archive, JobEngineHost jobs, TimeProvider time, ILogger<ArchivePolling> logger)
public sealed class ArchivePolling(TitanoDatabase db, ServerArchive archive, ArchiveService archives, JobEngineHost jobs, TimeProvider time,
ILogger<ArchivePolling> logger)
: BackgroundService
{
/// <summary>The desktop's rhythm (it polls its archive the same way).</summary>
@@ -26,6 +28,7 @@ public sealed class ArchivePolling(TitanoDatabase db, ServerArchive archive, Job
if (!jobs.CanRun(JobKind.Scan)) return null;
var current = archive.Current;
if (ArchiveService.GetAvailability(current) != ArchiveAvailability.Online) return null;
current = await archive.RefreshAsync(archives, db, cancellationToken);
foreach (var kind in new[] { JobKind.Scan, JobKind.Rebuild })
{
foreach (var state in Pending)
@@ -19,6 +19,29 @@ public sealed class ServerArchive(Archive archive)
set => _current = value;
}
/// <summary>
/// Serves <paramref name="value"/> unless <see cref="Current"/> is no longer <paramref name="expected"/>, the archive
/// it was read from: an edit an administrator saved meanwhile is never undone. False when it was not replaced.
/// </summary>
public bool TryReplace(Archive expected, Archive value) => ReferenceEquals(Interlocked.CompareExchange(ref _current, value, expected), expected);
/// <summary>
/// <see cref="Current"/> once it and the index row hold the settings another writer sharing the archive (a desktop)
/// put into its archive.json (<see cref="ArchiveService.RefreshSettingsAsync"/>): uploads, the polling and the admin
/// panel, whose form saves every field, never work from older ones. Unchanged while the file cannot be read.
/// </summary>
public async Task<Archive> RefreshAsync(ArchiveService archives, TitanoDatabase db, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(archives);
ArgumentNullException.ThrowIfNull(db);
var current = Current;
// Only a change the refresh registered is served, and never over an edit an administrator saved since the read above.
if (await archives.RefreshSettingsAsync(current.Id, cancellationToken).ConfigureAwait(false) is { } settings && !settings.IsRegisteredIn(current)
&& await db.Archives.GetAsync(current.Id, cancellationToken).ConfigureAwait(false) is { } row)
TryReplace(current, row);
return Current;
}
public Guid Id => _current.Id;
public string Root => _current.RootPath;
+6 -3
View File
@@ -41,13 +41,16 @@ public sealed class SampleData
],
};
/// <summary>A view model over in-memory sample services; settings changes are discarded.</summary>
public MainViewModel CreateViewModel()
/// <summary>
/// A view model over in-memory sample services; settings changes are discarded. <paramref name="startup"/> stands for
/// the sign-in entry (an in-memory one, on, by default).
/// </summary>
public MainViewModel CreateViewModel(IStartupRegistration? startup = null)
{
var memory = new ProcessedFileMemory();
_session.BandwidthLimit = Settings.BandwidthLimit;
_vm = new MainViewModel(new UploaderServices(
Settings, () => { }, _session, _queue, new SampleEngine(_queue), new SampleStartup(), new UploaderDialogs(),
Settings, () => { }, _session, _queue, new SampleEngine(_queue), startup ?? new SampleStartup(), new UploaderDialogs(),
new WatchFolderService(memory, _queue.ContainsPath), memory, string.Empty));
foreach (var w in _vm.WatchFolders) w.IsAvailable = true;
// A disconnected drive: its chip shows the hollow ring and wraps to a second line.
@@ -1,3 +1,4 @@
using System.IO;
using System.Security;
using Microsoft.Win32;
using Titano.Core.Diagnostics;
@@ -15,49 +16,65 @@ public interface IStartupRegistration
/// <summary>
/// <c>HKCU\Software\Microsoft\Windows\CurrentVersion\Run</c> 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. Uninstalling removes the value when
/// it starts the Uploader the uninstaller removes (<see cref="StartupCommand"/> names it for both).
/// The registry stays the source of truth because Task Manager can turn it off: an entry it turned off
/// (<see cref="StartupApproval"/>) shows as off, and ticking the box turns it on again. Uninstalling removes the value
/// when it starts the Uploader the uninstaller removes (<see cref="StartupCommand"/> names it for both).
/// </summary>
public sealed class RunKeyStartupRegistration : IStartupRegistration
/// <param name="executable">The Uploader's program; the running one by default.</param>
/// <param name="root">The registry hive holding the entries; <c>HKEY_CURRENT_USER</c> by default (tests pass a scratch key).</param>
public sealed class RunKeyStartupRegistration(string? executable = null, RegistryKey? root = null) : IStartupRegistration
{
private const string RunKey = StartupCommand.RunKey;
private const string ValueName = StartupCommand.UploaderValue;
public bool IsEnabled
private readonly string? _executable = executable ?? Environment.ProcessPath;
private readonly RegistryKey _root = root ?? Registry.CurrentUser;
/// <summary>The entry exists and Task Manager has not turned it off.</summary>
public bool IsEnabled => HasEntry && !StartupApproval.IsTurnedOff(Read(StartupApproval.RunKey) as byte[]);
private bool HasEntry => Read(RunKey) is string { Length: > 0 };
private string Command => StartupCommand.Format(_executable ?? string.Empty, CommandLine.TrayOption);
public void SetEnabled(bool enabled) => Update(key =>
{
get
{
try
{
using var key = Registry.CurrentUser.OpenSubKey(RunKey);
return key?.GetValue(ValueName) is string { Length: > 0 };
}
catch (SecurityException)
{
return false;
}
}
if (enabled) key.SetValue(ValueName, Command, RegistryValueKind.String);
else key.DeleteValue(ValueName, throwOnMissingValue: false);
// Task Manager's "Disable" outlives a new command: ticking the box undoes it, and unticking leaves nothing behind.
using var approval = _root.OpenSubKey(StartupApproval.RunKey, writable: true);
approval?.DeleteValue(ValueName, throwOnMissingValue: false);
});
/// <summary>Points an existing entry at the current executable (after an update moved it); one Task Manager turned off stays off.</summary>
public void Refresh()
{
if (HasEntry) Update(key => key.SetValue(ValueName, Command, RegistryValueKind.String));
}
private static string Command => $"\"{Environment.ProcessPath}\" {CommandLine.TrayOption}";
public void SetEnabled(bool enabled)
private object? Read(string subKey)
{
try
{
using var key = Registry.CurrentUser.CreateSubKey(RunKey, writable: true);
if (enabled) key.SetValue(ValueName, Command, RegistryValueKind.String);
else key.DeleteValue(ValueName, throwOnMissingValue: false);
using var key = _root.OpenSubKey(subKey);
return key?.GetValue(ValueName);
}
catch (Exception ex) when (ex is SecurityException or UnauthorizedAccessException)
catch (Exception ex) when (ex is SecurityException or IOException)
{
return null;
}
}
private void Update(Action<RegistryKey> change)
{
try
{
using var key = _root.CreateSubKey(RunKey, writable: true);
change(key);
}
catch (Exception ex) when (ex is SecurityException or UnauthorizedAccessException or IOException)
{
Log.Warning("startup", "Run key not updated", ex);
}
}
/// <summary>Points an existing entry at the current executable (after an update moved it).</summary>
public void Refresh()
{
if (IsEnabled) SetEnabled(true);
}
}
@@ -4,7 +4,8 @@ namespace Titano.Uploader.Infrastructure;
/// <summary>
/// Where the uploader keeps its files: <c>%LOCALAPPDATA%\Titano</c> (shared with the client), or <c>.\data</c> next
/// to the executable when <c>portable.txt</c> exists — the same rule as the desktop client.
/// to the executable when <c>portable.txt</c> exists — the desktop client's rule, except that the client never keeps
/// its SQLite index in a folder OneDrive synchronises; the Uploader's JSON files, written atomically, stay there.
/// </summary>
public sealed class UploaderEnvironment
{
+7 -1
View File
@@ -156,7 +156,13 @@ public sealed class MainViewModel : LocalizedViewModel
public bool IsSettingsOpen
{
get => _isSettingsOpen;
set => Set(ref _isSettingsOpen, value);
set
{
if (!Set(ref _isSettingsOpen, value) || !value) return;
// The Uploader runs for the whole session: Task Manager may have turned its sign-in entry off meanwhile.
_startWithWindows = _s.Startup.IsEnabled;
OnPropertyChanged(nameof(StartWithWindows));
}
}
// ---------------- Target ----------------
@@ -0,0 +1,82 @@
using System.IO;
using Titano.App.Infrastructure;
using Titano.Core.Windows.Shell;
using Titano.Testing;
namespace Titano.App.Tests.Infrastructure;
/// <summary>BRIEF §6.2: the client's data folder, which is never inside a folder OneDrive synchronises.</summary>
public sealed class AppEnvironmentTests(TestContext context)
{
[Test]
public void APortableCopyInOneDriveKeepsItsDataInTheUserFolderAndSaysSo()
{
var oneDrive = context.CreateTempDirectory("onedrive");
var app = Directory.CreateDirectory(Path.Combine(oneDrive, "Desktop", "Titano")).FullName;
File.WriteAllText(Path.Combine(app, PortableMode.MarkerFileName), "");
var local = context.CreateTempDirectory("local");
var environment = AppEnvironment.From(AppPaths.Resolve(app, local, [oneDrive]));
Assert.Equal(Path.Combine(local, "Titano", "titano.db"), environment.DatabasePath);
Assert.True(environment.IsPortable, "still a portable copy: updates fetch the portable zip, no sign-in entry");
Assert.Equal<string?>(oneDrive, environment.PortableSyncRoot);
Assert.Null(environment.SyncedFolder);
Assert.Null(environment.EarlierPortableData);
Assert.True(Directory.Exists(environment.LogDirectory));
Assert.False(Directory.Exists(Path.Combine(app, "data")), "nothing is written into the synchronised folder");
// Elsewhere (a USB stick) a portable copy keeps its data beside it.
var stick = context.CreateTempDirectory("stick");
File.WriteAllText(Path.Combine(stick, PortableMode.MarkerFileName), "");
var beside = AppEnvironment.From(AppPaths.Resolve(stick, local, [oneDrive]));
Assert.Equal(Path.Combine(stick, "data"), beside.DataDirectory);
Assert.Null(beside.PortableSyncRoot);
Assert.Null(beside.SyncedFolder);
}
[Test]
public void TheDataAPortableCopyKeptInOneDriveBeforeIsNamedAndLeftAlone()
{
var oneDrive = context.CreateTempDirectory("onedrive");
var app = Directory.CreateDirectory(Path.Combine(oneDrive, "Documents", "Titano")).FullName;
File.WriteAllText(Path.Combine(app, PortableMode.MarkerFileName), "");
// An earlier version kept its index and settings beside the program.
var earlier = Directory.CreateDirectory(Path.Combine(app, "data")).FullName;
File.WriteAllText(Path.Combine(earlier, "settings.json"), "{}");
File.WriteAllBytes(Path.Combine(earlier, "titano.db"), [1, 2, 3]);
var local = context.CreateTempDirectory("local");
var environment = AppEnvironment.From(AppPaths.Resolve(app, local, [oneDrive]));
Assert.Equal<string?>(earlier, environment.EarlierPortableData);
Assert.Equal(Path.Combine(local, "Titano"), environment.DataDirectory);
Assert.SequenceEqual(new byte[] { 1, 2, 3 }, File.ReadAllBytes(Path.Combine(earlier, "titano.db")));
Assert.Equal("{}", File.ReadAllText(Path.Combine(earlier, "settings.json")));
// A data folder with neither (logs only) holds nothing the user would miss.
File.Delete(Path.Combine(earlier, "settings.json"));
File.Delete(Path.Combine(earlier, "titano.db"));
Directory.CreateDirectory(Path.Combine(earlier, "logs"));
Assert.Null(AppEnvironment.From(AppPaths.Resolve(app, local, [oneDrive])).EarlierPortableData);
}
[Test]
public void AUserFolderOneDriveSynchronisesIsReportedNotHidden()
{
// Nowhere is safe: Titano starts all the same, and the folder that is synchronised is named for the warning.
var oneDrive = context.CreateTempDirectory("onedrive");
var local = Directory.CreateDirectory(Path.Combine(oneDrive, "AppData", "Local")).FullName;
var installed = AppEnvironment.From(AppPaths.Resolve(context.CreateTempDirectory("app"), local, [oneDrive]));
Assert.Equal<string?>(oneDrive, installed.SyncedFolder);
Assert.Null(installed.PortableSyncRoot);
Assert.True(Directory.Exists(installed.LogDirectory));
// A portable copy in that OneDrive has nowhere safe either: its data is not said to be kept outside it.
var app = Directory.CreateDirectory(Path.Combine(oneDrive, "Desktop", "Titano")).FullName;
File.WriteAllText(Path.Combine(app, PortableMode.MarkerFileName), "");
var portable = AppEnvironment.From(AppPaths.Resolve(app, local, [oneDrive]));
Assert.Equal<(string?, string?)>((oneDrive, oneDrive), (portable.SyncedFolder, portable.PortableSyncRoot));
}
}
@@ -51,6 +51,66 @@ public sealed class AppServicesTests
}
}
/// <summary>BRIEF §7: polling follows the archive folder, also one chosen after the start (first run, Settings, relink).</summary>
[Test]
[WindowsOnly]
public void RescansFollowTheArchiveFolderChosenAfterTheStart()
{
var environment = AppEnvironment.ForCapture();
try
{
SingleThreadedContext.Run(async () =>
{
// The first run: the index opens before any archive folder is set.
var settings = new AppSettings { Language = "en" };
var services = new AppServices(environment, settings, () => { }, new NoDialogs());
try
{
await services.OpenAsync(environment.DatabasePath);
Assert.Null(await services.RescanAsync());
// The rescans run all the same: Settings › Archive › Rescan every reaches them.
settings.ScanIntervalMinutes = 30;
services.SaveSettings();
Assert.Equal<TimeSpan?>(TimeSpan.FromMinutes(30), services.PollingPeriod);
// The first-run dialog creates an archive: the next rescan is of it.
var firstRoot = Path.Combine(environment.DataDirectory, "first");
await services.ArchiveSetup.CreateAsync(firstRoot);
var first = Assert.NotNull(await services.RescanAsync());
Assert.Equal("first", first.Name);
// Settings › Archive moves to another archive, which the index lists after the first one: the next rescan
// is of the archive at the folder, no longer of the first one.
var other = Path.Combine(environment.DataDirectory, "zeta");
await new ArchiveService(services.Database!).CreateAsync(other, "zeta");
Assert.Equal("first", (await services.Database!.Archives.ListAsync())[0].Name);
async Task<int> ScansOfAsync(Guid archiveId) =>
(await services.Database!.Jobs.ListAsync(null, JobKind.Scan)).Items.Count(j => j.TargetIds.Contains(archiveId));
var scansOfFirst = await ScansOfAsync(first.Id);
settings.LastArchivePath = other;
services.SaveSettings();
var rescanned = Assert.NotNull(await services.RescanAsync());
Assert.Equal("zeta", rescanned.Name);
Assert.True(await ScansOfAsync(rescanned.Id) > 0, "the archive at the folder is rescanned");
Assert.Equal(scansOfFirst, await ScansOfAsync(first.Id));
// And back: the folder decides, whatever the order of the index.
settings.LastArchivePath = firstRoot;
services.SaveSettings();
Assert.Equal(first.Id, (await services.RescanAsync())?.Id);
}
finally
{
Assert.True(services.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(10)), "services stopped");
}
});
}
finally
{
environment.DeleteCaptureData();
}
}
/// <summary>BRIEF §6.2: a restore staged in Settings › Advanced recovers an index that no longer opens.</summary>
[Test]
[WindowsOnly]
@@ -1,6 +1,8 @@
using Microsoft.Win32;
using Titano.App.Infrastructure;
using Titano.Core.IO;
using Titano.Testing;
using Titano.Uploader.Infrastructure;
namespace Titano.App.Tests.Infrastructure;
@@ -31,6 +33,77 @@ public sealed class StartWithWindowsTests
Assert.False(RunKeyStartWithWindows.Follows(installed, null, Gone));
}
[Test]
[WindowsOnly]
public void AnEntryTaskManagerTurnedOffShowsOffUntilTheBoxIsTickedAgain()
{
// A scratch hive of its own: the user's sign-in entries are never touched.
var hive = @"Software\Titano.StartupTests." + Guid.NewGuid().ToString("N");
try
{
using var root = Registry.CurrentUser.CreateSubKey(hive, writable: true);
var startup = new RunKeyStartWithWindows(Installed, root);
startup.SetEnabled(true);
Assert.True(startup.IsEnabled);
// Task Manager › Startup › Disable keeps the Run value and writes the switch apart.
TurnOff(root, StartupCommand.ClientValue);
Assert.False(startup.IsEnabled, "shown as off");
Assert.True(StartupCommand.Starts(Value(root, StartupCommand.RunKey, StartupCommand.ClientValue) as string, Installed), "the command stays");
// An update renamed the program: the command follows it, and the entry stays off.
const string renamed = @"C:\Users\ada\AppData\Local\Programs\Titano\Titano.next.exe";
var updated = new RunKeyStartWithWindows(renamed, root);
updated.Refresh();
Assert.True(StartupCommand.Starts(Value(root, StartupCommand.RunKey, StartupCommand.ClientValue) as string, renamed));
Assert.False(updated.IsEnabled, "still off after the update");
// Ticking the box turns it on again; unticking leaves nothing behind.
updated.SetEnabled(true);
Assert.True(updated.IsEnabled);
Assert.Null(Value(root, StartupApproval.RunKey, StartupCommand.ClientValue));
TurnOff(root, StartupCommand.ClientValue);
updated.SetEnabled(false);
Assert.Null(Value(root, StartupCommand.RunKey, StartupCommand.ClientValue));
Assert.Null(Value(root, StartupApproval.RunKey, StartupCommand.ClientValue));
}
finally
{
Registry.CurrentUser.DeleteSubKeyTree(hive, throwOnMissingSubKey: false);
}
}
[Test]
[WindowsOnly]
public void TheUploadersEntryHonoursTaskManagerToo()
{
var hive = @"Software\Titano.StartupTests." + Guid.NewGuid().ToString("N");
try
{
using var root = Registry.CurrentUser.CreateSubKey(hive, writable: true);
var uploader = @"C:\Users\ada\AppData\Local\Programs\Titano\Uploader\Titano.Uploader.exe";
var startup = new RunKeyStartupRegistration(uploader, root);
startup.SetEnabled(true);
Assert.True(startup.IsEnabled);
TurnOff(root, StartupCommand.UploaderValue);
Assert.False(startup.IsEnabled, "shown as off");
startup.Refresh();
Assert.False(startup.IsEnabled, "a refresh keeps it off");
startup.SetEnabled(true);
Assert.True(startup.IsEnabled);
TurnOff(root, StartupCommand.UploaderValue);
startup.SetEnabled(false);
Assert.Null(Value(root, StartupCommand.RunKey, StartupCommand.UploaderValue));
Assert.Null(Value(root, StartupApproval.RunKey, StartupCommand.UploaderValue));
}
finally
{
Registry.CurrentUser.DeleteSubKeyTree(hive, throwOnMissingSubKey: false);
}
}
[Test]
public void ScreenshotsAndPortableCopiesKeepTheChoiceInMemory()
{
@@ -42,4 +115,17 @@ public sealed class StartWithWindowsTests
startup.SetEnabled(false);
Assert.False(startup.IsEnabled);
}
/// <summary>What Task Manager writes when the user disables an entry: 0x03, three zero bytes, then when.</summary>
private static void TurnOff(RegistryKey root, string name)
{
using var approved = root.CreateSubKey(StartupApproval.RunKey, writable: true);
approved.SetValue(name, new byte[] { 0x03, 0, 0, 0, 0x60, 0x1B, 0x3C, 0x92, 0x8A, 0x3F, 0xDB, 0x01 }, RegistryValueKind.Binary);
}
private static object? Value(RegistryKey root, string subKey, string name)
{
using var key = root.OpenSubKey(subKey);
return key?.GetValue(name);
}
}
@@ -169,6 +169,76 @@ public sealed class SettingsScreenSmokeTests
installs[0].Command.Execute(null);
});
[Test]
public Task ArchiveRowsEditOnlyTheArchiveAtTheFolderAndKeepEditsMadeWhileItOpens() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var shell = app.Shell;
await app.Sample.FillAsync();
var settings = shell.Settings;
var db = shell.Services.Database!;
var archive = Assert.NotNull(await Titano.App.Archiving.CurrentArchive.FindAsync(db, null));
var manifestPath = new Titano.Core.Archiving.ArchivePaths(archive.RootPath).ManifestPath;
static Titano.Core.Archiving.ArchiveManifest Read(string path) => Titano.Core.Archiving.ManifestStore.ReadArchive(path);
shell.Navigate(SectionKey.Settings);
settings.Page = SettingsPage.Archive;
// No archive folder: a template edit is this PC's default only, never the first archive of the index. The edit is
// made once the rows follow the empty folder, so it cannot wait for anything that would hide a write.
settings.ArchiveRoot.Text = string.Empty;
Assert.True(settings.ArchiveRoot.Commit());
await settings.ArchiveRetarget;
settings.FolderTemplate.Text = "{camera}/{date}";
Assert.True(settings.FolderTemplate.Commit());
Assert.Equal("{camera}/{date}", shell.Services.Settings.FolderTemplate);
// The archive's folder is chosen and a template edited at once, while that archive is still opening: the edit
// reaches its archive.json instead of being undone when it opens, and the row shows it.
settings.ArchiveRoot.Text = archive.RootPath;
Assert.True(settings.ArchiveRoot.Commit());
settings.FileTemplate.Text = "{date}_{n:0000}";
Assert.True(settings.FileTemplate.Commit());
await WaitAsync(() => Read(manifestPath).LayoutTemplates.File == "{date}_{n:0000}", "the edit reached the archive that was opening");
await WaitAsync(() => settings.FileTemplate.Text == "{date}_{n:0000}" && shell.Services.Settings.FileTemplate == "{date}_{n:0000}", "the row shows it");
Assert.NotEqual("{camera}/{date}", Read(manifestPath).LayoutTemplates.Folder);
// An edit made before a second folder change, while the first folder's archive is still opening, goes to that
// archive: never to the archive at the folder chosen after it.
var otherRoot = System.IO.Path.Combine(shell.Services.Environment.DataDirectory, "other-archive");
await shell.Services.Archives!.CreateAsync(otherRoot, "Other");
var otherManifestPath = new Titano.Core.Archiving.ArchivePaths(otherRoot).ManifestPath;
settings.ArchiveRoot.Text = otherRoot;
Assert.True(settings.ArchiveRoot.Commit());
await settings.ArchiveRetarget;
settings.ArchiveRoot.Text = archive.RootPath;
Assert.True(settings.ArchiveRoot.Commit());
settings.FileTemplate.Text = "{date}-{n:0000}";
Assert.True(settings.FileTemplate.Commit());
settings.ArchiveRoot.Text = otherRoot;
Assert.True(settings.ArchiveRoot.Commit());
await WaitAsync(() => Read(manifestPath).LayoutTemplates.File == "{date}-{n:0000}", "the edit reached the archive of the folder it was made for");
await settings.ArchiveRetarget;
Assert.NotEqual("{date}-{n:0000}", Read(otherManifestPath).LayoutTemplates.File);
Assert.Equal(Read(otherManifestPath).LayoutTemplates.File, settings.FileTemplate.Text);
settings.ArchiveRoot.Text = archive.RootPath;
Assert.True(settings.ArchiveRoot.Commit());
await settings.ArchiveRetarget;
// Offline, only archive.json knows the thumbnail size: this PC's stays instead of becoming the default.
Titano.Core.Archiving.ManifestStore.WriteArchive(manifestPath, Read(manifestPath) with { ThumbnailPolicy = new Titano.Core.Archiving.ThumbnailPolicy { LongEdge = 480 } });
shell.Navigate(SectionKey.Library);
shell.Navigate(SectionKey.Settings);
await WaitAsync(() => shell.Services.Settings.ThumbnailLongEdge == 480, "the archive's thumbnail size is shown");
var row = Assert.NotNull(await db.Archives.GetAsync(archive.Id));
await db.Archives.UpsertAsync(row with { ProxyLongEdge = 2560 });
System.IO.File.Move(manifestPath, manifestPath + ".away");
shell.Navigate(SectionKey.Library);
shell.Navigate(SectionKey.Settings);
await WaitAsync(() => shell.Services.Settings.ProxyLongEdge == 2560, "the index's proxy size is shown while offline");
Assert.Equal(480, shell.Services.Settings.ThumbnailLongEdge);
Assert.Equal(480, settings.SelectedThumbnailSize.Value);
});
[Test]
public Task TheFirstRunDialogKeepsTheKeyboardInside() => ScreenHost.RunAsync(async () =>
{
@@ -125,6 +125,34 @@ public sealed class UploaderScreenSmokeTests
}
});
[Test]
public Task StartWithWindowsShowsWhatTaskManagerLeftWhenTheSettingsOpen() => ScreenHost.RunAsync(() =>
{
UiLanguage.Apply("en");
var startup = new SignInEntry { IsEnabled = true };
var vm = new SampleData().CreateViewModel(startup);
Assert.True(vm.StartWithWindows);
// The Uploader runs for the whole session: Task Manager turns its entry off meanwhile, and the box follows when
// the settings open.
startup.IsEnabled = false;
var changed = new List<string?>();
vm.PropertyChanged += (_, e) => changed.Add(e.PropertyName);
vm.OpenSettingsCommand.Execute(null);
Assert.False(vm.StartWithWindows, "shown as Task Manager left it");
Assert.Contains(nameof(MainViewModel.StartWithWindows), changed);
vm.CloseSettingsCommand.Execute(null);
return Task.CompletedTask;
});
/// <summary>A sign-in entry another program (Task Manager) can turn off.</summary>
private sealed class SignInEntry : Titano.Uploader.Infrastructure.IStartupRegistration
{
public bool IsEnabled { get; set; }
public void SetEnabled(bool enabled) => IsEnabled = enabled;
}
/// <summary>A <see cref="MainWindow"/> on <see cref="SampleData"/>, shown off screen like <c>--capture</c>.</summary>
private sealed class UploaderScreen : IDisposable
{
@@ -0,0 +1,68 @@
using Titano.Core.IO;
using Titano.Testing;
namespace Titano.Core.Tests.Foundation;
/// <summary>BRIEF §6.2: where the client keeps its index, and never inside a folder OneDrive synchronises.</summary>
public sealed class DataLocationTests(TestContext context)
{
[Test]
public void AnInstalledCopyUsesThePerUserFolderAndAPortableOneItsOwn()
{
var app = context.CreateTempDirectory("app");
var local = context.CreateTempDirectory("local");
var installed = DataLocation.Choose(app, portable: false, local, []);
Assert.Equal(new DataLocation(Path.Combine(local, "Titano"), false, null, null), installed);
var portable = DataLocation.Choose(app, portable: true, local, []);
Assert.Equal(new DataLocation(Path.Combine(app, "data"), true, null, null), portable);
}
[Test]
public void APortableCopyInASynchronisedFolderKeepsItsDataInThePerUserFolder()
{
// A portable copy unpacked on a Desktop that OneDrive's folder backup moved into the sync root.
var oneDrive = context.CreateTempDirectory("onedrive");
var app = Path.Combine(oneDrive, "Desktop", "Titano");
var local = context.CreateTempDirectory("local");
var location = DataLocation.Choose(app, portable: true, local, [Path.Combine(context.CreateTempDirectory("other"), "OneDrive"), oneDrive]);
Assert.Equal(Path.Combine(local, "Titano"), location.Root);
Assert.True(location.IsPortable, "still a portable copy (updates, no sign-in entry)");
Assert.Equal<string?>(oneDrive, location.PortableSyncRoot);
Assert.Null(location.SyncedFolder);
// A sync root that only shares the start of the name is another folder.
var beside = DataLocation.Choose(oneDrive + "Backup", portable: true, local, [oneDrive]);
Assert.Equal(new DataLocation(Path.Combine(oneDrive + "Backup", "data"), true, null, null), beside);
}
[Test]
public void APerUserFolderInsideASyncRootIsReported()
{
var oneDrive = context.CreateTempDirectory("onedrive");
var local = Path.Combine(oneDrive, "AppData", "Local");
var installed = DataLocation.Choose(context.CreateTempDirectory("app"), portable: false, local, [oneDrive]);
Assert.Equal<string?>(oneDrive, installed.SyncedFolder);
var portable = DataLocation.Choose(Path.Combine(oneDrive, "Titano"), portable: true, local, [oneDrive]);
Assert.Equal<(string, string?, string?)>((Path.Combine(local, "Titano"), oneDrive, oneDrive), (portable.Root, portable.SyncedFolder, portable.PortableSyncRoot));
}
[Test]
public void SyncRootMatchingIsSegmentWiseAndIgnoresCase()
{
var root = Path.Combine(context.CreateTempDirectory(), "OneDrive");
Assert.True(DataLocation.IsUnder(root, root));
Assert.True(DataLocation.IsUnder(Path.Combine(root, "Pictures"), root + Path.DirectorySeparatorChar));
Assert.True(DataLocation.IsUnder(Path.Combine(root, "x").ToUpperInvariant(), root));
Assert.True(DataLocation.IsUnder(@"C:\Users\ada\OneDrive\Desktop\Titano\data", @"c:\users\ada\onedrive"), "Windows paths on any platform");
Assert.False(DataLocation.IsUnder(root + "Backup", root));
Assert.False(DataLocation.IsUnder(root, string.Empty));
Assert.Null(DataLocation.SyncRootOf(root + "Backup", [root]));
Assert.Equal<string?>(root, DataLocation.SyncRootOf(Path.Combine(root, "Documents"), ["", root]));
}
}
@@ -0,0 +1,21 @@
using Titano.Core.IO;
using Titano.Testing;
namespace Titano.Core.Tests.Foundation;
/// <summary>The switch Task Manager's Startup tab keeps apart from a sign-in entry's command.</summary>
public sealed class StartupApprovalTests
{
[Test]
public void AnOddFirstByteMeansTurnedOff()
{
// As Task Manager writes them: a state, three zero bytes, then the time it was turned off.
Assert.True(StartupApproval.IsTurnedOff([0x03, 0, 0, 0, 0x60, 0x1B, 0x3C, 0x92, 0x8A, 0x3F, 0xDB, 0x01]));
Assert.True(StartupApproval.IsTurnedOff([0x01, 0, 0, 0]));
Assert.False(StartupApproval.IsTurnedOff([0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]));
Assert.False(StartupApproval.IsTurnedOff([0x06, 0, 0, 0]));
// Never touched in Task Manager, or a value of another type: the entry is on.
Assert.False(StartupApproval.IsTurnedOff(null));
Assert.False(StartupApproval.IsTurnedOff([]));
}
}
@@ -17,6 +17,7 @@ public sealed class AppPathsTests(TestContext context)
Assert.Equal(Path.Combine(app, "data"), paths.DataRoot);
Assert.Equal(Path.Combine(app, "data", "titano.db"), paths.DatabasePath);
Assert.False(paths.IsInSyncedFolder);
Assert.Null(paths.PortableSyncRoot);
paths.CreateDirectories();
Assert.True(Directory.Exists(paths.LogsDirectory));
@@ -37,13 +38,31 @@ public sealed class AppPathsTests(TestContext context)
}
[Test]
public void DataInsideOneDriveIsReportedAndRefused()
public void APortableCopyInOneDriveKeepsItsDataInLocalAppData()
{
var oneDrive = context.CreateTempDirectory("onedrive");
var app = Directory.CreateDirectory(Path.Combine(oneDrive, "Tools", "Titano")).FullName;
File.WriteAllText(Path.Combine(app, PortableMode.MarkerFileName), "");
var local = context.CreateTempDirectory("local");
var paths = AppPaths.Resolve(app, context.CreateTempDirectory("local"), [oneDrive]);
var paths = AppPaths.Resolve(app, local, [oneDrive]);
Assert.True(paths.IsPortable);
Assert.Equal(Path.Combine(local, "Titano"), paths.DataRoot);
Assert.Equal<string?>(oneDrive, paths.PortableSyncRoot);
Assert.False(paths.IsInSyncedFolder);
paths.CreateDirectories();
Assert.True(Directory.Exists(paths.LogsDirectory));
Assert.False(Directory.Exists(Path.Combine(app, "data")), "nothing is written into the synchronised folder");
}
[Test]
public void DataInsideOneDriveIsReportedAndRefused()
{
// Local application data inside a sync root: nowhere is safe, so nothing is created.
var oneDrive = context.CreateTempDirectory("onedrive");
var local = Directory.CreateDirectory(Path.Combine(oneDrive, "AppData", "Local")).FullName;
var paths = AppPaths.Resolve(context.CreateTempDirectory("app"), local, [oneDrive]);
Assert.True(paths.IsInSyncedFolder);
Assert.Equal<string?>(oneDrive, paths.SyncedFolder);
Assert.Throws<InvalidOperationException>(paths.CreateDirectories);
@@ -54,10 +73,7 @@ public sealed class AppPathsTests(TestContext context)
public void SyncRootMatchingIsSegmentWise()
{
var root = Path.Combine(context.CreateTempDirectory(), "OneDrive");
Assert.True(OneDriveFolders.IsUnder(root, root));
Assert.True(OneDriveFolders.IsUnder(Path.Combine(root, "Pictures"), root + Path.DirectorySeparatorChar));
Assert.True(OneDriveFolders.IsUnder(Path.Combine(root, "x").ToUpperInvariant(), root));
Assert.False(OneDriveFolders.IsUnder(root + "Backup", root));
Assert.Equal<string?>(root, OneDriveFolders.Containing(Path.Combine(root, "Pictures"), [root]));
Assert.Null(OneDriveFolders.Containing(root + "Backup", [root]));
}
@@ -68,8 +84,10 @@ public sealed class AppPathsTests(TestContext context)
var app = context.CreateTempDirectory("app");
File.WriteAllText(Path.Combine(app, PortableMode.MarkerFileName), "");
var paths = AppPaths.Resolve(app, KnownFolders.LocalAppData);
var roots = OneDriveFolders.SyncRoots();
Assert.True(paths.IsPortable);
Assert.Equal(OneDriveFolders.Containing(paths.DataRoot, OneDriveFolders.SyncRoots()), paths.SyncedFolder);
Assert.True(OneDriveFolders.SyncRoots().All(Path.IsPathFullyQualified));
Assert.Equal(OneDriveFolders.Containing(Path.Combine(app, PortableMode.DataFolderName), roots), paths.PortableSyncRoot);
Assert.Equal(OneDriveFolders.Containing(paths.DataRoot, roots), paths.SyncedFolder);
Assert.True(roots.All(Path.IsPathFullyQualified));
}
}
@@ -0,0 +1,39 @@
using Titano.Core.Windows.Shell;
using Titano.Testing;
namespace Titano.Core.Windows.Tests.Shell;
/// <summary>The OneDrive folders of the user as Windows reports them. Serial: a test sets a process environment variable.</summary>
[Serial]
public sealed class OneDriveFoldersTests(TestContext context)
{
private const string Variable = "OneDriveCommercial";
[Test]
[WindowsOnly]
public void APortableCopyInTheUsersOneDriveKeepsItsDataInLocalAppData()
{
var oneDrive = context.CreateTempDirectory("onedrive");
var previous = Environment.GetEnvironmentVariable(Variable);
Environment.SetEnvironmentVariable(Variable, oneDrive);
try
{
Assert.Contains(OneDriveFolders.SyncRoots(), root => string.Equals(root, Path.TrimEndingDirectorySeparator(oneDrive), StringComparison.OrdinalIgnoreCase));
// A Desktop that OneDrive's folder backup moved into the sync root, with a portable copy unpacked on it.
var app = Directory.CreateDirectory(Path.Combine(oneDrive, "Desktop", "Titano")).FullName;
File.WriteAllText(Path.Combine(app, PortableMode.MarkerFileName), "");
var local = context.CreateTempDirectory("local");
var paths = AppPaths.Resolve(app, local);
Assert.True(paths.IsPortable);
Assert.Equal(Path.Combine(local, AppPaths.ProductFolderName), paths.DataRoot);
Assert.NotNull(paths.PortableSyncRoot);
Assert.False(paths.IsInSyncedFolder);
}
finally
{
Environment.SetEnvironmentVariable(Variable, previous);
}
}
}
@@ -114,6 +114,48 @@ public sealed class ArchiveSettingsTests(TestContext context)
fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Proxies = s.Proxies with { LongEdge = 2560 } }, fx.Ct));
var shown = await fx.Service.GetSettingsAsync(fx.Archive.Id, fx.Ct);
Assert.Equal((1280, FrameImageRenderer.ThumbnailLongEdge), (shown.Proxies.LongEdge, shown.Thumbnails.LongEdge));
// A refresh reports that only the index's stand-ins are known: the thumbnail size above is not the archive's.
Assert.Null(await fx.Service.RefreshSettingsAsync(fx.Archive.Id, fx.Ct));
}
[Test]
public async Task ARefreshBringsTheIndexUpToSettingsChangedElsewhere()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
// Another process sharing the archive (a server's admin panel) changed archive.json: this index still has the old row.
var manifest = ManifestStore.ReadArchive(fx.Paths.ManifestPath);
ManifestStore.WriteArchive(fx.Paths.ManifestPath, manifest with
{
Name = "Shared",
LayoutTemplates = manifest.LayoutTemplates with { Folder = "{year}/{camera}" },
ProxyPolicy = manifest.ProxyPolicy with { LongEdge = 2560 },
ThumbnailPolicy = manifest.ThumbnailPolicy with { LongEdge = 480 },
});
Assert.Equal(fx.Archive.FolderTemplate, (await fx.Db.Archives.GetAsync(fx.Archive.Id, fx.Ct))!.FolderTemplate);
var settings = Assert.NotNull(await fx.Service.RefreshSettingsAsync(fx.Archive.Id, fx.Ct));
Assert.Equal(("{year}/{camera}", 2560, 480), (settings.Templates.Folder, settings.Proxies.LongEdge, settings.Thumbnails.LongEdge));
var row = (await fx.Db.Archives.GetAsync(fx.Archive.Id, fx.Ct))!;
Assert.Equal(("Shared", "{year}/{camera}", 2560), (row.Name, row.FolderTemplate, row.ProxyLongEdge));
// The drive is unplugged: nothing is known beyond the index, which stays as it is.
File.Move(fx.Paths.ManifestPath, fx.Paths.ManifestPath + ".away");
Assert.Null(await fx.Service.RefreshSettingsAsync(fx.Archive.Id, fx.Ct));
Assert.Equal("{year}/{camera}", (await fx.Db.Archives.GetAsync(fx.Archive.Id, fx.Ct))!.FolderTemplate);
// A newer Titano rewrote the file: what this one reads of it is neither shown nor registered.
ManifestStore.WriteArchive(fx.Paths.ManifestPath, manifest with { Name = "Newer", LayoutTemplates = manifest.LayoutTemplates with { Folder = "{camera}" } });
var newer = JsonNode.Parse(await File.ReadAllTextAsync(fx.Paths.ManifestPath, fx.Ct))!;
newer["schemaVersion"] = ArchiveManifest.CurrentSchemaVersion + 1;
await File.WriteAllTextAsync(fx.Paths.ManifestPath, newer.ToJsonString(), fx.Ct);
Assert.Null(await fx.Service.RefreshSettingsAsync(fx.Archive.Id, fx.Ct));
var kept = (await fx.Db.Archives.GetAsync(fx.Archive.Id, fx.Ct))!;
Assert.Equal(("Shared", "{year}/{camera}"), (kept.Name, kept.FolderTemplate));
// The folder now holds another archive: its settings are neither shown nor registered as this one's.
ManifestStore.WriteArchive(fx.Paths.ManifestPath, manifest with { Id = Guid.CreateVersion7(), Name = "Other" });
Assert.Null(await fx.Service.RefreshSettingsAsync(fx.Archive.Id, fx.Ct));
Assert.Equal("Shared", (await fx.Db.Archives.GetAsync(fx.Archive.Id, fx.Ct))!.Name);
}
[Test]
@@ -106,6 +106,47 @@ public sealed class ArchiveModuleTests(TestContext context)
await UntilImagesAsync(server, editor, archive.Id, "garden");
}
[Test]
public async Task SettingsADesktopChangedInArchiveJsonReachUploadsAndTheAdminPanel()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var archive = server.Services.GetRequiredService<ServerArchive>();
var polling = server.Services.GetRequiredService<ArchivePolling>();
// Nothing changed: the served archive (the one an administrator's edit put there) is not replaced by a row read again.
var served = archive.Current;
await polling.PollAsync(context.Cancellation);
Assert.True(ReferenceEquals(served, archive.Current), "a poll that registered nothing keeps the served archive");
// A desktop sharing the archive changed its folder template and proxy size in archive.json.
var path = new ArchivePaths(archive.Root).ManifestPath;
var manifest = ManifestStore.ReadArchive(path);
ManifestStore.WriteArchive(path, manifest with
{
LayoutTemplates = manifest.LayoutTemplates with { Folder = "{camera}/{date}" },
ProxyPolicy = manifest.ProxyPolicy with { LongEdge = 2560 },
});
await polling.PollAsync(context.Cancellation);
// Uploads (the index row) and the admin panel (the served archive) follow it.
Assert.Equal(("{camera}/{date}", 2560), (archive.Current.FolderTemplate, archive.Current.ProxyLongEdge));
var row = Assert.NotNull(await server.Database.Archives.GetAsync(archive.Id, context.Cancellation));
Assert.Equal(("{camera}/{date}", 2560), (row.FolderTemplate, row.ProxyLongEdge));
// The admin panel opens before the next poll: its form, which saves every field, starts from the desktop's change.
ManifestStore.WriteArchive(path, ManifestStore.ReadArchive(path) with { LayoutTemplates = manifest.LayoutTemplates with { Folder = "{year}/{camera}" } });
var admin = await server.AdminAsync();
using (var read = await admin.GetAsync("/api/v1/archive/settings"))
Assert.Equal("{year}/{camera}", (await read.ReadAsync(ProtocolJson.Default.ArchiveSettingsDto)).FolderTemplate);
Assert.Equal("{year}/{camera}", archive.Current.FolderTemplate);
// A refresh that read the archive before an administrator saved an edit never puts it back over that edit.
var before = archive.Current;
archive.Current = before with { Name = "Edited" };
Assert.False(archive.TryReplace(before, before with { Name = "Stale" }), "the edit saved meanwhile stays");
Assert.Equal("Edited", archive.Current.Name);
}
private static async Task UntilIndexedAsync(TestServer server, Guid archiveId, string folder)
{
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);