feat(app): server sync table, conflict resolution, sync options and Library sync glyphs
SyncHost runs the sync agent of the signed-in session and gives transfer jobs their connection; the Server screen lists every sequence of this PC and of the server with its state and actions (upload, download originals, open with proxies, keep mine / take server / save both, pause, resume), filter chips, search, Upload all local and the comparison footer. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
16 files changed
+1072
-10
No files matched your search
@@ -0,0 +1,137 @@
|
||||
using System.IO;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data;
|
||||
using Titano.Data.Sync;
|
||||
using Titano.Protocol.Client;
|
||||
|
||||
namespace Titano.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"/>) and a <see cref="SyncAgent"/> that keeps the
|
||||
/// table current while a session is open, started and stopped in order as the session changes. Options come from
|
||||
/// <see cref="AppSettings.SyncSettingsAutomatically"/> and <see cref="AppSettings.KeepProxiesOffline"/>.
|
||||
/// </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 (SyncAgent Agent, ISyncRemote Remote, Credentials Credentials)? _running;
|
||||
|
||||
/// <summary>Connections over <see cref="TitanoClient"/>; screenshots substitute a fake server.</summary>
|
||||
public SyncRemoteFactory RemoteFactory { get; set; } = (address, token, trusted) =>
|
||||
new TitanoSyncRemote(new TitanoClient(address, new CertificatePinning(trusted), $"Titano ({Environment.MachineName})") { Token = token }, ownsClient: true);
|
||||
|
||||
/// <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 => _running?.Agent;
|
||||
|
||||
/// <summary>The agent's connection, for the table's own calls (conflict resolution); null while signed out.</summary>
|
||||
public ISyncRemote? Remote => _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;
|
||||
|
||||
public SyncPolicy Policy => new(services.Settings.SyncSettingsAutomatically, services.Settings.KeepProxiesOffline);
|
||||
|
||||
/// <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(TitanoDatabase database, Titano.Data.Archiving.ArchiveService archives, Titano.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);
|
||||
}
|
||||
|
||||
/// <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);
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
Volatile.Write(ref _credentials, null);
|
||||
await _switch;
|
||||
await StopAsync();
|
||||
}
|
||||
|
||||
private async Task SwitchAsync(Task previous, Credentials? wanted)
|
||||
{
|
||||
await previous;
|
||||
if (_running is { } running && wanted is { } same && running.Credentials.Address == same.Address && running.Credentials.Token == same.Token) return;
|
||||
await StopAsync();
|
||||
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();
|
||||
_running = (agent, remote, start);
|
||||
Log.Info("sync", $"Comparing with {remote.Server}");
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
private async Task StopAsync()
|
||||
{
|
||||
if (_running is not { } running) return;
|
||||
_running = null;
|
||||
await running.Agent.DisposeAsync();
|
||||
running.Remote.Dispose();
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
private sealed record Credentials(Uri Address, string Token, IReadOnlyCollection<string> Fingerprints);
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
using System.Windows.Input;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Data.Sync;
|
||||
using Titano.Ui.Controls;
|
||||
using Titano.Ui.Mvvm;
|
||||
|
||||
namespace Titano.App.Server;
|
||||
|
||||
/// <summary>A row button: "Upload", "Keep mine", …</summary>
|
||||
public sealed record SyncRowAction(SyncAction Action, string Text, string ToolTip, ICommand Command);
|
||||
|
||||
/// <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 SyncRights _rights;
|
||||
|
||||
public SyncRow(SyncEntry entry, SyncRights rights, Func<SyncRow, SyncAction, Task> act)
|
||||
{
|
||||
_entry = entry;
|
||||
_rights = rights;
|
||||
_act = act;
|
||||
Actions = BuildActions();
|
||||
}
|
||||
|
||||
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;
|
||||
public string StateToolTip => SyncText.State(_entry).ToolTip;
|
||||
public IReadOnlyList<SyncRowAction> Actions { get; private set; }
|
||||
|
||||
/// <summary>Takes a fresher comparison of the same sequence.</summary>
|
||||
public void Update(SyncEntry entry, SyncRights rights)
|
||||
{
|
||||
_entry = entry;
|
||||
_rights = rights;
|
||||
Actions = BuildActions();
|
||||
OnAllPropertiesChanged();
|
||||
}
|
||||
|
||||
private List<SyncRowAction> BuildActions() =>
|
||||
[
|
||||
.. SyncText.Actions(_entry, _rights).Select(action => new SyncRowAction(action, Loc.L("Server.Sync.Action." + action), ToolTip(action),
|
||||
new AsyncRelayCommand(() => _act(this, action)))),
|
||||
];
|
||||
|
||||
private string ToolTip(SyncAction action) => action switch
|
||||
{
|
||||
SyncAction.Upload or SyncAction.DownloadOriginals => Loc.L("Tooltips.Server.Sync." + action, Formatting.Bytes(SyncText.Size(_entry, action))),
|
||||
_ => Loc.L("Tooltips.Server.Sync." + action),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Net;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Threading;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.App.Shell;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Jobs;
|
||||
using Titano.Data.Sync;
|
||||
using Titano.Protocol.Client;
|
||||
using Titano.Ui.Mvvm;
|
||||
|
||||
namespace Titano.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.</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>
|
||||
/// 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, settle a settings 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;
|
||||
private readonly HashSet<Guid> _openWhenCached = [];
|
||||
private readonly ConcurrentDictionary<Guid, JobProgressInfo> _progress = new();
|
||||
private readonly SemaphoreSlim _reloading = new(1, 1);
|
||||
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 })];
|
||||
UploadAllCommand = new AsyncRelayCommand(UploadAllAsync, () => Rights.CanUpload && LocalOnly.Any());
|
||||
OpenAdminCommand = new RelayCommand(() =>
|
||||
{
|
||||
if (Host.Server is { } server) ShellActions.OpenUrl(server + "/admin");
|
||||
});
|
||||
}
|
||||
|
||||
public ObservableCollection<SyncRow> Rows { get; } = [];
|
||||
public IReadOnlyList<SyncFilterChip> Chips => _chips;
|
||||
public ICommand UploadAllCommand { get; }
|
||||
public ICommand OpenAdminCommand { get; }
|
||||
|
||||
public string SearchText
|
||||
{
|
||||
get => _search;
|
||||
set
|
||||
{
|
||||
if (Set(ref _search, value ?? string.Empty)) ApplyFilter();
|
||||
}
|
||||
}
|
||||
|
||||
/// <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;
|
||||
|
||||
/// <summary>"Not connected to a server", "Nothing to compare yet" or "No sequence matches"; null when rows show.</summary>
|
||||
public string? EmptyText => HasRows ? null
|
||||
: !IsActive ? Loc.L("Server.Empty")
|
||||
: _entries.Count == 0 ? Loc.L("Server.Sync.Empty")
|
||||
: Loc.L("Server.Sync.NoMatch");
|
||||
|
||||
public string UploadAllToolTip => Loc.L("Tooltips.Server.Sync.UploadAll", Formatting.Count(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 (it admits administrators only).</summary>
|
||||
public bool CanOpenAdmin => IsActive;
|
||||
|
||||
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 and the transfer jobs.</summary>
|
||||
public void Attach()
|
||||
{
|
||||
if (_attached) return;
|
||||
_attached = true;
|
||||
Host.Changed += OnChanged;
|
||||
if (_shell.Services.Jobs is { } jobs)
|
||||
{
|
||||
jobs.JobChanged += OnJobChanged;
|
||||
jobs.Progress += OnProgress;
|
||||
}
|
||||
_ = ReloadAsync();
|
||||
}
|
||||
|
||||
/// <summary>Reads the table again; concurrent requests collapse into one more pass.</summary>
|
||||
public async Task ReloadAsync()
|
||||
{
|
||||
Interlocked.Exchange(ref _reloadQueued, 1);
|
||||
if (!await _reloading.WaitAsync(0)) return;
|
||||
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;
|
||||
Host.Changed -= OnChanged;
|
||||
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();
|
||||
}
|
||||
|
||||
/// <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();
|
||||
UpdateLibrary();
|
||||
OpenCachedProxies();
|
||||
OnPropertyChanged(nameof(IsActive));
|
||||
OnPropertyChanged(nameof(UploadAllToolTip));
|
||||
OnPropertyChanged(nameof(LastSyncText));
|
||||
OnPropertyChanged(nameof(ArchiveText));
|
||||
OnPropertyChanged(nameof(ErrorText));
|
||||
OnPropertyChanged(nameof(ErrorToolTip));
|
||||
OnPropertyChanged(nameof(CanOpenAdmin));
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
|
||||
/// <summary>Updates the rows in place (scroll position and recycled containers survive), adding and removing as needed.</summary>
|
||||
private void ApplyFilter()
|
||||
{
|
||||
var rights = Rights;
|
||||
var wanted = _entries.Where(e => SyncText.Matches(e, _filter, _search.Trim())).ToList();
|
||||
var byId = Rows.ToDictionary(r => r.Id);
|
||||
for (var i = 0; i < wanted.Count; i++)
|
||||
{
|
||||
var entry = wanted[i];
|
||||
if (byId.Remove(entry.Id, out var row))
|
||||
{
|
||||
row.Update(entry, rights);
|
||||
var at = Rows.IndexOf(row);
|
||||
if (at != i) Rows.Move(at, i);
|
||||
}
|
||||
else
|
||||
{
|
||||
Rows.Insert(i, new SyncRow(entry, rights, ActAsync));
|
||||
}
|
||||
}
|
||||
while (Rows.Count > wanted.Count) Rows.RemoveAt(Rows.Count - 1);
|
||||
OnPropertyChanged(nameof(HasRows));
|
||||
OnPropertyChanged(nameof(EmptyText));
|
||||
}
|
||||
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"Open with proxies" waits for the proxy download; the editor opens once it is in the cache.</summary>
|
||||
private void OpenCachedProxies()
|
||||
{
|
||||
foreach (var entry in _entries)
|
||||
{
|
||||
if (entry.Status == SyncStatus.ProxiesOnly && _openWhenCached.Remove(entry.Id)) _shell.OpenSequence(entry.Id);
|
||||
}
|
||||
}
|
||||
|
||||
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.DownloadOriginals:
|
||||
if ((entry.Local?.ArchiveId ?? (await Host.CurrentArchiveAsync())?.Id) is not { } archive)
|
||||
{
|
||||
_shell.Notify(Loc.L("Errors.Sync.NoArchive"));
|
||||
return;
|
||||
}
|
||||
await service.EnqueueDownloadAsync(engine, server, entry.Id, entry.Title, SyncDownloadMode.Originals, archive);
|
||||
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:
|
||||
_openWhenCached.Add(entry.Id);
|
||||
await service.EnqueueDownloadAsync(engine, server, entry.Id, entry.Title, SyncDownloadMode.Proxies, null);
|
||||
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, 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; overwriting one side is confirmed first with the settings that differ (the dry run).</summary>
|
||||
private async Task ResolveAsync(SyncService service, ISyncRemote remote, SyncEntry entry, SyncAction action)
|
||||
{
|
||||
var resolution = action switch
|
||||
{
|
||||
SyncAction.KeepMine => SyncResolution.KeepMine,
|
||||
SyncAction.TakeServer => SyncResolution.TakeServer,
|
||||
_ => SyncResolution.SaveBoth,
|
||||
};
|
||||
if (resolution != SyncResolution.SaveBoth && !_shell.Services.Dialogs.Confirm(new ConfirmRequest
|
||||
{
|
||||
Heading = Loc.L("Server.Conflict." + action + ".Title"),
|
||||
Message = Loc.L("Server.Conflict." + action + ".Message", entry.Title),
|
||||
Detail = SyncText.Conflict(entry),
|
||||
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 = true,
|
||||
})) return;
|
||||
try
|
||||
{
|
||||
await service.ResolveAsync(remote, entry.Id, resolution, CancellationToken.None);
|
||||
}
|
||||
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.Conflict)
|
||||
{
|
||||
// The server copy changed again meanwhile: compare again and let the user choose on fresh content.
|
||||
_shell.Notify(Loc.L("Server.Sync.ChangedAgain"));
|
||||
await service.RefreshSequencesAsync(remote, [entry.Id], Host.Policy, CancellationToken.None);
|
||||
}
|
||||
}
|
||||
|
||||
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 OnJobChanged(Job job)
|
||||
{
|
||||
if (job.Kind is not (JobKind.UploadCommit or JobKind.Download)) return;
|
||||
_progress.TryRemove(job.Id, out _);
|
||||
OnChanged();
|
||||
}
|
||||
|
||||
/// <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);
|
||||
var rights = Rights;
|
||||
foreach (var row in Rows)
|
||||
{
|
||||
if (row.Entry.Transfer is { } job && _progress.TryGetValue(job.Id, out var p))
|
||||
row.Update(row.Entry with { Transfer = job with { ProgressDone = p.Done, ProgressTotal = p.Total } }, rights);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
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,147 @@
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Sync;
|
||||
using Titano.Ui.Controls;
|
||||
|
||||
namespace Titano.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,
|
||||
Pause,
|
||||
Resume,
|
||||
}
|
||||
|
||||
/// <summary>What the signed-in account may do (server permission bits).</summary>
|
||||
/// <param name="CanUpload">Send originals and settings.</param>
|
||||
/// <param name="CanFetchOriginals">Download originals (editors and render nodes).</param>
|
||||
public readonly record struct SyncRights(bool CanUpload, bool CanFetchOriginals)
|
||||
{
|
||||
public static SyncRights Of(long permissions) => new(
|
||||
(permissions & (long)Permissions.Upload) != 0 && (permissions & (long)Permissions.Edit) != 0,
|
||||
(permissions & (long)(Permissions.Edit | Permissions.RenderNode)) != 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>"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")),
|
||||
};
|
||||
}
|
||||
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"), Conflict(entry)),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>"exposure.deflickerWindow.manual: 41 here, 33 on the server" for each setting that differs (at most three).</summary>
|
||||
public static string Conflict(SyncEntry entry)
|
||||
{
|
||||
var differences = entry.Link?.ConflictSettingsJson is { } theirs ? SyncRules.Differences(entry.Local?.SettingsJson, theirs) : [];
|
||||
if (differences.Count == 0) return Loc.L("Tooltips.Server.Sync.State.Conflict");
|
||||
return string.Join("\n", differences.Select(d => Loc.L("Server.Conflict.Difference", d.Path, d.Mine ?? Loc.L("Server.Sync.None"), d.Theirs ?? Loc.L("Server.Sync.None"))));
|
||||
}
|
||||
|
||||
/// <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 or SyncStatus.ServerAhead:
|
||||
actions.Add(SyncAction.SyncSettings);
|
||||
break;
|
||||
case SyncStatus.Conflict:
|
||||
actions.AddRange([SyncAction.KeepMine, SyncAction.TakeServer, SyncAction.SaveBoth]);
|
||||
break;
|
||||
}
|
||||
return actions;
|
||||
}
|
||||
|
||||
/// <summary>The bytes an upload or download of the row 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,
|
||||
_ => 0,
|
||||
};
|
||||
|
||||
public static bool Matches(SyncEntry entry, SyncFilter filter, string search) =>
|
||||
(filter switch
|
||||
{
|
||||
SyncFilter.LocalOnly => entry.Status == SyncStatus.LocalOnly,
|
||||
SyncFilter.Remote => entry.Status is SyncStatus.RemoteOnly or SyncStatus.ProxiesOnly,
|
||||
SyncFilter.Conflicts => entry.Status == SyncStatus.Conflict,
|
||||
_ => true,
|
||||
}) && (search.Length == 0 || entry.Title.Contains(search, StringComparison.CurrentCultureIgnoreCase));
|
||||
|
||||
private static string Join(params string[] parts) => string.Join(" · ", parts);
|
||||
}
|
||||
Reference in new issue
Block a user