using System.ComponentModel;
using System.Net;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Text.Json;
using Titano.Core.Diagnostics;
using Titano.Protocol;
using Titano.Protocol.Client;
using Titano.Uploader.Infrastructure;
using Titano.Uploader.Uploads;
namespace Titano.Uploader.Server;
/// Connection shown in the header.
public enum ConnectionState
{
/// First run: no server chosen yet.
NotConfigured,
SigningIn,
Connected,
/// Signed in, but the server cannot be reached; probed every 30 s.
Offline,
/// A server is known but there is no valid token.
SignedOut,
}
/// Outcome of the sign-in form.
public enum SignInResult
{
Success,
InvalidAddress,
Unreachable,
NotTitano,
/// The certificate is self-signed and unknown: ask the user to trust its fingerprint.
Untrusted,
BadCredentials,
Failed,
}
/// The server connection as the window sees it.
public interface IServerSession : INotifyPropertyChanged
{
ConnectionState State { get; }
/// Server address as the user typed or discovered it.
string? Address { get; }
string? Username { get; }
/// Quota in bytes; 0 = unlimited.
long QuotaBytes { get; }
long UsedBytes { get; }
/// Upload limit in MB/s; 0 = unlimited.
int BandwidthLimit { get; set; }
/// Raised when the server ended the session (token rejected or certificate changed).
event EventHandler? SessionEnded;
/// Signs in; comes with the fingerprint to show.
Task<(SignInResult Result, string? Fingerprint)> SignInAsync(string address, string username, string password, CancellationToken ct);
/// Remembers a certificate fingerprint the user confirmed (trust on first use).
void Trust(string fingerprint);
Task SignOutAsync();
/// Refreshes the account (quota) when connected.
Task RefreshAsync();
Task> ListSequencesAsync(CancellationToken ct);
}
///
/// Owns the : sign-in with trust-on-first-use, token restore from DPAPI, offline probing,
/// and the upload transport. Runs on the UI thread.
///
public sealed class ServerSession : IServerSession, IUploadTransport, IDisposable
{
private static readonly TimeSpan ProbeInterval = TimeSpan.FromSeconds(30);
private readonly UploaderSettings _settings;
private readonly Action _saveSettings;
private TitanoClient? _client;
private ConnectionState _state;
private string? _username;
private long _quotaBytes;
private long _usedBytes;
private int _bandwidthLimit;
private CancellationTokenSource? _probe;
public ServerSession(UploaderSettings settings, Action saveSettings)
{
_settings = settings;
_saveSettings = saveSettings;
_username = settings.Username;
_bandwidthLimit = Math.Max(0, settings.BandwidthLimit);
_state = settings.ServerUrl is null ? ConnectionState.NotConfigured : ConnectionState.SignedOut;
}
public event PropertyChangedEventHandler? PropertyChanged;
public event EventHandler? ReadyChanged;
public event EventHandler? SessionEnded;
public ConnectionState State
{
get => _state;
private set
{
if (_state == value) return;
var wasReady = IsReady;
_state = value;
OnPropertyChanged();
if (wasReady != IsReady) ReadyChanged?.Invoke(this, EventArgs.Empty);
}
}
public bool IsReady => _state == ConnectionState.Connected && _client is not null;
public string? Address => _settings.ServerUrl;
public string? Username
{
get => _username;
private set => Set(ref _username, value);
}
public long QuotaBytes
{
get => _quotaBytes;
private set => Set(ref _quotaBytes, value);
}
public long UsedBytes
{
get => _usedBytes;
private set => Set(ref _usedBytes, value);
}
public int BandwidthLimit
{
get => _bandwidthLimit;
set
{
if (!Set(ref _bandwidthLimit, Math.Max(0, value))) return;
ApplyBandwidth();
}
}
/// Restores the saved session, if any, in the background.
public void Start()
{
if (_settings.ServerUrl is null || _settings.ProtectedToken is null) return;
var token = TokenProtector.Unprotect(_settings.ProtectedToken);
if (token is null || !ServerAddress.TryParse(_settings.ServerUrl, out var uri))
{
Log.Warning("session", "Saved token cannot be used; sign in again");
State = ConnectionState.SignedOut;
return;
}
UseClient(CreateClient(uri));
_client!.Token = token;
State = ConnectionState.SigningIn;
_ = RefreshAsync();
}
public async Task<(SignInResult Result, string? Fingerprint)> SignInAsync(string address, string username, string password, CancellationToken ct)
{
if (!ServerAddress.TryParse(address, out var uri)) return (SignInResult.InvalidAddress, null);
StopProbing();
var previous = State;
State = ConnectionState.SigningIn;
var client = CreateClient(uri);
try
{
await client.GetInfoAsync(ct);
var login = await client.LoginAsync(username, password, ct);
if (login.Token is null) throw new TitanoApiException(HttpStatusCode.Unauthorized, new ApiError("no_token", "No token issued"));
_settings.ServerUrl = uri.ToString();
_settings.Username = login.User.Username;
_settings.ProtectedToken = TokenProtector.Protect(login.Token);
_saveSettings();
UseClient(client);
OnPropertyChanged(nameof(Address));
Username = login.User.Username;
SetQuota(login.User);
State = ConnectionState.Connected;
Log.Info("session", $"Signed in to {uri} as {login.User.Username}");
return (SignInResult.Success, null);
}
catch (Exception ex)
{
client.Dispose();
State = previous == ConnectionState.SigningIn ? ConnectionState.NotConfigured : previous;
var result = Classify(ex, ct);
if (result == SignInResult.Failed) Log.Warning("session", $"Sign-in to {uri} failed", ex);
return (result, (ex as UntrustedCertificateException)?.Fingerprint);
}
}
public void Trust(string fingerprint)
{
if (_settings.TrustedFingerprints.Contains(fingerprint, StringComparer.OrdinalIgnoreCase)) return;
_settings.TrustedFingerprints.Add(fingerprint);
_saveSettings();
Log.Info("session", $"Trusted certificate {fingerprint}");
}
public async Task SignOutAsync()
{
StopProbing();
if (_client is { Token: not null } client)
{
try
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await client.LogoutAsync(timeout.Token);
}
catch (Exception ex) when (ex is HttpRequestException or TitanoApiException or OperationCanceledException or UntrustedCertificateException)
{
// The token is forgotten locally either way.
Log.Info("session", "Logout not confirmed by the server: " + ex.Message);
}
}
ForgetToken();
}
public async Task RefreshAsync()
{
if (_client is not { } client) return;
try
{
var me = await client.MeAsync();
Username = me.Username;
SetQuota(me);
State = ConnectionState.Connected;
StopProbing();
}
catch (Exception ex) when (IsServerProblem(ex, CancellationToken.None, out var problem))
{
OnServerProblem(problem, ex);
}
catch (TitanoApiException ex)
{
Log.Warning("session", "Account refresh failed", ex);
}
}
public async Task> ListSequencesAsync(CancellationToken ct)
{
if (!IsReady) return [];
var all = new List();
string? cursor = null;
try
{
// Five pages of 200 cover any realistic choice list.
for (var page = 0; page < 5; page++)
{
var result = await _client!.ListSequencesAsync(cursor: cursor, ct: ct);
all.AddRange(result.Items);
cursor = result.NextCursor;
if (cursor is null) break;
}
}
catch (Exception ex) when (IsServerProblem(ex, ct, out var problem))
{
OnServerProblem(problem, ex);
}
catch (TitanoApiException ex)
{
Log.Warning("session", "Sequence list unavailable", ex);
}
return all;
}
// ---------------- IUploadTransport ----------------
public async Task<(UploadOutcome Outcome, Guid? FrameId)> UploadAsync(UploadItem item, Guid? sequenceId, string sha256, IProgress progress, CancellationToken ct)
{
var client = _client ?? throw new ServerUnavailableException(ServerProblem.SignedOut);
try
{
var result = await client.UploadFileAsync(item.Path, sequenceId, item.CapturedAt, item.SessionKey, sha256, progress, ct);
// The client reports an existing file as index −1 (or no frame at all).
return result is null || result.Index < 0 ? (UploadOutcome.AlreadyOnServer, result?.FrameId) : (UploadOutcome.Verified, result.FrameId);
}
catch (Exception ex) when (IsServerProblem(ex, ct, out var problem))
{
OnServerProblem(problem, ex);
throw new ServerUnavailableException(problem, ex);
}
}
public async Task CreateSequenceAsync(string? title, CancellationToken ct)
{
var client = _client ?? throw new ServerUnavailableException(ServerProblem.SignedOut);
try
{
var created = await client.CreateSequenceAsync(new CreateSequenceRequest(string.IsNullOrWhiteSpace(title) ? null : title.Trim(), null), ct);
Log.Info("session", $"Created sequence {created.Id} \"{created.DisplayTitle}\"");
return created.Id;
}
catch (Exception ex) when (IsServerProblem(ex, ct, out var problem))
{
OnServerProblem(problem, ex);
throw new ServerUnavailableException(problem, ex);
}
}
public void Dispose()
{
StopProbing();
_client?.Dispose();
}
// ---------------- Plumbing ----------------
private TitanoClient CreateClient(Uri uri)
{
// A fresh pinning per client: the protocol's last-rejected fingerprint must not outlive a trust decision.
var client = new TitanoClient(uri, new CertificatePinning(_settings.TrustedFingerprints), $"Titano Uploader ({Environment.MachineName})");
client.Bandwidth.BytesPerSecond = _bandwidthLimit * 1_000_000L;
return client;
}
private void UseClient(TitanoClient client)
{
if (ReferenceEquals(_client, client)) return;
_client?.Dispose();
_client = client;
}
private void ApplyBandwidth()
{
if (_client is not null) _client.Bandwidth.BytesPerSecond = _bandwidthLimit * 1_000_000L;
}
private void SetQuota(UserDto user)
{
QuotaBytes = user.QuotaBytes;
UsedBytes = user.UsedBytes;
}
private void ForgetToken()
{
if (_client is not null) _client.Token = null;
_settings.ProtectedToken = null;
_saveSettings();
QuotaBytes = 0;
UsedBytes = 0;
State = _settings.ServerUrl is null ? ConnectionState.NotConfigured : ConnectionState.SignedOut;
}
private bool IsServerProblem(Exception ex, CancellationToken ct, out ServerProblem problem)
{
problem = ServerProblem.Unreachable;
switch (ex)
{
case TitanoApiException { Status: HttpStatusCode.Unauthorized }:
problem = ServerProblem.SignedOut;
return true;
case TitanoApiException api:
return api.IsTransient;
case UntrustedCertificateException untrusted:
// The pinning remembers its last rejection; once trusted, a later network error can still carry it.
if (!_settings.TrustedFingerprints.Contains(untrusted.Fingerprint, StringComparer.OrdinalIgnoreCase))
problem = ServerProblem.CertificateChanged;
return true;
case HttpRequestException:
return true;
case OperationCanceledException when !ct.IsCancellationRequested:
return true; // request timeout
default:
return false;
}
}
private void OnServerProblem(ServerProblem problem, Exception ex)
{
switch (problem)
{
case ServerProblem.SignedOut:
Log.Warning("session", "The server rejected the token; signing out");
StopProbing();
ForgetToken();
SessionEnded?.Invoke(this, problem);
break;
case ServerProblem.CertificateChanged:
// Never upload to a server whose certificate changed: the user must sign in and confirm it again.
Log.Warning("session", "The server certificate changed; sign in again to review it", ex);
StopProbing();
ForgetToken();
SessionEnded?.Invoke(this, problem);
break;
default:
if (State != ConnectionState.Offline) Log.Warning("session", "Server unreachable; retrying every 30 s", ex);
State = ConnectionState.Offline;
StartProbing();
break;
}
}
private void StartProbing()
{
if (_probe is not null) return;
_probe = new CancellationTokenSource();
_ = ProbeAsync(_probe.Token);
}
private void StopProbing()
{
_probe?.Cancel();
_probe?.Dispose();
_probe = null;
}
private async Task ProbeAsync(CancellationToken ct)
{
try
{
while (!ct.IsCancellationRequested && State == ConnectionState.Offline)
{
await Task.Delay(ProbeInterval, ct);
await RefreshAsync();
}
}
catch (OperationCanceledException)
{
}
}
private static SignInResult Classify(Exception ex, CancellationToken ct) => ex switch
{
UntrustedCertificateException => SignInResult.Untrusted,
TitanoApiException { Status: HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden } => SignInResult.BadCredentials,
TitanoApiException { Status: HttpStatusCode.NotFound } => SignInResult.NotTitano,
TitanoApiException api when api.IsTransient => SignInResult.Unreachable,
JsonException or NotSupportedException => SignInResult.NotTitano,
HttpRequestException => SignInResult.Unreachable,
OperationCanceledException when !ct.IsCancellationRequested => SignInResult.Unreachable,
_ => SignInResult.Failed,
};
private bool Set(ref T field, T value, [CallerMemberName] string? name = null)
{
if (EqualityComparer.Default.Equals(field, value)) return false;
field = value;
OnPropertyChanged(name);
return true;
}
private void OnPropertyChanged([CallerMemberName] string? name = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}