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
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:
1 parent
c99842cc86
commit
f2b58522b9
1801 files changed
+11804
-10676
No files matched your search
@@ -0,0 +1,305 @@
|
||||
using System.Diagnostics;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Protocol.Client;
|
||||
|
||||
namespace Chronos.App.Server;
|
||||
|
||||
/// <summary>The calls the connection makes; implemented over <see cref="ChronosClient"/>, faked in tests.</summary>
|
||||
public interface IServerApi : IDisposable
|
||||
{
|
||||
Uri BaseAddress { get; }
|
||||
|
||||
/// <summary>Bearer token sent with every request.</summary>
|
||||
string? Token { get; set; }
|
||||
|
||||
/// <summary>Throws <see cref="UntrustedCertificateException"/> while the certificate is neither valid nor trusted.</summary>
|
||||
Task<ServerInfo> GetInfoAsync(CancellationToken ct);
|
||||
|
||||
Task<LoginResponse> LoginAsync(string username, string password, CancellationToken ct);
|
||||
|
||||
Task<UserDto> MeAsync(CancellationToken ct);
|
||||
|
||||
Task LogoutAsync(CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>Creates API clients pinned to the certificates the user trusts.</summary>
|
||||
public interface IServerApiFactory
|
||||
{
|
||||
IServerApi Create(Uri baseAddress, IReadOnlyCollection<string> trustedFingerprints);
|
||||
}
|
||||
|
||||
/// <summary>Certificates trusted on first use (persisted in the settings).</summary>
|
||||
public interface ITrustStore
|
||||
{
|
||||
IReadOnlyCollection<string> Fingerprints { get; }
|
||||
|
||||
void Trust(string server, string fingerprint);
|
||||
}
|
||||
|
||||
/// <summary>Where the connection stands (BRIEF §12.7).</summary>
|
||||
public enum ConnectStep
|
||||
{
|
||||
/// <summary>Nothing started, or signed out.</summary>
|
||||
Idle,
|
||||
|
||||
/// <summary>Reading the server's identity (no credentials are sent).</summary>
|
||||
Probing,
|
||||
|
||||
/// <summary>The certificate is self-signed and unknown: the user must confirm its fingerprint first.</summary>
|
||||
AwaitingTrust,
|
||||
|
||||
/// <summary>The server is identified and trusted: the login form may send the password.</summary>
|
||||
AwaitingCredentials,
|
||||
|
||||
SigningIn,
|
||||
Connected,
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// <summary>Why the last step failed.</summary>
|
||||
public enum ConnectError
|
||||
{
|
||||
None,
|
||||
InvalidAddress,
|
||||
Unreachable,
|
||||
NotChronos,
|
||||
Untrusted,
|
||||
BadCredentials,
|
||||
|
||||
/// <summary>A saved session was rejected (expired or revoked token); sign in again.</summary>
|
||||
SessionExpired,
|
||||
|
||||
/// <summary>The certificate differs from the trusted one; the saved session was dropped.</summary>
|
||||
CertificateChanged,
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Trust-on-first-use connection state machine, mirroring the uploader: the server's identity is read first
|
||||
/// (<c>GET server/info</c>, which needs no credentials); a self-signed certificate that is not trusted yet stops the
|
||||
/// flow at <see cref="ConnectStep.AwaitingTrust"/> until the user confirms its fingerprint; only then can
|
||||
/// <see cref="SignInAsync"/> send the password. A saved token is restored the same way, and a changed certificate
|
||||
/// never reuses it. Not thread-safe; drive it from the UI.
|
||||
/// </summary>
|
||||
public sealed class ConnectFlow(IServerApiFactory factory, ITrustStore trust) : IDisposable
|
||||
{
|
||||
private IServerApi? _api;
|
||||
|
||||
public ConnectStep Step { get; private set; } = ConnectStep.Idle;
|
||||
public ConnectError Error { get; private set; }
|
||||
|
||||
/// <summary>Normalised API base ("https://nas.local:8443/").</summary>
|
||||
public Uri? Address { get; private set; }
|
||||
|
||||
/// <summary>The fingerprint waiting for the user's decision.</summary>
|
||||
public string? PendingFingerprint { get; private set; }
|
||||
|
||||
public ServerInfo? Info { get; private set; }
|
||||
public UserDto? User { get; private set; }
|
||||
|
||||
/// <summary>Round trip of the identity request.</summary>
|
||||
public TimeSpan? Latency { get; private set; }
|
||||
|
||||
/// <summary>The token of the signed-in session (store it encrypted).</summary>
|
||||
public string? Token => Step == ConnectStep.Connected ? _api?.Token : null;
|
||||
|
||||
/// <summary>The signed-in client, for the screens that talk to the server.</summary>
|
||||
public IServerApi? Api => Step == ConnectStep.Connected ? _api : null;
|
||||
|
||||
/// <summary>Raised after every step change.</summary>
|
||||
public event EventHandler? Changed;
|
||||
|
||||
/// <summary>Identifies the server at <paramref name="address"/>: ends in AwaitingTrust, AwaitingCredentials or Failed.</summary>
|
||||
public async Task<ConnectStep> ProbeAsync(string address, CancellationToken ct = default)
|
||||
{
|
||||
Reset();
|
||||
if (!ServerAddress.TryParse(address, out var uri)) return Fail(ConnectError.InvalidAddress);
|
||||
Address = uri;
|
||||
return await IdentifyAsync(ct);
|
||||
}
|
||||
|
||||
/// <summary>The user's answer to the fingerprint question; trusting it identifies the server again.</summary>
|
||||
public async Task<ConnectStep> ConfirmTrustAsync(bool trusted, CancellationToken ct = default)
|
||||
{
|
||||
if (Step != ConnectStep.AwaitingTrust || PendingFingerprint is null || Address is null) return Step;
|
||||
if (!trusted) return Fail(ConnectError.Untrusted);
|
||||
trust.Trust(ServerAddress.Display(Address), PendingFingerprint);
|
||||
PendingFingerprint = null;
|
||||
return await IdentifyAsync(ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends the credentials; only possible once the server is identified and trusted. An answer that arrives after the
|
||||
/// flow moved on (disconnected, or connecting elsewhere) changes nothing.
|
||||
/// </summary>
|
||||
public async Task<ConnectStep> SignInAsync(string username, string password, CancellationToken ct = default)
|
||||
{
|
||||
if (Step is not (ConnectStep.AwaitingCredentials or ConnectStep.SigningIn) || _api is not { } api) return Step;
|
||||
if (string.IsNullOrWhiteSpace(username)) return Retry(ConnectError.BadCredentials);
|
||||
Set(ConnectStep.SigningIn, ConnectError.None);
|
||||
try
|
||||
{
|
||||
var login = await api.LoginAsync(username.Trim(), password, ct);
|
||||
if (!ReferenceEquals(api, _api)) return Step;
|
||||
if (login.Token is null) return Retry(ConnectError.BadCredentials);
|
||||
// ChronosClient keeps the token itself; set it explicitly so every IServerApi behaves the same.
|
||||
api.Token = login.Token;
|
||||
User = login.User;
|
||||
return Set(ConnectStep.Connected, ConnectError.None);
|
||||
}
|
||||
catch (Exception ex) when (Classify(ex, ct) is { } error)
|
||||
{
|
||||
if (!ReferenceEquals(api, _api)) return Step;
|
||||
return error is ConnectError.BadCredentials ? Retry(error) : Fail(error);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Resumes a saved session: Connected, or AwaitingCredentials/AwaitingTrust when it cannot be reused.</summary>
|
||||
public async Task<ConnectStep> RestoreAsync(string address, string token, CancellationToken ct = default)
|
||||
{
|
||||
Reset();
|
||||
if (!ServerAddress.TryParse(address, out var uri)) return Fail(ConnectError.InvalidAddress);
|
||||
Address = uri;
|
||||
if (await IdentifyAsync(ct) != ConnectStep.AwaitingCredentials)
|
||||
{
|
||||
// Never resend a token to a server whose certificate is no longer the trusted one.
|
||||
if (Step == ConnectStep.AwaitingTrust) Error = ConnectError.CertificateChanged;
|
||||
Changed?.Invoke(this, EventArgs.Empty);
|
||||
return Step;
|
||||
}
|
||||
_api!.Token = token;
|
||||
try
|
||||
{
|
||||
User = await _api.MeAsync(ct);
|
||||
return Set(ConnectStep.Connected, ConnectError.None);
|
||||
}
|
||||
catch (Exception ex) when (Classify(ex, ct) is { } error)
|
||||
{
|
||||
_api.Token = null;
|
||||
return error is ConnectError.BadCredentials ? Retry(ConnectError.SessionExpired) : Fail(error);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Ends the session on the server (best effort) and forgets it here.</summary>
|
||||
public async Task SignOutAsync()
|
||||
{
|
||||
if (_api is { Token: not null } api)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
|
||||
await api.LogoutAsync(timeout.Token);
|
||||
}
|
||||
catch (Exception ex) when (ex is HttpRequestException or ChronosApiException or OperationCanceledException or UntrustedCertificateException)
|
||||
{
|
||||
// The token is forgotten locally either way.
|
||||
}
|
||||
}
|
||||
Reset();
|
||||
Changed?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
/// <summary>Drops the connection without signing out (the saved token stays valid).</summary>
|
||||
public void Disconnect()
|
||||
{
|
||||
Reset();
|
||||
Changed?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
public void Dispose() => Reset();
|
||||
|
||||
private async Task<ConnectStep> IdentifyAsync(CancellationToken ct)
|
||||
{
|
||||
Set(ConnectStep.Probing, ConnectError.None);
|
||||
_api?.Dispose();
|
||||
_api = factory.Create(Address!, trust.Fingerprints);
|
||||
try
|
||||
{
|
||||
var clock = Stopwatch.StartNew();
|
||||
Info = await _api.GetInfoAsync(ct);
|
||||
Latency = clock.Elapsed;
|
||||
return Set(ConnectStep.AwaitingCredentials, ConnectError.None);
|
||||
}
|
||||
catch (UntrustedCertificateException untrusted)
|
||||
{
|
||||
PendingFingerprint = untrusted.Fingerprint;
|
||||
return Set(ConnectStep.AwaitingTrust, ConnectError.None);
|
||||
}
|
||||
catch (Exception ex) when (Classify(ex, ct) is { } error)
|
||||
{
|
||||
return Fail(error);
|
||||
}
|
||||
}
|
||||
|
||||
private void Reset()
|
||||
{
|
||||
_api?.Dispose();
|
||||
_api = null;
|
||||
Step = ConnectStep.Idle;
|
||||
Error = ConnectError.None;
|
||||
Address = null;
|
||||
PendingFingerprint = null;
|
||||
Info = null;
|
||||
User = null;
|
||||
Latency = null;
|
||||
}
|
||||
|
||||
private ConnectStep Set(ConnectStep step, ConnectError error)
|
||||
{
|
||||
Step = step;
|
||||
Error = error;
|
||||
Changed?.Invoke(this, EventArgs.Empty);
|
||||
return step;
|
||||
}
|
||||
|
||||
/// <summary>Back to the login form with an error (wrong password, expired session).</summary>
|
||||
private ConnectStep Retry(ConnectError error) => Set(ConnectStep.AwaitingCredentials, error);
|
||||
|
||||
private ConnectStep Fail(ConnectError error)
|
||||
{
|
||||
_api?.Dispose();
|
||||
_api = null;
|
||||
return Set(ConnectStep.Failed, error);
|
||||
}
|
||||
|
||||
/// <summary>Expected failures as an error code; null lets unexpected exceptions propagate.</summary>
|
||||
internal static ConnectError? Classify(Exception ex, CancellationToken ct) => ex switch
|
||||
{
|
||||
UntrustedCertificateException => ConnectError.Untrusted,
|
||||
ChronosApiException { Status: HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden } => ConnectError.BadCredentials,
|
||||
ChronosApiException { Status: HttpStatusCode.NotFound } => ConnectError.NotChronos,
|
||||
ChronosApiException api when api.IsTransient => ConnectError.Unreachable,
|
||||
ChronosApiException => ConnectError.Failed,
|
||||
JsonException or NotSupportedException => ConnectError.NotChronos,
|
||||
HttpRequestException => ConnectError.Unreachable,
|
||||
OperationCanceledException when !ct.IsCancellationRequested => ConnectError.Unreachable,
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Server addresses as typed in the address field.</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;
|
||||
}
|
||||
|
||||
/// <summary>The address as shown in the field: the base URL without its trailing slash.</summary>
|
||||
public static string Display(Uri uri) => uri.ToString().TrimEnd('/');
|
||||
|
||||
/// <summary>Same, for stored text.</summary>
|
||||
public static string Display(string? address) => address?.TrimEnd('/') ?? string.Empty;
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
using Chronos.App.Editor;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Protocol.Client;
|
||||
|
||||
namespace Chronos.App.Server;
|
||||
|
||||
/// <summary>Makes the connection of the editor of a server sequence for a signed-in session.</summary>
|
||||
public delegate IRemoteSequenceApi RemoteSequenceApiFactory(Uri address, string token, IReadOnlyCollection<string> trustedFingerprints);
|
||||
|
||||
/// <summary><see cref="IRemoteSequenceApi"/> over a signed-in <see cref="ChronosClient"/>, which it owns.</summary>
|
||||
public sealed class ChronosRemoteSequenceApi(ChronosClient client) : IRemoteSequenceApi
|
||||
{
|
||||
private static readonly JobState[] ActiveStates = [JobState.Queued, JobState.Running, JobState.Paused];
|
||||
private static readonly JobKind[] EditorKinds = [JobKind.DeepAnalyse, JobKind.LightAnalyse, JobKind.Render];
|
||||
|
||||
public Task<SequenceDto> GetSequenceAsync(Guid id, CancellationToken cancellationToken) => client.GetSequenceAsync(id, cancellationToken);
|
||||
|
||||
public Task<SequenceManifest> GetManifestAsync(Guid id, CancellationToken cancellationToken) => client.GetManifestAsync(id, cancellationToken);
|
||||
|
||||
public Task<SequenceDto> UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken) =>
|
||||
client.UpdateSequenceAsync(id, request, cancellationToken);
|
||||
|
||||
public Task<string?> GetAnalysisReportAsync(Guid id, CancellationToken cancellationToken) => client.GetAnalysisReportAsync(id, cancellationToken);
|
||||
|
||||
public Task<JobDto> CreateJobAsync(CreateJobRequest request, CancellationToken cancellationToken) => client.CreateJobAsync(request, cancellationToken);
|
||||
|
||||
public Task<JobDto> GetJobAsync(Guid id, CancellationToken cancellationToken) => client.GetJobAsync(id, cancellationToken);
|
||||
|
||||
/// <summary>Filtered by state and kind and read to the last page: a busy server queues thumbnails and proxies by the thousand.</summary>
|
||||
public async Task<IReadOnlyList<JobDto>> ListActiveJobsAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var jobs = new List<JobDto>();
|
||||
foreach (var state in ActiveStates)
|
||||
{
|
||||
foreach (var kind in EditorKinds)
|
||||
{
|
||||
string? cursor = null;
|
||||
do
|
||||
{
|
||||
var page = await client.ListJobsAsync(JobWire.State(state), JobWire.Kind(kind), cursor, cancellationToken);
|
||||
jobs.AddRange(page.Items);
|
||||
cursor = page.NextCursor;
|
||||
}
|
||||
while (cursor is not null);
|
||||
}
|
||||
}
|
||||
return jobs;
|
||||
}
|
||||
|
||||
public Task<JobDto> CancelJobAsync(Guid id, CancellationToken cancellationToken) => client.CancelJobAsync(id, cancellationToken);
|
||||
|
||||
public Task<JobDto> RetryJobAsync(Guid id, CancellationToken cancellationToken) => client.RetryJobAsync(id, cancellationToken);
|
||||
|
||||
public Task<JobDto> SetJobPriorityAsync(Guid id, string priority, CancellationToken cancellationToken) =>
|
||||
client.SetJobPriorityAsync(id, priority, cancellationToken);
|
||||
|
||||
public IAsyncEnumerable<ServerEvent> EventsAsync(CancellationToken cancellationToken) => client.EventsAsync(cancellationToken);
|
||||
|
||||
public void Dispose() => client.Dispose();
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Security.Cryptography;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Windows.Security;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Protocol.Client;
|
||||
|
||||
namespace Chronos.App.Server;
|
||||
|
||||
/// <summary><see cref="IServerApi"/> over the protocol's <see cref="ChronosClient"/>.</summary>
|
||||
public sealed class ChronosServerApi(ChronosClient client) : IServerApi
|
||||
{
|
||||
public ChronosClient Client { get; } = client;
|
||||
|
||||
public Uri BaseAddress => Client.BaseAddress;
|
||||
|
||||
public string? Token
|
||||
{
|
||||
get => Client.Token;
|
||||
set => Client.Token = value;
|
||||
}
|
||||
|
||||
public Task<ServerInfo> GetInfoAsync(CancellationToken ct) => Client.GetInfoAsync(ct);
|
||||
|
||||
public Task<LoginResponse> LoginAsync(string username, string password, CancellationToken ct) => Client.LoginAsync(username, password, ct);
|
||||
|
||||
public Task<UserDto> MeAsync(CancellationToken ct) => Client.MeAsync(ct);
|
||||
|
||||
public Task LogoutAsync(CancellationToken ct) => Client.LogoutAsync(ct);
|
||||
|
||||
public void Dispose() => Client.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>Creates <see cref="ChronosServerApi"/> clients with a fresh certificate pinning per connection attempt.</summary>
|
||||
public sealed class ChronosServerApiFactory : IServerApiFactory
|
||||
{
|
||||
public IServerApi Create(Uri baseAddress, IReadOnlyCollection<string> trustedFingerprints) =>
|
||||
// A fresh pinning per client: the last rejected fingerprint must not outlive a trust decision.
|
||||
new ChronosServerApi(new ChronosClient(baseAddress, new CertificatePinning(trustedFingerprints), $"Chronos ({Environment.MachineName})"));
|
||||
}
|
||||
|
||||
/// <summary>Encrypts the session token at rest.</summary>
|
||||
public interface ITokenProtector
|
||||
{
|
||||
string Protect(string token);
|
||||
|
||||
/// <summary>The token, or null when the blob is corrupt or belongs to another Windows user.</summary>
|
||||
string? Unprotect(string protectedToken);
|
||||
}
|
||||
|
||||
/// <summary>DPAPI, current-user scope, with entropy that ties the blob to the desktop client.</summary>
|
||||
public sealed class DpapiTokenProtector : ITokenProtector
|
||||
{
|
||||
private static readonly byte[] Entropy = "Chronos.App.Token.v1"u8.ToArray();
|
||||
|
||||
public string Protect(string token) => Dpapi.ProtectString(token, Entropy);
|
||||
|
||||
public string? Unprotect(string protectedToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Dpapi.UnprotectString(protectedToken, Entropy);
|
||||
}
|
||||
catch (Exception ex) when (ex is FormatException or CryptographicException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <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"/>) 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 synchronization context of the thread that called <see cref="Start"/>.</summary>
|
||||
public event Action<DiscoveredServer>? Found;
|
||||
|
||||
public bool IsRunning => _cts is not null;
|
||||
|
||||
public void Start()
|
||||
{
|
||||
if (_cts is not null) return;
|
||||
_cts = new CancellationTokenSource();
|
||||
var context = SynchronizationContext.Current;
|
||||
var token = _cts.Token;
|
||||
_ = Task.Run(() => ListenAsync(context, token));
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_cts?.Cancel();
|
||||
_cts?.Dispose();
|
||||
_cts = null;
|
||||
}
|
||||
|
||||
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 uploader 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);
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Server;
|
||||
|
||||
/// <summary>
|
||||
/// The client's server connection (BRIEF §12.7): drives <see cref="ConnectFlow"/> with the dialogs (fingerprint
|
||||
/// confirmation before any password is sent, login form), keeps the session token encrypted with DPAPI in the
|
||||
/// settings, restores it at start, and lists servers announced on the LAN. Runs on the UI thread.
|
||||
/// </summary>
|
||||
public sealed class ServerSession : ObservableObject, ITrustStore, IDisposable
|
||||
{
|
||||
private readonly AppSettings _settings;
|
||||
private readonly Action _save;
|
||||
private readonly ITokenProtector _protector;
|
||||
private readonly ConnectFlow _flow;
|
||||
private DiscoveryListener? _discovery;
|
||||
private bool _busy;
|
||||
|
||||
public ServerSession(AppSettings settings, Action save, IServerApiFactory factory, ITokenProtector protector)
|
||||
{
|
||||
_settings = settings;
|
||||
_save = save;
|
||||
_protector = protector;
|
||||
_flow = new ConnectFlow(factory, this);
|
||||
_flow.Changed += (_, _) => OnAllPropertiesChanged();
|
||||
}
|
||||
|
||||
public ConnectFlow Flow => _flow;
|
||||
|
||||
/// <summary>Servers that announced themselves on this network.</summary>
|
||||
public ObservableCollection<DiscoveredServer> Discovered { get; } = [];
|
||||
|
||||
public bool IsConnected => _flow.Step == ConnectStep.Connected;
|
||||
|
||||
/// <summary>A connection attempt is running.</summary>
|
||||
public bool IsBusy
|
||||
{
|
||||
get => _busy;
|
||||
private set => Set(ref _busy, value);
|
||||
}
|
||||
|
||||
/// <summary>Server name for the status strip; null when not connected.</summary>
|
||||
public string? ServerName => IsConnected ? _flow.Info?.Name : null;
|
||||
|
||||
/// <summary>The saved address (last server used).</summary>
|
||||
public string? SavedAddress => _settings.ServerUrl;
|
||||
|
||||
/// <summary>The token of the saved session is present (Disconnect keeps it).</summary>
|
||||
public bool HasSavedSession => _settings.ServerUrl is not null && _settings.ProtectedToken is not null;
|
||||
|
||||
// ---------------- ITrustStore ----------------
|
||||
|
||||
public IReadOnlyCollection<string> Fingerprints => [.. _settings.TrustedCertificates.Select(c => c.Fingerprint)];
|
||||
|
||||
public void Trust(string server, string fingerprint)
|
||||
{
|
||||
if (_settings.TrustedCertificates.Any(c => c.Fingerprint.Equals(fingerprint, StringComparison.OrdinalIgnoreCase))) return;
|
||||
_settings.TrustedCertificates.Add(new TrustedCertificate { Fingerprint = fingerprint, Server = server, TrustedAt = DateTimeOffset.UtcNow });
|
||||
_save();
|
||||
Log.Info("server", $"Trusted certificate {fingerprint} of {server}");
|
||||
}
|
||||
|
||||
/// <summary>The trust record of a fingerprint, if the user trusted it.</summary>
|
||||
public TrustedCertificate? TrustOf(string? fingerprint) =>
|
||||
fingerprint is null ? null : _settings.TrustedCertificates.FirstOrDefault(c => c.Fingerprint.Equals(fingerprint, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
/// <summary>Forgets a trusted certificate; the next connection asks again.</summary>
|
||||
public void Forget(string fingerprint)
|
||||
{
|
||||
if (_settings.TrustedCertificates.RemoveAll(c => c.Fingerprint.Equals(fingerprint, StringComparison.OrdinalIgnoreCase)) == 0) return;
|
||||
_save();
|
||||
OnAllPropertiesChanged();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Forgets a trusted certificate once the user confirmed it (Server screen and Settings › Server alike); the session
|
||||
/// that relies on it is closed first. True when it was forgotten.
|
||||
/// </summary>
|
||||
public bool ConfirmForget(string fingerprint, IAppDialogs dialogs)
|
||||
{
|
||||
if (!dialogs.Confirm(ForgetRequest(fingerprint))) return false;
|
||||
if (IsConnected && string.Equals(TrustOf(_flow.Info?.TlsFingerprint)?.Fingerprint, fingerprint, StringComparison.OrdinalIgnoreCase)) Disconnect();
|
||||
Forget(fingerprint);
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---------------- Session ----------------
|
||||
|
||||
/// <summary>Resumes the saved session at start; stays signed out quietly when it cannot be reused.</summary>
|
||||
public async Task RestoreAsync(CancellationToken ct = default)
|
||||
{
|
||||
if (_settings.ServerUrl is not { } address || _settings.ProtectedToken is not { } blob) return;
|
||||
var token = _protector.Unprotect(blob);
|
||||
if (token is null)
|
||||
{
|
||||
Log.Warning("server", "The saved session cannot be decrypted; sign in again");
|
||||
ForgetToken();
|
||||
return;
|
||||
}
|
||||
IsBusy = true;
|
||||
try
|
||||
{
|
||||
var step = await _flow.RestoreAsync(address, token, ct);
|
||||
if (step == ConnectStep.Connected) Log.Info("server", $"Session restored on {address}");
|
||||
else if (_flow.Error is ConnectError.SessionExpired or ConnectError.CertificateChanged) ForgetToken();
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Connects to <paramref name="address"/>: identifies the server, asks to trust an unknown self-signed
|
||||
/// certificate, then reuses the saved session or shows the login form. True when connected.
|
||||
/// </summary>
|
||||
public async Task<bool> ConnectAsync(string address, IAppDialogs dialogs, CancellationToken ct = default)
|
||||
{
|
||||
IsBusy = true;
|
||||
try
|
||||
{
|
||||
var step = await _flow.ProbeAsync(address, ct);
|
||||
if (step == ConnectStep.AwaitingTrust && _flow.PendingFingerprint is { } fingerprint)
|
||||
{
|
||||
var trusted = dialogs.Confirm(TrustRequest(ServerAddress.Display(_flow.Address!), fingerprint));
|
||||
step = await _flow.ConfirmTrustAsync(trusted, ct);
|
||||
}
|
||||
if (step != ConnectStep.AwaitingCredentials) return false;
|
||||
|
||||
var display = ServerAddress.Display(_flow.Address!);
|
||||
if (HasSavedSession && ServerAddress.Display(_settings.ServerUrl) == display && _protector.Unprotect(_settings.ProtectedToken!) is { } token)
|
||||
{
|
||||
step = await _flow.RestoreAsync(display, token, ct);
|
||||
if (step == ConnectStep.Connected)
|
||||
{
|
||||
Remember();
|
||||
return true;
|
||||
}
|
||||
if (step != ConnectStep.AwaitingCredentials) return false;
|
||||
}
|
||||
|
||||
// The form may be cancelled while the server is still answering: that answer must not sign this PC in.
|
||||
using var attempt = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
var signedIn = dialogs.SignIn(display, _settings.ServerUsername, async (user, password) =>
|
||||
{
|
||||
var result = await _flow.SignInAsync(user, password, attempt.Token);
|
||||
// An answer the flow dropped (the form was cancelled meanwhile) carries no error of its own.
|
||||
return result == ConnectStep.Connected ? null : ErrorText(_flow.Error is ConnectError.None ? ConnectError.Failed : _flow.Error);
|
||||
});
|
||||
if (signedIn && IsConnected)
|
||||
{
|
||||
Remember();
|
||||
return true;
|
||||
}
|
||||
await attempt.CancelAsync();
|
||||
// Signed in just before the cancel was handled: the session the user turned down ends on the server too.
|
||||
if (IsConnected) await _flow.SignOutAsync();
|
||||
else if (_flow.Step is ConnectStep.AwaitingCredentials or ConnectStep.SigningIn) _flow.Disconnect();
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Signs out on the server and removes the token from this PC.</summary>
|
||||
public async Task SignOutAsync()
|
||||
{
|
||||
await _flow.SignOutAsync();
|
||||
ForgetToken();
|
||||
}
|
||||
|
||||
/// <summary>Closes the connection and works locally; the saved session is kept for the next Connect.</summary>
|
||||
public void Disconnect() => _flow.Disconnect();
|
||||
|
||||
public void StartDiscovery()
|
||||
{
|
||||
if (_discovery is not null) return;
|
||||
_discovery = new DiscoveryListener();
|
||||
_discovery.Found += server =>
|
||||
{
|
||||
if (Discovered.Any(d => d.Address.Equals(server.Address, StringComparison.OrdinalIgnoreCase))) return;
|
||||
Discovered.Add(server);
|
||||
};
|
||||
_discovery.Start();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_discovery?.Dispose();
|
||||
_discovery = null;
|
||||
_flow.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>One sentence for a failed step (BRIEF §0.2 rule 6).</summary>
|
||||
public static string ErrorText(ConnectError error) => Loc.L("Server.Error." + error);
|
||||
|
||||
/// <summary>The trust-on-first-use question with the fingerprint split over two lines.</summary>
|
||||
public static ConfirmRequest TrustRequest(string server, string fingerprint) => new()
|
||||
{
|
||||
Heading = Loc.L("Server.Trust.Title"),
|
||||
Message = Loc.L("Server.Trust.Message", server),
|
||||
Detail = FormatFingerprint(fingerprint),
|
||||
DetailToolTip = Loc.L("Tooltips.Server.Fingerprint"),
|
||||
SafeText = Loc.L("Server.Trust.Cancel"),
|
||||
SafeToolTip = Loc.L("Tooltips.Server.DontTrust"),
|
||||
ActionText = Loc.L("Server.Trust.Accept"),
|
||||
ActionToolTip = Loc.L("Tooltips.Server.Trust"),
|
||||
};
|
||||
|
||||
/// <summary>The destructive question before a trusted certificate is forgotten, with its fingerprint.</summary>
|
||||
public static ConfirmRequest ForgetRequest(string fingerprint) => new()
|
||||
{
|
||||
Heading = Loc.L("Server.Certificate.Title"),
|
||||
Message = Loc.L("Server.Certificate.Message"),
|
||||
Detail = FormatFingerprint(fingerprint),
|
||||
DetailToolTip = Loc.L("Tooltips.Server.Fingerprint"),
|
||||
SafeText = Loc.L("Server.Certificate.Keep"),
|
||||
SafeToolTip = Loc.L("Tooltips.Server.KeepTrust"),
|
||||
ActionText = Loc.L("Server.Certificate.Forget"),
|
||||
ActionToolTip = Loc.L("Tooltips.Server.ForgetTrust"),
|
||||
IsDestructive = true,
|
||||
};
|
||||
|
||||
/// <summary>Splits the 32-byte SHA-256 fingerprint into two lines of 16 bytes, each kept left to right.</summary>
|
||||
public static string FormatFingerprint(string fingerprint)
|
||||
{
|
||||
var bytes = fingerprint.Split(':');
|
||||
return bytes.Length <= 16
|
||||
? Formatting.LeftToRight(fingerprint)
|
||||
: Formatting.LeftToRight(string.Join(':', bytes.Take(16))) + "\n" + Formatting.LeftToRight(string.Join(':', bytes.Skip(16)));
|
||||
}
|
||||
|
||||
/// <summary>"9A:3C:71:E0:…" for the status line.</summary>
|
||||
public static string ShortFingerprint(string fingerprint)
|
||||
{
|
||||
var bytes = fingerprint.Split(':');
|
||||
return bytes.Length <= 4 ? fingerprint : string.Join(':', bytes.Take(4)) + ":…";
|
||||
}
|
||||
|
||||
/// <summary>The account of the session (role, quota) for the Server screen.</summary>
|
||||
public UserDto? User => IsConnected ? _flow.User : null;
|
||||
|
||||
private void Remember()
|
||||
{
|
||||
if (_flow.Address is null || _flow.Token is null) return;
|
||||
var display = ServerAddress.Display(_flow.Address);
|
||||
_settings.ServerUrl = display;
|
||||
_settings.ServerUsername = _flow.User?.Username ?? _settings.ServerUsername;
|
||||
_settings.ProtectedToken = _protector.Protect(_flow.Token);
|
||||
_settings.RecentServers.RemoveAll(s => s.Equals(display, StringComparison.OrdinalIgnoreCase));
|
||||
_settings.RecentServers.Insert(0, display);
|
||||
if (_settings.RecentServers.Count > 8) _settings.RecentServers.RemoveRange(8, _settings.RecentServers.Count - 8);
|
||||
_save();
|
||||
Log.Info("server", $"Signed in to {display} as {_settings.ServerUsername}");
|
||||
OnAllPropertiesChanged();
|
||||
}
|
||||
|
||||
private void ForgetToken()
|
||||
{
|
||||
if (_settings.ProtectedToken is null) return;
|
||||
_settings.ProtectedToken = null;
|
||||
_save();
|
||||
OnAllPropertiesChanged();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
using System.IO;
|
||||
using Chronos.App.Editor;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Protocol.Client;
|
||||
|
||||
namespace Chronos.App.Server;
|
||||
|
||||
/// <summary>Makes the sync connection of a signed-in session.</summary>
|
||||
public delegate ISyncRemote SyncRemoteFactory(Uri address, string token, IReadOnlyCollection<string> trustedFingerprints);
|
||||
|
||||
/// <summary>
|
||||
/// This PC's sync with the signed-in server (BRIEF §4.4, §14.5): the <see cref="SyncService"/> of the index, the
|
||||
/// connection of upload and download jobs (<see cref="ISyncConnector"/>), a <see cref="SyncAgent"/> that keeps the
|
||||
/// table current while a session is open, started and stopped in order as the session changes, the
|
||||
/// <see cref="UploadHold"/> for metered connections, the connections of editors of server sequences
|
||||
/// (<see cref="ConnectEditor"/>) and the Export "Sync" of finished renders (<see cref="ExportSync"/>). Options come from
|
||||
/// <see cref="AppSettings.SyncSettingsAutomatically"/>, <see cref="AppSettings.KeepProxiesOffline"/> and
|
||||
/// <see cref="AppSettings.PauseUploadsOnMetered"/>.
|
||||
/// </summary>
|
||||
public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDisposable
|
||||
{
|
||||
/// <summary>How long a job resumed at start waits for the saved session to be restored.</summary>
|
||||
private static readonly TimeSpan RestoreWait = TimeSpan.FromSeconds(30);
|
||||
|
||||
private Task _switch = Task.CompletedTask;
|
||||
private Credentials? _credentials;
|
||||
private Running? _running;
|
||||
private JobEngine? _renders;
|
||||
|
||||
/// <summary>Connections over <see cref="ChronosClient"/>; screenshots substitute a fake server.</summary>
|
||||
public SyncRemoteFactory RemoteFactory { get; set; } = (address, token, trusted) =>
|
||||
new ChronosSyncRemote(new ChronosClient(address, new CertificatePinning(trusted), $"Chronos ({Environment.MachineName})") { Token = token }, ownsClient: true);
|
||||
|
||||
/// <summary>Connections of editors of server sequences over <see cref="ChronosClient"/>; screenshots substitute a fake server.</summary>
|
||||
public RemoteSequenceApiFactory EditorFactory { get; set; } = (address, token, trusted) =>
|
||||
new ChronosRemoteSequenceApi(new ChronosClient(address, new CertificatePinning(trusted), $"Chronos ({Environment.MachineName})") { Token = token });
|
||||
|
||||
/// <summary>The engine; null until the index is open.</summary>
|
||||
public SyncService? Service { get; private set; }
|
||||
|
||||
/// <summary>The background comparison of the signed-in server; null while signed out.</summary>
|
||||
public SyncAgent? Agent => Volatile.Read(ref _running)?.Agent;
|
||||
|
||||
/// <summary>The agent's connection, for the table's own calls (conflict resolution); null while signed out.</summary>
|
||||
public ISyncRemote? Remote => Volatile.Read(ref _running)?.Remote;
|
||||
|
||||
/// <summary>Key of the signed-in server (<see cref="SyncService.ServerKey"/>); null while signed out.</summary>
|
||||
public string? Server => Volatile.Read(ref _credentials) is { } c ? SyncService.ServerKey(c.Address) : null;
|
||||
|
||||
/// <summary>The options, and whether the account may change server sequences (without it this PC's edits are not sent).</summary>
|
||||
public SyncPolicy Policy => new(services.Settings.SyncSettingsAutomatically, services.Settings.KeepProxiesOffline, Allows(Permissions.Edit));
|
||||
|
||||
/// <summary>The signed-in account may send files (originals, renders) to the server.</summary>
|
||||
public bool CanUpload => Allows(Permissions.Upload);
|
||||
|
||||
/// <summary>The signed-in account may queue renders on the server.</summary>
|
||||
public bool CanRender => Allows(Permissions.Render);
|
||||
|
||||
/// <summary>Pauses uploads while the connection is metered and the option is on.</summary>
|
||||
public UploadHold Uploads { get; } = new(services);
|
||||
|
||||
/// <summary>The agent started, stopped or compared, or the table of the signed-in server changed (any thread).</summary>
|
||||
public event Action? Changed;
|
||||
|
||||
/// <summary>Creates the engine over the open index; the proxy cache lives in the client's cache folder.</summary>
|
||||
public SyncService Open(ChronosDatabase database, Chronos.Data.Archiving.ArchiveService archives, Chronos.Data.Archiving.ArchiveServiceOptions options)
|
||||
{
|
||||
var cache = CacheStore.Folder(services.Environment, services.Settings);
|
||||
Service = new SyncService(database, archives, new SyncOptions { Archive = options, ProxyCacheDirectory = Path.Combine(cache, "proxies") });
|
||||
Service.Changed += server =>
|
||||
{
|
||||
if (server == Server) Changed?.Invoke();
|
||||
};
|
||||
return Service;
|
||||
}
|
||||
|
||||
/// <summary>Follows the server session (UI thread): starts the agent for a new sign-in, stops it on sign-out.</summary>
|
||||
public void Update()
|
||||
{
|
||||
var session = services.Server;
|
||||
Credentials? wanted = session.IsConnected && session.Flow is { Address: { } address, Token: { } token }
|
||||
? new Credentials(address, token, session.Fingerprints)
|
||||
: null;
|
||||
Volatile.Write(ref _credentials, wanted);
|
||||
_switch = SwitchAsync(_switch, wanted);
|
||||
if (services.Engine is not { } engine) return;
|
||||
Uploads.Attach(engine);
|
||||
if (ReferenceEquals(_renders, engine)) return;
|
||||
if (_renders is not null) _renders.JobChanged -= OnJobChanged;
|
||||
_renders = engine;
|
||||
engine.JobChanged += OnJobChanged;
|
||||
}
|
||||
|
||||
/// <summary>A connection for the editor of a sequence of the signed-in server; null while signed out.</summary>
|
||||
public IRemoteSequenceApi? ConnectEditor() =>
|
||||
Volatile.Read(ref _credentials) is { } c ? EditorFactory(c.Address, c.Token, c.Fingerprints) : null;
|
||||
|
||||
/// <summary>Compares now, once the session switch in progress settled; null while signed out.</summary>
|
||||
public async Task<SyncSnapshot?> RefreshAsync(CancellationToken ct = default)
|
||||
{
|
||||
await _switch.ConfigureAwait(false);
|
||||
return Agent is { } agent ? await agent.RefreshAsync(ct).ConfigureAwait(false) : null;
|
||||
}
|
||||
|
||||
/// <summary>Compares again soon (an option changed, an edit on this PC).</summary>
|
||||
public void RequestRefresh() => Agent?.RequestRefresh();
|
||||
|
||||
/// <summary>The archive downloaded originals go to when a sequence has no local copy: the one this PC works with.</summary>
|
||||
public async Task<Archive?> CurrentArchiveAsync(CancellationToken ct = default)
|
||||
{
|
||||
if (services.Database is not { } db) return null;
|
||||
var archives = await db.Archives.ListAsync(ct);
|
||||
if (services.Settings.LastArchivePath is { Length: > 0 } root)
|
||||
{
|
||||
var full = Path.GetFullPath(root).TrimEnd(Path.DirectorySeparatorChar);
|
||||
if (archives.FirstOrDefault(a => string.Equals(Path.GetFullPath(a.RootPath).TrimEnd(Path.DirectorySeparatorChar), full, StringComparison.OrdinalIgnoreCase))
|
||||
is { } current) return current;
|
||||
}
|
||||
return archives.Count == 1 ? archives[0] : null;
|
||||
}
|
||||
|
||||
public async ValueTask<ISyncRemote?> ConnectAsync(string server, CancellationToken cancellationToken)
|
||||
{
|
||||
// A job resumed at start runs before the saved session is restored: give the restore a moment.
|
||||
var until = DateTime.UtcNow + RestoreWait;
|
||||
while (Volatile.Read(ref _credentials) is null && services.Settings.ProtectedToken is not null && DateTime.UtcNow < until)
|
||||
await Task.Delay(500, cancellationToken);
|
||||
if (Volatile.Read(ref _credentials) is not { } c || SyncService.ServerKey(c.Address) != server) return null;
|
||||
CacheStore.Prepare(CacheStore.Folder(services.Environment, services.Settings));
|
||||
return RemoteFactory(c.Address, c.Token, c.Fingerprints);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stops the agent once the session switch in progress settled. The app's exit waits for this on the UI thread, so
|
||||
/// nothing here, in the switch or in the stop continues on it.
|
||||
/// </summary>
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
Volatile.Write(ref _credentials, null);
|
||||
Uploads.Dispose();
|
||||
if (_renders is not null) _renders.JobChanged -= OnJobChanged;
|
||||
await _switch.ConfigureAwait(false);
|
||||
await StopAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private bool Allows(Permissions permission) => services.Server.User is { } user && (user.Permissions & (long)permission) != 0;
|
||||
|
||||
/// <summary>
|
||||
/// Export "Sync": a render of this PC that asked for it is sent to the server once done (<see cref="ExportSync"/>),
|
||||
/// also when it ends while the session is down: the send is queued for the saved session's server and waits for it.
|
||||
/// </summary>
|
||||
private void OnJobChanged(Job job)
|
||||
{
|
||||
if (job is not { Kind: JobKind.Render, State: JobState.Done } || Service is not { } service || services.Database is not { } db || _renders is not { } engine)
|
||||
return;
|
||||
var signedIn = Server;
|
||||
_ = SendRenderAsync(new ExportSync(db, service, engine), job, signedIn ?? SavedServer(), signedIn is null || CanUpload);
|
||||
}
|
||||
|
||||
/// <summary>Key of the server of the saved session (Disconnect keeps it); null without one.</summary>
|
||||
private string? SavedServer() =>
|
||||
services.Server.HasSavedSession && ServerAddress.TryParse(services.Settings.ServerUrl, out var address) ? SyncService.ServerKey(address) : null;
|
||||
|
||||
private static async Task SendRenderAsync(ExportSync exports, Job job, string? server, bool canUpload)
|
||||
{
|
||||
try
|
||||
{
|
||||
switch (await exports.SendAsync(job, server, canUpload))
|
||||
{
|
||||
case { Send: { } send }:
|
||||
Log.Info("sync", $"{job.TargetLabel} will be sent to the server (job {send.Id})");
|
||||
break;
|
||||
case { Gate: var gate }:
|
||||
Log.Warning("sync", $"{job.TargetLabel} asked to be sent to the server but was not ({gate})");
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
// Nobody awaits this: the render itself succeeded, and the send can be asked for again on the Server screen.
|
||||
Log.Warning("sync", $"The render {job.TargetLabel} could not be queued for the server", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Switches are chained (each waits for the previous one) and continue on the thread pool: a switch still stopping
|
||||
/// the old agent when the app exits must not need the UI thread its exit blocks.
|
||||
/// </summary>
|
||||
private async Task SwitchAsync(Task previous, Credentials? wanted)
|
||||
{
|
||||
await previous.ConfigureAwait(false);
|
||||
if (Volatile.Read(ref _running) is { } running && wanted is { } same && running.Credentials.Address == same.Address && running.Credentials.Token == same.Token)
|
||||
return;
|
||||
await StopAsync().ConfigureAwait(false);
|
||||
if (wanted is not { } start || Service is not { } service)
|
||||
{
|
||||
Changed?.Invoke();
|
||||
return;
|
||||
}
|
||||
var remote = RemoteFactory(start.Address, start.Token, start.Fingerprints);
|
||||
var agent = new SyncAgent(service, remote, () => Policy, services.Engine);
|
||||
agent.Changed += () => Changed?.Invoke();
|
||||
agent.Start();
|
||||
Volatile.Write(ref _running, new Running(agent, remote, start));
|
||||
Log.Info("sync", $"Comparing with {remote.Server}");
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
private async Task StopAsync()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _running, null) is not { } running) return;
|
||||
await running.Agent.DisposeAsync().ConfigureAwait(false);
|
||||
running.Remote.Dispose();
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
private sealed record Credentials(Uri Address, string Token, IReadOnlyCollection<string> Fingerprints);
|
||||
|
||||
/// <summary>The agent of the signed-in session: one reference, so the UI thread never reads half of a switch.</summary>
|
||||
private sealed record Running(SyncAgent Agent, ISyncRemote Remote, Credentials Credentials);
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
using System.Windows.Input;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Ui.Controls;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Server;
|
||||
|
||||
/// <summary>A row button: "Upload", "Keep mine", …; kept while the row offers it, so focus, tooltips and clicks survive updates.</summary>
|
||||
public sealed class SyncRowAction(SyncAction action, ICommand command) : ObservableObject
|
||||
{
|
||||
private string _toolTip = string.Empty;
|
||||
private string _sequence = string.Empty;
|
||||
|
||||
public SyncAction Action { get; } = action;
|
||||
public string Text => Loc.L("Server.Sync.Action." + Action);
|
||||
public ICommand Command { get; } = command;
|
||||
|
||||
public string ToolTip
|
||||
{
|
||||
get => _toolTip;
|
||||
set => Set(ref _toolTip, value);
|
||||
}
|
||||
|
||||
/// <summary>The title of the row's sequence.</summary>
|
||||
public string Sequence
|
||||
{
|
||||
get => _sequence;
|
||||
set
|
||||
{
|
||||
if (Set(ref _sequence, value)) OnPropertyChanged(nameof(AccessibleName));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"Upload: Clouds over the Langhe": screen readers name the sequence each of the many identical buttons acts on.</summary>
|
||||
public string AccessibleName => Loc.L("Server.Sync.ActionFor", Text, _sequence);
|
||||
|
||||
/// <summary>The label in the current language.</summary>
|
||||
public void Relabel()
|
||||
{
|
||||
OnPropertyChanged(nameof(Text));
|
||||
OnPropertyChanged(nameof(AccessibleName));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One row of the sync table (Server.html): sequence, this PC, server, state and the actions that apply.</summary>
|
||||
public sealed class SyncRow : ObservableObject
|
||||
{
|
||||
private readonly Func<SyncRow, SyncAction, Task> _act;
|
||||
private SyncEntry _entry;
|
||||
private IReadOnlyList<SyncRowAction> _actions = [];
|
||||
|
||||
public SyncRow(SyncEntry entry, SyncRights rights, Func<SyncRow, SyncAction, Task> act)
|
||||
{
|
||||
_entry = entry;
|
||||
_act = act;
|
||||
UpdateActions(rights);
|
||||
}
|
||||
|
||||
public SyncEntry Entry => _entry;
|
||||
public Guid Id => _entry.Id;
|
||||
public string Title => _entry.Title;
|
||||
public string LocalText => SyncText.Local(_entry);
|
||||
public string ServerText => SyncText.Server(_entry);
|
||||
public StatusKind StateKind => SyncText.State(_entry).Kind;
|
||||
public string StateText => SyncText.State(_entry).Text;
|
||||
|
||||
/// <summary>"Clouds over the Langhe: In sync": what a screen reader announces when the state changes (not progress).</summary>
|
||||
public string StateAnnouncement => Loc.L("Server.Sync.Row.State", Title, StateText);
|
||||
|
||||
/// <summary>The state whole (its fixed column cuts the longer ones), then what it means or what differs.</summary>
|
||||
public string StateToolTip => string.Join(Loc.Separator, StateText, SyncText.State(_entry).ToolTip);
|
||||
|
||||
/// <summary>Settings differ on both sides: the row is drawn on the warning tint (the word in the State column says it too).</summary>
|
||||
public bool IsConflict => _entry.Status == SyncStatus.Conflict && _entry.Transfer is null;
|
||||
|
||||
public IReadOnlyList<SyncRowAction> Actions
|
||||
{
|
||||
get => _actions;
|
||||
private set => Set(ref _actions, value);
|
||||
}
|
||||
|
||||
/// <summary>Takes a fresher comparison of the same sequence; buttons the row still offers are kept.</summary>
|
||||
public void Update(SyncEntry entry, SyncRights rights)
|
||||
{
|
||||
_entry = entry;
|
||||
UpdateActions(rights);
|
||||
RaiseTexts();
|
||||
}
|
||||
|
||||
/// <summary>Takes the progress of the row's transfer ("46 % received") without touching its buttons.</summary>
|
||||
public void UpdateProgress(long done, long total)
|
||||
{
|
||||
if (_entry.Transfer is not { } job) return;
|
||||
_entry = _entry with { Transfer = job with { ProgressDone = done, ProgressTotal = total } };
|
||||
OnPropertyChanged(nameof(ServerText));
|
||||
}
|
||||
|
||||
/// <summary>Texts in the current language.</summary>
|
||||
public void Relabel()
|
||||
{
|
||||
foreach (var action in _actions)
|
||||
{
|
||||
action.Relabel();
|
||||
action.ToolTip = SyncText.ToolTip(_entry, action.Action);
|
||||
}
|
||||
RaiseTexts();
|
||||
}
|
||||
|
||||
private void UpdateActions(SyncRights rights)
|
||||
{
|
||||
var wanted = SyncText.Actions(_entry, rights);
|
||||
if (!wanted.SequenceEqual(_actions.Select(a => a.Action)))
|
||||
{
|
||||
var kept = _actions.ToDictionary(a => a.Action);
|
||||
Actions = [.. wanted.Select(action => kept.GetValueOrDefault(action) ?? new SyncRowAction(action, new AsyncRelayCommand(() => _act(this, action))))];
|
||||
}
|
||||
foreach (var action in _actions)
|
||||
{
|
||||
action.ToolTip = SyncText.ToolTip(_entry, action.Action);
|
||||
action.Sequence = Title;
|
||||
}
|
||||
}
|
||||
|
||||
private void RaiseTexts()
|
||||
{
|
||||
OnPropertyChanged(nameof(Title));
|
||||
OnPropertyChanged(nameof(LocalText));
|
||||
OnPropertyChanged(nameof(ServerText));
|
||||
OnPropertyChanged(nameof(StateKind));
|
||||
OnPropertyChanged(nameof(StateText));
|
||||
OnPropertyChanged(nameof(StateAnnouncement));
|
||||
OnPropertyChanged(nameof(StateToolTip));
|
||||
OnPropertyChanged(nameof(IsConflict));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,460 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.IO;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Threading;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Shell;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Server;
|
||||
|
||||
/// <summary>A filter chip of the sync table: "Conflicts · 1".</summary>
|
||||
public sealed class SyncFilterChip(SyncFilter filter, Action<SyncFilter> select) : ObservableObject
|
||||
{
|
||||
private int _count;
|
||||
private bool _isSelected;
|
||||
|
||||
public SyncFilter Filter { get; } = filter;
|
||||
public string Text => Loc.L("Server.Sync.Filter." + Filter, Formatting.Count(_count));
|
||||
public string ToolTip => Loc.L("Tooltips.Server.Sync.Filter." + Filter);
|
||||
public ICommand SelectCommand { get; } = new RelayCommand(() => select(filter));
|
||||
|
||||
/// <summary>Conflicts waiting for a choice: the chip is drawn in the warning colour unless it is the selected one.</summary>
|
||||
public bool NeedsAttention => Filter == SyncFilter.Conflicts && _count > 0;
|
||||
|
||||
public bool IsSelected
|
||||
{
|
||||
get => _isSelected;
|
||||
set => Set(ref _isSelected, value);
|
||||
}
|
||||
|
||||
public int Count
|
||||
{
|
||||
get => _count;
|
||||
set
|
||||
{
|
||||
if (!Set(ref _count, value)) return;
|
||||
OnPropertyChanged(nameof(Text));
|
||||
OnPropertyChanged(nameof(NeedsAttention));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Texts in the current language.</summary>
|
||||
public void Relabel()
|
||||
{
|
||||
OnPropertyChanged(nameof(Text));
|
||||
OnPropertyChanged(nameof(ToolTip));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Why the sync table shows no rows; each case has its one action (BRIEF §0.2 rule 6).</summary>
|
||||
public enum SyncEmpty
|
||||
{
|
||||
None,
|
||||
SignedOut,
|
||||
Nothing,
|
||||
NoMatch,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sync table of the Server screen (BRIEF §12.7, Server.html): every sequence of this PC and of the signed-in
|
||||
/// server with what each side holds, where it stands and what can be done (upload, download originals, open with
|
||||
/// proxies, get or send exports, settle a conflict, pause or resume a transfer), filter chips, search, "Upload all
|
||||
/// local" and the footer (last comparison, server archive, admin panel). Reloads when the sync engine reports a change;
|
||||
/// transfer progress is applied at most a few times a second. Runs on the UI thread.
|
||||
/// </summary>
|
||||
public sealed class SyncTableViewModel : ObservableObject, IDisposable
|
||||
{
|
||||
private readonly ShellViewModel _shell;
|
||||
private readonly IReadOnlyList<SyncFilterChip> _chips;
|
||||
|
||||
/// <summary>"Open with proxies" waiting for its proxy download: server id → the job that fills the cache.</summary>
|
||||
private readonly Dictionary<Guid, Guid> _openWhenCached = [];
|
||||
|
||||
private readonly ConcurrentDictionary<Guid, JobProgressInfo> _progress = new();
|
||||
private readonly SemaphoreSlim _reloading = new(1, 1);
|
||||
private readonly AsyncRelayCommand _uploadAll;
|
||||
private IReadOnlyList<SyncEntry> _entries = [];
|
||||
private SyncFilter _filter = SyncFilter.All;
|
||||
private string _search = string.Empty;
|
||||
private int _progressQueued;
|
||||
private int _reloadQueued;
|
||||
private bool _attached;
|
||||
|
||||
public SyncTableViewModel(ShellViewModel shell)
|
||||
{
|
||||
_shell = shell;
|
||||
_chips = [.. Enum.GetValues<SyncFilter>().Select(f => new SyncFilterChip(f, Select) { IsSelected = f == SyncFilter.All })];
|
||||
_uploadAll = new AsyncRelayCommand(UploadAllAsync, () => IsActive && Rights.CanUpload && LocalOnly.Any());
|
||||
OpenAdminCommand = new RelayCommand(() =>
|
||||
{
|
||||
if (Host.Server is { } server) ShellActions.OpenUrl(server + "/admin");
|
||||
});
|
||||
ClearFiltersCommand = new RelayCommand(() =>
|
||||
{
|
||||
_search = string.Empty;
|
||||
OnPropertyChanged(nameof(SearchText));
|
||||
Select(SyncFilter.All);
|
||||
});
|
||||
ImportCommand = new RelayCommand(() => _shell.Navigate(SectionKey.Import));
|
||||
}
|
||||
|
||||
public ObservableCollection<SyncRow> Rows { get; } = [];
|
||||
public IReadOnlyList<SyncFilterChip> Chips => _chips;
|
||||
public ICommand UploadAllCommand => _uploadAll;
|
||||
public ICommand OpenAdminCommand { get; }
|
||||
|
||||
/// <summary>"No sequence matches": back to every sequence.</summary>
|
||||
public ICommand ClearFiltersCommand { get; }
|
||||
|
||||
/// <summary>"Nothing to compare yet": bring photos in.</summary>
|
||||
public ICommand ImportCommand { get; }
|
||||
|
||||
public string SearchText
|
||||
{
|
||||
get => _search;
|
||||
set
|
||||
{
|
||||
if (Set(ref _search, value ?? string.Empty)) ApplyFilter(rebuild: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Signed in: the table compares this PC with that server.</summary>
|
||||
public bool IsActive => Host.Server is not null;
|
||||
|
||||
public bool HasRows => Rows.Count > 0;
|
||||
|
||||
public SyncEmpty Empty => HasRows ? SyncEmpty.None
|
||||
: !IsActive ? SyncEmpty.SignedOut
|
||||
: _entries.Count == 0 ? SyncEmpty.Nothing
|
||||
: SyncEmpty.NoMatch;
|
||||
|
||||
/// <summary>"Not connected to a server", "Nothing to compare yet" or "No sequence matches"; null when rows show.</summary>
|
||||
public string? EmptyText => Empty switch
|
||||
{
|
||||
SyncEmpty.SignedOut => Loc.L("Server.Empty"),
|
||||
SyncEmpty.Nothing => Loc.L("Server.Sync.Empty"),
|
||||
SyncEmpty.NoMatch => Loc.L("Server.Sync.NoMatch"),
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <summary>What "Upload all local" sends, or why it is disabled.</summary>
|
||||
public string UploadAllToolTip =>
|
||||
!IsActive ? Loc.L("Tooltips.Server.Sync.UploadAll.NotConnected")
|
||||
: !Rights.CanUpload ? Loc.L("Tooltips.Server.Sync.UploadAll.NoRight")
|
||||
: !LocalOnly.Any() ? Loc.L("Tooltips.Server.Sync.UploadAll.Nothing")
|
||||
: Loc.Plural("Tooltips.Server.Sync.UploadAll", LocalOnly.Count(), Formatting.Bytes(LocalOnly.Sum(e => e.Local!.TotalBytes)));
|
||||
|
||||
/// <summary>"Last sync 10:15 · manifest diff 0.4 s"; null before the first comparison.</summary>
|
||||
public string? LastSyncText => Host.Agent?.Snapshot is { } s
|
||||
? Loc.L("Server.Sync.Last", Formatting.TimeOfDay(s.RefreshedAt), s.Duration.TotalSeconds.ToString("0.0", Loc.Culture))
|
||||
: null;
|
||||
|
||||
/// <summary>"Server archive 9.4 TB · 412 sequences".</summary>
|
||||
public string? ArchiveText => Host.Agent?.Snapshot is { } s ? Loc.Plural("Server.Sync.Archive", s.ServerSequences, Formatting.Bytes(s.ServerBytes)) : null;
|
||||
|
||||
/// <summary>The last comparison failed (it is retried with growing pauses); null when it worked.</summary>
|
||||
public string? ErrorText => Host.Agent?.LastError is not null ? Loc.L("Server.Sync.Retrying") : null;
|
||||
|
||||
public string? ErrorToolTip => Host.Agent?.LastError is { } error ? Loc.L("Tooltips.Server.Sync.Retrying", error.Message) : null;
|
||||
|
||||
/// <summary>The server's web admin admits administrators only: the link shows for accounts that manage the archive or users.</summary>
|
||||
public bool CanOpenAdmin => _shell.Services.Server.User is { } user && IsActive
|
||||
&& (user.Permissions & (long)(Permissions.ManageArchive | Permissions.ManageUsers)) != 0;
|
||||
|
||||
private SyncHost Host => _shell.Services.Sync;
|
||||
|
||||
private SyncRights Rights => _shell.Services.Server.User is { } user ? SyncRights.Of(user.Permissions) : default;
|
||||
|
||||
private IEnumerable<SyncEntry> LocalOnly => _entries.Where(e => e.Status == SyncStatus.LocalOnly);
|
||||
|
||||
/// <summary>Starts following the sync engine, the transfer jobs and the language.</summary>
|
||||
public void Attach()
|
||||
{
|
||||
if (_attached) return;
|
||||
_attached = true;
|
||||
Host.Changed += OnChanged;
|
||||
Loc.CultureChanged += OnCultureChanged;
|
||||
if (_shell.Services.Jobs is { } jobs)
|
||||
{
|
||||
jobs.JobChanged += OnJobChanged;
|
||||
jobs.Progress += OnProgress;
|
||||
}
|
||||
_ = ReloadAsync();
|
||||
}
|
||||
|
||||
/// <summary>Reads the table again; requests made while a pass runs share the next one, which they wait for.</summary>
|
||||
public async Task ReloadAsync()
|
||||
{
|
||||
Interlocked.Exchange(ref _reloadQueued, 1);
|
||||
await _reloading.WaitAsync();
|
||||
try
|
||||
{
|
||||
while (Interlocked.Exchange(ref _reloadQueued, 0) == 1)
|
||||
{
|
||||
_entries = Host is { Service: { } service, Server: { } server } ? await service.ListAsync(server, CancellationToken.None) : [];
|
||||
Refresh();
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is Data.DatabaseException or InvalidOperationException)
|
||||
{
|
||||
Log.Warning("sync", "The sync table could not be read", ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_reloading.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (!_attached) return;
|
||||
_attached = false;
|
||||
Host.Changed -= OnChanged;
|
||||
Loc.CultureChanged -= OnCultureChanged;
|
||||
if (_shell.Services.Jobs is { } jobs)
|
||||
{
|
||||
jobs.JobChanged -= OnJobChanged;
|
||||
jobs.Progress -= OnProgress;
|
||||
}
|
||||
}
|
||||
|
||||
private void Select(SyncFilter filter)
|
||||
{
|
||||
_filter = filter;
|
||||
foreach (var chip in _chips) chip.IsSelected = chip.Filter == filter;
|
||||
ApplyFilter(rebuild: true);
|
||||
}
|
||||
|
||||
/// <summary>Counts, rows, footer and the Library's sync glyphs after a reload.</summary>
|
||||
private void Refresh()
|
||||
{
|
||||
foreach (var chip in _chips) chip.Count = _entries.Count(e => SyncText.Matches(e, chip.Filter, string.Empty));
|
||||
ApplyFilter(rebuild: false);
|
||||
UpdateLibrary();
|
||||
OnPropertyChanged(nameof(IsActive));
|
||||
OnPropertyChanged(nameof(UploadAllToolTip));
|
||||
OnPropertyChanged(nameof(LastSyncText));
|
||||
OnPropertyChanged(nameof(ArchiveText));
|
||||
OnPropertyChanged(nameof(ErrorText));
|
||||
OnPropertyChanged(nameof(ErrorToolTip));
|
||||
OnPropertyChanged(nameof(CanOpenAdmin));
|
||||
_uploadAll.RaiseCanExecuteChanged();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Shows the entries the filter and search keep. A reload updates the rows in place (scroll position, focus and
|
||||
/// recycled containers survive); a new filter or search lays the rows out again.
|
||||
/// </summary>
|
||||
private void ApplyFilter(bool rebuild)
|
||||
{
|
||||
var rights = Rights;
|
||||
var wanted = _entries.Where(e => SyncText.Matches(e, _filter, _search.Trim())).ToList();
|
||||
var byId = Rows.ToDictionary(r => r.Id);
|
||||
if (rebuild)
|
||||
{
|
||||
Rows.Clear();
|
||||
foreach (var entry in wanted) Rows.Add(Row(entry, rights, byId));
|
||||
}
|
||||
else
|
||||
{
|
||||
for (var i = 0; i < wanted.Count; i++)
|
||||
{
|
||||
var entry = wanted[i];
|
||||
if (i < Rows.Count && Rows[i].Id == entry.Id)
|
||||
{
|
||||
Rows[i].Update(entry, rights);
|
||||
continue;
|
||||
}
|
||||
var row = Row(entry, rights, byId);
|
||||
var at = byId.ContainsKey(entry.Id) ? Rows.IndexOf(row) : -1;
|
||||
if (at >= 0) Rows.Move(at, i);
|
||||
else Rows.Insert(i, row);
|
||||
}
|
||||
while (Rows.Count > wanted.Count) Rows.RemoveAt(Rows.Count - 1);
|
||||
}
|
||||
OnPropertyChanged(nameof(HasRows));
|
||||
OnPropertyChanged(nameof(Empty));
|
||||
OnPropertyChanged(nameof(EmptyText));
|
||||
}
|
||||
|
||||
/// <summary>The existing row of an entry, updated, or a new one.</summary>
|
||||
private SyncRow Row(SyncEntry entry, SyncRights rights, Dictionary<Guid, SyncRow> existing)
|
||||
{
|
||||
if (!existing.TryGetValue(entry.Id, out var row)) return new SyncRow(entry, rights, ActAsync);
|
||||
row.Update(entry, rights);
|
||||
return row;
|
||||
}
|
||||
|
||||
/// <summary>The Library shows each local copy's sync state: rows it has loaded take the fresh state.</summary>
|
||||
private void UpdateLibrary()
|
||||
{
|
||||
var locals = _entries.Where(e => e.Local is not null).ToDictionary(e => e.Local!.Id, e => e.Local!);
|
||||
foreach (var item in _shell.Library.Items)
|
||||
{
|
||||
if (locals.TryGetValue(item.Id, out var fresh) && fresh.SyncState != item.Sequence.SyncState) item.Update(fresh);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ActAsync(SyncRow row, SyncAction action)
|
||||
{
|
||||
if (Host is not { Service: { } service, Server: { } server } || _shell.Services.Engine is not { } engine) return;
|
||||
var entry = row.Entry;
|
||||
switch (action)
|
||||
{
|
||||
case SyncAction.Upload:
|
||||
await service.EnqueueUploadAsync(engine, server, entry.Local!);
|
||||
break;
|
||||
case SyncAction.SendExports:
|
||||
await service.EnqueueSendExportsAsync(engine, server, entry.Local!);
|
||||
break;
|
||||
case SyncAction.DownloadOriginals:
|
||||
if ((entry.Local?.ArchiveId ?? (await Host.CurrentArchiveAsync())?.Id) is not { } archive)
|
||||
{
|
||||
_shell.Notify(Loc.L("Errors.Sync.NoArchive"), isError: true);
|
||||
return;
|
||||
}
|
||||
await service.EnqueueDownloadAsync(engine, server, entry.Id, entry.Title, SyncDownloadMode.Originals, archive);
|
||||
break;
|
||||
case SyncAction.GetExports:
|
||||
await service.EnqueueDownloadAsync(engine, server, entry.Id, entry.Title, SyncDownloadMode.Exports, null);
|
||||
break;
|
||||
case SyncAction.OpenWithProxies when entry.Status == SyncStatus.ProxiesOnly && service.OpenRemote(server, entry.Id) is not null:
|
||||
_shell.OpenSequence(entry.Id);
|
||||
return;
|
||||
case SyncAction.OpenWithProxies:
|
||||
var job = await service.EnqueueDownloadAsync(engine, server, entry.Id, entry.Title, SyncDownloadMode.Proxies, null);
|
||||
_openWhenCached[entry.Id] = job.Id;
|
||||
// A download that finished before it was recorded here opens at once.
|
||||
if (await _shell.Services.Database!.Jobs.GetAsync(job.Id) is { State: JobState.Done or JobState.Failed or JobState.Cancelled } ended)
|
||||
OpenWhenCached(ended);
|
||||
break;
|
||||
case SyncAction.Pause:
|
||||
await _shell.Services.Jobs!.PauseAsync(entry.Transfer!.Id);
|
||||
break;
|
||||
case SyncAction.Resume:
|
||||
await _shell.Services.Jobs!.ResumeAsync(entry.Transfer!.Id);
|
||||
break;
|
||||
case SyncAction.SyncSettings when Host.Remote is { } remote:
|
||||
await service.SyncSettingsAsync(remote, entry.Id, Host.Policy, CancellationToken.None);
|
||||
break;
|
||||
case SyncAction.KeepMine or SyncAction.TakeServer or SyncAction.SaveBoth when Host.Remote is { } remote:
|
||||
await ResolveAsync(service, remote, entry, action);
|
||||
break;
|
||||
}
|
||||
await ReloadAsync();
|
||||
}
|
||||
|
||||
/// <summary>Settles a conflict once the user confirmed the plan: the settings that differ and what each choice overwrites.</summary>
|
||||
private async Task ResolveAsync(SyncService service, ISyncRemote remote, SyncEntry entry, SyncAction action)
|
||||
{
|
||||
if (!_shell.Services.Dialogs.Confirm(ConflictRequest(entry, action))) return;
|
||||
var resolution = action switch
|
||||
{
|
||||
SyncAction.KeepMine => SyncResolution.KeepMine,
|
||||
SyncAction.TakeServer => SyncResolution.TakeServer,
|
||||
_ => SyncResolution.SaveBoth,
|
||||
};
|
||||
try
|
||||
{
|
||||
if (await service.ResolveAsync(remote, entry.Id, resolution, CancellationToken.None) is { } saved)
|
||||
{
|
||||
_shell.Notify(Loc.L("Server.Sync.SavedBoth"), Path.GetFileName(saved), Loc.L("Server.Sync.ShowCopy"), Loc.L("Tooltips.Server.Sync.ShowCopy"),
|
||||
() => ShellActions.Reveal(saved));
|
||||
}
|
||||
}
|
||||
catch (SyncConflictChangedException ex)
|
||||
{
|
||||
// One side changed after the choice was shown: the row now shows the fresh content.
|
||||
_shell.Notify(ex.Message, isError: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The dry run of a resolution: what is replaced, by which side's values, and where "Save both" keeps this PC's.</summary>
|
||||
internal static ConfirmRequest ConflictRequest(SyncEntry entry, SyncAction action) => new()
|
||||
{
|
||||
Heading = Loc.L("Server.Conflict." + action + ".Title"),
|
||||
Message = Loc.L("Server.Conflict." + action + ".Message", entry.Title),
|
||||
Detail = string.Join(Environment.NewLine, SyncText.Conflict(entry, 10)),
|
||||
DetailToolTip = Loc.L("Tooltips.Server.Conflict.Detail"),
|
||||
SafeText = Loc.L("Server.Conflict.Cancel"),
|
||||
SafeToolTip = Loc.L("Tooltips.Server.Conflict.Cancel"),
|
||||
ActionText = Loc.L("Server.Sync.Action." + action),
|
||||
ActionToolTip = Loc.L("Tooltips.Server.Sync." + action),
|
||||
IsDestructive = action != SyncAction.SaveBoth,
|
||||
};
|
||||
|
||||
private async Task UploadAllAsync()
|
||||
{
|
||||
if (Host is not { Service: { } service, Server: { } server } || _shell.Services.Engine is not { } engine) return;
|
||||
var queued = 0;
|
||||
foreach (var entry in LocalOnly.ToList())
|
||||
{
|
||||
await service.EnqueueUploadAsync(engine, server, entry.Local!);
|
||||
queued++;
|
||||
}
|
||||
_shell.Notify(Loc.Plural("Server.Sync.Queued", queued));
|
||||
await ReloadAsync();
|
||||
}
|
||||
|
||||
private void OnChanged() => Dispatch(() => _ = ReloadAsync());
|
||||
|
||||
private void OnCultureChanged(object? sender, EventArgs e) => Dispatch(() =>
|
||||
{
|
||||
foreach (var chip in _chips) chip.Relabel();
|
||||
foreach (var row in Rows) row.Relabel();
|
||||
OnAllPropertiesChanged();
|
||||
});
|
||||
|
||||
private void OnJobChanged(Job job)
|
||||
{
|
||||
if (job.Kind is not (JobKind.UploadCommit or JobKind.Download)) return;
|
||||
_progress.TryRemove(job.Id, out _);
|
||||
Dispatch(() =>
|
||||
{
|
||||
OpenWhenCached(job);
|
||||
_ = ReloadAsync();
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "Open with proxies" opens the editor when the download it queued is done, if the Server screen is still the one
|
||||
/// in front; a failed or cancelled download drops the request.
|
||||
/// </summary>
|
||||
private void OpenWhenCached(Job job)
|
||||
{
|
||||
if (job.State is not (JobState.Done or JobState.Failed or JobState.Cancelled)) return;
|
||||
var remoteId = _openWhenCached.FirstOrDefault(p => p.Value == job.Id).Key;
|
||||
if (!_openWhenCached.Remove(remoteId)) return;
|
||||
if (job.State == JobState.Done && ReferenceEquals(_shell.Current, _shell.Server)) _shell.OpenSequence(remoteId);
|
||||
}
|
||||
|
||||
/// <summary>Transfer progress ("46 % received") without reading the table again, at most a few times a second.</summary>
|
||||
private void OnProgress(JobProgressInfo info)
|
||||
{
|
||||
if (info.Kind is not (JobKind.UploadCommit or JobKind.Download)) return;
|
||||
_progress[info.JobId] = info;
|
||||
if (Interlocked.Exchange(ref _progressQueued, 1) == 1) return;
|
||||
System.Windows.Application.Current?.Dispatcher.BeginInvoke(DispatcherPriority.Background, async () =>
|
||||
{
|
||||
await Task.Delay(250);
|
||||
Interlocked.Exchange(ref _progressQueued, 0);
|
||||
foreach (var row in Rows)
|
||||
{
|
||||
if (row.Entry.Transfer is { } job && _progress.TryGetValue(job.Id, out var p)) row.UpdateProgress(p.Done, p.Total);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static void Dispatch(Action action)
|
||||
{
|
||||
if (System.Windows.Application.Current?.Dispatcher is not { } dispatcher || dispatcher.CheckAccess()) action();
|
||||
else dispatcher.BeginInvoke(action);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Ui.Controls;
|
||||
|
||||
namespace Chronos.App.Server;
|
||||
|
||||
/// <summary>Filter chips of the sync table (Server.html).</summary>
|
||||
public enum SyncFilter
|
||||
{
|
||||
All,
|
||||
LocalOnly,
|
||||
Remote,
|
||||
Conflicts,
|
||||
}
|
||||
|
||||
/// <summary>What a row of the sync table offers.</summary>
|
||||
public enum SyncAction
|
||||
{
|
||||
Upload,
|
||||
OpenWithProxies,
|
||||
DownloadOriginals,
|
||||
SyncSettings,
|
||||
KeepMine,
|
||||
TakeServer,
|
||||
SaveBoth,
|
||||
GetExports,
|
||||
SendExports,
|
||||
Pause,
|
||||
Resume,
|
||||
}
|
||||
|
||||
/// <summary>What the signed-in account may do (server permission bits).</summary>
|
||||
/// <param name="CanUpload">Send originals, settings and renders (upload and edit rights).</param>
|
||||
/// <param name="CanFetchOriginals">Download originals (editors and render nodes).</param>
|
||||
/// <param name="CanEdit">Change the server's copy of a sequence's settings, title, tags, rating and notes.</param>
|
||||
public readonly record struct SyncRights(bool CanUpload, bool CanFetchOriginals, bool CanEdit)
|
||||
{
|
||||
public static SyncRights Of(long permissions) => new(
|
||||
(permissions & (long)Permissions.Upload) != 0 && (permissions & (long)Permissions.Edit) != 0,
|
||||
(permissions & (long)(Permissions.Edit | Permissions.RenderNode)) != 0,
|
||||
(permissions & (long)Permissions.Edit) != 0);
|
||||
}
|
||||
|
||||
/// <summary>The words, glyphs and actions of the sync table (BRIEF §12.7): plain functions of a <see cref="SyncEntry"/>.</summary>
|
||||
public static class SyncText
|
||||
{
|
||||
/// <summary>Resource keys of the settings and sequence fields a conflict can show, by JSON path (sections, then members).</summary>
|
||||
private static readonly Dictionary<string, string> SettingKeys = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["sequence.title"] = "Server.Setting.Title",
|
||||
["sequence.tags"] = "Server.Setting.Tags",
|
||||
["sequence.rating"] = "Server.Setting.Rating",
|
||||
["sequence.notes"] = "Server.Setting.Notes",
|
||||
["timing.mode"] = "Server.Setting.TimingMode",
|
||||
["timing.frameRate"] = "Server.Setting.FrameRate",
|
||||
["timing.fitToSeconds"] = "Server.Setting.FitToDuration",
|
||||
["timing.remapCurve"] = "Server.Setting.TimeRemap",
|
||||
["exposure.deflicker"] = "Server.Setting.Deflicker",
|
||||
["exposure.deflickerWindow"] = "Server.Setting.DeflickerWindow",
|
||||
["exposure.deflickerStrength"] = "Server.Setting.DeflickerStrength",
|
||||
["exposure.regions"] = "Server.Setting.Regions",
|
||||
["exposure.holyGrail"] = "Server.Setting.HolyGrail",
|
||||
["exposure.transitionLength"] = "Server.Setting.Transitions",
|
||||
["exposure.whiteBalanceSmoothing"] = "Server.Setting.WhiteBalance",
|
||||
["exposure.exposureOffsetEv"] = "Server.Setting.ExposureOffset",
|
||||
["exposure.highlightKnee"] = "Server.Setting.HighlightKnee",
|
||||
["motion.motionBlur"] = "Server.Setting.MotionBlur",
|
||||
["motion.targetShutterAngle"] = "Server.Setting.ShutterAngle",
|
||||
["motion.flowQuality"] = "Server.Setting.FlowQuality",
|
||||
["motion.stabilize"] = "Server.Setting.Stabilize",
|
||||
["motion.stabilizeSmoothing"] = "Server.Setting.StabilizeSmoothing",
|
||||
["camera.crop"] = "Server.Setting.Crop",
|
||||
["camera.aspect"] = "Server.Setting.Aspect",
|
||||
["camera.offsetX"] = "Server.Setting.CameraOffset",
|
||||
["camera.offsetY"] = "Server.Setting.CameraOffset",
|
||||
["camera.keyframes"] = "Server.Setting.Keyframes",
|
||||
["stack.mode"] = "Server.Setting.Stacking",
|
||||
["stack.length"] = "Server.Setting.TrailLength",
|
||||
["export.preset"] = "Server.Setting.ExportPreset",
|
||||
["export.overrides"] = "Server.Setting.ExportValues",
|
||||
["export.nameTemplate"] = "Server.Setting.OutputName",
|
||||
["export.folder"] = "Server.Setting.ExportFolder",
|
||||
["export.batch"] = "Server.Setting.Batch",
|
||||
["excludedFrames"] = "Server.Setting.ExcludedFrames",
|
||||
["heroFrame"] = "Server.Setting.HeroFrame",
|
||||
};
|
||||
|
||||
/// <summary>"originals · proxies", "proxies" (cached server proxies) or "—".</summary>
|
||||
public static string Local(SyncEntry entry)
|
||||
{
|
||||
if (entry.HasLocalOriginals)
|
||||
{
|
||||
return (entry.Local!.Status & SequenceStatus.ProxiesBuilt) != 0
|
||||
? Join(Loc.L("Server.Sync.Originals"), Loc.L("Server.Sync.Proxies"))
|
||||
: Loc.L("Server.Sync.Originals");
|
||||
}
|
||||
return entry.Link is { ProxiesCached: > 0 } ? Loc.L("Server.Sync.Proxies") : Loc.L("Server.Sync.None");
|
||||
}
|
||||
|
||||
/// <summary>"originals · proxies · 3 exports", "46 % received" while uploading, or "—".</summary>
|
||||
public static string Server(SyncEntry entry)
|
||||
{
|
||||
if (entry.Transfer is { Kind: JobKind.UploadCommit, State: JobState.Running, ProgressTotal: > 0 } upload)
|
||||
return Loc.L("Server.Sync.Received", Formatting.Percent((double)upload.ProgressDone / upload.ProgressTotal));
|
||||
if (entry.Link is not { } link) return Loc.L("Server.Sync.None");
|
||||
var parts = new List<string>(3) { Loc.L("Server.Sync.Originals") };
|
||||
if (link.ServerHasProxies) parts.Add(Loc.L("Server.Sync.Proxies"));
|
||||
if (link.RenderCount > 0) parts.Add(Loc.Plural("Server.Sync.Exports", link.RenderCount));
|
||||
return Join([.. parts]);
|
||||
}
|
||||
|
||||
/// <summary>The State column: glyph kind, word and tooltip (never colour alone).</summary>
|
||||
public static (StatusKind Kind, string Text, string ToolTip) State(SyncEntry entry)
|
||||
{
|
||||
if (entry.Transfer is { } job)
|
||||
{
|
||||
var upload = job.Kind == JobKind.UploadCommit;
|
||||
return job.State switch
|
||||
{
|
||||
JobState.Paused => (StatusKind.Paused, Loc.L("Server.Sync.State.Paused"), Loc.L("Tooltips.Server.Sync.State.Paused")),
|
||||
JobState.Queued => (StatusKind.Queued, Loc.L("Server.Sync.State.Waiting"), Loc.L("Tooltips.Server.Sync.State.Waiting")),
|
||||
_ => (StatusKind.Running, Loc.L(upload ? "Server.Sync.State.Uploading" : "Server.Sync.State.Downloading"),
|
||||
Loc.L(upload ? "Tooltips.Server.Sync.State.Uploading" : "Tooltips.Server.Sync.State.Downloading")),
|
||||
};
|
||||
}
|
||||
if (entry.Link?.Error is { } error) return (StatusKind.Warning, Loc.L("Server.Sync.State.Failed"), Loc.L("Tooltips.Server.Sync.State.Failed", error));
|
||||
return entry.Status switch
|
||||
{
|
||||
SyncStatus.InSync => (StatusKind.Done, Loc.L("Server.Sync.State.InSync"), Loc.L("Tooltips.Server.Sync.State.InSync")),
|
||||
SyncStatus.LocalOnly => (StatusKind.Offline, Loc.L("Server.Sync.State.LocalOnly"), Loc.L("Tooltips.Server.Sync.State.LocalOnly")),
|
||||
SyncStatus.RemoteOnly => (StatusKind.Remote, Loc.L("Server.Sync.State.RemoteOnly"), Loc.L("Tooltips.Server.Sync.State.RemoteOnly")),
|
||||
SyncStatus.ProxiesOnly => (StatusKind.Remote, Loc.L("Server.Sync.State.ProxiesOnly"), Loc.L("Tooltips.Server.Sync.State.ProxiesOnly")),
|
||||
SyncStatus.LocalAhead => (StatusKind.Synced, Loc.L("Server.Sync.State.LocalAhead"), Loc.L("Tooltips.Server.Sync.State.LocalAhead")),
|
||||
SyncStatus.ServerAhead => (StatusKind.Remote, Loc.L("Server.Sync.State.ServerAhead"), Loc.L("Tooltips.Server.Sync.State.ServerAhead")),
|
||||
_ => (StatusKind.Warning, Loc.L("Server.Sync.State.Conflict"), ConflictSummary(entry)),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>One line for the State tooltip: "Deflicker window 41 here, 33 on the server · +2".</summary>
|
||||
public static string ConflictSummary(SyncEntry entry)
|
||||
{
|
||||
var lines = Conflict(entry, int.MaxValue);
|
||||
return lines.Count switch
|
||||
{
|
||||
0 => Loc.L("Tooltips.Server.Sync.State.Conflict"),
|
||||
1 => lines[0],
|
||||
_ => Loc.L("Server.Conflict.More", lines[0], Formatting.Count(lines.Count - 1)),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What differs, one line per setting or sequence field in project order ("Deflicker window 41 here, 33 on the
|
||||
/// server", "Tags differ"), at most <paramref name="max"/>.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<string> Conflict(SyncEntry entry, int max) => entry is { Local: { } local, Link.ConflictRemote: { } theirs }
|
||||
? Differences(SyncRules.Differences(SyncPayload.Of(local), theirs, 64), max)
|
||||
: [];
|
||||
|
||||
/// <summary>
|
||||
/// One line per setting or sequence field among <paramref name="differences"/> ("Deflicker window 41 here, 33 on the
|
||||
/// server", "Tags differ"), at most <paramref name="max"/>; the editor's settings conflicts read the same.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<string> Differences(IEnumerable<SettingsDifference> differences, int max)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(differences);
|
||||
var lines = new List<string>();
|
||||
var shown = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var difference in differences)
|
||||
{
|
||||
var (key, field) = Setting(difference.Path);
|
||||
if (!shown.Add(key)) continue;
|
||||
var label = Loc.L(key);
|
||||
var metadata = difference.Path.StartsWith(SyncRules.MetadataPath, StringComparison.Ordinal);
|
||||
lines.Add((metadata ? Text(difference.Mine) : Value(difference.Mine, field)) is { } mine
|
||||
&& (metadata ? Text(difference.Theirs) : Value(difference.Theirs, field)) is { } server
|
||||
? Loc.L("Server.Conflict.Difference", label, mine, server)
|
||||
: Loc.L("Server.Conflict.Changed", label));
|
||||
if (lines.Count == max) break;
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
/// <summary>The row's buttons, in the order the mockup shows them.</summary>
|
||||
public static IReadOnlyList<SyncAction> Actions(SyncEntry entry, SyncRights rights)
|
||||
{
|
||||
if (entry.Transfer is { } job) return job.State == JobState.Paused ? [SyncAction.Resume] : [SyncAction.Pause];
|
||||
var actions = new List<SyncAction>(3);
|
||||
switch (entry.Status)
|
||||
{
|
||||
case SyncStatus.LocalOnly when rights.CanUpload:
|
||||
actions.Add(SyncAction.Upload);
|
||||
break;
|
||||
case SyncStatus.RemoteOnly or SyncStatus.ProxiesOnly:
|
||||
actions.Add(SyncAction.OpenWithProxies);
|
||||
if (rights.CanFetchOriginals) actions.Add(SyncAction.DownloadOriginals);
|
||||
break;
|
||||
case SyncStatus.LocalAhead when entry.Link is { MissingRemote: > 0 }:
|
||||
if (rights.CanUpload) actions.Add(SyncAction.Upload);
|
||||
break;
|
||||
case SyncStatus.ServerAhead when entry.Link is { MissingLocal: > 0 }:
|
||||
if (rights.CanFetchOriginals) actions.Add(SyncAction.DownloadOriginals);
|
||||
break;
|
||||
case SyncStatus.LocalAhead when rights.CanEdit:
|
||||
case SyncStatus.ServerAhead:
|
||||
actions.Add(SyncAction.SyncSettings);
|
||||
break;
|
||||
case SyncStatus.Conflict:
|
||||
if (rights.CanEdit) actions.Add(SyncAction.KeepMine);
|
||||
actions.AddRange([SyncAction.TakeServer, SyncAction.SaveBoth]);
|
||||
return actions;
|
||||
}
|
||||
// Renders travel on request once no original is waiting to go either way.
|
||||
if (entry is { Local: not null, Link: { MissingRemote: 0, MissingLocal: 0 } link })
|
||||
{
|
||||
if (link.ExportsToGet > 0) actions.Add(SyncAction.GetExports);
|
||||
if (link.ExportsToSend > 0 && rights.CanUpload) actions.Add(SyncAction.SendExports);
|
||||
}
|
||||
return actions;
|
||||
}
|
||||
|
||||
/// <summary>The bytes an action moves (for the tooltips).</summary>
|
||||
public static long Size(SyncEntry entry, SyncAction action) => action switch
|
||||
{
|
||||
SyncAction.Upload => entry.Local?.TotalBytes ?? 0,
|
||||
SyncAction.DownloadOriginals => entry.Link?.TotalBytes ?? 0,
|
||||
SyncAction.GetExports => entry.Link?.ExportsToGetBytes ?? 0,
|
||||
SyncAction.SendExports => entry.Link?.ExportsToSendBytes ?? 0,
|
||||
_ => 0,
|
||||
};
|
||||
|
||||
/// <summary>The tooltip of a row button: what it does and, for transfers, what it moves.</summary>
|
||||
public static string ToolTip(SyncEntry entry, SyncAction action) => action switch
|
||||
{
|
||||
SyncAction.Upload or SyncAction.DownloadOriginals => Loc.L("Tooltips.Server.Sync." + action, Formatting.Bytes(Size(entry, action))),
|
||||
SyncAction.GetExports => Loc.Plural("Tooltips.Server.Sync.GetExports", entry.Link!.ExportsToGet, Formatting.Bytes(Size(entry, action))),
|
||||
SyncAction.SendExports => Loc.Plural("Tooltips.Server.Sync.SendExports", entry.Link!.ExportsToSend, Formatting.Bytes(Size(entry, action))),
|
||||
_ => Loc.L("Tooltips.Server.Sync." + action),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The chips sort by where the originals are: a sequence being transferred still counts as only on this PC (no server
|
||||
/// copy yet) or only on the server (no local originals yet), as the chip tooltips say.
|
||||
/// </summary>
|
||||
public static bool Matches(SyncEntry entry, SyncFilter filter, string search) =>
|
||||
(filter switch
|
||||
{
|
||||
SyncFilter.LocalOnly => entry.Status == SyncStatus.LocalOnly || entry is { Status: SyncStatus.Transferring, Link: null },
|
||||
SyncFilter.Remote => entry.Status is SyncStatus.RemoteOnly or SyncStatus.ProxiesOnly
|
||||
|| entry is { Status: SyncStatus.Transferring, HasLocalOriginals: false, Link: not null },
|
||||
SyncFilter.Conflicts => entry.Status == SyncStatus.Conflict,
|
||||
_ => true,
|
||||
}) && (search.Length == 0 || entry.Title.Contains(search, StringComparison.CurrentCultureIgnoreCase));
|
||||
|
||||
/// <summary>
|
||||
/// The label key of a difference path and the member below the setting it reaches ("isAuto", "manual", … of an
|
||||
/// Auto parameter; null for the setting itself): "exposure.deflickerWindow.manual" is the deflicker window's manual value.
|
||||
/// </summary>
|
||||
private static (string Key, string? Field) Setting(string path)
|
||||
{
|
||||
var segments = path.Split('.');
|
||||
for (var length = segments.Length; length > 0; length--)
|
||||
{
|
||||
if (SettingKeys.TryGetValue(string.Join('.', segments[..length]), out var key)) return (key, length < segments.Length ? segments[length] : null);
|
||||
}
|
||||
return ("Server.Setting.Other", segments[^1]);
|
||||
}
|
||||
|
||||
/// <summary>A title, tags, rating or notes value as shown ("—" when empty).</summary>
|
||||
private static string Text(string? value) => string.IsNullOrWhiteSpace(value) ? Loc.L("Server.Sync.None") : Shorten(value);
|
||||
|
||||
/// <summary>A side's value as shown ("41", "on", "auto"); null when it is not a single value worth printing.</summary>
|
||||
private static string? Value(string? json, string? field)
|
||||
{
|
||||
if (json is null) return field is null or "manual" ? Loc.L("Server.Sync.None") : null;
|
||||
if (field is not (null or "manual" or "autoValue" or "isAuto")) return null;
|
||||
JsonNode? node;
|
||||
try
|
||||
{
|
||||
node = JsonNode.Parse(json);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
if (field == "isAuto") return node is JsonValue v && v.TryGetValue<bool>(out var auto) ? Loc.L(auto ? "Server.Setting.Auto" : "Server.Setting.Manual") : null;
|
||||
return node switch
|
||||
{
|
||||
null => Loc.L("Server.Sync.None"),
|
||||
JsonValue value when value.TryGetValue<bool>(out var flag) => Loc.L(flag ? "Server.Setting.On" : "Server.Setting.Off"),
|
||||
JsonValue value when value.TryGetValue<double>(out var number) => number.ToString("0.###", Loc.Culture),
|
||||
JsonValue value when value.TryGetValue<string>(out var text) => Shorten(text),
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
private static string Shorten(string text) => text.Length <= 40 ? text : string.Concat(text.AsSpan(0, 39), "…");
|
||||
|
||||
private static string Join(params string[] parts) => string.Join(Loc.Separator, parts);
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
using System.Net.NetworkInformation;
|
||||
using System.Runtime.InteropServices;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Jobs;
|
||||
|
||||
namespace Chronos.App.Server;
|
||||
|
||||
/// <summary>
|
||||
/// "Pause uploads on metered networks" (Server.html): while <see cref="AppSettings.PauseUploadsOnMetered"/> is on and
|
||||
/// Windows reports the connection as metered, upload jobs are paused (a running one stops after its current chunk and
|
||||
/// keeps its checkpoint); they are resumed when the connection is no longer metered or the option goes off. Only the
|
||||
/// uploads it paused are resumed. Checked when the network or an upload job changes, and every minute.
|
||||
/// </summary>
|
||||
public sealed class UploadHold : IDisposable
|
||||
{
|
||||
private static readonly TimeSpan Interval = TimeSpan.FromMinutes(1);
|
||||
|
||||
private readonly AppServices _services;
|
||||
private readonly HashSet<Guid> _held = [];
|
||||
private readonly SemaphoreSlim _gate = new(1, 1);
|
||||
private readonly Timer _timer;
|
||||
private JobEngine? _engine;
|
||||
|
||||
public UploadHold(AppServices services)
|
||||
{
|
||||
_services = services;
|
||||
_timer = new Timer(_ => Request(), null, Interval, Interval);
|
||||
NetworkChange.NetworkAddressChanged += OnNetworkChanged;
|
||||
NetworkChange.NetworkAvailabilityChanged += OnNetworkChanged;
|
||||
}
|
||||
|
||||
/// <summary>Follows the jobs of <paramref name="engine"/> (once the index is open).</summary>
|
||||
public void Attach(JobEngine engine)
|
||||
{
|
||||
if (ReferenceEquals(_engine, engine)) return;
|
||||
if (_engine is not null) _engine.JobChanged -= OnJobChanged;
|
||||
_engine = engine;
|
||||
engine.JobChanged += OnJobChanged;
|
||||
Request();
|
||||
}
|
||||
|
||||
/// <summary>Applies the option and the connection's cost now (the option changed).</summary>
|
||||
public void Request() => _ = ApplyAsync();
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_timer.Dispose();
|
||||
NetworkChange.NetworkAddressChanged -= OnNetworkChanged;
|
||||
NetworkChange.NetworkAvailabilityChanged -= OnNetworkChanged;
|
||||
if (_engine is not null) _engine.JobChanged -= OnJobChanged;
|
||||
}
|
||||
|
||||
private bool Holding => _services.Settings.PauseUploadsOnMetered && MeteredNetwork.IsMetered();
|
||||
|
||||
private void OnNetworkChanged(object? sender, EventArgs e) => Request();
|
||||
|
||||
private void OnJobChanged(Job job)
|
||||
{
|
||||
if (job is { Kind: JobKind.UploadCommit, State: JobState.Queued or JobState.Running }) Request();
|
||||
}
|
||||
|
||||
private async Task ApplyAsync()
|
||||
{
|
||||
if (_engine is not { } engine || _services.Database is not { } db) return;
|
||||
await _gate.WaitAsync();
|
||||
try
|
||||
{
|
||||
if (Holding)
|
||||
{
|
||||
foreach (var state in new[] { JobState.Queued, JobState.Running })
|
||||
{
|
||||
foreach (var job in (await db.Jobs.ListAsync(state, JobKind.UploadCommit, 500)).Items)
|
||||
{
|
||||
await engine.PauseAsync(job.Id);
|
||||
_held.Add(job.Id);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
foreach (var id in _held)
|
||||
{
|
||||
if (await db.Jobs.GetAsync(id) is { State: JobState.Paused }) await engine.ResumeAsync(id);
|
||||
}
|
||||
_held.Clear();
|
||||
}
|
||||
catch (Data.DatabaseException ex)
|
||||
{
|
||||
Log.Warning("sync", "Uploads could not be paused or resumed for the metered connection", ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The connection cost Windows reports (Settings › Network › Metered connection) through <c>INetworkCostManager</c>.</summary>
|
||||
internal static class MeteredNetwork
|
||||
{
|
||||
private const uint Fixed = 0x2;
|
||||
private const uint Variable = 0x4;
|
||||
private const uint OverDataLimit = 0x10000;
|
||||
private const uint Roaming = 0x40000;
|
||||
|
||||
/// <summary>True when the machine's connection is metered (fixed or variable cost, over its data limit, or roaming); false when unknown.</summary>
|
||||
public static bool IsMetered()
|
||||
{
|
||||
try
|
||||
{
|
||||
var manager = (INetworkCostManager)new NetworkListManagerClass();
|
||||
try
|
||||
{
|
||||
return manager.GetCost(out var cost, IntPtr.Zero) == 0 && (cost & (Fixed | Variable | OverDataLimit | Roaming)) != 0;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Marshal.ReleaseComObject(manager);
|
||||
}
|
||||
}
|
||||
catch (COMException ex)
|
||||
{
|
||||
Log.Warning("sync", "The connection cost could not be read", ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
[ComImport]
|
||||
[Guid("DCB00C01-570F-4A9B-8D69-199FDBA5723B")]
|
||||
private class NetworkListManagerClass;
|
||||
|
||||
[ComImport]
|
||||
[Guid("DCB00008-570F-4A9B-8D69-199FDBA5723B")]
|
||||
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
private interface INetworkCostManager
|
||||
{
|
||||
[PreserveSig]
|
||||
int GetCost(out uint cost, IntPtr destination);
|
||||
|
||||
[PreserveSig]
|
||||
int GetDataPlanStatus(IntPtr status, IntPtr destination);
|
||||
|
||||
[PreserveSig]
|
||||
int SetDestinationAddresses(uint length, IntPtr addresses, short append);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user