Checks the certificate before sending the password and returns an unknown self-signed fingerprint for confirmation; restores the saved token, reports quota, probes every 30 s while offline, signs out when the token is rejected or the certificate changes, and maps transport failures for the engine. UDP beacon listener for servers on the LAN. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
461 lines
16 KiB
C#
461 lines
16 KiB
C#
using System.ComponentModel;
|
||
using System.Net;
|
||
using System.Net.Http;
|
||
using System.Runtime.CompilerServices;
|
||
using System.Text.Json;
|
||
using Titano.Core.Diagnostics;
|
||
using Titano.Protocol;
|
||
using Titano.Protocol.Client;
|
||
using Titano.Uploader.Infrastructure;
|
||
using Titano.Uploader.Uploads;
|
||
|
||
namespace Titano.Uploader.Server;
|
||
|
||
/// <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,
|
||
NotTitano,
|
||
|
||
/// <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="TitanoClient"/>: 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 TitanoClient? _client;
|
||
private ConnectionState _state;
|
||
private string? _username;
|
||
private long _quotaBytes;
|
||
private long _usedBytes;
|
||
private int _bandwidthLimit;
|
||
private CancellationTokenSource? _probe;
|
||
|
||
public ServerSession(UploaderSettings settings, Action saveSettings)
|
||
{
|
||
_settings = settings;
|
||
_saveSettings = saveSettings;
|
||
_username = settings.Username;
|
||
_bandwidthLimit = Math.Max(0, settings.BandwidthLimit);
|
||
_state = settings.ServerUrl is null ? ConnectionState.NotConfigured : ConnectionState.SignedOut;
|
||
}
|
||
|
||
public event PropertyChangedEventHandler? PropertyChanged;
|
||
|
||
public event EventHandler? ReadyChanged;
|
||
|
||
public event EventHandler<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 TitanoApiException(HttpStatusCode.Unauthorized, new ApiError("no_token", "No token issued"));
|
||
|
||
_settings.ServerUrl = uri.ToString();
|
||
_settings.Username = login.User.Username;
|
||
_settings.ProtectedToken = TokenProtector.Protect(login.Token);
|
||
_saveSettings();
|
||
UseClient(client);
|
||
OnPropertyChanged(nameof(Address));
|
||
Username = login.User.Username;
|
||
SetQuota(login.User);
|
||
State = ConnectionState.Connected;
|
||
Log.Info("session", $"Signed in to {uri} as {login.User.Username}");
|
||
return (SignInResult.Success, null);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
client.Dispose();
|
||
State = previous == ConnectionState.SigningIn ? ConnectionState.NotConfigured : previous;
|
||
var result = Classify(ex, ct);
|
||
if (result == SignInResult.Failed) Log.Warning("session", $"Sign-in to {uri} failed", ex);
|
||
return (result, (ex as UntrustedCertificateException)?.Fingerprint);
|
||
}
|
||
}
|
||
|
||
public void Trust(string fingerprint)
|
||
{
|
||
if (_settings.TrustedFingerprints.Contains(fingerprint, StringComparer.OrdinalIgnoreCase)) return;
|
||
_settings.TrustedFingerprints.Add(fingerprint);
|
||
_saveSettings();
|
||
Log.Info("session", $"Trusted certificate {fingerprint}");
|
||
}
|
||
|
||
public async Task SignOutAsync()
|
||
{
|
||
StopProbing();
|
||
if (_client is { Token: not null } client)
|
||
{
|
||
try
|
||
{
|
||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
|
||
await client.LogoutAsync(timeout.Token);
|
||
}
|
||
catch (Exception ex) when (ex is HttpRequestException or TitanoApiException or OperationCanceledException or UntrustedCertificateException)
|
||
{
|
||
// The token is forgotten locally either way.
|
||
Log.Info("session", "Logout not confirmed by the server: " + ex.Message);
|
||
}
|
||
}
|
||
ForgetToken();
|
||
}
|
||
|
||
public async Task RefreshAsync()
|
||
{
|
||
if (_client is not { } client) return;
|
||
try
|
||
{
|
||
var me = await client.MeAsync();
|
||
Username = me.Username;
|
||
SetQuota(me);
|
||
State = ConnectionState.Connected;
|
||
StopProbing();
|
||
}
|
||
catch (Exception ex) when (IsServerProblem(ex, CancellationToken.None, out var problem))
|
||
{
|
||
OnServerProblem(problem, ex);
|
||
}
|
||
catch (TitanoApiException ex)
|
||
{
|
||
Log.Warning("session", "Account refresh failed", ex);
|
||
}
|
||
}
|
||
|
||
public async Task<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 (TitanoApiException ex)
|
||
{
|
||
Log.Warning("session", "Sequence list unavailable", ex);
|
||
}
|
||
return all;
|
||
}
|
||
|
||
// ---------------- IUploadTransport ----------------
|
||
|
||
public async Task<(UploadOutcome Outcome, Guid? FrameId)> UploadAsync(UploadItem item, Guid? sequenceId, string sha256, IProgress<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 TitanoClient CreateClient(Uri uri)
|
||
{
|
||
// A fresh pinning per client: the protocol's last-rejected fingerprint must not outlive a trust decision.
|
||
var client = new TitanoClient(uri, new CertificatePinning(_settings.TrustedFingerprints), $"Titano Uploader ({Environment.MachineName})");
|
||
client.Bandwidth.BytesPerSecond = _bandwidthLimit * 1_000_000L;
|
||
return client;
|
||
}
|
||
|
||
private void UseClient(TitanoClient client)
|
||
{
|
||
if (ReferenceEquals(_client, client)) return;
|
||
_client?.Dispose();
|
||
_client = client;
|
||
}
|
||
|
||
private void ApplyBandwidth()
|
||
{
|
||
if (_client is not null) _client.Bandwidth.BytesPerSecond = _bandwidthLimit * 1_000_000L;
|
||
}
|
||
|
||
private void SetQuota(UserDto user)
|
||
{
|
||
QuotaBytes = user.QuotaBytes;
|
||
UsedBytes = user.UsedBytes;
|
||
}
|
||
|
||
private void ForgetToken()
|
||
{
|
||
if (_client is not null) _client.Token = null;
|
||
_settings.ProtectedToken = null;
|
||
_saveSettings();
|
||
QuotaBytes = 0;
|
||
UsedBytes = 0;
|
||
State = _settings.ServerUrl is null ? ConnectionState.NotConfigured : ConnectionState.SignedOut;
|
||
}
|
||
|
||
private bool IsServerProblem(Exception ex, CancellationToken ct, out ServerProblem problem)
|
||
{
|
||
problem = ServerProblem.Unreachable;
|
||
switch (ex)
|
||
{
|
||
case TitanoApiException { Status: HttpStatusCode.Unauthorized }:
|
||
problem = ServerProblem.SignedOut;
|
||
return true;
|
||
case TitanoApiException api:
|
||
return api.IsTransient;
|
||
case UntrustedCertificateException untrusted:
|
||
// The pinning remembers its last rejection; once trusted, a later network error can still carry it.
|
||
if (!_settings.TrustedFingerprints.Contains(untrusted.Fingerprint, StringComparer.OrdinalIgnoreCase))
|
||
problem = ServerProblem.CertificateChanged;
|
||
return true;
|
||
case HttpRequestException:
|
||
return true;
|
||
case OperationCanceledException when !ct.IsCancellationRequested:
|
||
return true; // request timeout
|
||
default:
|
||
return false;
|
||
}
|
||
}
|
||
|
||
private void OnServerProblem(ServerProblem problem, Exception ex)
|
||
{
|
||
switch (problem)
|
||
{
|
||
case ServerProblem.SignedOut:
|
||
Log.Warning("session", "The server rejected the token; signing out");
|
||
StopProbing();
|
||
ForgetToken();
|
||
SessionEnded?.Invoke(this, problem);
|
||
break;
|
||
case ServerProblem.CertificateChanged:
|
||
// Never upload to a server whose certificate changed: the user must sign in and confirm it again.
|
||
Log.Warning("session", "The server certificate changed; sign in again to review it", ex);
|
||
StopProbing();
|
||
ForgetToken();
|
||
SessionEnded?.Invoke(this, problem);
|
||
break;
|
||
default:
|
||
if (State != ConnectionState.Offline) Log.Warning("session", "Server unreachable; retrying every 30 s", ex);
|
||
State = ConnectionState.Offline;
|
||
StartProbing();
|
||
break;
|
||
}
|
||
}
|
||
|
||
private void StartProbing()
|
||
{
|
||
if (_probe is not null) return;
|
||
_probe = new CancellationTokenSource();
|
||
_ = ProbeAsync(_probe.Token);
|
||
}
|
||
|
||
private void StopProbing()
|
||
{
|
||
_probe?.Cancel();
|
||
_probe?.Dispose();
|
||
_probe = null;
|
||
}
|
||
|
||
private async Task ProbeAsync(CancellationToken ct)
|
||
{
|
||
try
|
||
{
|
||
while (!ct.IsCancellationRequested && State == ConnectionState.Offline)
|
||
{
|
||
await Task.Delay(ProbeInterval, ct);
|
||
await RefreshAsync();
|
||
}
|
||
}
|
||
catch (OperationCanceledException)
|
||
{
|
||
}
|
||
}
|
||
|
||
private static SignInResult Classify(Exception ex, CancellationToken ct) => ex switch
|
||
{
|
||
UntrustedCertificateException => SignInResult.Untrusted,
|
||
TitanoApiException { Status: HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden } => SignInResult.BadCredentials,
|
||
TitanoApiException { Status: HttpStatusCode.NotFound } => SignInResult.NotTitano,
|
||
TitanoApiException api when api.IsTransient => SignInResult.Unreachable,
|
||
JsonException or NotSupportedException => SignInResult.NotTitano,
|
||
HttpRequestException => SignInResult.Unreachable,
|
||
OperationCanceledException when !ct.IsCancellationRequested => SignInResult.Unreachable,
|
||
_ => SignInResult.Failed,
|
||
};
|
||
|
||
private bool Set<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));
|
||
}
|