refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s

The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout and the system SQLite. The release cross-compiles the Windows
  programs, checks their icon, version and DPI manifest, packs installers
  and zips, publishes the Gitea release and pushes the server image
  (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows
  runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow; the
  throw-away server runs without durability) and pe-check.
- Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR,
  3 on the shared runner; the weekly performance gates keep theirs).

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #6.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-10-23 12:45:18 +02:00
1 parent c99842cc86
commit f2b58522b9
1801 files changed
+11804 -10676

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
<Application x:Class="Chronos.Uploader.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
ShutdownMode="OnExplicitShutdown">
</Application>
+339
View File
@@ -0,0 +1,339 @@
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Windows;
using System.Windows.Threading;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Ui.Interop;
using Chronos.Ui.Mvvm;
using Chronos.Ui.Theming;
using Chronos.Uploader.Infrastructure;
using Chronos.Uploader.Server;
using Chronos.Uploader.Shell;
using Chronos.Uploader.Uploads;
using Chronos.Uploader.Watching;
namespace Chronos.Uploader;
/// <summary>
/// Chronos Uploader (BRIEF §15): one instance per session, logging, language and theme, the persisted queue, the
/// server session, watch folders and the tray icon. <c>--capture &lt;dir&gt;</c> renders screenshots and exits.
/// </summary>
public partial class App : Application
{
private const int TrayShow = 1;
private const int TrayPause = 2;
private const int TrayExit = 3;
private readonly CoalescingWriter _writer = new();
private FileLogSink? _log;
private SingleInstance? _instance;
private UploaderEnvironment? _environment;
private UploaderSettings? _settings;
private UploadQueue? _queue;
private ProcessedFileMemory? _memory;
private ServerSession? _session;
private UploadEngine? _engine;
private WatchFolderService? _watch;
private DiscoveryListener? _discovery;
private MainViewModel? _vm;
private Shell.MainWindow? _window;
private TrayIcon? _tray;
private DispatcherTimer? _persist;
private bool _queueDirty;
private bool _exiting;
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var command = CommandLine.Parse(e.Args);
_environment = UploaderEnvironment.Detect();
_log = new FileLogSink(_environment.LogDirectory, "uploader");
Log.SetSink(_log);
Log.Info("app", $"Chronos Uploader {typeof(App).Assembly.GetName().Version} starting; data at {_environment.DataDirectory}");
HookUnhandledExceptions();
if (command.CaptureDirectory is { } captureDirectory)
{
RunCapture(captureDirectory);
return;
}
_instance = SingleInstance.TryAcquire();
if (_instance is null)
{
SingleInstance.HandOver([.. command.Paths.Select(Absolute).OfType<string>()]);
Log.Info("app", "Another uploader runs in this session; arguments handed over");
Shutdown();
return;
}
_settings = UploaderSettings.Load(_environment.SettingsPath);
ApplyLanguage(_settings.Language);
ThemeManager.Initialize(this, _settings.Theme);
BuildServices(_environment, _settings);
_instance.Listen(args => Dispatcher.BeginInvoke(() => OnHandOver(args)));
_session!.Start();
_engine!.Start();
_vm!.Start();
_vm.StartWatching();
UpdateTray();
UpdateDiscovery();
if (command.Paths.Count > 0) _ = _vm.EnqueueAsync(command.Paths);
if (command.StartInTray && _settings.MinimizeToTray) return;
if (command.StartInTray) _window!.WindowState = WindowState.Minimized;
_window!.Show();
}
protected override void OnExit(ExitEventArgs e)
{
_persist?.Stop();
_vm?.Dispose();
// Cancels transfers; interrupted items are written as queued and resume from the server's chunks.
_engine?.Dispose();
if (_queue is not null && _environment is not null)
{
Persist();
_writer.Flush(TimeSpan.FromSeconds(10));
}
if (_window is not null && _settings is not null) _window.SavePlacement();
SaveSettings();
_watch?.Dispose();
_discovery?.Dispose();
_session?.Dispose();
_tray?.Dispose();
_instance?.Dispose();
Log.Info("app", "Chronos Uploader exiting");
_log?.Dispose();
base.OnExit(e);
}
private void BuildServices(UploaderEnvironment environment, UploaderSettings settings)
{
_queue = new UploadQueue();
QueueStore.Load(environment.QueuePath, _queue);
_memory = ProcessedFileMemory.Load(environment.WatchMemoryPath);
_session = new ServerSession(settings, SaveSettings);
_engine = new UploadEngine(_queue, _session, () => settings.DeleteAfterUpload);
_watch = new WatchFolderService(_memory, _queue.ContainsPath);
var startup = new RunKeyStartupRegistration();
startup.Refresh();
var dialogs = new UploaderDialogs();
_vm = new MainViewModel(new UploaderServices(settings, SaveSettings, _session, _queue, _engine, startup, dialogs, _watch, _memory, environment.LogDirectory));
_window = new Shell.MainWindow(_vm, settings);
dialogs.Owner = _window;
MainWindow = _window;
AsyncRelayCommand.Failed += _vm.ReportError;
_engine.ItemConfirmed += (_, item) =>
{
if (item.WatchRoot is { } root) _memory.Add(root, item.Path, item.Size, item.ModifiedUtc);
};
_watch.FilesReady += _vm.OnWatchFilesReady;
_watch.AvailabilityChanged += _vm.OnWatchAvailabilityChanged;
_queue.Changed += (_, _) => _queueDirty = true;
_vm.UploadsCompleted += OnUploadsCompleted;
_vm.PropertyChanged += OnViewModelChanged;
_window.Closing += OnWindowClosing;
_window.Closed += (_, _) => ExitApplication();
_window.StateChanged += OnWindowStateChanged;
_persist = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromSeconds(2) };
_persist.Tick += (_, _) => Persist();
_persist.Start();
}
/// <summary>Switches the UI language (BRIEF §16); an unknown code falls back to the OS language.</summary>
private static void ApplyLanguage(string? code)
{
CultureInfo requested;
try
{
requested = code is null ? CultureInfo.CurrentUICulture : CultureInfo.GetCultureInfo(code);
}
catch (CultureNotFoundException)
{
requested = CultureInfo.CurrentUICulture;
}
var culture = Languages.BestMatch(requested);
CultureInfo.DefaultThreadCurrentUICulture = culture;
CultureInfo.CurrentUICulture = culture;
Loc.SetCulture(culture);
}
/// <summary>Writes the queue and the watch memory when they changed (every 2 s and at exit).</summary>
private void Persist()
{
if (_queue is null || _memory is null || _environment is null) return;
if (_queueDirty)
{
_queueDirty = false;
_writer.Write(_environment.QueuePath, QueueStore.Serialize(_queue));
}
if (_memory.IsDirty) _writer.Write(_environment.WatchMemoryPath, _memory.Serialize());
}
private void SaveSettings()
{
if (_settings is null || _environment is null) return;
try
{
_settings.Save(_environment.SettingsPath);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("app", "Settings not saved", ex);
}
}
private void OnHandOver(IReadOnlyList<string> paths)
{
ShowWindow();
if (paths.Count > 0) _ = _vm!.EnqueueAsync(paths);
}
private void OnViewModelChanged(object? sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case nameof(MainViewModel.MinimizeToTray):
UpdateTray();
break;
case nameof(MainViewModel.IsConnectVisible):
UpdateDiscovery();
break;
case nameof(MainViewModel.TrayText):
_tray?.SetToolTip(_vm!.TrayText);
break;
}
}
/// <summary>The tray icon exists while "Minimise to tray" is on.</summary>
private void UpdateTray()
{
if (_settings!.MinimizeToTray && _tray is null)
{
_tray = new TrayIcon(_vm!.TrayText, TrayMenu, OnTrayCommand, ShowWindow);
}
else if (!_settings.MinimizeToTray && _tray is not null)
{
_tray.Dispose();
_tray = null;
if (_window is { IsVisible: false }) ShowWindow();
}
}
private IReadOnlyList<TrayMenuItem> TrayMenu() =>
[
new(TrayShow, Loc.L("Uploader.Tray.Show")),
new(TrayPause, _vm!.PauseLabel),
new(0, null),
new(TrayExit, Loc.L("Uploader.Tray.Exit")),
];
private void OnTrayCommand(int id)
{
switch (id)
{
case TrayShow:
ShowWindow();
break;
case TrayPause:
_vm!.TogglePause();
break;
case TrayExit:
ExitApplication();
break;
}
}
/// <summary>Listens for server beacons only while the sign-in form is shown.</summary>
private void UpdateDiscovery()
{
if (_vm!.IsConnectVisible)
{
if (_discovery is not null) return;
_discovery = new DiscoveryListener();
_discovery.Found += _vm.Connect.AddDiscovered;
_discovery.Start();
}
else if (_discovery is not null)
{
_discovery.Dispose();
_discovery = null;
}
}
private void OnUploadsCompleted(int count)
{
if (_window is { IsVisible: true, WindowState: not WindowState.Minimized }) return;
_tray?.ShowBalloon(Loc.L("Uploader.Tray.Done.Title"), Loc.Plural("Uploader.Tray.Done.Message", count));
}
/// <summary>Closing keeps the uploader running in the tray when "Minimise to tray" is on.</summary>
private void OnWindowClosing(object? sender, CancelEventArgs e)
{
if (_exiting || !_settings!.MinimizeToTray) return;
e.Cancel = true;
_window!.SavePlacement();
_window.Hide();
}
private void OnWindowStateChanged(object? sender, EventArgs e)
{
if (_window is { WindowState: WindowState.Minimized } && _settings!.MinimizeToTray) _window.Hide();
}
private void ShowWindow()
{
if (_window is null) return;
_window.Show();
if (_window.WindowState == WindowState.Minimized) _window.WindowState = WindowState.Normal;
_window.Activate();
}
private void ExitApplication()
{
if (_exiting) return;
_exiting = true;
Shutdown();
}
private void RunCapture(string directory)
{
ThemeManager.Initialize(this, AppTheme.Dark);
ScreenCapture.Run(directory, ApplyLanguage);
}
private void HookUnhandledExceptions()
{
DispatcherUnhandledException += (_, e) =>
{
Log.Error("app", "Unhandled UI exception", e.Exception);
if (_vm is null) return;
_vm.ReportError(e.Exception);
e.Handled = true;
};
AppDomain.CurrentDomain.UnhandledException += (_, e) => Log.Error("app", "Unhandled exception", e.ExceptionObject as Exception);
TaskScheduler.UnobservedTaskException += (_, e) =>
{
Log.Error("app", "Unobserved task exception", e.Exception);
e.SetObserved();
};
}
/// <summary>Paths handed to the running instance must not depend on this process's working directory.</summary>
private static string? Absolute(string path)
{
try
{
return Path.GetFullPath(path);
}
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
{
return null;
}
}
}
@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<UseWPF>true</UseWPF>
<RootNamespace>Chronos.Uploader</RootNamespace>
<AssemblyName>Chronos.Uploader</AssemblyName>
<ApplicationManifest>app.manifest</ApplicationManifest>
<ChronosIconVariant>chronos-uploader</ChronosIconVariant>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Chronos.Core\Chronos.Core.csproj" />
<ProjectReference Include="..\Chronos.Protocol\Chronos.Protocol.csproj" />
<ProjectReference Include="..\Chronos.Ui\Chronos.Ui.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,181 @@
using System.ComponentModel;
using System.Globalization;
using System.Runtime.CompilerServices;
using Chronos.Protocol;
using Chronos.Uploader.Infrastructure;
using Chronos.Uploader.Server;
using Chronos.Uploader.Shell;
using Chronos.Uploader.Uploads;
using Chronos.Uploader.Watching;
namespace Chronos.Uploader.DesignTime;
/// <summary>
/// Sample content for <c>--capture</c> screenshots ONLY: a fake signed-in session, a running queue of 4,812 files
/// with one failure, and three watch folders (one unreachable). Nothing here touches the network, the registry or the
/// user's data files.
/// </summary>
public sealed class SampleData
{
private const int FileCount = 4_812;
private const long FileSize = 20_000_000;
/// <summary>The sample's "now" (when the failed file failed): fixed, so the screenshots are the same on any day.</summary>
private static readonly DateTime Now = new(2026, 9, 28, 19, 2, 0, DateTimeKind.Utc);
private readonly SampleSession _session = new();
private readonly UploadQueue _queue = new();
private MainViewModel? _vm;
public UploaderSettings Settings { get; } = new()
{
ServerUrl = "https://nas.local:8443/",
Username = "alberto",
BandwidthLimit = 50,
MinimizeToTray = true,
WatchFolders =
[
new UploaderSettings.WatchFolderSettings { Path = @"D:\Cam\Roof", IntervalSeconds = 60 },
new UploaderSettings.WatchFolderSettings { Path = @"\\garage-pi\cam", IntervalSeconds = 300 },
new UploaderSettings.WatchFolderSettings { Path = @"F:\Timelapse\Construction site north tower", IntervalSeconds = 900 },
],
};
/// <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), 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.
_vm.WatchFolders[^1].IsAvailable = false;
return _vm;
}
/// <summary>First run: no server yet, one server found on the LAN.</summary>
public void ShowConnect()
{
_session.SetState(ConnectionState.NotConfigured);
_vm!.Connect.Address = string.Empty;
_vm.Connect.Username = string.Empty;
_vm.Connect.Discovered.Clear();
_vm.Connect.Discovered.Add(new DiscoveredServer("Studio NAS", "https://192.168.1.20:8443"));
}
/// <summary>Signed in, a card being uploaded at 38 MB/s.</summary>
public void ShowQueue()
{
_session.SetState(ConnectionState.Connected);
if (_queue.Items.Count == 0) FillQueue();
_vm!.Sequences.Clear();
_vm.Sequences.Add(new SequenceOption(Guid.Empty, "Harbour sunset"));
_vm.SelectedSequence = _vm.Sequences[0];
_vm.RefreshQueue();
}
private void FillQueue()
{
var batch = new UploadBatch { Id = Guid.CreateVersion7(), Mode = UploadTargetMode.Sessions };
var start = new DateTime(2026, 9, 28, 15, 22, 0);
_queue.Add(batch, Enumerable.Range(0, FileCount).Select(i =>
{
var shot = start.AddSeconds(i * 5);
var name = shot.ToString("yyyy-MM-dd_HH-mm-ss", CultureInfo.InvariantCulture) + "_" + (i + 1).ToString("0000", CultureInfo.InvariantCulture) + ".CR2";
return new QueueEntry(@"E:\DCIM\100CANON\" + name, FileSize, shot.ToUniversalTime(), shot, "1a2b3c4d-20260928-152200", null);
}));
for (var i = 0; i < 2_201; i++) _queue.Items[i].State = i % 200 == 7 ? UploadItemState.Skipped : UploadItemState.Verified;
_queue.Items[1_640].Retries = 1;
_queue.Items[2_201].State = UploadItemState.Uploading;
_queue.Items[2_201].BytesSent = FileSize * 46 / 100;
_queue.Items[2_202].State = UploadItemState.Hashing;
_queue.Fail(_queue.Items[2_203], UploadFailure.FileUnreadable, null, Now);
}
private sealed class SampleSession : IServerSession
{
private ConnectionState _state = ConnectionState.Connected;
public event PropertyChangedEventHandler? PropertyChanged;
public event EventHandler<ServerProblem>? SessionEnded
{
add { }
remove { }
}
public ConnectionState State => _state;
public string? Address => "https://nas.local:8443/";
public string? Username => "alberto";
public long QuotaBytes => 5_000_000_000_000;
public long UsedBytes => 3_100_000_000_000;
public int BandwidthLimit { get; set; }
public void SetState(ConnectionState state)
{
_state = state;
Raise(nameof(State));
}
public Task<(SignInResult Result, string? Fingerprint)> SignInAsync(string address, string username, string password, CancellationToken ct) =>
Task.FromResult<(SignInResult, string?)>((SignInResult.Failed, null));
public void Trust(string fingerprint)
{
}
public Task SignOutAsync() => Task.CompletedTask;
public Task RefreshAsync() => Task.CompletedTask;
public Task<IReadOnlyList<SequenceDto>> ListSequencesAsync(CancellationToken ct) => Task.FromResult<IReadOnlyList<SequenceDto>>([]);
private void Raise([CallerMemberName] string? name = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
private sealed class SampleEngine(UploadQueue queue) : IUploadEngine
{
public event PropertyChangedEventHandler? PropertyChanged
{
add { }
remove { }
}
public event EventHandler? Drained
{
add { }
remove { }
}
public EngineStatus Status => queue.IsPaused ? EngineStatus.Paused : EngineStatus.Running;
public double BytesPerSecond => 38_000_000;
public void Pump()
{
}
public void Pause() => queue.IsPaused = true;
public void Resume() => queue.IsPaused = false;
public void StopAndClear()
{
}
public void Retry(UploadItem item)
{
}
}
private sealed class SampleStartup : IStartupRegistration
{
public bool IsEnabled { get; private set; } = true;
public void SetEnabled(bool enabled) => IsEnabled = enabled;
}
}
@@ -0,0 +1,62 @@
using System.IO;
using Chronos.Core.Diagnostics;
using Chronos.Core.IO;
namespace Chronos.Uploader.Infrastructure;
/// <summary>
/// Writes state files off the UI thread with <see cref="AtomicFile"/>. Only the newest content of each file is kept
/// while a write is in progress, so a slow disk never writes an older snapshot after a newer one.
/// </summary>
public sealed class CoalescingWriter
{
private readonly Lock _gate = new();
private readonly Dictionary<string, byte[]> _pending = new(StringComparer.OrdinalIgnoreCase);
private Task _worker = Task.CompletedTask;
private bool _running;
public void Write(string path, byte[] content)
{
lock (_gate)
{
_pending[path] = content;
if (_running) return;
_running = true;
_worker = Task.Run(Drain);
}
}
/// <summary>Waits for pending writes (at exit).</summary>
public void Flush(TimeSpan timeout)
{
Task worker;
lock (_gate) worker = _worker;
if (!worker.Wait(timeout)) Log.Warning("persist", "State files still being written at exit");
}
private void Drain()
{
while (true)
{
KeyValuePair<string, byte[]> next;
lock (_gate)
{
if (_pending.Count == 0)
{
_running = false;
return;
}
next = _pending.First();
_pending.Remove(next.Key);
}
try
{
AtomicFile.WriteAllBytes(next.Key, next.Value);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("persist", $"{next.Key} not written", ex);
}
}
}
}
@@ -0,0 +1,27 @@
namespace Chronos.Uploader.Infrastructure;
/// <summary>
/// <c>Chronos.Uploader.exe [--tray] [--capture &lt;dir&gt;] [files or folders…]</c>: paths are enqueued, <c>--tray</c>
/// starts hidden (used by the Run key), <c>--capture</c> renders screenshots and exits.
/// </summary>
public sealed record CommandLine(IReadOnlyList<string> Paths, bool StartInTray, string? CaptureDirectory)
{
public const string TrayOption = "--tray";
public const string CaptureOption = "--capture";
public static CommandLine Parse(IReadOnlyList<string> args)
{
var paths = new List<string>();
var tray = false;
string? capture = null;
for (var i = 0; i < args.Count; i++)
{
var a = args[i];
if (a.Equals(TrayOption, StringComparison.OrdinalIgnoreCase)) tray = true;
else if (a.Equals(CaptureOption, StringComparison.OrdinalIgnoreCase))
capture = i + 1 < args.Count && !args[i + 1].StartsWith("--", StringComparison.Ordinal) ? args[++i] : "screenshots";
else if (!a.StartsWith("--", StringComparison.Ordinal) && a.Length > 0) paths.Add(a);
}
return new CommandLine(paths, tray, capture);
}
}
@@ -0,0 +1,98 @@
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Text;
using Chronos.Core.Diagnostics;
namespace Chronos.Uploader.Infrastructure;
/// <summary>
/// One uploader per Windows session: a named mutex marks the running instance, and a second launch hands its
/// file arguments over a named pipe (current user only) before exiting.
/// </summary>
public sealed class SingleInstance : IDisposable
{
private const string MutexName = @"Local\Chronos.Uploader";
private const string Header = "CHRONOS-UPLOADER/1";
private const int MaxMessageBytes = 1 << 20;
private readonly Mutex _mutex;
private readonly CancellationTokenSource _stop = new();
private SingleInstance(Mutex mutex) => _mutex = mutex;
private static string PipeName => $"Chronos.Uploader.{Process.GetCurrentProcess().SessionId}.{Environment.UserName}";
/// <summary>The instance guard, or null when another uploader already runs in this session.</summary>
public static SingleInstance? TryAcquire()
{
var mutex = new Mutex(initiallyOwned: true, MutexName, out var createdNew);
if (createdNew) return new SingleInstance(mutex);
mutex.Dispose();
return null;
}
/// <summary>Sends <paramref name="args"/> (absolute paths; empty = just show the window) to the running instance.</summary>
public static void HandOver(IReadOnlyList<string> args)
{
try
{
using var pipe = new NamedPipeClientStream(".", PipeName, PipeDirection.Out, PipeOptions.CurrentUserOnly);
pipe.Connect(3000);
pipe.Write(Encode(args));
pipe.Flush();
}
catch (Exception ex) when (ex is IOException or TimeoutException or UnauthorizedAccessException)
{
Log.Warning("instance", "Could not reach the running uploader", ex);
}
}
/// <summary>Receives messages from later launches; <paramref name="received"/> runs on a pool thread.</summary>
public void Listen(Action<IReadOnlyList<string>> received) => _ = ListenAsync(received, _stop.Token);
public void Dispose()
{
_stop.Cancel();
_mutex.ReleaseMutex();
_mutex.Dispose();
_stop.Dispose();
}
/// <summary>UTF-8: a header line, then one argument per line (paths cannot contain line breaks).</summary>
public static byte[] Encode(IReadOnlyList<string> args) =>
Encoding.UTF8.GetBytes(Header + "\n" + string.Join("\n", args.Where(a => !a.Contains('\n', StringComparison.Ordinal))));
/// <summary>Arguments of a message, or null when it is not one of ours.</summary>
public static IReadOnlyList<string>? Decode(ReadOnlySpan<byte> message)
{
if (message.Length > MaxMessageBytes) return null;
var lines = Encoding.UTF8.GetString(message).Split('\n');
if (lines[0] != Header) return null;
return [.. lines.Skip(1).Where(l => l.Length > 0)];
}
private static async Task ListenAsync(Action<IReadOnlyList<string>> received, CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
try
{
await using var pipe = new NamedPipeServerStream(PipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte,
PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly);
await pipe.WaitForConnectionAsync(ct).ConfigureAwait(false);
using var buffer = new MemoryStream();
await pipe.CopyToAsync(buffer, ct).ConfigureAwait(false);
if (Decode(buffer.GetBuffer().AsSpan(0, (int)buffer.Length)) is { } args) received(args);
}
catch (OperationCanceledException)
{
return;
}
catch (IOException ex)
{
Log.Warning("instance", "Hand-over pipe failed; listening again", ex);
}
}
}
}
@@ -0,0 +1,80 @@
using System.IO;
using System.Security;
using Microsoft.Win32;
using Chronos.Core.Diagnostics;
using Chronos.Core.IO;
namespace Chronos.Uploader.Infrastructure;
/// <summary>"Start with Windows".</summary>
public interface IStartupRegistration
{
bool IsEnabled { get; }
void SetEnabled(bool enabled);
}
/// <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: 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>
/// <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;
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 =>
{
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 object? Read(string subKey)
{
try
{
using var key = _root.OpenSubKey(subKey);
return key?.GetValue(ValueName);
}
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);
}
}
}
@@ -0,0 +1,98 @@
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
namespace Chronos.Uploader.Infrastructure;
/// <summary>
/// Encrypts the sign-in token for the current Windows user with DPAPI (<c>CryptProtectData</c>, no machine scope),
/// so <c>uploader.json</c> copied to another account or PC cannot be used.
/// </summary>
public static partial class TokenProtector
{
private const int CryptProtectUiForbidden = 0x1;
// Ties the blob to this program; other DPAPI consumers of the same user cannot unwrap it by accident.
private static readonly byte[] Entropy = "Chronos.Uploader.Token.v1"u8.ToArray();
/// <summary>Base64 DPAPI blob of <paramref name="token"/>.</summary>
public static string Protect(string token)
{
var plain = Encoding.UTF8.GetBytes(token);
try
{
return Convert.ToBase64String(Transform(plain, protect: true));
}
finally
{
CryptographicOperations.ZeroMemory(plain);
}
}
/// <summary>The token, or null when the blob is corrupt or belongs to another user.</summary>
public static string? Unprotect(string protectedToken)
{
byte[] blob;
try
{
blob = Convert.FromBase64String(protectedToken);
}
catch (FormatException)
{
return null;
}
try
{
var plain = Transform(blob, protect: false);
var token = Encoding.UTF8.GetString(plain);
CryptographicOperations.ZeroMemory(plain);
return token;
}
catch (CryptographicException)
{
return null;
}
}
private static unsafe byte[] Transform(byte[] input, bool protect)
{
fixed (byte* inPtr = input)
fixed (byte* entropyPtr = Entropy)
{
var source = new DataBlob { Size = input.Length, Data = (IntPtr)inPtr };
var entropy = new DataBlob { Size = Entropy.Length, Data = (IntPtr)entropyPtr };
var ok = protect
? CryptProtectData(source, null, entropy, IntPtr.Zero, IntPtr.Zero, CryptProtectUiForbidden, out var output)
: CryptUnprotectData(source, IntPtr.Zero, entropy, IntPtr.Zero, IntPtr.Zero, CryptProtectUiForbidden, out output);
if (!ok) throw new CryptographicException(Marshal.GetLastPInvokeError());
try
{
var result = new byte[output.Size];
Marshal.Copy(output.Data, result, 0, output.Size);
return result;
}
finally
{
LocalFree(output.Data);
}
}
}
[StructLayout(LayoutKind.Sequential)]
private struct DataBlob
{
public int Size;
public IntPtr Data;
}
[LibraryImport("crypt32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool CryptProtectData(in DataBlob dataIn, string? description, in DataBlob entropy, IntPtr reserved, IntPtr prompt, int flags, out DataBlob dataOut);
[LibraryImport("crypt32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool CryptUnprotectData(in DataBlob dataIn, IntPtr description, in DataBlob entropy, IntPtr reserved, IntPtr prompt, int flags, out DataBlob dataOut);
[LibraryImport("kernel32.dll")]
private static partial IntPtr LocalFree(IntPtr memory);
}
@@ -0,0 +1,38 @@
using System.IO;
namespace Chronos.Uploader.Infrastructure;
/// <summary>
/// Where the uploader keeps its files: <c>%LOCALAPPDATA%\Chronos</c> (shared with the client), or <c>.\data</c> next
/// 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
{
private UploaderEnvironment(string dataDirectory)
{
DataDirectory = dataDirectory;
Directory.CreateDirectory(DataDirectory);
Directory.CreateDirectory(LogDirectory);
}
public string DataDirectory { get; }
public string LogDirectory => Path.Combine(DataDirectory, "logs");
/// <summary>Settings, DPAPI-protected token and trusted certificate fingerprints.</summary>
public string SettingsPath => Path.Combine(DataDirectory, "uploader.json");
/// <summary>The persisted upload queue.</summary>
public string QueuePath => Path.Combine(DataDirectory, "uploader-queue.json");
/// <summary>Files of watch folders the server already confirmed.</summary>
public string WatchMemoryPath => Path.Combine(DataDirectory, "uploader-watch.json");
public static UploaderEnvironment Detect()
{
var exeDir = AppContext.BaseDirectory;
if (File.Exists(Path.Combine(exeDir, "portable.txt"))) return new UploaderEnvironment(Path.Combine(exeDir, "data"));
var local = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
return new UploaderEnvironment(Path.Combine(local, "Chronos"));
}
}
@@ -0,0 +1,77 @@
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using Chronos.Core.Diagnostics;
using Chronos.Core.IO;
using Chronos.Ui.Theming;
using Chronos.Uploader.Uploads;
namespace Chronos.Uploader.Infrastructure;
/// <summary>
/// <c>uploader.json</c>. The bearer token is stored only DPAPI-protected for the current Windows user
/// (<see cref="TokenProtector"/>); "Start with Windows" lives in the registry, which stays the source of truth.
/// </summary>
public sealed class UploaderSettings
{
public string? ServerUrl { get; set; }
public string? Username { get; set; }
/// <summary>Base64 of the DPAPI (CurrentUser) blob of the bearer token.</summary>
public string? ProtectedToken { get; set; }
/// <summary>SHA-256 fingerprints (XX:XX:…) of self-signed certificates the user trusted (TOFU).</summary>
public List<string> TrustedFingerprints { get; set; } = [];
/// <summary>Upload limit in MB/s (decimal megabytes); 0 = unlimited.</summary>
public int BandwidthLimit { get; set; }
public bool MinimizeToTray { get; set; } = true;
public bool DeleteAfterUpload { get; set; }
public UploadTargetMode Target { get; set; } = UploadTargetMode.Sessions;
public Guid? TargetSequenceId { get; set; }
public string? NewSequenceTitle { get; set; }
public List<WatchFolderSettings> WatchFolders { get; set; } = [];
public string? Language { get; set; }
public AppTheme Theme { get; set; } = AppTheme.Dark;
public WindowPlacement? Window { get; set; }
public sealed class WatchFolderSettings
{
public string Path { get; set; } = string.Empty;
public int IntervalSeconds { get; set; } = 60;
}
public sealed class WindowPlacement
{
public double Left { get; set; }
public double Top { get; set; }
public double Width { get; set; }
public double Height { get; set; }
}
public static UploaderSettings Load(string path)
{
try
{
if (File.Exists(path))
return JsonSerializer.Deserialize(File.ReadAllBytes(path), UploaderSettingsJson.Default.UploaderSettings) ?? new UploaderSettings();
}
catch (JsonException ex)
{
// A corrupt settings file must never block startup; defaults apply.
Log.Warning("settings", "uploader.json unreadable; using defaults", ex);
}
catch (IOException ex)
{
Log.Warning("settings", "uploader.json unreadable; using defaults", ex);
}
return new UploaderSettings();
}
public void Save(string path) => AtomicFile.WriteAllBytes(path, JsonSerializer.SerializeToUtf8Bytes(this, UploaderSettingsJson.Default.UploaderSettings));
}
[JsonSourceGenerationOptions(WriteIndented = true, PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, UseStringEnumConverter = true)]
[JsonSerializable(typeof(UploaderSettings))]
internal sealed partial class UploaderSettingsJson : JsonSerializerContext;
+187
View File
@@ -0,0 +1,187 @@
using System.Runtime.InteropServices;
namespace Chronos.Uploader.Interop;
/// <summary>A filter of the Open dialog: display name and patterns such as <c>*.jpg;*.cr2</c>.</summary>
public readonly record struct FileFilter(string Name, string Patterns);
/// <summary>
/// The shell's Open dialog through <c>IFileOpenDialog</c> COM (no WinForms): several files at once, or one folder
/// (which also picks a card root such as <c>E:\</c>).
/// </summary>
public static class FileDialogs
{
private const uint FosPickFolders = 0x20;
private const uint FosForceFileSystem = 0x40;
private const uint FosAllowMultiSelect = 0x200;
private const uint FosPathMustExist = 0x800;
private const uint FosFileMustExist = 0x1000;
private const uint SigdnFileSysPath = 0x80058000;
private const int ErrorCancelled = unchecked((int)0x800704C7);
/// <summary>Selected files; empty when cancelled.</summary>
public static IReadOnlyList<string> PickFiles(IntPtr owner, string title, IReadOnlyList<FileFilter> filters) =>
Show(owner, title, FosAllowMultiSelect | FosFileMustExist, filters);
/// <summary>Selected folder; null when cancelled.</summary>
public static string? PickFolder(IntPtr owner, string title) => Show(owner, title, FosPickFolders, []).FirstOrDefault();
private static List<string> Show(IntPtr owner, string title, uint options, IReadOnlyList<FileFilter> filters)
{
var dialog = (IFileOpenDialog)new FileOpenDialogClass();
try
{
dialog.GetOptions(out var current);
dialog.SetOptions(current | options | FosForceFileSystem | FosPathMustExist);
dialog.SetTitle(title);
if (filters.Count > 0)
{
var specs = filters.Select(f => new FilterSpec { Name = f.Name, Spec = f.Patterns }).ToArray();
dialog.SetFileTypes((uint)specs.Length, specs);
dialog.SetFileTypeIndex(1);
}
var hr = dialog.Show(owner);
if (hr == ErrorCancelled) return [];
Marshal.ThrowExceptionForHR(hr);
dialog.GetResults(out var items);
try
{
items.GetCount(out var count);
var paths = new List<string>((int)count);
for (uint i = 0; i < count; i++)
{
items.GetItemAt(i, out var item);
try
{
item.GetDisplayName(SigdnFileSysPath, out var path);
paths.Add(path);
}
finally
{
Marshal.ReleaseComObject(item);
}
}
return paths;
}
finally
{
Marshal.ReleaseComObject(items);
}
}
finally
{
Marshal.ReleaseComObject(dialog);
}
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct FilterSpec
{
[MarshalAs(UnmanagedType.LPWStr)]
public string Name;
[MarshalAs(UnmanagedType.LPWStr)]
public string Spec;
}
[ComImport]
[Guid("DC1C5A9C-E88A-4dde-A5A1-60F82A20AEF7")]
private class FileOpenDialogClass;
// Classic COM interop does not inherit vtables: IModalWindow and IFileDialog members are repeated in order.
[ComImport]
[Guid("d57c7288-d4ad-4768-be02-9d969532d960")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IFileOpenDialog
{
[PreserveSig]
int Show(IntPtr owner);
void SetFileTypes(uint count, [In, MarshalAs(UnmanagedType.LPArray)] FilterSpec[] filters);
void SetFileTypeIndex(uint index);
void GetFileTypeIndex(out uint index);
void Advise(IntPtr events, out uint cookie);
void Unadvise(uint cookie);
void SetOptions(uint options);
void GetOptions(out uint options);
void SetDefaultFolder(IShellItem item);
void SetFolder(IShellItem item);
void GetFolder(out IShellItem item);
void GetCurrentSelection(out IShellItem item);
void SetFileName([MarshalAs(UnmanagedType.LPWStr)] string name);
void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string name);
void SetTitle([MarshalAs(UnmanagedType.LPWStr)] string title);
void SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string text);
void SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string label);
void GetResult(out IShellItem item);
void AddPlace(IShellItem item, int placement);
void SetDefaultExtension([MarshalAs(UnmanagedType.LPWStr)] string extension);
void Close(int hr);
void SetClientGuid(ref Guid guid);
void ClearClientData();
void SetFilter(IntPtr filter);
void GetResults(out IShellItemArray items);
void GetSelectedItems(out IShellItemArray items);
}
[ComImport]
[Guid("43826d1e-e718-42ee-bc55-a1e261c37bfe")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IShellItem
{
void BindToHandler(IntPtr bindContext, ref Guid handler, ref Guid iid, out IntPtr result);
void GetParent(out IShellItem parent);
void GetDisplayName(uint form, [MarshalAs(UnmanagedType.LPWStr)] out string name);
void GetAttributes(uint mask, out uint attributes);
void Compare(IShellItem other, uint hint, out int order);
}
[ComImport]
[Guid("b63ea76d-1f85-456f-a19c-48159efa858b")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IShellItemArray
{
void BindToHandler(IntPtr bindContext, ref Guid handler, ref Guid iid, out IntPtr result);
void GetPropertyStore(int flags, ref Guid iid, out IntPtr store);
void GetPropertyDescriptionList(IntPtr keyType, ref Guid iid, out IntPtr list);
void GetAttributes(int flags, uint mask, out uint attributes);
void GetCount(out uint count);
void GetItemAt(uint index, out IShellItem item);
void EnumItems(out IntPtr items);
}
}
@@ -0,0 +1,74 @@
using System.Net;
using System.Net.Sockets;
using Chronos.Core.Diagnostics;
using Chronos.Protocol;
namespace Chronos.Uploader.Server;
/// <summary>A Chronos Server announced on the LAN.</summary>
public sealed record DiscoveredServer(string Name, string Address);
/// <summary>
/// Listens for the server's UDP beacon (<see cref="DiscoveryBeacon.Port"/>) while the connect form is open and reports
/// each server once. Beacons are unauthenticated: they only fill the address field, never trust a certificate.
/// </summary>
public sealed class DiscoveryListener : IDisposable
{
private readonly HashSet<string> _seen = new(StringComparer.OrdinalIgnoreCase);
private CancellationTokenSource? _cts;
/// <summary>Raised on the thread that called <see cref="Start"/>.</summary>
public event Action<DiscoveredServer>? Found;
public void Start()
{
if (_cts is not null) return;
_cts = new CancellationTokenSource();
var context = SynchronizationContext.Current;
_ = Task.Run(() => ListenAsync(context, _cts.Token));
}
public void Dispose()
{
_cts?.Cancel();
_cts?.Dispose();
_cts = null;
}
/// <summary>The address the client should use for <paramref name="beacon"/> sent from <paramref name="sender"/>.</summary>
private static string AddressOf(DiscoveryBeacon beacon, IPAddress sender)
{
var host = sender.AddressFamily == AddressFamily.InterNetworkV6 ? "[" + sender + "]" : sender.ToString();
return beacon.HttpsPort > 0 ? $"https://{host}:{beacon.HttpsPort}" : $"http://{host}:{beacon.HttpPort}";
}
private async Task ListenAsync(SynchronizationContext? context, CancellationToken ct)
{
try
{
using var udp = new UdpClient();
// The desktop client may listen on the same port.
udp.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
udp.Client.Bind(new IPEndPoint(IPAddress.Any, DiscoveryBeacon.Port));
while (!ct.IsCancellationRequested)
{
var datagram = await udp.ReceiveAsync(ct).ConfigureAwait(false);
if (DiscoveryBeacon.TryParse(datagram.Buffer) is not { } beacon) continue;
var server = new DiscoveredServer(beacon.Name, AddressOf(beacon, datagram.RemoteEndPoint.Address));
lock (_seen)
{
if (!_seen.Add(server.Address)) continue;
}
if (context is null) Found?.Invoke(server);
else context.Post(_ => Found?.Invoke(server), null);
}
}
catch (OperationCanceledException)
{
}
catch (SocketException ex)
{
Log.Info("discovery", "LAN discovery unavailable: " + ex.Message);
}
}
}
@@ -0,0 +1,21 @@
namespace Chronos.Uploader.Server;
/// <summary>Server addresses as typed in the sign-in form.</summary>
public static class ServerAddress
{
/// <summary>
/// Accepts "nas.local:8443" (https assumed) or a full http(s) URL; the result is the API base, ending with "/".
/// </summary>
public static bool TryParse(string? text, out Uri uri)
{
uri = null!;
if (string.IsNullOrWhiteSpace(text)) return false;
var trimmed = text.Trim();
if (!trimmed.Contains("://", StringComparison.Ordinal)) trimmed = "https://" + trimmed;
if (!Uri.TryCreate(trimmed, UriKind.Absolute, out var parsed) || parsed.Scheme is not ("https" or "http") || parsed.Host.Length == 0) return false;
var builder = new UriBuilder(parsed) { Query = string.Empty, Fragment = string.Empty };
if (!builder.Path.EndsWith('/')) builder.Path += "/";
uri = builder.Uri;
return true;
}
}
@@ -0,0 +1,460 @@
using System.ComponentModel;
using System.Net;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Text.Json;
using Chronos.Core.Diagnostics;
using Chronos.Protocol;
using Chronos.Protocol.Client;
using Chronos.Uploader.Infrastructure;
using Chronos.Uploader.Uploads;
namespace Chronos.Uploader.Server;
/// <summary>Connection shown in the header.</summary>
public enum ConnectionState
{
/// <summary>First run: no server chosen yet.</summary>
NotConfigured,
SigningIn,
Connected,
/// <summary>Signed in, but the server cannot be reached; probed every 30 s.</summary>
Offline,
/// <summary>A server is known but there is no valid token.</summary>
SignedOut,
}
/// <summary>Outcome of the sign-in form.</summary>
public enum SignInResult
{
Success,
InvalidAddress,
Unreachable,
NotChronos,
/// <summary>The certificate is self-signed and unknown: ask the user to trust its fingerprint.</summary>
Untrusted,
BadCredentials,
Failed,
}
/// <summary>The server connection as the window sees it.</summary>
public interface IServerSession : INotifyPropertyChanged
{
ConnectionState State { get; }
/// <summary>Server address as the user typed or discovered it.</summary>
string? Address { get; }
string? Username { get; }
/// <summary>Quota in bytes; 0 = unlimited.</summary>
long QuotaBytes { get; }
long UsedBytes { get; }
/// <summary>Upload limit in MB/s; 0 = unlimited.</summary>
int BandwidthLimit { get; set; }
/// <summary>Raised when the server ended the session (token rejected or certificate changed).</summary>
event EventHandler<ServerProblem>? SessionEnded;
/// <summary>Signs in; <see cref="SignInResult.Untrusted"/> comes with the fingerprint to show.</summary>
Task<(SignInResult Result, string? Fingerprint)> SignInAsync(string address, string username, string password, CancellationToken ct);
/// <summary>Remembers a certificate fingerprint the user confirmed (trust on first use).</summary>
void Trust(string fingerprint);
Task SignOutAsync();
/// <summary>Refreshes the account (quota) when connected.</summary>
Task RefreshAsync();
Task<IReadOnlyList<SequenceDto>> ListSequencesAsync(CancellationToken ct);
}
/// <summary>
/// Owns the <see cref="ChronosClient"/>: sign-in with trust-on-first-use, token restore from DPAPI, offline probing,
/// and the upload transport. Runs on the UI thread.
/// </summary>
public sealed class ServerSession : IServerSession, IUploadTransport, IDisposable
{
private static readonly TimeSpan ProbeInterval = TimeSpan.FromSeconds(30);
private readonly UploaderSettings _settings;
private readonly Action _saveSettings;
private ChronosClient? _client;
private ConnectionState _state;
private string? _username;
private long _quotaBytes;
private long _usedBytes;
private int _bandwidthLimit;
private CancellationTokenSource? _probe;
public ServerSession(UploaderSettings settings, Action saveSettings)
{
_settings = settings;
_saveSettings = saveSettings;
_username = settings.Username;
_bandwidthLimit = Math.Max(0, settings.BandwidthLimit);
_state = settings.ServerUrl is null ? ConnectionState.NotConfigured : ConnectionState.SignedOut;
}
public event PropertyChangedEventHandler? PropertyChanged;
public event EventHandler? ReadyChanged;
public event EventHandler<ServerProblem>? SessionEnded;
public ConnectionState State
{
get => _state;
private set
{
if (_state == value) return;
var wasReady = IsReady;
_state = value;
OnPropertyChanged();
if (wasReady != IsReady) ReadyChanged?.Invoke(this, EventArgs.Empty);
}
}
public bool IsReady => _state == ConnectionState.Connected && _client is not null;
public string? Address => _settings.ServerUrl;
public string? Username
{
get => _username;
private set => Set(ref _username, value);
}
public long QuotaBytes
{
get => _quotaBytes;
private set => Set(ref _quotaBytes, value);
}
public long UsedBytes
{
get => _usedBytes;
private set => Set(ref _usedBytes, value);
}
public int BandwidthLimit
{
get => _bandwidthLimit;
set
{
if (!Set(ref _bandwidthLimit, Math.Max(0, value))) return;
ApplyBandwidth();
}
}
/// <summary>Restores the saved session, if any, in the background.</summary>
public void Start()
{
if (_settings.ServerUrl is null || _settings.ProtectedToken is null) return;
var token = TokenProtector.Unprotect(_settings.ProtectedToken);
if (token is null || !ServerAddress.TryParse(_settings.ServerUrl, out var uri))
{
Log.Warning("session", "Saved token cannot be used; sign in again");
State = ConnectionState.SignedOut;
return;
}
UseClient(CreateClient(uri));
_client!.Token = token;
State = ConnectionState.SigningIn;
_ = RefreshAsync();
}
public async Task<(SignInResult Result, string? Fingerprint)> SignInAsync(string address, string username, string password, CancellationToken ct)
{
if (!ServerAddress.TryParse(address, out var uri)) return (SignInResult.InvalidAddress, null);
StopProbing();
var previous = State;
State = ConnectionState.SigningIn;
var client = CreateClient(uri);
try
{
await client.GetInfoAsync(ct);
var login = await client.LoginAsync(username, password, ct);
if (login.Token is null) throw new ChronosApiException(HttpStatusCode.Unauthorized, new ApiError("no_token", "No token issued"));
_settings.ServerUrl = uri.ToString();
_settings.Username = login.User.Username;
_settings.ProtectedToken = TokenProtector.Protect(login.Token);
_saveSettings();
UseClient(client);
OnPropertyChanged(nameof(Address));
Username = login.User.Username;
SetQuota(login.User);
State = ConnectionState.Connected;
Log.Info("session", $"Signed in to {uri} as {login.User.Username}");
return (SignInResult.Success, null);
}
catch (Exception ex)
{
client.Dispose();
State = previous == ConnectionState.SigningIn ? ConnectionState.NotConfigured : previous;
var result = Classify(ex, ct);
if (result == SignInResult.Failed) Log.Warning("session", $"Sign-in to {uri} failed", ex);
return (result, (ex as UntrustedCertificateException)?.Fingerprint);
}
}
public void Trust(string fingerprint)
{
if (_settings.TrustedFingerprints.Contains(fingerprint, StringComparer.OrdinalIgnoreCase)) return;
_settings.TrustedFingerprints.Add(fingerprint);
_saveSettings();
Log.Info("session", $"Trusted certificate {fingerprint}");
}
public async Task SignOutAsync()
{
StopProbing();
if (_client is { Token: not null } client)
{
try
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await client.LogoutAsync(timeout.Token);
}
catch (Exception ex) when (ex is HttpRequestException or ChronosApiException or OperationCanceledException or UntrustedCertificateException)
{
// The token is forgotten locally either way.
Log.Info("session", "Logout not confirmed by the server: " + ex.Message);
}
}
ForgetToken();
}
public async Task RefreshAsync()
{
if (_client is not { } client) return;
try
{
var me = await client.MeAsync();
Username = me.Username;
SetQuota(me);
State = ConnectionState.Connected;
StopProbing();
}
catch (Exception ex) when (IsServerProblem(ex, CancellationToken.None, out var problem))
{
OnServerProblem(problem, ex);
}
catch (ChronosApiException ex)
{
Log.Warning("session", "Account refresh failed", ex);
}
}
public async Task<IReadOnlyList<SequenceDto>> ListSequencesAsync(CancellationToken ct)
{
if (!IsReady) return [];
var all = new List<SequenceDto>();
string? cursor = null;
try
{
// Five pages of 200 cover any realistic choice list.
for (var page = 0; page < 5; page++)
{
var result = await _client!.ListSequencesAsync(cursor: cursor, ct: ct);
all.AddRange(result.Items);
cursor = result.NextCursor;
if (cursor is null) break;
}
}
catch (Exception ex) when (IsServerProblem(ex, ct, out var problem))
{
OnServerProblem(problem, ex);
}
catch (ChronosApiException ex)
{
Log.Warning("session", "Sequence list unavailable", ex);
}
return all;
}
// ---------------- IUploadTransport ----------------
public async Task<(UploadOutcome Outcome, Guid? FrameId)> UploadAsync(UploadItem item, Guid? sequenceId, string sha256, IProgress<UploadProgress> progress, CancellationToken ct)
{
var client = _client ?? throw new ServerUnavailableException(ServerProblem.SignedOut);
try
{
var result = await client.UploadFileAsync(item.Path, sequenceId, item.CapturedAt, item.SessionKey, sha256, progress, ct);
// The client reports an existing file as index −1 (or no frame at all).
return result is null || result.Index < 0 ? (UploadOutcome.AlreadyOnServer, result?.FrameId) : (UploadOutcome.Verified, result.FrameId);
}
catch (Exception ex) when (IsServerProblem(ex, ct, out var problem))
{
OnServerProblem(problem, ex);
throw new ServerUnavailableException(problem, ex);
}
}
public async Task<Guid> CreateSequenceAsync(string? title, CancellationToken ct)
{
var client = _client ?? throw new ServerUnavailableException(ServerProblem.SignedOut);
try
{
var created = await client.CreateSequenceAsync(new CreateSequenceRequest(string.IsNullOrWhiteSpace(title) ? null : title.Trim(), null), ct);
Log.Info("session", $"Created sequence {created.Id} \"{created.DisplayTitle}\"");
return created.Id;
}
catch (Exception ex) when (IsServerProblem(ex, ct, out var problem))
{
OnServerProblem(problem, ex);
throw new ServerUnavailableException(problem, ex);
}
}
public void Dispose()
{
StopProbing();
_client?.Dispose();
}
// ---------------- Plumbing ----------------
private ChronosClient CreateClient(Uri uri)
{
// A fresh pinning per client: the protocol's last-rejected fingerprint must not outlive a trust decision.
var client = new ChronosClient(uri, new CertificatePinning(_settings.TrustedFingerprints), $"Chronos Uploader ({Environment.MachineName})");
client.Bandwidth.BytesPerSecond = _bandwidthLimit * 1_000_000L;
return client;
}
private void UseClient(ChronosClient client)
{
if (ReferenceEquals(_client, client)) return;
_client?.Dispose();
_client = client;
}
private void ApplyBandwidth()
{
if (_client is not null) _client.Bandwidth.BytesPerSecond = _bandwidthLimit * 1_000_000L;
}
private void SetQuota(UserDto user)
{
QuotaBytes = user.QuotaBytes;
UsedBytes = user.UsedBytes;
}
private void ForgetToken()
{
if (_client is not null) _client.Token = null;
_settings.ProtectedToken = null;
_saveSettings();
QuotaBytes = 0;
UsedBytes = 0;
State = _settings.ServerUrl is null ? ConnectionState.NotConfigured : ConnectionState.SignedOut;
}
private bool IsServerProblem(Exception ex, CancellationToken ct, out ServerProblem problem)
{
problem = ServerProblem.Unreachable;
switch (ex)
{
case ChronosApiException { Status: HttpStatusCode.Unauthorized }:
problem = ServerProblem.SignedOut;
return true;
case ChronosApiException api:
return api.IsTransient;
case UntrustedCertificateException untrusted:
// The pinning remembers its last rejection; once trusted, a later network error can still carry it.
if (!_settings.TrustedFingerprints.Contains(untrusted.Fingerprint, StringComparer.OrdinalIgnoreCase))
problem = ServerProblem.CertificateChanged;
return true;
case HttpRequestException:
return true;
case OperationCanceledException when !ct.IsCancellationRequested:
return true; // request timeout
default:
return false;
}
}
private void OnServerProblem(ServerProblem problem, Exception ex)
{
switch (problem)
{
case ServerProblem.SignedOut:
Log.Warning("session", "The server rejected the token; signing out");
StopProbing();
ForgetToken();
SessionEnded?.Invoke(this, problem);
break;
case ServerProblem.CertificateChanged:
// Never upload to a server whose certificate changed: the user must sign in and confirm it again.
Log.Warning("session", "The server certificate changed; sign in again to review it", ex);
StopProbing();
ForgetToken();
SessionEnded?.Invoke(this, problem);
break;
default:
if (State != ConnectionState.Offline) Log.Warning("session", "Server unreachable; retrying every 30 s", ex);
State = ConnectionState.Offline;
StartProbing();
break;
}
}
private void StartProbing()
{
if (_probe is not null) return;
_probe = new CancellationTokenSource();
_ = ProbeAsync(_probe.Token);
}
private void StopProbing()
{
_probe?.Cancel();
_probe?.Dispose();
_probe = null;
}
private async Task ProbeAsync(CancellationToken ct)
{
try
{
while (!ct.IsCancellationRequested && State == ConnectionState.Offline)
{
await Task.Delay(ProbeInterval, ct);
await RefreshAsync();
}
}
catch (OperationCanceledException)
{
}
}
private static SignInResult Classify(Exception ex, CancellationToken ct) => ex switch
{
UntrustedCertificateException => SignInResult.Untrusted,
ChronosApiException { Status: HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden } => SignInResult.BadCredentials,
ChronosApiException { Status: HttpStatusCode.NotFound } => SignInResult.NotChronos,
ChronosApiException api when api.IsTransient => SignInResult.Unreachable,
JsonException or NotSupportedException => SignInResult.NotChronos,
HttpRequestException => SignInResult.Unreachable,
OperationCanceledException when !ct.IsCancellationRequested => SignInResult.Unreachable,
_ => SignInResult.Failed,
};
private bool Set<T>(ref T field, T value, [CallerMemberName] string? name = null)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
OnPropertyChanged(name);
return true;
}
private void OnPropertyChanged([CallerMemberName] string? name = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
@@ -0,0 +1,24 @@
<ui:ChronosWindow x:Class="Chronos.Uploader.Shell.ConfirmDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="clr-namespace:Chronos.Ui.Controls;assembly=Chronos.Ui"
xmlns:l="clr-namespace:Chronos.Ui.Localization;assembly=Chronos.Ui"
Title="{l:Loc Uploader.App.Title}" AutomationProperties.Name="{Binding Heading}" AutomationProperties.HelpText="{Binding Message}"
IsDialog="True" ResizeMode="NoResize" SizeToContent="Height" Width="440"
WindowStartupLocation="CenterOwner" ShowInTaskbar="False">
<!-- DESIGN §4 dialog: two buttons, safe action left and default, the action on the right. -->
<StackPanel Margin="24,18,24,20">
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextWrapping="Wrap" TextTrimming="None" />
<TextBlock Text="{Binding Message}" Margin="0,8,0,0" Foreground="{DynamicResource Brush.TextMuted}" TextWrapping="Wrap" />
<!-- Address and fingerprint read left to right in every language. -->
<Border Style="{StaticResource Border.Card}" Margin="0,16,0,0" Padding="12,10" ToolTip="{Binding DetailToolTip}"
Visibility="{Binding Detail, Converter={x:Static ui:NullToCollapsedConverter.Instance}}">
<TextBlock Text="{Binding Detail}" FontFamily="{StaticResource Font.Mono}" FontSize="{StaticResource Size.Secondary}" TextWrapping="Wrap" LineHeight="18"
FlowDirection="LeftToRight" />
</Border>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,24,0,0">
<Button x:Name="Safe" Content="{Binding SafeText}" ToolTip="{Binding SafeToolTip}" IsDefault="True" IsCancel="True" MinWidth="96" Click="OnSafe" />
<Button x:Name="Action" Content="{Binding ActionText}" ToolTip="{Binding ActionToolTip}" MinWidth="96" Margin="8,0,0,0" Click="OnAction" />
</StackPanel>
</StackPanel>
</ui:ChronosWindow>
@@ -0,0 +1,49 @@
using System.Windows;
using Chronos.Ui.Controls;
namespace Chronos.Uploader.Shell;
/// <summary>Texts of a <see cref="ConfirmDialog"/>.</summary>
public sealed record ConfirmRequest
{
public required string Heading { get; init; }
public required string Message { get; init; }
/// <summary>Monospaced detail (certificate fingerprint); null hides it.</summary>
public string? Detail { get; init; }
public string? DetailToolTip { get; init; }
public required string SafeText { get; init; }
public required string SafeToolTip { get; init; }
public required string ActionText { get; init; }
public required string ActionToolTip { get; init; }
/// <summary>Warning-outlined action (never a primary) for data-destroying choices.</summary>
public bool IsDestructive { get; init; }
}
/// <summary>Modal confirmation used for trusting a certificate and for destructive options (BRIEF §12.1).</summary>
public sealed partial class ConfirmDialog : ChronosWindow
{
private ConfirmDialog(ConfirmRequest request)
{
DataContext = request;
InitializeComponent();
Action.SetResourceReference(StyleProperty, request.IsDestructive ? "Button.Destructive" : "Button.Primary");
// The keyboard starts on the safe default, as in Windows dialogs.
Loaded += (_, _) => Safe.Focus();
}
/// <summary>True when the user chose the action.</summary>
public static bool Ask(Window? owner, ConfirmRequest request)
{
var dialog = new ConfirmDialog(request);
if (owner is { IsVisible: true }) dialog.Owner = owner;
else dialog.WindowStartupLocation = WindowStartupLocation.CenterScreen;
return dialog.ShowDialog() == true;
}
private void OnSafe(object sender, RoutedEventArgs e) => DialogResult = false;
private void OnAction(object sender, RoutedEventArgs e) => DialogResult = true;
}
@@ -0,0 +1,189 @@
using System.Collections;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Input;
using Chronos.Core.Localization;
using Chronos.Ui.Mvvm;
using Chronos.Uploader.Server;
namespace Chronos.Uploader.Shell;
/// <summary>
/// First-run and signed-out form: server address (with servers found on the LAN), user, password. A self-signed
/// certificate is shown to the user once (trust on first use) before the password is sent. A wrong address or
/// password marks that field (DESIGN §4: error border, message in the tooltip); other failures show one sentence
/// with Retry where trying again can help.
/// </summary>
public sealed class ConnectViewModel : ObservableObject, INotifyDataErrorInfo
{
private readonly IServerSession _session;
private readonly IUploaderDialogs _dialogs;
private string _address;
private string _username;
private string _password = string.Empty;
private string? _addressError;
private string? _passwordError;
private string? _errorText;
private bool _canRetry;
private bool _isSigningIn;
public ConnectViewModel(IServerSession session, IUploaderDialogs dialogs, string? address, string? username)
{
_session = session;
_dialogs = dialogs;
_address = Display(address);
_username = username ?? string.Empty;
SignInCommand = new AsyncRelayCommand(SignInAsync);
UseServerCommand = new RelayCommand(p =>
{
if (p is DiscoveredServer s) Address = s.Address;
});
}
public event EventHandler<DataErrorsChangedEventArgs>? ErrorsChanged;
/// <summary>Servers that announced themselves on this network.</summary>
public ObservableCollection<DiscoveredServer> Discovered { get; } = [];
public ICommand SignInCommand { get; }
public ICommand UseServerCommand { get; }
public string Address
{
get => _address;
set
{
if (Set(ref _address, value)) AddressError = null;
}
}
public string Username
{
get => _username;
set => Set(ref _username, value);
}
/// <summary>Set from the view's PasswordBox; never stored.</summary>
public string Password
{
private get => _password;
set
{
if (_password == value) return;
_password = value;
PasswordError = null;
}
}
/// <summary>Why the address was refused (invalid, or not a Chronos Server); null when it is not in question.</summary>
public string? AddressError
{
get => _addressError;
private set
{
if (!Set(ref _addressError, value)) return;
OnPropertyChanged(nameof(AddressToolTip));
ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(nameof(Address)));
}
}
/// <summary>Wrong user name or password; null otherwise. The password box has no binding, so the view reads this.</summary>
public string? PasswordError
{
get => _passwordError;
private set
{
if (Set(ref _passwordError, value)) OnPropertyChanged(nameof(PasswordToolTip));
}
}
public string AddressToolTip => AddressError ?? Loc.L("Tooltips.Uploader.ServerAddress");
public string PasswordToolTip => PasswordError ?? Loc.L("Tooltips.Uploader.Password");
/// <summary>One sentence for failures that are not about a field; null otherwise.</summary>
public string? ErrorText
{
get => _errorText;
private set => Set(ref _errorText, value);
}
/// <summary>True when trying the same request again can help (no answer, server error).</summary>
public bool CanRetry
{
get => _canRetry;
private set => Set(ref _canRetry, value);
}
/// <summary>True while a sign-in started from this form runs; the form stays on screen until it has an outcome.</summary>
public bool IsSigningIn
{
get => _isSigningIn;
private set => Set(ref _isSigningIn, value);
}
public bool HasErrors => AddressError is not null;
public IEnumerable GetErrors(string? propertyName) =>
propertyName == nameof(Address) && AddressError is { } error ? new[] { error } : Array.Empty<string>();
/// <summary>Shows the server address without the trailing slash of the stored base URL.</summary>
public static string Display(string? address) => address?.TrimEnd('/') ?? string.Empty;
public void AddDiscovered(DiscoveredServer server)
{
if (Discovered.Any(d => d.Address == server.Address)) return;
Discovered.Add(server);
if (Address.Length == 0 && Discovered.Count == 1) Address = server.Address;
}
private async Task SignInAsync()
{
if (_session.State is not (ConnectionState.NotConfigured or ConnectionState.SignedOut)) return;
ShowResult(null);
IsSigningIn = true;
try
{
var result = await SignInOrTrustAsync();
ShowResult(result);
if (result != SignInResult.Success) return;
Address = Display(_session.Address);
Password = string.Empty;
}
finally
{
IsSigningIn = false;
}
}
/// <summary>Signs in; an unknown self-signed certificate is shown to the user first and, once trusted, the sign-in is repeated.</summary>
private async Task<SignInResult> SignInOrTrustAsync()
{
var (result, fingerprint) = await _session.SignInAsync(Address, Username.Trim(), Password, CancellationToken.None);
if (result != SignInResult.Untrusted || fingerprint is null) return result;
if (!_dialogs.ConfirmTrust(Display(Address), fingerprint)) return SignInResult.Untrusted;
_session.Trust(fingerprint);
(result, _) = await _session.SignInAsync(Address, Username.Trim(), Password, CancellationToken.None);
return result;
}
/// <summary>Puts each failure where it belongs: on the field it is about, or in the sentence under the form.</summary>
private void ShowResult(SignInResult? result)
{
AddressError = result switch
{
SignInResult.InvalidAddress => Loc.L("Uploader.Connect.Error.InvalidAddress"),
SignInResult.NotChronos => Loc.L("Uploader.Connect.Error.NotChronos"),
_ => null,
};
PasswordError = result == SignInResult.BadCredentials ? Loc.L("Uploader.Connect.Error.BadCredentials") : null;
CanRetry = result is SignInResult.Unreachable or SignInResult.Failed;
ErrorText = result switch
{
SignInResult.Unreachable => Loc.L("Uploader.Connect.Error.Unreachable"),
SignInResult.Untrusted => Loc.L("Uploader.Connect.Error.Untrusted"),
SignInResult.Failed => Loc.L("Uploader.Connect.Error.Failed"),
_ => null,
};
}
}
+108
View File
@@ -0,0 +1,108 @@
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using Chronos.Core.Localization;
using Chronos.Ui.Controls;
using Chronos.Uploader.Text;
using Chronos.Uploader.Uploads;
namespace Chronos.Uploader.Shell;
/// <summary><see cref="UploadItemState"/> → status glyph kind (DESIGN §4: colour always paired with a glyph and a word).</summary>
public sealed class UploadStateKindConverter : IValueConverter
{
public static UploadStateKindConverter Instance { get; } = new();
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) => value switch
{
UploadItemState.Hashing => StatusKind.Analysing,
UploadItemState.Uploading => StatusKind.Running,
UploadItemState.Verified => StatusKind.Done,
UploadItemState.Skipped => StatusKind.Synced,
UploadItemState.Failed => StatusKind.Failed,
_ => StatusKind.Queued,
};
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) => throw new NotSupportedException();
}
/// <summary><see cref="UploadItemState"/> → its localized word.</summary>
public sealed class UploadStateTextConverter : IValueConverter
{
public static UploadStateTextConverter Instance { get; } = new();
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) => value is UploadItemState state ? Text(state) : string.Empty;
public static string Text(UploadItemState state) => state switch
{
UploadItemState.Hashing => Loc.L("Uploader.State.Hashing"),
UploadItemState.Uploading => Loc.L("Uploader.State.Uploading"),
UploadItemState.Verified => Loc.L("Uploader.State.Verified"),
UploadItemState.Skipped => Loc.L("Uploader.State.Skipped"),
UploadItemState.Failed => Loc.L("Uploader.State.Failed"),
_ => Loc.L("Uploader.State.Queued"),
};
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) => throw new NotSupportedException();
}
/// <summary>(<see cref="UploadFailure"/>, detail) → one sentence for the tooltip of a failed item; null otherwise.</summary>
public sealed class FailureTextConverter : IMultiValueConverter
{
public static FailureTextConverter Instance { get; } = new();
public object? Convert(object?[] values, Type targetType, object? parameter, CultureInfo culture) =>
values is [UploadFailure failure, var detail, ..] ? Describe(failure, detail as string) : null;
public object[] ConvertBack(object? value, Type[] targetTypes, object? parameter, CultureInfo culture) => throw new NotSupportedException();
public static string? Describe(UploadFailure failure, string? detail) => failure switch
{
UploadFailure.FileMissing => Loc.L("Uploader.Failure.FileMissing"),
UploadFailure.FileUnreadable => Loc.L("Uploader.Failure.FileUnreadable"),
UploadFailure.FileChanged => Loc.L("Uploader.Failure.FileChanged"),
UploadFailure.ServerRejected => Loc.L("Uploader.Failure.ServerRejected", detail ?? string.Empty),
UploadFailure.Unexpected => Loc.L("Uploader.Failure.Unexpected"),
_ => null,
};
}
/// <summary>
/// (file name, state, failure, detail) → a queue row's accessible name, "IMG_0413.CR2 · Failed · The file could not be
/// read.", so a screen reader announces each row instead of its type name.
/// </summary>
public sealed class QueueRowNameConverter : IMultiValueConverter
{
public static QueueRowNameConverter Instance { get; } = new();
public object Convert(object?[] values, Type targetType, object? parameter, CultureInfo culture)
{
if (values is not [string file, UploadItemState state, UploadFailure failure, var detail, ..]) return string.Empty;
var name = file + Loc.Separator + UploadStateTextConverter.Text(state);
return state == UploadItemState.Failed && FailureTextConverter.Describe(failure, detail as string) is { } reason ? name + Loc.Separator + reason : name;
}
public object[] ConvertBack(object? value, Type[] targetTypes, object? parameter, CultureInfo culture) => throw new NotSupportedException();
}
/// <summary>Visible only for <see cref="UploadItemState.Failed"/>; hidden (keeping its space) otherwise so rows stay aligned.</summary>
public sealed class FailedToVisibleConverter : IValueConverter
{
public static FailedToVisibleConverter Instance { get; } = new();
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
value is UploadItemState.Failed ? Visibility.Visible : Visibility.Hidden;
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) => throw new NotSupportedException();
}
/// <summary>Byte count → "25.4 MB".</summary>
public sealed class SizeConverter : IValueConverter
{
public static SizeConverter Instance { get; } = new();
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
value is long bytes ? UploaderText.Bytes(bytes, Loc.Culture) : string.Empty;
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) => throw new NotSupportedException();
}
@@ -0,0 +1,20 @@
namespace Chronos.Uploader.Shell;
/// <summary>Pickers and confirmations the view model asks for.</summary>
public interface IUploaderDialogs
{
/// <summary>Photos to add; empty when cancelled.</summary>
IReadOnlyList<string> PickFiles();
/// <summary>A folder or card root to add; null when cancelled.</summary>
string? PickFolder();
/// <summary>A folder to watch; null when cancelled.</summary>
string? PickWatchFolder();
/// <summary>Trust-on-first-use: shows the certificate fingerprint; true when the user trusts it.</summary>
bool ConfirmTrust(string address, string fingerprint);
/// <summary>Destructive confirmation for "Delete after upload"; true when the user turns it on.</summary>
bool ConfirmDeleteAfterUpload();
}
+603
View File
@@ -0,0 +1,603 @@
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Windows.Input;
using System.Windows.Threading;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Ui.Controls;
using Chronos.Ui.Mvvm;
using Chronos.Uploader.Infrastructure;
using Chronos.Uploader.Server;
using Chronos.Uploader.Sources;
using Chronos.Uploader.Text;
using Chronos.Uploader.Uploads;
using Chronos.Uploader.Watching;
namespace Chronos.Uploader.Shell;
/// <summary>A sequence offered as upload target.</summary>
public sealed record SequenceOption(Guid Id, string Title);
/// <summary>Everything the window works with; the capture mode passes design-time implementations.</summary>
public sealed record UploaderServices(
UploaderSettings Settings,
Action SaveSettings,
IServerSession Session,
UploadQueue Queue,
IUploadEngine Engine,
IStartupRegistration Startup,
IUploaderDialogs Dialogs,
WatchFolderService Watch,
ProcessedFileMemory Memory,
string LogDirectory);
/// <summary>State of the uploader window (BRIEF §15, mockup Uploader.html).</summary>
public sealed class MainViewModel : LocalizedViewModel
{
private readonly UploaderServices _s;
private readonly DispatcherTimer _refresh;
private UploadTargetMode _target;
private SequenceOption? _selectedSequence;
private bool _loadingSequences;
private string _newTitle;
private bool _isSettingsOpen;
private bool _startWithWindows;
private string _queueText = string.Empty;
private string _progressText = string.Empty;
private string? _failedText;
private string? _currentFileText;
private double _progress;
private UploadItem? _currentItem;
private QueueActivity _activity;
public MainViewModel(UploaderServices services)
{
_s = services;
_target = services.Settings.Target;
_newTitle = services.Settings.NewSequenceTitle ?? string.Empty;
_startWithWindows = services.Startup.IsEnabled;
Connect = new ConnectViewModel(services.Session, services.Dialogs, services.Settings.ServerUrl, services.Settings.Username);
Connect.PropertyChanged += (_, e) =>
{
if (e.PropertyName == nameof(ConnectViewModel.IsSigningIn)) OnPropertyChanged(nameof(IsConnectVisible));
};
foreach (var w in services.Settings.WatchFolders) WatchFolders.Add(NewWatchFolder(w.Path, w.IntervalSeconds));
OpenSettingsCommand = new RelayCommand(() => IsSettingsOpen = true);
CloseSettingsCommand = new RelayCommand(() => IsSettingsOpen = false);
SignOutCommand = new AsyncRelayCommand(SignOutAsync);
BrowseFilesCommand = new AsyncRelayCommand(() => EnqueueAsync(_s.Dialogs.PickFiles()));
BrowseFolderCommand = new AsyncRelayCommand(() => _s.Dialogs.PickFolder() is { } folder ? EnqueueAsync([folder]) : Task.CompletedTask);
RefreshSequencesCommand = new AsyncRelayCommand(LoadSequencesAsync);
PauseCommand = new RelayCommand(TogglePause, () => HasItems);
StopCommand = new RelayCommand(() => _s.Engine.StopAndClear(), () => HasItems);
RetryItemCommand = new RelayCommand(p =>
{
if (p is UploadItem item) _s.Engine.Retry(item);
});
AddWatchFolderCommand = new RelayCommand(AddWatchFolder);
ToggleDeleteAfterUploadCommand = new RelayCommand(ToggleDeleteAfterUpload);
_s.Session.PropertyChanged += OnSessionChanged;
_s.Session.SessionEnded += OnSessionEnded;
_s.Engine.PropertyChanged += (_, _) => RefreshQueue();
_s.Engine.Drained += OnDrained;
_s.Queue.Items.CollectionChanged += (_, _) =>
{
OnPropertyChanged(nameof(HasItems));
OnPropertyChanged(nameof(PauseToolTip));
OnPropertyChanged(nameof(StopToolTip));
CommandManager.InvalidateRequerySuggested();
};
_refresh = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromMilliseconds(500) };
_refresh.Tick += (_, _) => RefreshQueue();
RefreshQueue();
}
/// <summary>Raised when the queue finished while work was done, with the number of files the server confirmed.</summary>
public event Action<int>? UploadsCompleted;
/// <summary>Raised by the "Sign in" action of a session-ended toast; the view focuses the password box.</summary>
public event EventHandler? SignInRequested;
public ConnectViewModel Connect { get; }
/// <summary>In-window notifications; the window forwards them to its <see cref="ToastHost"/>.</summary>
public ObservableCollection<Toast> PendingToasts { get; } = [];
public ICommand OpenSettingsCommand { get; }
public ICommand CloseSettingsCommand { get; }
public ICommand SignOutCommand { get; }
public ICommand BrowseFilesCommand { get; }
public ICommand BrowseFolderCommand { get; }
public ICommand RefreshSequencesCommand { get; }
public ICommand PauseCommand { get; }
public ICommand StopCommand { get; }
public ICommand RetryItemCommand { get; }
public ICommand AddWatchFolderCommand { get; }
public ICommand ToggleDeleteAfterUploadCommand { get; }
// ---------------- Header ----------------
public string ServerText => _s.Session.State == ConnectionState.NotConfigured
? Loc.L("Uploader.Header.NotConnected")
: ConnectViewModel.Display(_s.Session.Address);
public string? UserText => _s.Session.State is ConnectionState.Connected or ConnectionState.Offline or ConnectionState.SigningIn ? _s.Session.Username : null;
public StatusKind ConnectionKind => _s.Session.State switch
{
ConnectionState.Connected => StatusKind.Online,
ConnectionState.SigningIn => StatusKind.Running,
_ => StatusKind.Offline,
};
/// <summary>Null on first run, when the server line already says "Not connected".</summary>
public string? ConnectionText => _s.Session.State switch
{
ConnectionState.Connected => Loc.L("Uploader.Status.Connected"),
ConnectionState.SigningIn => Loc.L("Uploader.Status.SigningIn"),
ConnectionState.Offline => Loc.L("Uploader.Status.Offline"),
ConnectionState.SignedOut => Loc.L("Uploader.Status.SignedOut"),
_ => null,
};
/// <summary>"1.9 TB free of 5 TB"; null without a quota.</summary>
public string? QuotaText => _s.Session.State == ConnectionState.Connected && _s.Session.QuotaBytes > 0
? Loc.L("Uploader.Header.Quota", UploaderText.Bytes(Math.Max(0, _s.Session.QuotaBytes - _s.Session.UsedBytes), Loc.Culture), UploaderText.Bytes(_s.Session.QuotaBytes, Loc.Culture))
: null;
/// <summary>The sign-in form replaces the queue on first run and after signing out, and stays while its own sign-in runs.</summary>
public bool IsConnectVisible => Connect.IsSigningIn || _s.Session.State is ConnectionState.NotConfigured or ConnectionState.SignedOut;
public bool IsSettingsOpen
{
get => _isSettingsOpen;
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 ----------------
public bool IsSessionsTarget
{
get => _target == UploadTargetMode.Sessions;
set => SetTarget(value, UploadTargetMode.Sessions);
}
public bool IsSequenceTarget
{
get => _target == UploadTargetMode.Sequence;
set => SetTarget(value, UploadTargetMode.Sequence);
}
public bool IsNewTarget
{
get => _target == UploadTargetMode.NewSequence;
set => SetTarget(value, UploadTargetMode.NewSequence);
}
public ObservableCollection<SequenceOption> Sequences { get; } = [];
/// <summary>The sequence list is disabled unless "Sequence" is chosen; its tooltip then says so (DESIGN §4).</summary>
public string SequenceToolTip => Loc.L(IsSequenceTarget ? "Tooltips.Uploader.ChooseSequence" : "Tooltips.Uploader.SequenceDisabled");
public SequenceOption? SelectedSequence
{
get => _selectedSequence;
set
{
if (_loadingSequences || !Set(ref _selectedSequence, value)) return;
_s.Settings.TargetSequenceId = value?.Id;
_s.SaveSettings();
}
}
public string NewTitle
{
get => _newTitle;
set
{
if (!Set(ref _newTitle, value)) return;
_s.Settings.NewSequenceTitle = value;
_s.SaveSettings();
}
}
// ---------------- Queue ----------------
public ObservableCollection<UploadItem> Items => _s.Queue.Items;
public bool HasItems => _s.Queue.Items.Count > 0;
/// <summary>"4,812 files · 96.2 GB · 38 MB/s · 41 min left".</summary>
public string QueueText
{
get => _queueText;
private set => Set(ref _queueText, value);
}
/// <summary>"2,214 of 4,812 sent · 2,201 verified by the server · 0 retries".</summary>
public string ProgressText
{
get => _progressText;
private set => Set(ref _progressText, value);
}
/// <summary>"3 failed", a link to the first failed file; null when nothing failed.</summary>
public string? FailedText
{
get => _failedText;
private set => Set(ref _failedText, value);
}
/// <summary>What the queue is doing; changes only when the activity does, so the view can announce it.</summary>
public QueueActivity Activity
{
get => _activity;
private set => Set(ref _activity, value);
}
public string? CurrentFileText
{
get => _currentFileText;
private set => Set(ref _currentFileText, value);
}
public double Progress
{
get => _progress;
private set => Set(ref _progress, value);
}
/// <summary>The item being uploaded; the list keeps it in view.</summary>
public UploadItem? CurrentItem
{
get => _currentItem;
private set => Set(ref _currentItem, value);
}
public bool IsPaused => _s.Queue.IsPaused;
/// <summary>Pause and Stop are disabled while nothing is queued; their tooltips then say so (DESIGN §4).</summary>
public string PauseToolTip => Loc.L(!HasItems ? "Tooltips.Uploader.QueueEmpty" : IsPaused ? "Tooltips.Uploader.Resume" : "Tooltips.Uploader.Pause");
public string StopToolTip => Loc.L(HasItems ? "Tooltips.Uploader.Stop" : "Tooltips.Uploader.QueueEmpty");
/// <summary>Accessible name of the pause/resume button (also the tray menu entry).</summary>
public string PauseLabel => Loc.L(IsPaused ? "Uploader.Action.Resume" : "Uploader.Action.Pause");
/// <summary>Upload limit in MB/s as typed; 0 = unlimited. Text that is not a whole number reverts.</summary>
public string BandwidthLimitText
{
get => _s.Session.BandwidthLimit.ToString(Loc.Culture);
set
{
if (int.TryParse(value, NumberStyles.Integer, Loc.Culture, out var limit))
{
limit = Math.Clamp(limit, 0, 100_000);
if (limit != _s.Session.BandwidthLimit)
{
_s.Session.BandwidthLimit = limit;
_s.Settings.BandwidthLimit = limit;
_s.SaveSettings();
}
}
OnPropertyChanged();
}
}
/// <summary>Tray hover text.</summary>
public string TrayText => Loc.L("Uploader.App.Title") + (HasItems ? Loc.Separator + QueueText : string.Empty);
// ---------------- Watch folders ----------------
public ObservableCollection<WatchFolderViewModel> WatchFolders { get; } = [];
// ---------------- Options ----------------
/// <summary>Turned on only through <see cref="ToggleDeleteAfterUploadCommand"/>, which asks first.</summary>
public bool DeleteAfterUpload => _s.Settings.DeleteAfterUpload;
public bool StartWithWindows
{
get => _startWithWindows;
set
{
_s.Startup.SetEnabled(value);
// Read back: the registry may refuse the change.
_startWithWindows = _s.Startup.IsEnabled;
OnPropertyChanged();
}
}
public bool MinimizeToTray
{
get => _s.Settings.MinimizeToTray;
set
{
if (_s.Settings.MinimizeToTray == value) return;
_s.Settings.MinimizeToTray = value;
_s.SaveSettings();
OnPropertyChanged();
}
}
// ---------------- Actions ----------------
/// <summary>Starts the periodic refresh and, when signed in, loads the sequence list.</summary>
public void Start()
{
_refresh.Start();
if (_s.Session.State == ConnectionState.Connected) _ = LoadSequencesAsync();
}
/// <summary>Starts watching every configured folder.</summary>
public void StartWatching()
{
foreach (var w in WatchFolders) _s.Watch.Watch(w.Path, TimeSpan.FromSeconds(w.IntervalSeconds));
}
/// <summary>Adds the photos under <paramref name="paths"/> (files, folders, card roots) to the queue.</summary>
public async Task EnqueueAsync(IReadOnlyList<string> paths)
{
if (paths.Count == 0) return;
if (_target == UploadTargetMode.Sequence && SelectedSequence is null)
{
ShowToast(Loc.L("Uploader.Toast.ChooseSequence"), isError: true);
return;
}
var found = await Task.Run(() => PhotoScanner.Scan(paths));
var fresh = found.Where(f => !_s.Queue.ContainsPath(f.Path)).ToList();
if (fresh.Count == 0)
{
ShowToast(Loc.L("Uploader.Toast.NothingFound"));
return;
}
var batch = new UploadBatch
{
Id = Guid.CreateVersion7(),
Mode = _target,
SequenceId = _target == UploadTargetMode.Sequence ? SelectedSequence?.Id : null,
Title = _target == UploadTargetMode.NewSequence ? NewTitle.Trim() : null,
};
var entries = _target == UploadTargetMode.Sessions
? SessionEntries(fresh, null, null, out _)
: [.. fresh.OrderBy(f => f.CapturedAt).Select(f => new QueueEntry(f.Path, f.Size, f.ModifiedUtc, f.CapturedAt, null, null))];
var added = Add(batch, entries);
Log.Info("queue", $"{added} file(s) added from {paths.Count} path(s), target {_target}");
ShowToast(Loc.Plural("Uploader.Toast.Added", added));
}
/// <summary>Queues stable new photos of a watch folder; they join the folder's last session when close in time.</summary>
public void OnWatchFilesReady(string root, IReadOnlyList<SourceFile> files)
{
var fresh = files.Where(f => !_s.Queue.ContainsPath(f.Path)).ToList();
if (fresh.Count == 0) return;
var entries = SessionEntries(fresh, root, _s.Memory.GetSession(root), out var last);
Add(new UploadBatch { Id = Guid.CreateVersion7(), Mode = UploadTargetMode.Sessions }, entries);
_s.Memory.SetSession(root, last);
}
public void OnWatchAvailabilityChanged(string root, bool available)
{
var folder = WatchFolders.FirstOrDefault(w => string.Equals(w.Path, root, StringComparison.OrdinalIgnoreCase));
if (folder is not null) folder.IsAvailable = available;
}
/// <summary>The failed file nearest the top of the queue; null when none failed.</summary>
public UploadItem? FirstFailed() => _s.Queue.Items.FirstOrDefault(i => i.State == UploadItemState.Failed);
/// <summary>Errors are one sentence plus one action (BRIEF §0.2 rule 6).</summary>
public void ReportError(Exception ex)
{
Log.Error("ui", "Operation failed", ex);
ShowToast(Loc.L("Errors.Unexpected"), Loc.L("Common.OpenLogs"), Loc.L("Tooltips.Common.OpenLogs"), new RelayCommand(OpenLogs), isError: true);
}
public void TogglePause()
{
if (_s.Queue.IsPaused) _s.Engine.Resume();
else _s.Engine.Pause();
RefreshQueue();
}
public override void Dispose()
{
_refresh.Stop();
_s.Session.PropertyChanged -= OnSessionChanged;
_s.Session.SessionEnded -= OnSessionEnded;
_s.Engine.Drained -= OnDrained;
base.Dispose();
}
private int Add(UploadBatch batch, IReadOnlyList<QueueEntry> entries)
{
// A new batch after a finished one starts a fresh count.
if (!_s.Queue.HasPending) _s.Queue.RemoveCompleted();
var added = _s.Queue.Add(batch, entries);
_s.Engine.Pump();
RefreshQueue();
return added;
}
/// <summary>Session keys per source folder (BRIEF §13 rules), entries in capture order.</summary>
private static List<QueueEntry> SessionEntries(IReadOnlyList<SourceFile> files, string? watchRoot, SessionContinuation? previous, out SessionContinuation? last)
{
var entries = new List<QueueEntry>(files.Count);
last = previous;
foreach (var group in files.GroupBy(f => watchRoot ?? f.Root, StringComparer.OrdinalIgnoreCase))
{
var ordered = group.OrderBy(f => f.CapturedAt).ToList();
var assignment = SessionGrouper.Assign([.. ordered.Select(f => f.CapturedAt)], SessionGrouper.SourceTag(group.Key), watchRoot is null ? null : previous);
for (var i = 0; i < ordered.Count; i++)
{
var f = ordered[i];
entries.Add(new QueueEntry(f.Path, f.Size, f.ModifiedUtc, f.CapturedAt, assignment.Keys[i], watchRoot));
}
last = assignment.Last;
}
return entries;
}
/// <summary>Recomputes the queue line, progress and current file (also every 500 ms once started).</summary>
public void RefreshQueue()
{
var summary = QueueSummary.From(_s.Queue.Items);
var rate = _s.Engine.BytesPerSecond;
var activity = summary.Files == 0 ? QueueActivity.Idle : _s.Engine.Status switch
{
EngineStatus.Paused => QueueActivity.Paused,
EngineStatus.WaitingForServer => QueueActivity.WaitingForServer,
EngineStatus.Running => QueueActivity.Running,
_ => QueueActivity.Done,
};
QueueText = UploaderText.QueueLine(summary, activity, rate, RateMeter.TimeLeft(summary.RemainingBytes, rate), Loc.Culture);
Activity = activity;
ProgressText = summary.Files == 0 ? string.Empty : UploaderText.ProgressLine(summary, Loc.Culture);
FailedText = UploaderText.Failed(summary, Loc.Culture);
Progress = summary.Progress;
CurrentFileText = summary.CurrentFile;
CurrentItem = _s.Queue.Items.FirstOrDefault(i => i.State == UploadItemState.Uploading) ?? _s.Queue.Items.FirstOrDefault(i => i.IsActive);
OnPropertyChanged(nameof(IsPaused));
OnPropertyChanged(nameof(PauseToolTip));
OnPropertyChanged(nameof(StopToolTip));
OnPropertyChanged(nameof(PauseLabel));
OnPropertyChanged(nameof(TrayText));
}
private void SetTarget(bool selected, UploadTargetMode mode)
{
if (!selected || _target == mode) return;
_target = mode;
_s.Settings.Target = mode;
_s.SaveSettings();
OnPropertyChanged(nameof(IsSessionsTarget));
OnPropertyChanged(nameof(IsSequenceTarget));
OnPropertyChanged(nameof(IsNewTarget));
OnPropertyChanged(nameof(SequenceToolTip));
if (mode == UploadTargetMode.Sequence && Sequences.Count == 0) _ = LoadSequencesAsync();
}
private async Task LoadSequencesAsync()
{
var list = await _s.Session.ListSequencesAsync(CancellationToken.None);
if (list.Count == 0 && Sequences.Count > 0) return;
_loadingSequences = true;
try
{
Sequences.Clear();
foreach (var s in list.OrderBy(s => s.DisplayTitle, StringComparer.CurrentCultureIgnoreCase)) Sequences.Add(new SequenceOption(s.Id, s.DisplayTitle));
}
finally
{
_loadingSequences = false;
}
_selectedSequence = Sequences.FirstOrDefault(s => s.Id == _s.Settings.TargetSequenceId);
OnPropertyChanged(nameof(SelectedSequence));
}
private async Task SignOutAsync()
{
IsSettingsOpen = false;
await _s.Session.SignOutAsync();
}
private void ToggleDeleteAfterUpload()
{
var enable = !_s.Settings.DeleteAfterUpload;
if (enable && !_s.Dialogs.ConfirmDeleteAfterUpload())
{
// The check box toggled itself; put it back.
OnPropertyChanged(nameof(DeleteAfterUpload));
return;
}
_s.Settings.DeleteAfterUpload = enable;
_s.SaveSettings();
Log.Info("settings", "Delete after verified upload " + (enable ? "on" : "off"));
OnPropertyChanged(nameof(DeleteAfterUpload));
}
private void AddWatchFolder()
{
if (_s.Dialogs.PickWatchFolder() is not { } path) return;
if (WatchFolders.Any(w => string.Equals(w.Path, path, StringComparison.OrdinalIgnoreCase))) return;
var interval = (int)WatchFolderService.DefaultInterval(path).TotalSeconds;
_s.Settings.WatchFolders.Add(new UploaderSettings.WatchFolderSettings { Path = path, IntervalSeconds = interval });
_s.SaveSettings();
WatchFolders.Add(NewWatchFolder(path, interval));
_s.Watch.Watch(path, TimeSpan.FromSeconds(interval));
}
private WatchFolderViewModel NewWatchFolder(string path, int intervalSeconds) =>
new(path, intervalSeconds, WatchFolderService.IsNetworkPath(path), SetWatchInterval, RemoveWatchFolder);
private void SetWatchInterval(WatchFolderViewModel folder, int seconds)
{
folder.IntervalSeconds = seconds;
foreach (var w in _s.Settings.WatchFolders.Where(w => string.Equals(w.Path, folder.Path, StringComparison.OrdinalIgnoreCase))) w.IntervalSeconds = seconds;
_s.SaveSettings();
_s.Watch.Watch(folder.Path, TimeSpan.FromSeconds(seconds));
}
private void RemoveWatchFolder(WatchFolderViewModel folder)
{
_s.Watch.Stop(folder.Path);
_s.Memory.RemoveFolder(folder.Path);
_s.Settings.WatchFolders.RemoveAll(w => string.Equals(w.Path, folder.Path, StringComparison.OrdinalIgnoreCase));
_s.SaveSettings();
WatchFolders.Remove(folder);
}
private void OnSessionChanged(object? sender, PropertyChangedEventArgs e)
{
OnPropertyChanged(nameof(ServerText));
OnPropertyChanged(nameof(UserText));
OnPropertyChanged(nameof(ConnectionKind));
OnPropertyChanged(nameof(ConnectionText));
OnPropertyChanged(nameof(QuotaText));
OnPropertyChanged(nameof(IsConnectVisible));
OnPropertyChanged(nameof(BandwidthLimitText));
if (e.PropertyName != nameof(IServerSession.State)) return;
if (_s.Session.State == ConnectionState.Connected) _ = LoadSequencesAsync();
// The form's own sign-in keeps what the user typed; only a session that ended refills it.
if (IsConnectVisible && !Connect.IsSigningIn)
{
Connect.Address = ConnectViewModel.Display(_s.Session.Address);
Connect.Username = _s.Session.Username ?? Connect.Username;
}
CommandManager.InvalidateRequerySuggested();
}
/// <summary>One sentence plus one action (BRIEF §0.2 rule 6): "Sign in" takes the user to the password box.</summary>
private void OnSessionEnded(object? sender, ServerProblem problem) =>
ShowToast(Loc.L(problem == ServerProblem.CertificateChanged ? "Uploader.Toast.CertificateChanged" : "Uploader.Toast.SignedOut"),
Loc.L("Uploader.Connect.SignIn"), Loc.L("Tooltips.Uploader.SignIn"), new RelayCommand(() => SignInRequested?.Invoke(this, EventArgs.Empty)),
isError: true);
private void OnDrained(object? sender, EventArgs e)
{
// The queue restarts its count with each new batch, so every confirmed item belongs to this run.
var confirmed = _s.Queue.Items.Count(i => i.IsDone);
RefreshQueue();
_ = _s.Session.RefreshAsync();
if (confirmed > 0) UploadsCompleted?.Invoke(confirmed);
}
/// <summary>One sentence and at most one action; <paramref name="isError"/> marks a failure or refusal, which screen readers say at once.</summary>
private void ShowToast(string title, string? actionText = null, string? actionToolTip = null, ICommand? action = null, bool isError = false) =>
PendingToasts.Add(new Toast { Title = title, ActionText = actionText, ActionToolTip = actionToolTip, ActionCommand = action, IsError = isError });
private void OpenLogs()
{
if (Directory.Exists(_s.LogDirectory)) Process.Start(new ProcessStartInfo(_s.LogDirectory) { UseShellExecute = true, Verb = "explore" });
}
}
+511
View File
@@ -0,0 +1,511 @@
<ui:ChronosWindow x:Class="Chronos.Uploader.Shell.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="clr-namespace:Chronos.Ui.Controls;assembly=Chronos.Ui"
xmlns:l="clr-namespace:Chronos.Ui.Localization;assembly=Chronos.Ui"
xmlns:s="clr-namespace:Chronos.Uploader.Shell"
xmlns:u="clr-namespace:Chronos.Uploader.Uploads"
Title="{l:Loc Uploader.App.Title}"
Width="760" Height="700" MinWidth="640" MinHeight="630"
WindowStartupLocation="CenterScreen" AllowDrop="True">
<Window.Resources>
<Style x:Key="Text.Label" TargetType="TextBlock" BasedOn="{StaticResource Text.Base}">
<Setter Property="Foreground" Value="{DynamicResource Brush.TextMuted}" />
<Setter Property="MinWidth" Value="92" />
<Setter Property="Margin" Value="0,0,12,0" />
</Style>
<!-- Labels of the settings panel's fixed label column wrap instead of being cut (+40 % text). -->
<Style x:Key="Text.PanelLabel" TargetType="TextBlock" BasedOn="{StaticResource Text.Label}">
<Setter Property="MinWidth" Value="0" />
<Setter Property="TextWrapping" Value="Wrap" />
<Setter Property="TextTrimming" Value="None" />
</Style>
<!-- Watch-folder chip (mockup: 28 px pill, Card fill, status dot). -->
<Style x:Key="Button.Chip" TargetType="Button" BasedOn="{StaticResource Button.Base}">
<Setter Property="Height" Value="28" />
<Setter Property="Padding" Value="10,0" />
<Setter Property="ui:ControlState.CornerRadius" Value="14" />
</Style>
<Style x:Key="Button.Round" TargetType="Button" BasedOn="{StaticResource Button.Icon}">
<Setter Property="Width" Value="28" />
<Setter Property="MinWidth" Value="28" />
<Setter Property="Height" Value="28" />
<Setter Property="ui:ControlState.CornerRadius" Value="14" />
</Style>
<Style x:Key="Button.Square" TargetType="Button" BasedOn="{StaticResource Button.Icon}">
<Setter Property="Width" Value="30" />
<Setter Property="MinWidth" Value="30" />
<Setter Property="Height" Value="30" />
</Style>
<!-- Keyboard focus on a queue row: the accent ring drawn inside the row, so neighbours do not cover it. -->
<Style x:Key="Focus.Row">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<Border BorderBrush="{DynamicResource Brush.Accent}" BorderThickness="2" CornerRadius="{StaticResource Radius.Control}" SnapsToDevicePixels="True" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- Queue rows: hover and keyboard focus, no selection look; named "file · state" for screen readers. -->
<Style x:Key="QueueRow" TargetType="ListBoxItem">
<Setter Property="FocusVisualStyle" Value="{StaticResource Focus.Row}" />
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="AutomationProperties.Name">
<Setter.Value>
<MultiBinding Converter="{x:Static s:QueueRowNameConverter.Instance}">
<Binding Path="FileName" />
<Binding Path="State" />
<Binding Path="Failure" />
<Binding Path="FailureDetail" />
</MultiBinding>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border x:Name="Bd" Background="Transparent" CornerRadius="{StaticResource Radius.Control}" Padding="10,0,4,0">
<ContentPresenter />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="Bd" Property="Background" Value="{DynamicResource Brush.Card}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="WatchMenuItem" TargetType="MenuItem" BasedOn="{StaticResource {x:Type MenuItem}}">
<Setter Property="Header" Value="{Binding Text}" />
<Setter Property="Command" Value="{Binding Command}" />
<Setter Property="IsChecked" Value="{Binding IsChecked, Mode=OneWay}" />
<Setter Property="ToolTip" Value="{Binding ToolTip}" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsSeparator}" Value="True">
<Setter Property="Height" Value="9" />
<Setter Property="IsEnabled" Value="False" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="MenuItem">
<Border Height="1" Margin="4" Background="{DynamicResource Brush.Stroke}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<!-- Header: server · user · connection, quota, settings. -->
<Border Height="40" Background="{DynamicResource Brush.Surface}" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,0,0,1" Padding="16,0">
<DockPanel LastChildFill="True">
<Button x:Name="SettingsButton" DockPanel.Dock="Right" Style="{StaticResource Button.Square}" ui:ButtonIcon.Glyph="{StaticResource Icon.Settings}"
Command="{Binding OpenSettingsCommand}" ToolTip="{l:Loc Tooltips.Uploader.Settings}" AutomationProperties.Name="{l:Loc Uploader.Settings.Title}" />
<TextBlock DockPanel.Dock="Right" Text="{Binding QuotaText}" Style="{StaticResource Text.Secondary}" Margin="12,0,12,0"
ToolTip="{l:Loc Tooltips.Uploader.Quota}" Visibility="{Binding QuotaText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}" />
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
<ui:Icon Glyph="{StaticResource Icon.Server}" Foreground="{DynamicResource Brush.Accent}" Margin="0,0,10,0" VerticalAlignment="Center" />
<!-- An address reads left to right in every language. -->
<TextBlock Text="{Binding ServerText}" Style="{StaticResource Text.Body}" MaxWidth="320" FlowDirection="LeftToRight" />
<StackPanel Orientation="Horizontal" Visibility="{Binding UserText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}">
<TextBlock Text="·" Foreground="{DynamicResource Brush.TextFaint}" Margin="10,0" VerticalAlignment="Center" />
<TextBlock Text="{Binding UserText}" Style="{StaticResource Text.Body}" />
</StackPanel>
<StackPanel Orientation="Horizontal" Visibility="{Binding ConnectionText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}">
<TextBlock Text="·" Foreground="{DynamicResource Brush.TextFaint}" Margin="10,0" VerticalAlignment="Center" />
<ui:StatusGlyph Kind="{Binding ConnectionKind}" Text="{Binding ConnectionText}" FontSize="{StaticResource Size.Body}" VerticalAlignment="Center" />
</StackPanel>
</StackPanel>
</DockPanel>
</Border>
<!-- First run / signed out: connect form. -->
<Grid Grid.Row="1" Visibility="{Binding IsConnectVisible, Converter={StaticResource BoolToVisibility}}">
<StackPanel DataContext="{Binding Connect}" Width="440" HorizontalAlignment="Center" VerticalAlignment="Center">
<ui:BrandMarkIcon Width="48" Height="48" HorizontalAlignment="Center" />
<TextBlock Text="{l:Loc Uploader.Connect.Title}" Style="{StaticResource Text.Title}" HorizontalAlignment="Center" Margin="0,14,0,20" />
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="92" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Text="{l:Loc Uploader.Connect.Server}" Style="{StaticResource Text.Label}" />
<!-- A wrong address shows the Error border; the message is the tooltip (DESIGN §4). -->
<TextBox x:Name="AddressBox" Grid.Column="1" Text="{Binding Address, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
ui:Field.Glyph="{StaticResource Icon.Server}" FlowDirection="LeftToRight"
ui:Field.Placeholder="{l:Loc Uploader.Connect.AddressPlaceholder}" ToolTip="{Binding AddressToolTip}" AutomationProperties.Name="{l:Loc Uploader.Connect.Server}" />
<!-- Top margin 14 = 8 + (28 − 16) / 2: the label sits on the chips' text line. -->
<TextBlock Grid.Row="1" Text="{l:Loc Uploader.Connect.Found}" Style="{StaticResource Text.Label}" Margin="0,14,12,0" VerticalAlignment="Top"
Visibility="{Binding Discovered.Count, Converter={x:Static ui:ZeroToCollapsedConverter.Instance}}" />
<ItemsControl Grid.Row="1" Grid.Column="1" ItemsSource="{Binding Discovered}" Margin="0,8,0,0" Focusable="False"
Visibility="{Binding Discovered.Count, Converter={x:Static ui:ZeroToCollapsedConverter.Instance}}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Style="{StaticResource Button.Chip}" Margin="0,0,8,4" Command="{Binding DataContext.UseServerCommand, RelativeSource={RelativeSource AncestorType=ItemsControl}}"
CommandParameter="{Binding}" ToolTip="{l:Loc Tooltips.Uploader.DiscoveredServer}" AutomationProperties.Name="{Binding Name}">
<StackPanel Orientation="Horizontal">
<Ellipse Width="8" Height="8" Fill="{DynamicResource Brush.Accent}" Margin="0,0,8,0" VerticalAlignment="Center" />
<TextBlock Text="{Binding Name}" VerticalAlignment="Center" />
<TextBlock Text="{Binding Address}" Foreground="{DynamicResource Brush.TextMuted}" Margin="8,0,0,0" VerticalAlignment="Center" FlowDirection="LeftToRight" />
</StackPanel>
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<TextBlock Grid.Row="2" Text="{l:Loc Uploader.Connect.User}" Style="{StaticResource Text.Label}" Margin="0,12,12,0" />
<TextBox x:Name="UserBox" Grid.Row="2" Grid.Column="1" Margin="0,12,0,0" Text="{Binding Username, UpdateSourceTrigger=PropertyChanged}" ui:Field.Glyph="{StaticResource Icon.User}"
ToolTip="{l:Loc Tooltips.Uploader.User}" AutomationProperties.Name="{l:Loc Uploader.Connect.User}" />
<TextBlock Grid.Row="3" Text="{l:Loc Uploader.Connect.Password}" Style="{StaticResource Text.Label}" Margin="0,12,12,0" />
<!-- A wrong password: the kit's error border (DESIGN §4); the message is the tooltip. -->
<PasswordBox x:Name="Password" Grid.Row="3" Grid.Column="1" Margin="0,12,0,0" PasswordChanged="OnPasswordChanged"
ToolTip="{Binding PasswordToolTip}" AutomationProperties.Name="{l:Loc Uploader.Connect.Password}" ui:Field.Error="{Binding PasswordError}" />
<Border Grid.Row="4" Grid.Column="1" Margin="0,12,0,0" Padding="10,6,6,6" CornerRadius="{StaticResource Radius.Control}" Background="{DynamicResource Brush.ErrorSubtle}"
Visibility="{Binding ErrorText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}">
<DockPanel>
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Compact}" Content="{l:Loc Uploader.Action.Retry}" Command="{Binding SignInCommand}"
ToolTip="{l:Loc Tooltips.Uploader.Retry}" Margin="8,0,0,0" Visibility="{Binding CanRetry, Converter={StaticResource BoolToVisibility}}" />
<ui:Icon Glyph="{StaticResource Icon.ErrorCircle}" Foreground="{DynamicResource Brush.Error}" Margin="0,0,8,0" VerticalAlignment="Center" />
<TextBlock x:Name="ErrorMessage" Text="{Binding ErrorText}" TextWrapping="Wrap" VerticalAlignment="Center" AutomationProperties.LiveSetting="Assertive" />
</DockPanel>
</Border>
<!-- Enter signs in while the form is on screen, but not from the settings panel drawn over it. -->
<Button Grid.Row="5" Grid.Column="1" Margin="0,20,0,0" HorizontalAlignment="Left" MinWidth="120"
Content="{l:Loc Uploader.Connect.SignIn}" Command="{Binding SignInCommand}" ToolTip="{l:Loc Tooltips.Uploader.SignIn}">
<Button.Style>
<Style TargetType="Button" BasedOn="{StaticResource Button.Primary}">
<Setter Property="IsDefault" Value="True" />
<Style.Triggers>
<Trigger Property="IsVisible" Value="False">
<Setter Property="IsDefault" Value="False" />
</Trigger>
<DataTrigger Binding="{Binding DataContext.IsSettingsOpen, RelativeSource={RelativeSource AncestorType=Window}}" Value="True">
<Setter Property="IsDefault" Value="False" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
</Grid>
</StackPanel>
</Grid>
<!-- Signed in: drop zone, target, queue, watch folders, options. -->
<Grid Grid.Row="1" Margin="16,14,16,14" Grid.IsSharedSizeScope="True"
Visibility="{Binding IsConnectVisible, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<!-- Drop zone: the empty state's sentence and button. -->
<Grid Height="150" Background="Transparent">
<Rectangle x:Name="DropBorder" RadiusX="8" RadiusY="8" StrokeThickness="2" StrokeDashArray="3 2" SnapsToDevicePixels="True"
Stroke="{DynamicResource Brush.Stroke}" Fill="Transparent" />
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<ui:Icon Glyph="{StaticResource Icon.Upload}" Size="28" Foreground="{DynamicResource Brush.TextMuted}" HorizontalAlignment="Center" />
<TextBlock Text="{l:Loc Uploader.Drop.Message}" FontSize="{StaticResource Size.Section}" Foreground="{DynamicResource Brush.TextMuted}"
HorizontalAlignment="Center" Margin="0,10,0,10" />
<Button x:Name="BrowseButton" Content="{l:Loc Uploader.Browse.Button}" Height="30" Padding="14,0" HorizontalAlignment="Center"
ToolTip="{l:Loc Tooltips.Uploader.Browse}" Click="OnBrowseClick">
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="{l:Loc Uploader.Browse.Files}" Command="{Binding BrowseFilesCommand}" ToolTip="{l:Loc Tooltips.Uploader.BrowseFiles}" />
<MenuItem Header="{l:Loc Uploader.Browse.Folder}" Command="{Binding BrowseFolderCommand}" ToolTip="{l:Loc Tooltips.Uploader.BrowseFolder}" />
</ContextMenu>
</Button.ContextMenu>
</Button>
</StackPanel>
</Grid>
<!-- Target: each choice wraps together with its field; the negative margin keeps one line at 30 px. -->
<Grid Grid.Row="1" Margin="0,12,0,0" MinHeight="30">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="Label" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{l:Loc Uploader.Target.Label}" Style="{StaticResource Text.Label}" />
<WrapPanel Grid.Column="1" VerticalAlignment="Center" Margin="0,-4,0,0">
<RadioButton GroupName="Target" Content="{l:Loc Uploader.Target.Sessions}" IsChecked="{Binding IsSessionsTarget}" Margin="0,4,16,0" VerticalAlignment="Center"
ToolTip="{l:Loc Tooltips.Uploader.TargetSessions}" />
<StackPanel Orientation="Horizontal" Margin="0,4,16,0">
<RadioButton GroupName="Target" Content="{l:Loc Uploader.Target.Sequence}" IsChecked="{Binding IsSequenceTarget}" Margin="0,0,8,0" VerticalAlignment="Center"
ToolTip="{l:Loc Tooltips.Uploader.TargetSequence}" />
<ComboBox Width="170" Height="30" ItemsSource="{Binding Sequences}" SelectedItem="{Binding SelectedSequence}" DisplayMemberPath="Title"
IsEnabled="{Binding IsSequenceTarget}" DropDownOpened="OnSequencesDropDownOpened" ToolTip="{Binding SequenceToolTip}"
AutomationProperties.Name="{l:Loc Uploader.Target.Sequence}" />
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,4,0,0">
<RadioButton GroupName="Target" Content="{l:Loc Uploader.Target.New}" IsChecked="{Binding IsNewTarget}" Margin="0,0,8,0" VerticalAlignment="Center"
ToolTip="{l:Loc Tooltips.Uploader.TargetNew}" />
<TextBox Width="170" Height="30" Text="{Binding NewTitle}" ui:Field.Placeholder="{l:Loc Uploader.Target.TitlePlaceholder}"
Visibility="{Binding IsNewTarget, Converter={StaticResource BoolToVisibility}}" ToolTip="{l:Loc Tooltips.Uploader.NewTitle}"
AutomationProperties.Name="{l:Loc Uploader.Target.TitlePlaceholder}" />
</StackPanel>
</WrapPanel>
</Grid>
<!-- Queue line, pause/stop, bandwidth limit -->
<Grid Grid.Row="2" Margin="0,12,0,0" MinHeight="30">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="Label" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="{l:Loc Uploader.Queue.Label}" Style="{StaticResource Text.Label}" />
<!-- Announced when the activity changes (running, paused, waiting, done), not on every refresh. -->
<TextBlock x:Name="QueueLine" Grid.Column="1" Text="{Binding QueueText}" Style="{StaticResource Text.Body}" Typography.NumeralAlignment="Tabular"
AutomationProperties.LiveSetting="Polite" />
<StackPanel Grid.Column="2" Orientation="Horizontal" Margin="10,0,0,0">
<!-- Media glyphs (pause, play) keep their direction in right-to-left languages. -->
<Button Command="{Binding PauseCommand}" ToolTip="{Binding PauseToolTip}" AutomationProperties.Name="{Binding PauseLabel}" FlowDirection="LeftToRight">
<Button.Style>
<Style TargetType="Button" BasedOn="{StaticResource Button.Square}">
<Setter Property="ui:ButtonIcon.Glyph" Value="{StaticResource Icon.Pause}" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsPaused}" Value="True">
<Setter Property="ui:ButtonIcon.Glyph" Value="{StaticResource Icon.Play}" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
<Button Style="{StaticResource Button.Square}" Margin="10,0,0,0" ui:ButtonIcon.Glyph="{StaticResource Icon.Stop}" Command="{Binding StopCommand}"
ToolTip="{Binding StopToolTip}" AutomationProperties.Name="{l:Loc Uploader.Action.Stop}" />
</StackPanel>
<StackPanel Grid.Column="3" Orientation="Horizontal" Margin="16,0,0,0">
<TextBlock Text="{l:Loc Uploader.Limit.Label}" Style="{StaticResource Text.Base}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,0,6,0" />
<TextBox Width="58" Height="30" Text="{Binding BandwidthLimitText}" TextAlignment="Right" FlowDirection="LeftToRight" ToolTip="{l:Loc Tooltips.Uploader.Limit}"
AutomationProperties.Name="{l:Loc Uploader.Limit.Label}" />
<TextBlock Text="{l:Loc Uploader.Limit.Unit}" Style="{StaticResource Text.Base}" Foreground="{DynamicResource Brush.TextMuted}" Margin="6,0,0,0" />
</StackPanel>
</Grid>
<!-- Progress: bar, current file, counts, failures -->
<StackPanel Grid.Row="3" Margin="0,12,0,0" Visibility="{Binding HasItems, Converter={StaticResource BoolToVisibility}}">
<ProgressBar Height="8" Maximum="1" Value="{Binding Progress, Mode=OneWay}" AutomationProperties.Name="{l:Loc Uploader.Queue.Progress}" />
<Grid Margin="0,5,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding CurrentFileText}" Style="{StaticResource Text.Secondary}" FlowDirection="LeftToRight" HorizontalAlignment="Left" />
<TextBlock Grid.Column="1" Text="{Binding ProgressText}" Style="{StaticResource Text.Secondary}" Margin="12,0,0,0" Typography.NumeralAlignment="Tabular" />
<!-- "✕ 3 failed" (DESIGN §4 status glyph) takes the keyboard to the first failed file. -->
<Button x:Name="FailedLink" Grid.Column="2" Style="{StaticResource Button.Subtle}" Height="18" MinWidth="0" Padding="4,0" Margin="6,0,0,0"
Click="OnShowFailedClick" ToolTip="{l:Loc Tooltips.Uploader.ShowFailed}" AutomationProperties.Name="{Binding FailedText}"
Visibility="{Binding FailedText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}">
<ui:StatusGlyph Kind="Failed" Text="{Binding FailedText}" FontSize="{StaticResource Size.Secondary}" Typography.NumeralAlignment="Tabular" />
</Button>
</Grid>
</StackPanel>
<!-- Watch folders: chips and the add button wrap; a long path is shortened (full path in the tooltip). -->
<Grid Grid.Row="4" Margin="0,12,0,0" MinHeight="30">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="Label" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{l:Loc Uploader.Watch.Label}" Style="{StaticResource Text.Label}" VerticalAlignment="Top" Margin="0,6,12,0" />
<WrapPanel Grid.Column="1">
<ItemsControl ItemsSource="{Binding WatchFolders}" Focusable="False">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type s:WatchFolderViewModel}">
<Button Style="{StaticResource Button.Chip}" Margin="0,0,10,4" Click="OnWatchChipClick" ToolTip="{Binding ToolTip}"
AutomationProperties.Name="{Binding Text}">
<Button.ContextMenu>
<ContextMenu ItemsSource="{Binding MenuOptions}" ItemContainerStyle="{StaticResource WatchMenuItem}" />
</Button.ContextMenu>
<DockPanel>
<Ellipse x:Name="Dot" DockPanel.Dock="Left" Width="8" Height="8" Margin="0,0,8,0" VerticalAlignment="Center" StrokeThickness="1.5"
Fill="{DynamicResource Brush.TextFaint}" />
<TextBlock DockPanel.Dock="Right" Text="{Binding IntervalText}" VerticalAlignment="Center" />
<TextBlock DockPanel.Dock="Right" Text="·" Foreground="{DynamicResource Brush.TextFaint}" Margin="6,0" VerticalAlignment="Center" />
<!-- The button template lays content out without a width limit, so the path carries its own. -->
<TextBlock Text="{Binding Path}" MaxWidth="180" FlowDirection="LeftToRight" HorizontalAlignment="Left" TextTrimming="CharacterEllipsis"
VerticalAlignment="Center" />
</DockPanel>
</Button>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding IsAvailable}" Value="True">
<Setter TargetName="Dot" Property="Fill" Value="{DynamicResource Brush.Success}" />
</DataTrigger>
<!-- Unreachable: hollow ring (shape, not colour alone), reason in the tooltip. -->
<DataTrigger Binding="{Binding IsAvailable}" Value="False">
<Setter TargetName="Dot" Property="Fill" Value="Transparent" />
<Setter TargetName="Dot" Property="Stroke" Value="{DynamicResource Brush.Error}" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Button Style="{StaticResource Button.Round}" Margin="0,0,0,4" ui:ButtonIcon.Glyph="{StaticResource Icon.Plus}" Command="{Binding AddWatchFolderCommand}"
ToolTip="{l:Loc Tooltips.Uploader.AddWatchFolder}" AutomationProperties.Name="{l:Loc Uploader.Action.AddFolder}" />
</WrapPanel>
</Grid>
<!-- Per-file state: rows take keyboard focus; Enter retries a failed file. -->
<Border Grid.Row="5" Margin="0,8,0,0" Style="{StaticResource Border.Panel}" Padding="4"
Visibility="{Binding HasItems, Converter={StaticResource BoolToVisibility}}">
<ListBox x:Name="ItemList" ItemsSource="{Binding Items}" ItemContainerStyle="{StaticResource QueueRow}" VirtualizingPanel.ScrollUnit="Item"
AutomationProperties.Name="{l:Loc Uploader.Queue.List}" KeyDown="OnItemListKeyDown">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type u:UploadItem}">
<Grid Height="{x:Static s:MainWindow.RowHeight}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" MinWidth="64" />
<ColumnDefinition Width="Auto" MinWidth="120" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding FileName}" Style="{StaticResource Text.Body}" FlowDirection="LeftToRight" HorizontalAlignment="Left" />
<TextBlock Grid.Column="1" Text="{Binding Size, Converter={x:Static s:SizeConverter.Instance}}" Style="{StaticResource Text.Secondary}"
Typography.NumeralAlignment="Tabular" HorizontalAlignment="Right" Margin="12,0,0,0" />
<ui:StatusGlyph Grid.Column="2" Margin="16,0,0,0" FontSize="{StaticResource Size.Secondary}" VerticalAlignment="Center"
Kind="{Binding State, Converter={x:Static s:UploadStateKindConverter.Instance}}"
Text="{Binding State, Converter={x:Static s:UploadStateTextConverter.Instance}}">
<ui:StatusGlyph.ToolTip>
<MultiBinding Converter="{x:Static s:FailureTextConverter.Instance}">
<Binding Path="Failure" />
<Binding Path="FailureDetail" />
</MultiBinding>
</ui:StatusGlyph.ToolTip>
</ui:StatusGlyph>
<!--
Mouse shortcut; keyboard users press Enter on the row, so the button is not a tab stop of its own.
The retry arrow turns clockwise, like a clock, in every language: it is not mirrored.
-->
<Button Grid.Column="3" Style="{StaticResource Button.IconSubtle}" Width="26" Height="26" MinWidth="26" Margin="4,0,0,0" IsTabStop="False"
FlowDirection="LeftToRight"
ui:ButtonIcon.Glyph="{StaticResource Icon.Retry}" CommandParameter="{Binding}"
Command="{Binding DataContext.RetryItemCommand, RelativeSource={RelativeSource AncestorType=ListBox}}"
Visibility="{Binding State, Converter={x:Static s:FailedToVisibleConverter.Instance}}"
ToolTip="{l:Loc Tooltips.Uploader.RetryItem}" AutomationProperties.Name="{l:Loc Uploader.Action.Retry}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Border>
<!-- Options -->
<WrapPanel Grid.Row="6" Margin="0,12,0,0" MinHeight="30">
<CheckBox Content="{l:Loc Uploader.Options.DeleteSource}" IsChecked="{Binding DeleteAfterUpload, Mode=OneWay}" Command="{Binding ToggleDeleteAfterUploadCommand}"
ToolTip="{l:Loc Tooltips.Uploader.DeleteSource}" Margin="0,0,22,0" VerticalAlignment="Center" />
<CheckBox Content="{l:Loc Uploader.Options.StartWithWindows}" IsChecked="{Binding StartWithWindows}" ToolTip="{l:Loc Tooltips.Uploader.StartWithWindows}"
Margin="0,0,22,0" VerticalAlignment="Center" />
<CheckBox Content="{l:Loc Uploader.Options.MinimizeToTray}" IsChecked="{Binding MinimizeToTray}" ToolTip="{l:Loc Tooltips.Uploader.MinimizeToTray}"
VerticalAlignment="Center" />
</WrapPanel>
</Grid>
<!-- Settings panel over the window content; Tab and arrow keys stay inside it while it is open. -->
<Grid Grid.RowSpan="2" Visibility="{Binding IsSettingsOpen, Converter={StaticResource BoolToVisibility}}">
<Border Background="{DynamicResource Brush.Scrim}">
<Border.InputBindings>
<MouseBinding MouseAction="LeftClick" Command="{Binding CloseSettingsCommand}" />
</Border.InputBindings>
</Border>
<Border x:Name="SettingsPanel" HorizontalAlignment="Right" Width="{StaticResource Width.SidePanel}" Background="{DynamicResource Brush.Surface}"
BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="1,0,0,0"
KeyboardNavigation.TabNavigation="Cycle" KeyboardNavigation.DirectionalNavigation="Cycle" KeyboardNavigation.ControlTabNavigation="Cycle">
<DockPanel Margin="20,12,12,20">
<DockPanel DockPanel.Dock="Top" Margin="0,0,0,12">
<Button x:Name="CloseSettingsButton" DockPanel.Dock="Right" Style="{StaticResource Button.IconSubtle}" ui:ButtonIcon.Glyph="{StaticResource Icon.Close}"
Command="{Binding CloseSettingsCommand}" ToolTip="{l:Loc Tooltips.Uploader.CloseSettings}" AutomationProperties.Name="{l:Loc Uploader.Action.Close}" />
<TextBlock Text="{l:Loc Uploader.Settings.Title}" Style="{StaticResource Text.Title}" />
</DockPanel>
<Grid Margin="0,0,8,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{StaticResource Grid.LabelColumn}" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" MinHeight="36" />
<RowDefinition Height="Auto" MinHeight="36" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" MinHeight="44" />
<RowDefinition Height="Auto" MinHeight="36" />
<RowDefinition Height="Auto" MinHeight="36" />
<RowDefinition Height="Auto" MinHeight="36" />
</Grid.RowDefinitions>
<TextBlock Text="{l:Loc Uploader.Settings.Server}" Style="{StaticResource Text.PanelLabel}" />
<TextBlock Grid.Column="1" Text="{Binding ServerText}" Style="{StaticResource Text.Body}" FlowDirection="LeftToRight" HorizontalAlignment="Left" />
<TextBlock Grid.Row="1" Text="{l:Loc Uploader.Settings.User}" Style="{StaticResource Text.PanelLabel}" />
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding UserText}" Style="{StaticResource Text.Body}" />
<Button Grid.Row="2" Grid.Column="1" HorizontalAlignment="Left" Margin="0,4,0,8" Content="{l:Loc Uploader.Settings.SignOut}" Command="{Binding SignOutCommand}"
ToolTip="{l:Loc Tooltips.Uploader.SignOut}" Visibility="{Binding IsConnectVisible, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
<TextBlock Grid.Row="3" Text="{l:Loc Uploader.Settings.Bandwidth}" Style="{StaticResource Text.PanelLabel}" />
<WrapPanel Grid.Row="3" Grid.Column="1" VerticalAlignment="Center">
<TextBlock Text="{l:Loc Uploader.Limit.Label}" Style="{StaticResource Text.Base}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,0,6,0" />
<TextBox Width="58" Height="30" Text="{Binding BandwidthLimitText}" TextAlignment="Right" FlowDirection="LeftToRight" ToolTip="{l:Loc Tooltips.Uploader.Limit}"
AutomationProperties.Name="{l:Loc Uploader.Limit.Label}" />
<TextBlock Text="{l:Loc Uploader.Limit.Unit}" Style="{StaticResource Text.Base}" Foreground="{DynamicResource Brush.TextMuted}" Margin="6,0,0,0" />
</WrapPanel>
<TextBlock Grid.Row="4" Text="{l:Loc Uploader.Settings.Startup}" Style="{StaticResource Text.PanelLabel}" />
<CheckBox Grid.Row="4" Grid.Column="1" IsChecked="{Binding StartWithWindows}" ToolTip="{l:Loc Tooltips.Uploader.StartWithWindows}" VerticalAlignment="Center">
<TextBlock Text="{l:Loc Uploader.Options.StartWithWindows}" TextWrapping="Wrap" />
</CheckBox>
<CheckBox Grid.Row="5" Grid.Column="1" IsChecked="{Binding MinimizeToTray}" ToolTip="{l:Loc Tooltips.Uploader.MinimizeToTray}" VerticalAlignment="Center">
<TextBlock Text="{l:Loc Uploader.Options.MinimizeToTray}" TextWrapping="Wrap" />
</CheckBox>
<TextBlock Grid.Row="6" Text="{l:Loc Uploader.Settings.Files}" Style="{StaticResource Text.PanelLabel}" />
<CheckBox Grid.Row="6" Grid.Column="1" IsChecked="{Binding DeleteAfterUpload, Mode=OneWay}" Command="{Binding ToggleDeleteAfterUploadCommand}"
ToolTip="{l:Loc Tooltips.Uploader.DeleteSource}" VerticalAlignment="Center">
<TextBlock Text="{l:Loc Uploader.Options.DeleteSource}" TextWrapping="Wrap" />
</CheckBox>
</Grid>
</DockPanel>
</Border>
</Grid>
<ui:ToastHost x:Name="Toasts" Grid.RowSpan="2" Margin="0,0,16,16" />
</Grid>
</ui:ChronosWindow>
@@ -0,0 +1,248 @@
using System.Collections.Specialized;
using System.ComponentModel;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Threading;
using Chronos.Ui.Controls;
using Chronos.Uploader.Infrastructure;
using Chronos.Uploader.Uploads;
namespace Chronos.Uploader.Shell;
/// <summary>The uploader's single window (mockup Uploader.html).</summary>
public sealed partial class MainWindow : ChronosWindow
{
/// <summary>Height of a queue row; the list scrolls by whole rows.</summary>
public const double RowHeight = 28;
private readonly MainViewModel _vm;
private readonly UploaderSettings _settings;
private bool _connectShown;
public MainWindow(MainViewModel vm, UploaderSettings settings)
{
_vm = vm;
_settings = settings;
_connectShown = vm.IsConnectVisible;
DataContext = vm;
InitializeComponent();
vm.PendingToasts.CollectionChanged += OnToastRequested;
vm.PropertyChanged += OnViewModelChanged;
vm.Connect.PropertyChanged += OnConnectChanged;
vm.SignInRequested += (_, _) => FocusLater(Password);
PreviewKeyDown += OnPreviewKeyDown;
Loaded += (_, _) => FocusStart();
RestorePlacement();
}
/// <summary>Remembers size and position (also when the window only hides to the tray).</summary>
public void SavePlacement()
{
var b = RestoreBounds;
if (b.IsEmpty || b.Width < MinWidth || b.Height < MinHeight) return;
_settings.Window = new UploaderSettings.WindowPlacement { Left = b.Left, Top = b.Top, Width = b.Width, Height = b.Height };
}
protected override void OnDragOver(DragEventArgs e)
{
var accepted = CanDrop(e);
e.Effects = accepted ? DragDropEffects.Copy : DragDropEffects.None;
SetDropHighlight(accepted);
e.Handled = true;
}
protected override void OnDragLeave(DragEventArgs e) => SetDropHighlight(false);
protected override void OnDrop(DragEventArgs e)
{
SetDropHighlight(false);
if (!CanDrop(e) || e.Data.GetData(DataFormats.FileDrop) is not string[] paths) return;
e.Handled = true;
_ = EnqueueAsync(paths);
}
private async Task EnqueueAsync(IReadOnlyList<string> paths)
{
try
{
await _vm.EnqueueAsync(paths);
}
catch (Exception ex)
{
// UI boundary: a drop must never take the window down.
_vm.ReportError(ex);
}
}
private bool CanDrop(DragEventArgs e) => !_vm.IsConnectVisible && e.Data.GetDataPresent(DataFormats.FileDrop);
private void SetDropHighlight(bool on)
{
DropBorder.SetResourceReference(Shape.StrokeProperty, on ? "Brush.Accent" : "Brush.Stroke");
if (on) DropBorder.SetResourceReference(Shape.FillProperty, "Brush.AccentSubtle");
else DropBorder.Fill = Brushes.Transparent;
}
private void OnBrowseClick(object sender, RoutedEventArgs e) => OpenMenu((Button)sender);
private void OnWatchChipClick(object sender, RoutedEventArgs e) => OpenMenu((Button)sender);
/// <summary>Opens a button's menu under it on a normal click.</summary>
private static void OpenMenu(Button button)
{
if (button.ContextMenu is not { } menu) return;
menu.DataContext = button.DataContext;
menu.PlacementTarget = button;
menu.Placement = PlacementMode.Bottom;
menu.IsOpen = true;
}
private void OnSequencesDropDownOpened(object? sender, EventArgs e) => _vm.RefreshSequencesCommand.Execute(null);
private void OnPasswordChanged(object sender, RoutedEventArgs e) => _vm.Connect.Password = Password.Password;
/// <summary>The "3 failed" link: brings the first failed file into view and gives it the keyboard (Enter retries it).</summary>
private void OnShowFailedClick(object sender, RoutedEventArgs e)
{
if (_vm.FirstFailed() is not { } item) return;
ScrollNearTop(item);
ItemList.UpdateLayout();
if (ItemList.ItemContainerGenerator.ContainerFromItem(item) is ListBoxItem row) row.Focus();
}
/// <summary>Enter on a failed row retries it: the keyboard path to the row's Retry button.</summary>
private void OnItemListKeyDown(object sender, KeyEventArgs e)
{
if (e.Key != Key.Enter || e.OriginalSource is not ListBoxItem { DataContext: UploadItem { State: UploadItemState.Failed } item }) return;
_vm.RetryItemCommand.Execute(item);
e.Handled = true;
}
/// <summary>DESIGN §4 inputs: Enter commits, Esc reverts; Esc also closes the settings panel.</summary>
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.OriginalSource is TextBox box && (e.Key is Key.Enter or Key.Escape) && box.GetBindingExpression(TextBox.TextProperty) is { } binding)
{
if (e.Key == Key.Enter) binding.UpdateSource();
else binding.UpdateTarget();
if (e.Key == Key.Escape) e.Handled = true;
return;
}
if (e.Key == Key.Escape && _vm.IsSettingsOpen)
{
_vm.IsSettingsOpen = false;
e.Handled = true;
}
}
private void OnViewModelChanged(object? sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case nameof(MainViewModel.CurrentItem) when _vm.CurrentItem is { } item && !ItemList.IsKeyboardFocusWithin:
// Follow the upload unless the user is reading the list with the keyboard; a list that has just
// appeared has its scroll viewer once it is laid out.
Dispatcher.BeginInvoke(DispatcherPriority.Loaded, () => ScrollNearTop(item));
break;
// Raised with every session change; only a real switch between the form and the queue moves the keyboard.
case nameof(MainViewModel.IsConnectVisible) when _vm.IsConnectVisible != _connectShown:
_connectShown = _vm.IsConnectVisible;
if (_connectShown) Password.Clear();
FocusStart();
break;
case nameof(MainViewModel.IsSettingsOpen):
// Focus moves into the panel and comes back to the gear, so it is never left behind the scrim.
FocusLater(_vm.IsSettingsOpen ? CloseSettingsButton : SettingsButton);
break;
case nameof(MainViewModel.Activity):
Announce(QueueLine);
break;
}
}
/// <summary>A refused address or password takes the keyboard to that field; other failures are announced.</summary>
private void OnConnectChanged(object? sender, PropertyChangedEventArgs e)
{
var connect = _vm.Connect;
switch (e.PropertyName)
{
case nameof(ConnectViewModel.AddressError) when connect.AddressError is not null:
FocusLater(AddressBox);
break;
case nameof(ConnectViewModel.PasswordError) when connect.PasswordError is not null:
FocusLater(Password);
break;
case nameof(ConnectViewModel.ErrorText) when connect.ErrorText is not null:
Dispatcher.BeginInvoke(DispatcherPriority.Loaded, () => Announce(ErrorMessage));
break;
}
}
/// <summary>Where the keyboard starts: the first empty field of the sign-in form, or Browse once signed in.</summary>
private void FocusStart()
{
if (!_vm.IsConnectVisible) FocusLater(BrowseButton);
else if (_vm.Connect.Address.Length == 0) FocusLater(AddressBox);
else FocusLater(_vm.Connect.Username.Length == 0 ? UserBox : Password);
}
/// <summary>Focuses <paramref name="target"/> once a visibility change has been laid out; text is selected so typing replaces it.</summary>
private void FocusLater(Control target) => Dispatcher.BeginInvoke(DispatcherPriority.Loaded, () =>
{
if (!target.IsVisible || !target.Focus()) return;
if (target is TextBox box) box.SelectAll();
else if (target is PasswordBox password) password.SelectAll();
});
/// <summary>Scrolls so <paramref name="item"/> is the second visible row (the list scrolls by rows), unless it is already in view.</summary>
private void ScrollNearTop(UploadItem item)
{
if (FindScrollViewer(ItemList) is not { } scroll) return;
var index = ItemList.Items.IndexOf(item);
if (index < 0) return;
if (index >= scroll.VerticalOffset && index + 1 <= scroll.VerticalOffset + scroll.ViewportHeight) return;
scroll.ScrollToVerticalOffset(Math.Max(0, index - 1));
}
private static ScrollViewer? FindScrollViewer(DependencyObject node)
{
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(node); i++)
{
var child = VisualTreeHelper.GetChild(node, i);
if (child is ScrollViewer scroll) return scroll;
if (FindScrollViewer(child) is { } found) return found;
}
return null;
}
/// <summary>Asks screen readers to read <paramref name="element"/> again (it carries <see cref="AutomationProperties.LiveSettingProperty"/>).</summary>
private static void Announce(UIElement element)
{
if (element.IsVisible) UIElementAutomationPeer.CreatePeerForElement(element)?.RaiseAutomationEvent(AutomationEvents.LiveRegionChanged);
}
private void OnToastRequested(object? sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action != NotifyCollectionChangedAction.Add || e.NewItems is null) return;
foreach (Toast t in e.NewItems) Toasts.Show(t);
Dispatcher.BeginInvoke(() => _vm.PendingToasts.Clear());
}
private void RestorePlacement()
{
if (_settings.Window is not { } p || p.Width < MinWidth || p.Height < MinHeight) return;
var screen = new Rect(SystemParameters.VirtualScreenLeft, SystemParameters.VirtualScreenTop, SystemParameters.VirtualScreenWidth, SystemParameters.VirtualScreenHeight);
if (!screen.IntersectsWith(new Rect(p.Left, p.Top, p.Width, p.Height))) return;
WindowStartupLocation = WindowStartupLocation.Manual;
Left = p.Left;
Top = p.Top;
Width = p.Width;
Height = p.Height;
}
}
+113
View File
@@ -0,0 +1,113 @@
using System.Globalization;
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Chronos.Core.Diagnostics;
using Chronos.Ui.Controls;
using Chronos.Ui.Theming;
using Chronos.Uploader.DesignTime;
namespace Chronos.Uploader.Shell;
/// <summary>
/// <c>Chronos.Uploader.exe --capture &lt;dir&gt;</c>: renders the window at its default 760×700 — first run (connect),
/// queue running, settings panel — from <see cref="SampleData"/> in the dark and light themes, in English whatever the
/// computer's language, then once more in Arabic (right to left, dark), and exits. Nothing animates, so the pictures
/// compare with their baselines pixel for pixel.
/// </summary>
public static class ScreenCapture
{
private const double Width = 760;
private const double Height = 700;
/// <param name="directory">Where the PNG files go.</param>
/// <param name="applyLanguage">Switches the UI language (a culture name).</param>
public static void Run(string directory, Action<string?> applyLanguage)
{
Directory.CreateDirectory(directory);
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, () =>
{
try
{
CultureInfo.CurrentCulture = CultureInfo.DefaultThreadCurrentCulture = CultureInfo.GetCultureInfo("en");
applyLanguage("en");
CaptureScreens(directory, string.Empty, [AppTheme.Dark, AppTheme.Light]);
// Mirrored layout with paths, addresses and file names kept left to right (BRIEF §16).
applyLanguage("ar");
CaptureScreens(directory, "-ar", [AppTheme.Dark]);
Log.Info("capture", $"Screenshots written to {Path.GetFullPath(directory)}");
}
catch (Exception ex)
{
Log.Error("capture", "Capture failed", ex);
Environment.ExitCode = 1;
}
finally
{
Application.Current.Shutdown();
}
});
}
/// <summary>A fresh window on fresh sample data, so every text is built in the current language.</summary>
private static void CaptureScreens(string directory, string language, IReadOnlyList<AppTheme> themes)
{
var sample = new SampleData();
var vm = sample.CreateViewModel();
var window = new MainWindow(vm, sample.Settings)
{
WindowStartupLocation = WindowStartupLocation.Manual,
Left = -20000,
Top = -20000,
Width = Width,
Height = Height,
ShowActivated = false,
ShowInTaskbar = false,
};
Motion.SetIsEnabled(window, false);
window.Show();
try
{
foreach (var theme in themes)
{
var suffix = language + "-" + theme.ToString().ToLowerInvariant();
ThemeManager.Apply(theme);
sample.ShowConnect();
Save(window, Path.Combine(directory, $"uploader-connect{suffix}.png"));
sample.ShowQueue();
Save(window, Path.Combine(directory, $"uploader-queue{suffix}.png"));
vm.IsSettingsOpen = true;
Save(window, Path.Combine(directory, $"uploader-settings{suffix}.png"));
vm.IsSettingsOpen = false;
}
}
finally
{
window.Close();
vm.Dispose();
}
}
private static void Save(Window window, string path)
{
// Let bindings, templates and deferred layout complete.
window.UpdateLayout();
window.Dispatcher.Invoke(DispatcherPriority.ApplicationIdle, () => { });
window.UpdateLayout();
if (VisualTreeHelper.GetChildrenCount(window) == 0) return;
var root = (FrameworkElement)VisualTreeHelper.GetChild(window, 0);
var dpi = VisualTreeHelper.GetDpi(window);
var width = (int)Math.Ceiling(root.ActualWidth * dpi.DpiScaleX);
var height = (int)Math.Ceiling(root.ActualHeight * dpi.DpiScaleY);
if (width <= 0 || height <= 0) return;
var bitmap = new RenderTargetBitmap(width, height, dpi.PixelsPerInchX, dpi.PixelsPerInchY, PixelFormats.Pbgra32);
// A right-to-left window's content already renders mirrored, as on screen.
bitmap.Render(root);
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmap));
using var stream = File.Create(path);
encoder.Save(stream);
}
}
@@ -0,0 +1,61 @@
using System.Windows;
using System.Windows.Interop;
using Chronos.Core.Imaging;
using Chronos.Core.Localization;
using Chronos.Uploader.Interop;
namespace Chronos.Uploader.Shell;
/// <summary>Window-owned implementation: shell Open dialogs and <see cref="ConfirmDialog"/>.</summary>
public sealed class UploaderDialogs : IUploaderDialogs
{
/// <summary>Owner of the dialogs; set once the main window exists.</summary>
public Window? Owner { get; set; }
private IntPtr OwnerHandle => Owner is null ? IntPtr.Zero : new WindowInteropHelper(Owner).Handle;
public IReadOnlyList<string> PickFiles()
{
var photos = string.Join(';', ImageFormatInfo.Known.SelectMany(f => f.Extensions).Select(e => "*." + e));
return FileDialogs.PickFiles(OwnerHandle, Loc.L("Uploader.Browse.FilesTitle"),
[
new FileFilter(Loc.L("Uploader.Browse.Photos"), photos),
new FileFilter(Loc.L("Uploader.Browse.AllFiles"), "*.*"),
]);
}
public string? PickFolder() => FileDialogs.PickFolder(OwnerHandle, Loc.L("Uploader.Browse.FolderTitle"));
public string? PickWatchFolder() => FileDialogs.PickFolder(OwnerHandle, Loc.L("Uploader.Browse.WatchTitle"));
public bool ConfirmTrust(string address, string fingerprint) => ConfirmDialog.Ask(Owner, new ConfirmRequest
{
Heading = Loc.L("Uploader.Trust.Title"),
Message = Loc.L("Uploader.Trust.Message"),
Detail = address + "\n" + FormatFingerprint(fingerprint),
DetailToolTip = Loc.L("Tooltips.Uploader.Fingerprint"),
SafeText = Loc.L("Uploader.Trust.Cancel"),
SafeToolTip = Loc.L("Tooltips.Uploader.CancelTrust"),
ActionText = Loc.L("Uploader.Trust.Accept"),
ActionToolTip = Loc.L("Tooltips.Uploader.Trust"),
IsDestructive = false,
});
public bool ConfirmDeleteAfterUpload() => ConfirmDialog.Ask(Owner, new ConfirmRequest
{
Heading = Loc.L("Uploader.Delete.Title"),
Message = Loc.L("Uploader.Delete.Message"),
SafeText = Loc.L("Uploader.Delete.Keep"),
SafeToolTip = Loc.L("Tooltips.Uploader.KeepFiles"),
ActionText = Loc.L("Uploader.Delete.Accept"),
ActionToolTip = Loc.L("Tooltips.Uploader.ConfirmDelete"),
IsDestructive = true,
});
/// <summary>Splits the 32-byte SHA-256 fingerprint into two readable lines of 16 bytes.</summary>
public static string FormatFingerprint(string fingerprint)
{
var bytes = fingerprint.Split(':');
return bytes.Length <= 16 ? fingerprint : string.Join(':', bytes.Take(16)) + "\n" + string.Join(':', bytes.Skip(16));
}
}
@@ -0,0 +1,86 @@
using System.Windows.Input;
using Chronos.Core.Localization;
using Chronos.Ui.Mvvm;
using Chronos.Uploader.Text;
namespace Chronos.Uploader.Shell;
/// <summary>An entry of a watch folder chip's menu: an interval choice, a separator (no text) or "Remove".</summary>
public sealed record WatchMenuOption(string? Text, string? ToolTip, ICommand? Command, bool IsChecked)
{
public bool IsSeparator => Text is null;
}
/// <summary>One watch folder chip: path, interval, reachability.</summary>
public sealed class WatchFolderViewModel : ObservableObject
{
/// <summary>Intervals offered in the chip menu.</summary>
public static readonly int[] IntervalChoices = [30, 60, 300, 900];
private readonly Action<WatchFolderViewModel, int> _setInterval;
private readonly Action<WatchFolderViewModel> _remove;
private int _intervalSeconds;
private bool? _isAvailable;
public WatchFolderViewModel(string path, int intervalSeconds, bool isNetwork, Action<WatchFolderViewModel, int> setInterval, Action<WatchFolderViewModel> remove)
{
Path = path;
IsNetwork = isNetwork;
_intervalSeconds = intervalSeconds;
_setInterval = setInterval;
_remove = remove;
}
public string Path { get; }
public bool IsNetwork { get; }
public int IntervalSeconds
{
get => _intervalSeconds;
set
{
if (!Set(ref _intervalSeconds, value)) return;
OnPropertyChanged(nameof(Text));
OnPropertyChanged(nameof(IntervalText));
OnPropertyChanged(nameof(ToolTip));
OnPropertyChanged(nameof(MenuOptions));
}
}
/// <summary>Null until the first check finished.</summary>
public bool? IsAvailable
{
get => _isAvailable;
set
{
if (Set(ref _isAvailable, value)) OnPropertyChanged(nameof(ToolTip));
}
}
/// <summary>"D:\Cam\Roof · every 1 min": the chip's accessible name.</summary>
public string Text => Loc.L("Uploader.Watch.Chip", Path, Interval(IntervalSeconds));
/// <summary>"every 1 min", shown after the path, which the chip draws left to right on its own and may shorten.</summary>
public string IntervalText => Loc.L("Uploader.Watch.Interval", Interval(IntervalSeconds));
/// <summary>The full path (the chip may shorten it), then the folder's state and interval.</summary>
public string ToolTip => LeftToRight(Path) + Loc.Separator + (IsAvailable == false ? Loc.L("Tooltips.Uploader.WatchFolderMissing", Interval(IntervalSeconds))
: IsNetwork ? Loc.L("Tooltips.Uploader.WatchFolderNetwork", Interval(IntervalSeconds))
: Loc.L("Tooltips.Uploader.WatchFolder", Interval(IntervalSeconds)));
public IReadOnlyList<WatchMenuOption> MenuOptions =>
[
.. IntervalChoices.Select(s => new WatchMenuOption(
Loc.L("Uploader.Watch.Every", Interval(s)),
Loc.L("Tooltips.Uploader.WatchInterval"),
new RelayCommand(() => _setInterval(this, s)),
s == IntervalSeconds)),
new WatchMenuOption(null, null, null, false),
new WatchMenuOption(Loc.L("Uploader.Watch.Remove"), Loc.L("Tooltips.Uploader.RemoveWatchFolder"), new RelayCommand(() => _remove(this)), false),
];
private static string Interval(int seconds) => UploaderText.Duration(TimeSpan.FromSeconds(seconds), Loc.Culture);
/// <summary>Embeds a path left to right (LRE … PDF) so a right-to-left tooltip does not reorder its separators.</summary>
private static string LeftToRight(string text) => "\u202A" + text + "\u202C";
}
@@ -0,0 +1,82 @@
using System.IO;
using Chronos.Core.Diagnostics;
using Chronos.Core.Imaging;
namespace Chronos.Uploader.Sources;
/// <summary>A photo found on disk. <see cref="Root"/> is the dropped folder (or the file's folder) it was found under.</summary>
public sealed record SourceFile(string Path, long Size, DateTime ModifiedUtc, DateTime CapturedAt, string Root);
/// <summary>Finds supported photos under dropped files, folders and card roots (BRIEF §15: zero analysis).</summary>
public static class PhotoScanner
{
private static readonly EnumerationOptions Recursive = new()
{
RecurseSubdirectories = true,
IgnoreInaccessible = true,
// Skips "System Volume Information", "$RECYCLE.BIN" and camera housekeeping files.
AttributesToSkip = FileAttributes.Hidden | FileAttributes.System,
MatchType = MatchType.Simple,
};
/// <summary>Supported photos under <paramref name="paths"/>, in path order, without duplicates.</summary>
public static IReadOnlyList<SourceFile> Scan(IEnumerable<string> paths, CancellationToken ct = default)
{
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var result = new List<SourceFile>();
foreach (var raw in paths)
{
ct.ThrowIfCancellationRequested();
string full;
try
{
full = Path.GetFullPath(raw);
}
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
{
Log.Warning("scan", $"Ignored path {raw}", ex);
continue;
}
if (Directory.Exists(full))
{
try
{
foreach (var file in Files(full, ct))
{
if (seen.Add(file.FullName)) result.Add(ToSource(file, full));
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// A card pulled mid-scan: keep what was found; the rest can be dropped again.
Log.Warning("scan", $"Listing of {full} stopped early", ex);
}
}
else if (File.Exists(full) && ImageFormatInfo.IsSupportedExtension(full) && seen.Add(full))
{
var info = new FileInfo(full);
result.Add(ToSource(info, info.DirectoryName ?? full));
}
}
return result;
}
/// <summary>Supported photos under <paramref name="folder"/>, recursively. I/O errors while listing propagate.</summary>
public static IEnumerable<FileInfo> Files(string folder, CancellationToken ct = default)
{
foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*", Recursive))
{
ct.ThrowIfCancellationRequested();
if (ImageFormatInfo.IsSupportedExtension(file.Name)) yield return file;
}
}
public static SourceFile ToSource(FileInfo file, string root) =>
new(file.FullName, file.Length, file.LastWriteTimeUtc, CaptureTime(file), root);
/// <summary>
/// Capture time read cheaply: the file's last-write time in local wall-clock, which cameras set to the shot time.
/// Exif dates replace it when the metadata reader lands in Chronos.Core.
/// </summary>
public static DateTime CaptureTime(FileInfo file) => DateTime.SpecifyKind(file.LastWriteTime, DateTimeKind.Unspecified);
}
@@ -0,0 +1,89 @@
using System.Globalization;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Chronos.Uploader.Sources;
/// <summary>The last session of a source, so later files within the gap join it (watch folders).</summary>
public sealed record SessionContinuation(string Key, DateTime LastCapture);
/// <summary>Session key per input frame (input order) and the session the next batch may continue.</summary>
public sealed record SessionAssignment(IReadOnlyList<string> Keys, SessionContinuation? Last);
/// <summary>
/// Splits frames of one source into shooting sessions with the card-import rules (BRIEF §13): a gap longer than
/// <see cref="Gap"/> starts a session; sessions with fewer than <see cref="MinimumFrames"/> frames (test shots) merge
/// into the previous session, or into the next one when they come first. The server turns each key into a sequence.
/// </summary>
public static class SessionGrouper
{
/// <summary><c>SessionGapMinutes</c> default.</summary>
public static readonly TimeSpan Gap = TimeSpan.FromMinutes(45);
/// <summary><c>MinimumSessionFrames</c> default.</summary>
public const int MinimumFrames = 8;
/// <summary>Groups <paramref name="captureTimes"/>; keys start with <paramref name="sourceTag"/> so sources never collide.</summary>
public static SessionAssignment Assign(IReadOnlyList<DateTime> captureTimes, string sourceTag, SessionContinuation? previous = null)
{
if (captureTimes.Count == 0) return new SessionAssignment([], previous);
var order = Enumerable.Range(0, captureTimes.Count).OrderBy(i => captureTimes[i]).ToArray();
// Split on gaps; a group that continues the previous batch keeps its key and is never "small".
var groups = new List<Group>();
var current = new Group { Continues = previous is not null && (captureTimes[order[0]] - previous.LastCapture).Duration() <= Gap };
for (var n = 0; n < order.Length; n++)
{
var i = order[n];
if (n > 0 && captureTimes[i] - captureTimes[order[n - 1]] > Gap)
{
groups.Add(current);
current = new Group();
}
current.Members.Add(i);
}
groups.Add(current);
var merged = new List<Group>();
foreach (var g in groups)
{
if (merged.Count > 0 && g.Members.Count < MinimumFrames) merged[^1].Members.AddRange(g.Members);
else merged.Add(g);
}
if (merged.Count > 1 && merged[0].Members.Count < MinimumFrames && !merged[0].Continues)
{
merged[0].Members.AddRange(merged[1].Members);
merged.RemoveAt(1);
}
var keys = new string[captureTimes.Count];
string? lastKey = null;
foreach (var g in merged)
{
var first = g.Members.Min(i => captureTimes[i]);
lastKey = g.Continues ? previous!.Key : Key(sourceTag, first);
foreach (var i in g.Members) keys[i] = lastKey;
}
var lastCapture = captureTimes[order[^1]];
if (previous is not null && previous.LastCapture > lastCapture && merged[^1].Continues) lastCapture = previous.LastCapture;
return new SessionAssignment(keys, new SessionContinuation(lastKey!, lastCapture));
}
/// <summary>Short stable tag for a source folder: 8 hex digits of the SHA-256 of its normalised path.</summary>
public static string SourceTag(string root)
{
var normalized = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)).ToUpperInvariant();
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(normalized)))[..8];
}
/// <summary><c>{tag}-{yyyyMMdd-HHmmss}</c> of the session's first frame.</summary>
public static string Key(string sourceTag, DateTime firstCapture) =>
sourceTag + "-" + firstCapture.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture);
private sealed class Group
{
public List<int> Members { get; } = [];
public bool Continues { get; init; }
}
}
+111
View File
@@ -0,0 +1,111 @@
using System.Globalization;
using Chronos.Core.Localization;
using Chronos.Uploader.Uploads;
namespace Chronos.Uploader.Text;
/// <summary>What the queue is doing, for the end of the queue line.</summary>
public enum QueueActivity
{
Idle,
Running,
Paused,
WaitingForServer,
Done,
}
/// <summary>
/// Culture-aware texts of the uploader: sizes, rates, durations and the queue/progress lines
/// ("4,812 files · 96.2 GB · 38 MB/s · 41 min left"). Every method takes the culture so results are deterministic.
/// </summary>
public static class UploaderText
{
/// <summary>Localized "{0} KB" formats from bytes to petabytes (BRIEF §16: sizes follow the language, "96,2 Go").</summary>
private static readonly string[] SizeFormats = ["Common.Size.B", "Common.Size.KB", "Common.Size.MB", "Common.Size.GB", "Common.Size.TB", "Common.Size.PB"];
/// <summary>Localized string for <paramref name="key"/> in <paramref name="culture"/>, formatted with <paramref name="args"/>.</summary>
public static string L(string key, CultureInfo culture, params object?[] args)
{
var format = Loc.Get(key, culture) ?? "⟦" + key + "⟧";
return args.Length == 0 ? format : string.Format(culture, format, args);
}
/// <summary>Plural-aware lookup of <c>key.one/few/many/other</c>; <c>{0}</c> receives the count.</summary>
public static string Plural(string key, long count, CultureInfo culture)
{
var category = PluralRules.Suffix(PluralRules.Select(culture, count));
var format = Loc.Get(key + "." + category, culture) ?? Loc.Get(key + ".other", culture) ?? "⟦" + key + "⟧";
return string.Format(culture, format, count);
}
/// <summary>1,536 → "1.5 KB" (decimal units, as Explorer shows for drives).</summary>
public static string Bytes(long bytes, CultureInfo culture)
{
var (value, unit) = Scale(bytes);
var format = unit == 0 || value >= 100 ? "0" : "0.#";
return L(SizeFormats[unit], culture, value.ToString(format, culture));
}
/// <summary>38,400,000 B/s → "38 MB/s"; one decimal below 10 units.</summary>
public static string Rate(double bytesPerSecond, CultureInfo culture)
{
var (value, unit) = Scale(Math.Max(0, bytesPerSecond));
var format = unit == 0 || value >= 10 ? "0" : "0.#";
return L("Uploader.Unit.PerSecond", culture, L(SizeFormats[unit], culture, value.ToString(format, culture)));
}
/// <summary>Compact duration: "2 h 05 m", "41 min", "40 s".</summary>
public static string Duration(TimeSpan t, CultureInfo culture)
{
if (t.TotalHours >= 24) return L("Common.Duration.Days", culture, (int)t.TotalDays, t.Hours);
if (t.TotalMinutes >= 59.5) return L("Common.Duration.Hours", culture, (int)Math.Round(t.TotalMinutes) / 60, ((int)Math.Round(t.TotalMinutes) % 60).ToString("00", culture));
if (t.TotalSeconds >= 59.5) return L("Common.Duration.Minutes", culture, (int)Math.Round(t.TotalMinutes));
return L("Common.Duration.Seconds", culture, (int)Math.Round(t.TotalSeconds));
}
/// <summary>"4,812 files · 96.2 GB · 38 MB/s · 41 min left", or the files and size followed by the activity.</summary>
public static string QueueLine(QueueSummary summary, QueueActivity activity, double bytesPerSecond, TimeSpan? left, CultureInfo culture)
{
if (summary.Files == 0) return L("Uploader.Queue.Empty", culture);
var parts = new List<string> { Plural("Uploader.Queue.Files", summary.Files, culture), Bytes(summary.Bytes, culture) };
switch (activity)
{
case QueueActivity.Running:
if (bytesPerSecond > 0) parts.Add(Rate(bytesPerSecond, culture));
if (left is { } l) parts.Add(L("Uploader.Queue.Left", culture, Duration(l, culture)));
break;
case QueueActivity.Paused:
parts.Add(L("Uploader.Queue.Paused", culture));
break;
case QueueActivity.WaitingForServer:
parts.Add(L("Uploader.Queue.Waiting", culture));
break;
case QueueActivity.Done:
parts.Add(L("Uploader.Queue.Done", culture));
break;
}
return string.Join(Loc.SeparatorOf(culture), parts);
}
/// <summary>"2,214 of 4,812 sent · 2,201 verified by the server · 0 retries" (failures have their own link, <see cref="Failed"/>).</summary>
public static string ProgressLine(QueueSummary summary, CultureInfo culture) => string.Join(Loc.SeparatorOf(culture),
L("Uploader.Progress.Sent", culture, summary.Sent, summary.Files),
L("Uploader.Progress.Verified", culture, summary.Verified),
Plural("Uploader.Progress.Retries", summary.Retries, culture));
/// <summary>"3 failed"; null when nothing failed.</summary>
public static string? Failed(QueueSummary summary, CultureInfo culture) =>
summary.Failed > 0 ? L("Uploader.Progress.Failed", culture, summary.Failed) : null;
private static (double Value, int Unit) Scale(double bytes)
{
var value = bytes;
var unit = 0;
while (value >= 999.95 && unit < SizeFormats.Length - 1)
{
value /= 1000;
unit++;
}
return (value, unit);
}
}
@@ -0,0 +1,47 @@
using Chronos.Protocol.Client;
namespace Chronos.Uploader.Uploads;
/// <summary>How the server answered a successful upload.</summary>
public enum UploadOutcome
{
/// <summary>Committed after the server checked the SHA-256 (<c>CompleteUploadResponse</c>).</summary>
Verified,
/// <summary>The server already held this SHA-256 (<c>AlreadyExists</c>).</summary>
AlreadyOnServer,
}
/// <summary>What the upload needs from the server connection.</summary>
public interface IUploadTransport
{
/// <summary>True while signed in and reachable; the engine waits otherwise.</summary>
bool IsReady { get; }
/// <summary>Raised (on the UI thread) when <see cref="IsReady"/> changes.</summary>
event EventHandler? ReadyChanged;
/// <summary>
/// Sends one file whose hash is known. Throws <see cref="ServerUnavailableException"/> when the server cannot be
/// used right now (offline, signed out, certificate changed); other failures concern this file only.
/// </summary>
Task<(UploadOutcome Outcome, Guid? FrameId)> UploadAsync(UploadItem item, Guid? sequenceId, string sha256, IProgress<UploadProgress> progress, CancellationToken ct);
/// <summary>Creates a sequence for a "new sequence" batch.</summary>
Task<Guid> CreateSequenceAsync(string? title, CancellationToken ct);
}
/// <summary>Why the server cannot be used.</summary>
public enum ServerProblem
{
Unreachable,
SignedOut,
CertificateChanged,
}
/// <summary>The server cannot take uploads right now; the item goes back in line without spending a retry.</summary>
public sealed class ServerUnavailableException(ServerProblem problem, Exception? inner = null)
: Exception("Server unavailable: " + problem, inner)
{
public ServerProblem Problem { get; } = problem;
}
+108
View File
@@ -0,0 +1,108 @@
using System.IO;
using System.Text.Json.Serialization;
using System.Text.Json;
using Chronos.Core.Diagnostics;
namespace Chronos.Uploader.Uploads;
/// <summary>
/// <c>uploader-queue.json</c>: the queue survives restarts (BRIEF §15). Server-side upload ids are not stored —
/// restarting an item calls <c>POST /uploads</c> again with the same SHA-256 and the server answers with the chunks
/// it already holds.
/// </summary>
public static class QueueStore
{
public const int Version = 1;
/// <summary>Serializes the queue on the calling (owning) thread; the bytes can be written anywhere.</summary>
public static byte[] Serialize(UploadQueue queue)
{
var file = new QueueFile
{
Version = Version,
Paused = queue.IsPaused,
Batches = [.. queue.Batches.Select(b => new BatchRecord(b.Id, b.Mode, b.SequenceId, b.Title))],
Items =
[
.. queue.Items.Select(i => new ItemRecord(
i.Id, i.BatchId, i.Path, i.Size, i.ModifiedUtc, i.CapturedAt, i.SessionKey, i.WatchRoot,
i.IsActive ? UploadItemState.Queued : i.State, i.Failure, i.FailureDetail, i.Retries, i.Sha256, i.FrameId, i.NextRetryUtc)),
],
};
return JsonSerializer.SerializeToUtf8Bytes(file, QueueJson.Default.QueueFile);
}
/// <summary>Loads <paramref name="path"/> into <paramref name="queue"/>; a missing or corrupt file leaves it empty.</summary>
public static void Load(string path, UploadQueue queue)
{
QueueFile? file = null;
try
{
if (File.Exists(path)) file = JsonSerializer.Deserialize(File.ReadAllBytes(path), QueueJson.Default.QueueFile);
}
catch (JsonException ex)
{
Log.Warning("queue", "Queue file unreadable; starting empty", ex);
}
catch (IOException ex)
{
Log.Warning("queue", "Queue file unreadable; starting empty", ex);
}
if (file is null || file.Version != Version) return;
queue.Restore(
file.Batches.Select(b => new UploadBatch { Id = b.Id, Mode = b.Mode, SequenceId = b.SequenceId, Title = b.Title }),
file.Items.Select(r => new UploadItem
{
Id = r.Id,
BatchId = r.BatchId,
Path = r.Path,
Size = r.Size,
ModifiedUtc = r.ModifiedUtc,
CapturedAt = r.CapturedAt,
SessionKey = r.SessionKey,
WatchRoot = r.WatchRoot,
State = r.State,
Failure = r.Failure,
FailureDetail = r.FailureDetail,
Retries = r.Retries,
Sha256 = r.Sha256,
FrameId = r.FrameId,
NextRetryUtc = r.NextRetryUtc,
}),
file.Paused);
}
internal sealed class QueueFile
{
public int Version { get; set; }
public bool Paused { get; set; }
public List<BatchRecord> Batches { get; set; } = [];
public List<ItemRecord> Items { get; set; } = [];
}
internal sealed record BatchRecord(Guid Id, UploadTargetMode Mode, Guid? SequenceId, string? Title);
internal sealed record ItemRecord(
Guid Id,
Guid BatchId,
string Path,
long Size,
DateTime ModifiedUtc,
DateTime? CapturedAt,
string? SessionKey,
string? WatchRoot,
UploadItemState State,
UploadFailure Failure,
string? FailureDetail,
int Retries,
string? Sha256,
Guid? FrameId,
DateTime? NextRetryUtc);
}
[JsonSourceGenerationOptions(
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
UseStringEnumConverter = true)]
[JsonSerializable(typeof(QueueStore.QueueFile))]
internal sealed partial class QueueJson : JsonSerializerContext;
@@ -0,0 +1,115 @@
namespace Chronos.Uploader.Uploads;
/// <summary>Aggregate figures behind the queue line and the progress bar.</summary>
public readonly record struct QueueSummary(
int Files,
long Bytes,
int Sent,
int Verified,
int Failed,
int Retries,
long DoneBytes,
string? CurrentFile)
{
/// <summary>0–1 share of bytes already on the server or in flight.</summary>
public double Progress => Bytes <= 0 ? 0 : Math.Clamp(DoneBytes / (double)Bytes, 0, 1);
/// <summary>Bytes still to send, counting only items that can still succeed.</summary>
public long RemainingBytes { get; init; }
public static QueueSummary From(IEnumerable<UploadItem> items)
{
int files = 0, sent = 0, verified = 0, failed = 0, retries = 0;
long bytes = 0, done = 0, remaining = 0;
UploadItem? current = null;
foreach (var item in items)
{
files++;
bytes += item.Size;
retries += item.Retries;
switch (item.State)
{
case UploadItemState.Verified or UploadItemState.Skipped:
sent++;
verified++;
done += item.Size;
break;
case UploadItemState.Uploading:
if (item.BytesSent >= item.Size) sent++;
done += Math.Min(item.BytesSent, item.Size);
remaining += Math.Max(0, item.Size - item.BytesSent);
current = item;
break;
case UploadItemState.Hashing:
remaining += item.Size;
current ??= item;
break;
case UploadItemState.Failed:
failed++;
if (item.NextRetryUtc is not null) remaining += item.Size;
break;
default:
remaining += item.Size;
break;
}
}
return new QueueSummary(files, bytes, sent, verified, failed, retries, done, current?.FileName) { RemainingBytes = remaining };
}
}
/// <summary>Throughput over a sliding window of cumulative byte counts.</summary>
public sealed class RateMeter(TimeSpan window)
{
private readonly List<(TimeSpan At, long Total)> _samples = [];
private long _total;
public RateMeter()
: this(TimeSpan.FromSeconds(10))
{
}
/// <summary>Adds <paramref name="bytes"/> sent at <paramref name="now"/> (monotonic clock).</summary>
public void Add(long bytes, TimeSpan now)
{
// The first sample is the zero baseline so the first chunk counts.
if (_samples.Count == 0) _samples.Add((now, _total));
_total += bytes;
_samples.Add((now, _total));
Trim(now);
}
/// <summary>Bytes per second over the window; 0 until the window spans at least one second.</summary>
public double BytesPerSecond(TimeSpan now)
{
Trim(now);
if (_samples.Count == 0) return 0;
var (at, total) = _samples[0];
// Measured up to now, so a stalled transfer decays towards zero.
var span = (now - at).TotalSeconds;
return span < 1 ? 0 : (_total - total) / span;
}
public void Reset()
{
_samples.Clear();
_total = 0;
}
/// <summary>Keeps the newest sample at or before <c>now − window</c> as the baseline and drops older ones.</summary>
private void Trim(TimeSpan now)
{
var cutoff = now - window;
var drop = 0;
while (drop + 1 < _samples.Count && _samples[drop + 1].At <= cutoff) drop++;
if (drop > 0) _samples.RemoveRange(0, drop);
}
/// <summary>Time to send <paramref name="remainingBytes"/> at <paramref name="bytesPerSecond"/>; null without a usable rate.</summary>
public static TimeSpan? TimeLeft(long remainingBytes, double bytesPerSecond)
{
if (remainingBytes <= 0) return TimeSpan.Zero;
if (bytesPerSecond < 1024) return null;
var seconds = Math.Ceiling(remainingBytes / bytesPerSecond);
return seconds >= TimeSpan.FromDays(365).TotalSeconds ? null : TimeSpan.FromSeconds(seconds);
}
}
@@ -0,0 +1,366 @@
using System.ComponentModel;
using System.IO;
using Chronos.Core.Diagnostics;
using Chronos.Protocol.Client;
namespace Chronos.Uploader.Uploads;
/// <summary>What the upload engine is doing.</summary>
public enum EngineStatus
{
Idle,
Running,
Paused,
WaitingForServer,
}
/// <summary>Queue control used by the window and the tray.</summary>
public interface IUploadEngine : INotifyPropertyChanged
{
EngineStatus Status { get; }
/// <summary>Current throughput over the last seconds.</summary>
double BytesPerSecond { get; }
/// <summary>Raised when the last pending item finished (balloon on completion).</summary>
event EventHandler? Drained;
/// <summary>Starts work for newly queued items without waiting for the next tick.</summary>
void Pump();
void Pause();
void Resume();
/// <summary>Stops every transfer and clears the queue; files already uploaded stay on the server.</summary>
void StopAndClear();
/// <summary>Puts a failed item back in line with a fresh retry budget.</summary>
void Retry(UploadItem item);
}
/// <summary>
/// Works through the <see cref="UploadQueue"/> with <see cref="Parallelism"/> concurrent files: hash, upload
/// (resumable chunks; the server verifies the SHA-256), then optionally delete the source whose bytes the server
/// received and verified. A file the server already held is kept: no copy of it was verified on this run.
/// Lives on the UI thread: state changes happen there while hashing and HTTP run on the thread pool.
/// </summary>
public sealed class UploadEngine : IUploadEngine, IDisposable
{
public const int Parallelism = 2;
private readonly UploadQueue _queue;
private readonly IUploadTransport _transport;
private readonly Func<bool> _deleteAfterUpload;
private readonly TimeProvider _time;
private readonly long _origin;
private readonly RateMeter _meter = new();
private readonly Dictionary<UploadItem, CancellationTokenSource> _running = [];
private readonly Dictionary<Guid, Task<Guid>> _creating = [];
private readonly CancellationTokenSource _lifetime = new();
private EngineStatus _status;
private double _bytesPerSecond;
private bool _hadWork;
public UploadEngine(UploadQueue queue, IUploadTransport transport, Func<bool> deleteAfterUpload, TimeProvider? time = null)
{
_queue = queue;
_transport = transport;
_deleteAfterUpload = deleteAfterUpload;
_time = time ?? TimeProvider.System;
_origin = _time.GetTimestamp();
_transport.ReadyChanged += (_, _) => Pump();
}
public event PropertyChangedEventHandler? PropertyChanged;
public event EventHandler? Drained;
/// <summary>Raised when the server confirmed an item (verified or already present).</summary>
public event EventHandler<UploadItem>? ItemConfirmed;
public EngineStatus Status
{
get => _status;
private set
{
if (_status == value) return;
_status = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Status)));
}
}
public double BytesPerSecond
{
get => _bytesPerSecond;
private set
{
if (_bytesPerSecond.Equals(value)) return;
_bytesPerSecond = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(BytesPerSecond)));
}
}
private TimeSpan Now => _time.GetElapsedTime(_origin);
private DateTime UtcNow => _time.GetUtcNow().UtcDateTime;
/// <summary>Starts the once-a-second pump on the calling (UI) thread.</summary>
public void Start() => _ = TickAsync(_lifetime.Token);
/// <summary>Starts work for newly queued items without waiting for the next tick.</summary>
public void Pump()
{
if (_lifetime.IsCancellationRequested) return;
while (!_queue.IsPaused && _transport.IsReady && _running.Count < Parallelism)
{
var item = _queue.NextReady(UtcNow);
if (item is null) break;
Begin(item);
}
Refresh();
}
public void Pause()
{
_queue.IsPaused = true;
CancelRunning();
Refresh();
}
public void Resume()
{
_queue.IsPaused = false;
Pump();
}
public void StopAndClear()
{
CancelRunning();
_queue.Clear();
_creating.Clear();
_meter.Reset();
_hadWork = false;
Refresh();
}
public void Retry(UploadItem item)
{
_queue.Requeue(item);
Pump();
}
public void Dispose()
{
_lifetime.Cancel();
CancelRunning();
_lifetime.Dispose();
}
private async Task TickAsync(CancellationToken ct)
{
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(1), _time);
try
{
do
{
Pump();
}
while (await timer.WaitForNextTickAsync(ct));
}
catch (OperationCanceledException)
{
}
}
private void Begin(UploadItem item)
{
if (item.State == UploadItemState.Failed)
{
item.Retries++;
item.NextRetryUtc = null;
item.Failure = UploadFailure.None;
item.FailureDetail = null;
}
// Leaving Queued/Failed synchronously keeps NextReady from handing the item out twice.
item.State = UploadItemState.Hashing;
var cts = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token);
_running[item] = cts;
_hadWork = true;
_ = RunAsync(item, cts);
}
private async Task RunAsync(UploadItem item, CancellationTokenSource cts)
{
var ct = cts.Token;
try
{
await HashIfNeededAsync(item, ct);
if (item.State == UploadItemState.Failed) return;
item.State = UploadItemState.Uploading;
item.BytesSent = 0;
var batch = _queue.GetBatch(item.BatchId);
Guid? sequenceId = batch?.Mode switch
{
UploadTargetMode.Sequence => batch.SequenceId,
UploadTargetMode.NewSequence => await EnsureSequenceAsync(batch, ct),
_ => null,
};
var baseline = true;
var progress = new Progress<UploadProgress>(p =>
{
if (item.State != UploadItemState.Uploading) return;
// The first report of a resumed upload counts chunks the server already had: not throughput.
if (!baseline) _meter.Add(Math.Max(0, p.BytesSent - item.BytesSent), Now);
baseline = false;
item.BytesSent = p.BytesSent;
});
var (outcome, frameId) = await _transport.UploadAsync(item, sequenceId, item.Sha256!, progress, ct);
item.FrameId = frameId;
item.BytesSent = item.Size;
item.State = outcome == UploadOutcome.Verified ? UploadItemState.Verified : UploadItemState.Skipped;
_queue.OnChanged();
ItemConfirmed?.Invoke(this, item);
if (outcome == UploadOutcome.Verified && _deleteAfterUpload()) DeleteConfirmedSource(item);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
Requeue(item);
}
catch (ServerUnavailableException ex)
{
Log.Info("upload", $"{item.FileName} waits for the server ({ex.Problem})");
Requeue(item);
}
catch (Exception ex) when (ex is FileNotFoundException or DirectoryNotFoundException)
{
_queue.Fail(item, UploadFailure.FileMissing, null, UtcNow);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("upload", $"Cannot read {item.Path}", ex);
_queue.Fail(item, File.Exists(item.Path) ? UploadFailure.FileUnreadable : UploadFailure.FileMissing, null, UtcNow);
}
catch (ChronosApiException ex)
{
Log.Warning("upload", $"Server refused {item.Path}: {ex.Error.Code}", ex);
_queue.Fail(item, UploadFailure.ServerRejected, ex.Error.Message, UtcNow);
}
catch (Exception ex)
{
// Worker boundary: nothing may leave an item stuck in an active state.
Log.Error("upload", $"Upload of {item.Path} failed", ex);
_queue.Fail(item, UploadFailure.Unexpected, null, UtcNow);
}
finally
{
_running.Remove(item);
cts.Dispose();
Pump();
}
}
/// <summary>Hashes when the file is new or changed; a file that changes while being read fails for a later retry.</summary>
private async Task HashIfNeededAsync(UploadItem item, CancellationToken ct)
{
var file = new FileInfo(item.Path);
if (!file.Exists)
{
_queue.Fail(item, UploadFailure.FileMissing, null, UtcNow);
return;
}
if (file.Length != item.Size || file.LastWriteTimeUtc != item.ModifiedUtc)
{
item.Sha256 = null;
item.Size = file.Length;
item.ModifiedUtc = file.LastWriteTimeUtc;
}
if (item.Sha256 is not null) return;
var sha = await Task.Run(() => ChronosClient.HashFileAsync(item.Path, ct), ct);
file.Refresh();
if (!file.Exists || file.Length != item.Size || file.LastWriteTimeUtc != item.ModifiedUtc)
{
_queue.Fail(item, UploadFailure.FileChanged, null, UtcNow);
return;
}
item.Sha256 = sha;
_queue.OnChanged();
}
/// <summary>Creates the batch's sequence once, shared by concurrent items of the same batch.</summary>
private async Task<Guid> EnsureSequenceAsync(UploadBatch batch, CancellationToken ct)
{
if (batch.SequenceId is { } known) return known;
if (!_creating.TryGetValue(batch.Id, out var creation))
{
creation = _transport.CreateSequenceAsync(batch.Title, _lifetime.Token);
_creating[batch.Id] = creation;
}
try
{
var id = await creation.WaitAsync(ct);
batch.SequenceId = id;
_queue.OnChanged();
return id;
}
catch when (creation.IsFaulted || creation.IsCanceled)
{
_creating.Remove(batch.Id);
throw;
}
}
/// <summary>
/// BRIEF §0.2 rule 8: deletes only a file whose bytes the server received and verified by hash before committing
/// them, and only when it is still exactly the bytes that were hashed (same size and write time).
/// </summary>
private static void DeleteConfirmedSource(UploadItem item)
{
try
{
var file = new FileInfo(item.Path);
if (!file.Exists) return;
if (file.Length != item.Size || file.LastWriteTimeUtc != item.ModifiedUtc)
{
Log.Warning("upload", $"Kept {item.Path}: it changed after the server verified it");
return;
}
file.Delete();
Log.Info("upload", $"Deleted {item.Path} after the server confirmed SHA-256 {item.Sha256}");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("upload", $"Could not delete {item.Path}", ex);
}
}
private void Requeue(UploadItem item)
{
if (!item.IsActive) return;
item.State = UploadItemState.Queued;
item.BytesSent = 0;
}
private void CancelRunning()
{
foreach (var cts in _running.Values.ToList()) cts.Cancel();
}
private void Refresh()
{
BytesPerSecond = _meter.BytesPerSecond(Now);
var pending = _queue.HasPending;
Status = _queue.IsPaused && pending ? EngineStatus.Paused
: pending && !_transport.IsReady ? EngineStatus.WaitingForServer
: pending || _running.Count > 0 ? EngineStatus.Running
: EngineStatus.Idle;
if (_hadWork && !pending && _running.Count == 0)
{
_hadWork = false;
_meter.Reset();
Drained?.Invoke(this, EventArgs.Empty);
}
}
}
+142
View File
@@ -0,0 +1,142 @@
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace Chronos.Uploader.Uploads;
/// <summary>Per-file state in the upload queue (BRIEF §15).</summary>
public enum UploadItemState
{
Queued,
Hashing,
Uploading,
/// <summary>The server committed the file after checking its SHA-256.</summary>
Verified,
/// <summary>The server already held a file with the same SHA-256.</summary>
Skipped,
Failed,
}
/// <summary>Why an item failed; the UI turns it into one localized sentence.</summary>
public enum UploadFailure
{
None,
FileMissing,
FileUnreadable,
/// <summary>The file changed while it was being hashed (still being written).</summary>
FileChanged,
ServerRejected,
Unexpected,
}
/// <summary>Where a batch of files goes on the server.</summary>
public enum UploadTargetMode
{
/// <summary>The server groups files by <see cref="UploadItem.SessionKey"/> into auto-created sequences.</summary>
Sessions,
/// <summary>Every file goes to one existing sequence.</summary>
Sequence,
/// <summary>One new sequence is created for the batch with the given title.</summary>
NewSequence,
}
/// <summary>Files added together share a target; a new sequence is created once per batch, on first upload.</summary>
public sealed class UploadBatch
{
public required Guid Id { get; init; }
public required UploadTargetMode Mode { get; init; }
/// <summary>Target sequence; for <see cref="UploadTargetMode.NewSequence"/> it is filled once the server created it.</summary>
public Guid? SequenceId { get; set; }
public string? Title { get; init; }
}
/// <summary>One file in the queue. Mutated only on the queue's owning (UI) thread.</summary>
public sealed class UploadItem : INotifyPropertyChanged
{
private UploadItemState _state;
private UploadFailure _failure;
private string? _failureDetail;
private int _retries;
private long _bytesSent;
public required Guid Id { get; init; }
public required Guid BatchId { get; init; }
public required string Path { get; init; }
/// <summary>Size and write time when the file was last hashed or enqueued; a change forces a new hash.</summary>
public required long Size { get; set; }
public required DateTime ModifiedUtc { get; set; }
/// <summary>Camera wall-clock capture time (unspecified kind).</summary>
public DateTime? CapturedAt { get; init; }
public string? SessionKey { get; init; }
/// <summary>Watch folder the file came from; null for files added by hand.</summary>
public string? WatchRoot { get; init; }
public string? Sha256 { get; set; }
public Guid? FrameId { get; set; }
/// <summary>Earliest time a failed item may be retried by the queue.</summary>
public DateTime? NextRetryUtc { get; set; }
public string FileName => System.IO.Path.GetFileName(Path);
public UploadItemState State
{
get => _state;
set => Set(ref _state, value);
}
public UploadFailure Failure
{
get => _failure;
set => Set(ref _failure, value);
}
/// <summary>Server message for <see cref="UploadFailure.ServerRejected"/>, otherwise null.</summary>
public string? FailureDetail
{
get => _failureDetail;
set => Set(ref _failureDetail, value);
}
/// <summary>Queue-level retries already spent on this item.</summary>
public int Retries
{
get => _retries;
set => Set(ref _retries, value);
}
/// <summary>Bytes sent in the current attempt (progress only; not persisted).</summary>
public long BytesSent
{
get => _bytesSent;
set => Set(ref _bytesSent, value);
}
public bool IsDone => _state is UploadItemState.Verified or UploadItemState.Skipped;
public bool IsActive => _state is UploadItemState.Hashing or UploadItemState.Uploading;
public event PropertyChangedEventHandler? PropertyChanged;
/// <summary>The file name: what UI Automation reads for a queue row the list has not realized (virtualized).</summary>
public override string ToString() => FileName;
private void Set<T>(ref T field, T value, [CallerMemberName] string? name = null)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return;
field = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
+167
View File
@@ -0,0 +1,167 @@
using System.Collections.Concurrent;
using System.Collections.ObjectModel;
namespace Chronos.Uploader.Uploads;
/// <summary>A file about to be enqueued.</summary>
public sealed record QueueEntry(string Path, long Size, DateTime ModifiedUtc, DateTime? CapturedAt, string? SessionKey, string? WatchRoot);
/// <summary>
/// Ordered upload queue with its batches. Owned by the UI thread: every mutation happens there, so bindings can
/// observe <see cref="Items"/> directly. <see cref="ContainsPath"/> is the only member safe from other threads.
/// </summary>
public sealed class UploadQueue
{
/// <summary>Queue-level retries per item after the client's own transient retries (BRIEF §15).</summary>
public const int MaxRetries = 3;
/// <summary>Delay before a failed item is tried again.</summary>
public static readonly TimeSpan RetryDelay = TimeSpan.FromSeconds(30);
private readonly Dictionary<Guid, UploadBatch> _batches = [];
private readonly ConcurrentDictionary<string, byte> _paths = new(StringComparer.OrdinalIgnoreCase);
private bool _isPaused;
public ObservableCollection<UploadItem> Items { get; } = [];
public IReadOnlyCollection<UploadBatch> Batches => _batches.Values;
/// <summary>True while the user has paused the queue; persisted so a restart keeps it paused.</summary>
public bool IsPaused
{
get => _isPaused;
set
{
if (_isPaused == value) return;
_isPaused = value;
OnChanged();
}
}
/// <summary>Raised after anything that must be persisted changed.</summary>
public event EventHandler? Changed;
/// <summary>True while an item for <paramref name="path"/> is queued (any state). Thread-safe.</summary>
public bool ContainsPath(string path) => _paths.ContainsKey(path);
/// <summary>True while some item still waits for, or is in, an upload attempt (retryable failures included).</summary>
public bool HasPending => Items.Any(IsPending);
/// <summary>Appends files not already queued, in the given order, under one batch; returns how many were added.</summary>
public int Add(UploadBatch batch, IEnumerable<QueueEntry> entries)
{
var added = 0;
foreach (var e in entries)
{
if (!_paths.TryAdd(e.Path, 0)) continue;
Items.Add(new UploadItem
{
Id = Guid.CreateVersion7(),
BatchId = batch.Id,
Path = e.Path,
Size = e.Size,
ModifiedUtc = e.ModifiedUtc,
CapturedAt = e.CapturedAt,
SessionKey = e.SessionKey,
WatchRoot = e.WatchRoot,
});
added++;
}
if (added > 0)
{
_batches[batch.Id] = batch;
OnChanged();
}
return added;
}
public UploadBatch? GetBatch(Guid id) => _batches.GetValueOrDefault(id);
/// <summary>
/// The next item to work on: the first queued one, otherwise the first failed one whose retry time has come.
/// </summary>
public UploadItem? NextReady(DateTime utcNow)
{
UploadItem? retry = null;
foreach (var item in Items)
{
if (item.State == UploadItemState.Queued) return item;
if (retry is null && IsRetryDue(item, utcNow)) retry = item;
}
return retry;
}
/// <summary>Records a failure and schedules the queue-level retry when retries are left.</summary>
public void Fail(UploadItem item, UploadFailure failure, string? detail, DateTime utcNow)
{
item.State = UploadItemState.Failed;
item.Failure = failure;
item.FailureDetail = detail;
item.BytesSent = 0;
item.NextRetryUtc = item.Retries < MaxRetries ? utcNow + RetryDelay : null;
OnChanged();
}
/// <summary>Puts a failed item back in line now, with a fresh retry budget (user action).</summary>
public void Requeue(UploadItem item)
{
if (item.State != UploadItemState.Failed) return;
item.State = UploadItemState.Queued;
item.Failure = UploadFailure.None;
item.FailureDetail = null;
item.Retries = 0;
item.NextRetryUtc = null;
OnChanged();
}
/// <summary>Drops finished items (verified or skipped) so a new batch starts a fresh count.</summary>
public void RemoveCompleted()
{
var removed = false;
for (var i = Items.Count - 1; i >= 0; i--)
{
if (!Items[i].IsDone) continue;
_paths.TryRemove(Items[i].Path, out _);
Items.RemoveAt(i);
removed = true;
}
if (!removed) return;
var used = Items.Select(i => i.BatchId).ToHashSet();
foreach (var id in _batches.Keys.Where(id => !used.Contains(id)).ToList()) _batches.Remove(id);
OnChanged();
}
public void Clear()
{
Items.Clear();
_paths.Clear();
_batches.Clear();
OnChanged();
}
/// <summary>Signals a persisted-state change made directly on an item.</summary>
public void OnChanged() => Changed?.Invoke(this, EventArgs.Empty);
/// <summary>Restores a persisted queue; interrupted attempts go back to <see cref="UploadItemState.Queued"/>.</summary>
public void Restore(IEnumerable<UploadBatch> batches, IEnumerable<UploadItem> items, bool paused)
{
Items.Clear();
_paths.Clear();
_batches.Clear();
foreach (var b in batches) _batches[b.Id] = b;
foreach (var item in items)
{
if (!_batches.ContainsKey(item.BatchId) || !_paths.TryAdd(item.Path, 0)) continue;
if (item.IsActive) item.State = UploadItemState.Queued;
Items.Add(item);
}
_isPaused = paused;
}
private static bool IsPending(UploadItem item) =>
item.State is UploadItemState.Queued or UploadItemState.Hashing or UploadItemState.Uploading
|| (item.State == UploadItemState.Failed && item.NextRetryUtc is not null);
private static bool IsRetryDue(UploadItem item, DateTime utcNow) =>
item.State == UploadItemState.Failed && item.NextRetryUtc is { } due && due <= utcNow;
}
@@ -0,0 +1,165 @@
using System.IO;
using System.Text.Json.Serialization;
using System.Text.Json;
using Chronos.Core.Diagnostics;
using Chronos.Uploader.Sources;
namespace Chronos.Uploader.Watching;
/// <summary>
/// Files of each watch folder the server already confirmed, keyed by path + size + write time, so a poll never
/// uploads them again; plus the last session of each folder so new frames keep joining it. Thread-safe.
/// Persisted in <c>uploader-watch.json</c>.
/// </summary>
public sealed class ProcessedFileMemory
{
public const int Version = 1;
private readonly Lock _gate = new();
private readonly Dictionary<string, Folder> _folders = new(StringComparer.OrdinalIgnoreCase);
private bool _dirty;
/// <summary>True when something changed since the last <see cref="Serialize"/>.</summary>
public bool IsDirty
{
get
{
lock (_gate) return _dirty;
}
}
public bool Contains(string root, string path, long size, DateTime modifiedUtc)
{
lock (_gate)
{
return _folders.TryGetValue(root, out var f)
&& f.Files.TryGetValue(Relative(root, path), out var known)
&& known.Size == size && known.ModifiedTicks == modifiedUtc.Ticks;
}
}
public void Add(string root, string path, long size, DateTime modifiedUtc)
{
lock (_gate)
{
GetOrAdd(root).Files[Relative(root, path)] = new Entry(size, modifiedUtc.Ticks);
_dirty = true;
}
}
/// <summary>Forgets files of <paramref name="root"/> that a complete scan no longer found.</summary>
public void Prune(string root, IEnumerable<string> presentPaths)
{
lock (_gate)
{
if (!_folders.TryGetValue(root, out var f) || f.Files.Count == 0) return;
var present = new HashSet<string>(presentPaths.Select(p => Relative(root, p)), StringComparer.OrdinalIgnoreCase);
foreach (var key in f.Files.Keys.Where(k => !present.Contains(k)).ToList())
{
f.Files.Remove(key);
_dirty = true;
}
}
}
public void RemoveFolder(string root)
{
lock (_gate)
{
if (_folders.Remove(root)) _dirty = true;
}
}
public SessionContinuation? GetSession(string root)
{
lock (_gate) return _folders.TryGetValue(root, out var f) ? f.Session : null;
}
public void SetSession(string root, SessionContinuation? session)
{
lock (_gate)
{
GetOrAdd(root).Session = session;
_dirty = true;
}
}
public byte[] Serialize()
{
lock (_gate)
{
var file = new MemoryFile
{
Version = Version,
Folders =
[
.. _folders.Select(kv => new FolderRecord(
kv.Key,
kv.Value.Session?.Key,
kv.Value.Session?.LastCapture,
[.. kv.Value.Files.Select(f => new FileRecord(f.Key, f.Value.Size, f.Value.ModifiedTicks))])),
],
};
_dirty = false;
return JsonSerializer.SerializeToUtf8Bytes(file, WatchJson.Default.MemoryFile);
}
}
/// <summary>Loads <paramref name="path"/>; a missing or corrupt file gives an empty memory.</summary>
public static ProcessedFileMemory Load(string path)
{
var memory = new ProcessedFileMemory();
MemoryFile? file = null;
try
{
if (File.Exists(path)) file = JsonSerializer.Deserialize(File.ReadAllBytes(path), WatchJson.Default.MemoryFile);
}
catch (JsonException ex)
{
Log.Warning("watch", "Watch memory unreadable; starting empty", ex);
}
catch (IOException ex)
{
Log.Warning("watch", "Watch memory unreadable; starting empty", ex);
}
if (file is null || file.Version != Version) return memory;
foreach (var record in file.Folders)
{
var folder = memory.GetOrAdd(record.Root);
if (record.SessionKey is not null && record.LastCapture is { } last) folder.Session = new SessionContinuation(record.SessionKey, last);
foreach (var f in record.Files) folder.Files[f.Path] = new Entry(f.Size, f.Modified);
}
return memory;
}
private Folder GetOrAdd(string root)
{
if (!_folders.TryGetValue(root, out var f)) _folders[root] = f = new Folder();
return f;
}
/// <summary>Paths are stored relative to the folder to keep the file small.</summary>
private static string Relative(string root, string path) => Path.GetRelativePath(root, path);
private readonly record struct Entry(long Size, long ModifiedTicks);
private sealed class Folder
{
public Dictionary<string, Entry> Files { get; } = new(StringComparer.OrdinalIgnoreCase);
public SessionContinuation? Session { get; set; }
}
internal sealed class MemoryFile
{
public int Version { get; set; }
public List<FolderRecord> Folders { get; set; } = [];
}
internal sealed record FolderRecord(string Root, string? SessionKey, DateTime? LastCapture, List<FileRecord> Files);
internal sealed record FileRecord(string Path, long Size, long Modified);
}
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
[JsonSerializable(typeof(ProcessedFileMemory.MemoryFile))]
internal sealed partial class WatchJson : JsonSerializerContext;
@@ -0,0 +1,47 @@
namespace Chronos.Uploader.Watching;
/// <summary>Size and last-write time of a file at one check.</summary>
public readonly record struct FileObservation(string Path, long Size, DateTime ModifiedUtc);
/// <summary>
/// Decides when a file in a watch folder has stopped growing: it is reported once its size and write time were
/// identical in <see cref="RequiredChecks"/> consecutive checks, then forgotten (the caller enqueues it).
/// </summary>
public sealed class StableFileTracker
{
public const int RequiredChecks = 2;
private readonly Dictionary<string, (long Size, DateTime Modified, int Count)> _seen = new(StringComparer.OrdinalIgnoreCase);
/// <summary>Files seen but not yet stable.</summary>
public int PendingCount => _seen.Count;
/// <summary>
/// Records a complete scan: returns the files that are now stable and forgets files missing from the scan.
/// </summary>
public IReadOnlyList<FileObservation> Check(IEnumerable<FileObservation> scan)
{
var present = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var stable = new List<FileObservation>();
foreach (var o in scan)
{
present.Add(o.Path);
if (Observe(o)) stable.Add(o);
}
foreach (var path in _seen.Keys.Where(p => !present.Contains(p)).ToList()) _seen.Remove(path);
return stable;
}
/// <summary>Records one observation; true when the file just became stable.</summary>
public bool Observe(FileObservation o)
{
var count = _seen.TryGetValue(o.Path, out var last) && last.Size == o.Size && last.Modified == o.ModifiedUtc ? last.Count + 1 : 1;
if (count >= RequiredChecks)
{
_seen.Remove(o.Path);
return true;
}
_seen[o.Path] = (o.Size, o.ModifiedUtc, count);
return false;
}
}
@@ -0,0 +1,188 @@
using System.IO;
using Chronos.Core.Diagnostics;
using Chronos.Uploader.Sources;
namespace Chronos.Uploader.Watching;
/// <summary>
/// Polls each watch folder at its interval, with <see cref="FileSystemWatcher"/> hints on local disks (change
/// notifications are unreliable on network shares, which are only polled). A photo is reported once it is stable
/// (<see cref="StableFileTracker"/>), not yet confirmed by the server (<see cref="ProcessedFileMemory"/>) and not queued.
/// </summary>
public sealed class WatchFolderService(ProcessedFileMemory memory, Func<string, bool> isQueued) : IDisposable
{
/// <summary>Re-check cadence while some file is still growing.</summary>
private static readonly TimeSpan QuickCheck = TimeSpan.FromSeconds(10);
/// <summary>Lets a burst of change notifications settle before scanning.</summary>
private static readonly TimeSpan HintDebounce = TimeSpan.FromSeconds(2);
private readonly Dictionary<string, Folder> _folders = new(StringComparer.OrdinalIgnoreCase);
private readonly ProcessedFileMemory _memory = memory;
private readonly Func<string, bool> _isQueued = isQueued;
/// <summary>Stable new photos of a folder; raised on the thread that called <see cref="Watch"/>.</summary>
public event Action<string, IReadOnlyList<SourceFile>>? FilesReady;
/// <summary>A folder became reachable (true) or unreachable (false); raised like <see cref="FilesReady"/>.</summary>
public event Action<string, bool>? AvailabilityChanged;
/// <summary>UNC paths and mapped network drives.</summary>
public static bool IsNetworkPath(string path)
{
if (path.StartsWith(@"\\", StringComparison.Ordinal)) return true;
try
{
var root = Path.GetPathRoot(Path.GetFullPath(path));
return !string.IsNullOrEmpty(root) && new DriveInfo(root).DriveType == DriveType.Network;
}
catch (Exception ex) when (ex is ArgumentException or IOException)
{
return false;
}
}
/// <summary>60 s on local disks; 5 min on network shares, where every poll lists the share.</summary>
public static TimeSpan DefaultInterval(string path) => IsNetworkPath(path) ? TimeSpan.FromMinutes(5) : TimeSpan.FromSeconds(60);
/// <summary>Starts (or restarts with a new interval) watching <paramref name="root"/>.</summary>
public void Watch(string root, TimeSpan interval)
{
Stop(root);
var folder = new Folder(root, interval, IsNetworkPath(root), SynchronizationContext.Current, this);
_folders[root] = folder;
folder.Start();
}
public void Stop(string root)
{
if (_folders.Remove(root, out var folder)) folder.Dispose();
}
public void Dispose()
{
foreach (var f in _folders.Values) f.Dispose();
_folders.Clear();
}
private void Raise(SynchronizationContext? context, Action action)
{
if (context is null) action();
else context.Post(_ => action(), null);
}
private sealed class Folder(string root, TimeSpan interval, bool network, SynchronizationContext? context, WatchFolderService owner) : IDisposable
{
private readonly StableFileTracker _tracker = new();
private readonly CancellationTokenSource _cts = new();
private FileSystemWatcher? _watcher;
private TaskCompletionSource _hint = NewHint();
private bool? _available;
public void Start() => _ = Task.Run(() => LoopAsync(_cts.Token));
public void Dispose()
{
_cts.Cancel();
_watcher?.Dispose();
_watcher = null;
}
private async Task LoopAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
// Replaced before the scan so notifications arriving during it trigger the next one.
Volatile.Write(ref _hint, NewHint());
var available = Scan(ct);
if (available != _available)
{
_available = available;
if (available && !network) StartWatcher();
owner.Raise(context, () => owner.AvailabilityChanged?.Invoke(root, available));
}
var wait = _tracker.PendingCount > 0 && QuickCheck < interval ? QuickCheck : interval;
try
{
var hint = Volatile.Read(ref _hint).Task;
if (await Task.WhenAny(Task.Delay(wait, ct), hint).ConfigureAwait(false) == hint)
await Task.Delay(HintDebounce, ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
return;
}
}
}
/// <summary>One complete listing; false when the folder cannot be reached.</summary>
private bool Scan(CancellationToken ct)
{
if (!Directory.Exists(root)) return false;
var present = new List<string>();
var candidates = new Dictionary<string, FileInfo>(StringComparer.OrdinalIgnoreCase);
try
{
foreach (var file in PhotoScanner.Files(root, ct))
{
present.Add(file.FullName);
if (IsKnown(file)) continue;
candidates[file.FullName] = file;
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// A partial listing must not prune the memory or report files.
Log.Info("watch", $"{root} not readable: {ex.Message}");
return false;
}
catch (OperationCanceledException)
{
return _available ?? false;
}
owner._memory.Prune(root, present);
var stable = _tracker.Check(candidates.Values.Select(f => new FileObservation(f.FullName, f.Length, f.LastWriteTimeUtc)));
if (stable.Count > 0)
{
var files = stable.Select(o => PhotoScanner.ToSource(candidates[o.Path], root)).ToList();
Log.Info("watch", $"{files.Count} new file(s) in {root}");
owner.Raise(context, () => owner.FilesReady?.Invoke(root, files));
}
return true;
}
/// <summary>Already confirmed by the server, or already in the queue.</summary>
private bool IsKnown(FileInfo file) =>
owner._memory.Contains(root, file.FullName, file.Length, file.LastWriteTimeUtc) || owner._isQueued(file.FullName);
private void StartWatcher()
{
_watcher?.Dispose();
try
{
_watcher = new FileSystemWatcher(root)
{
IncludeSubdirectories = true,
NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.Size | NotifyFilters.LastWrite,
};
_watcher.Created += (_, _) => Hint();
_watcher.Changed += (_, _) => Hint();
_watcher.Renamed += (_, _) => Hint();
// A lost buffer means unknown changes: scan.
_watcher.Error += (_, _) => Hint();
_watcher.EnableRaisingEvents = true;
}
catch (Exception ex) when (ex is ArgumentException or IOException or PlatformNotSupportedException)
{
Log.Info("watch", $"No change notifications for {root}; polling only: {ex.Message}");
_watcher?.Dispose();
_watcher = null;
}
}
private void Hint() => Volatile.Read(ref _hint).TrySetResult();
private static TaskCompletionSource NewHint() => new(TaskCreationOptions.RunContinuationsAsynchronously);
}
}
+29
View File
@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="Chronos.Uploader" />
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
</requestedPrivileges>
</security>
</trustInfo>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- Windows 10 and Windows 11 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
</application>
</compatibility>
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2, PerMonitor</dpiAwareness>
<longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
</windowsSettings>
</application>
<dependency>
<dependentAssembly>
<assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*" />
</dependentAssembly>
</dependency>
</assembly>