using System.Collections.Concurrent; using System.Collections.ObjectModel; using System.IO; 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.Ui.Mvvm; namespace Titano.App.Server; /// A filter chip of the sync table: "Conflicts · 1". public sealed class SyncFilterChip(SyncFilter filter, Action 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)); /// Conflicts waiting for a choice: the chip is drawn in the warning colour unless it is the selected one. 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)); } } /// Texts in the current language. public void Relabel() { OnPropertyChanged(nameof(Text)); OnPropertyChanged(nameof(ToolTip)); } } /// /// 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. /// public sealed class SyncTableViewModel : ObservableObject, IDisposable { private readonly ShellViewModel _shell; private readonly IReadOnlyList _chips; /// "Open with proxies" waiting for its proxy download: server id → the job that fills the cache. private readonly Dictionary _openWhenCached = []; private readonly ConcurrentDictionary _progress = new(); private readonly SemaphoreSlim _reloading = new(1, 1); private readonly AsyncRelayCommand _uploadAll; private IReadOnlyList _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().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"); }); } public ObservableCollection Rows { get; } = []; public IReadOnlyList Chips => _chips; public ICommand UploadAllCommand => _uploadAll; public ICommand OpenAdminCommand { get; } public string SearchText { get => _search; set { if (Set(ref _search, value ?? string.Empty)) ApplyFilter(rebuild: true); } } /// Signed in: the table compares this PC with that server. public bool IsActive => Host.Server is not null; public bool HasRows => Rows.Count > 0; /// "Not connected to a server", "Nothing to compare yet" or "No sequence matches"; null when rows show. public string? EmptyText => HasRows ? null : !IsActive ? Loc.L("Server.Empty") : _entries.Count == 0 ? Loc.L("Server.Sync.Empty") : Loc.L("Server.Sync.NoMatch"); /// What "Upload all local" sends, or why it is disabled. 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.L("Tooltips.Server.Sync.UploadAll", Formatting.Count(LocalOnly.Count()), Formatting.Bytes(LocalOnly.Sum(e => e.Local!.TotalBytes))); /// "Last sync 10:15 · manifest diff 0.4 s"; null before the first comparison. 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; /// "Server archive 9.4 TB · 412 sequences". public string? ArchiveText => Host.Agent?.Snapshot is { } s ? Loc.Plural("Server.Sync.Archive", s.ServerSequences, Formatting.Bytes(s.ServerBytes)) : null; /// The last comparison failed (it is retried with growing pauses); null when it worked. 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; /// The server's web admin (it admits administrators only). 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 LocalOnly => _entries.Where(e => e.Status == SyncStatus.LocalOnly); /// Starts following the sync engine, the transfer jobs and the language. 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(); } /// Reads the table again; requests made while a pass runs share the next one, which they wait for. 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); } /// Counts, rows, footer and the Library's sync glyphs after a reload. 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(); } /// /// 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. /// 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(EmptyText)); } /// The existing row of an entry, updated, or a new one. private SyncRow Row(SyncEntry entry, SyncRights rights, Dictionary existing) { if (!existing.TryGetValue(entry.Id, out var row)) return new SyncRow(entry, rights, ActAsync); row.Update(entry, rights); return row; } /// The Library shows each local copy's sync state: rows it has loaded take the fresh state. 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")); 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(); } /// Settles a conflict once the user confirmed the plan: the settings that differ and what each choice overwrites. 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); } } /// The dry run of a resolution: what is replaced, by which side's values, and where "Save both" keeps this PC's. 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(); }); } /// /// "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. /// 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); } /// Transfer progress ("46 % received") without reading the table again, at most a few times a second. 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); } }