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.Server.Copies; using Chronos.App.Shell; using Chronos.Core.Diagnostics; using Chronos.Core.Localization; using Chronos.Core.Model; using Chronos.Data.Copies; using Chronos.Data.Jobs; using Chronos.Data.Sync; using Chronos.Ui.Mvvm; namespace Chronos.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; private bool _attention; private bool _isVisible = true; 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, or matches, 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 : Filter == SyncFilter.FoundCopies && _attention; /// Matches: some pair asks for a choice (set by the sync table from the copy list). public bool Attention { get => _attention; set { if (Set(ref _attention, value)) OnPropertyChanged(nameof(NeedsAttention)); } } /// The Matches chip shows signed out too while this PC has more than one archive; the others only signed in. public bool IsVisible { get => _isVisible; set => Set(ref _isVisible, value); } 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)); } } /// Why the sync table shows no rows; each case has its one action (BRIEF §0.2 rule 6). public enum SyncEmpty { None, SignedOut, Nothing, NoMatch, } /// /// 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; private bool _hasArchives; /// The local-only sequences the last Upload all local left out, and why (owner review 6, Q8). private readonly Dictionary _skipped = []; /// Show was pressed on the Upload all toast: Local only lists the skipped sequences first. private bool _skippedFirst; public SyncTableViewModel(ShellViewModel shell) { _shell = shell; _chips = [.. Enum.GetValues().Select(f => new SyncFilterChip(f, Select) { IsSelected = f == SyncFilter.All })]; Copies = new CopyListViewModel(shell) { ShowList = search => ShowFilter(SyncFilter.FoundCopies, search) }; Copies.Changed += OnCopiesChanged; _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 Rows { get; } = []; public IReadOnlyList Chips => _chips; /// Server › Matches (owner review 6, #73): shown in place of the rows while its chip is selected. public CopyListViewModel Copies { get; } /// The Matches chip is selected: the copy list, its header and Find matches replace the sync rows. public bool IsMatches => _filter == SyncFilter.FoundCopies; public bool ShowSyncList => !IsMatches && HasRows; public bool ShowCopyList => IsMatches && Copies.HasRows; public bool ShowCopyEmpty => IsMatches && Copies.IsEmpty; /// The chips show while signed in, and signed out while this PC has more than one archive (local matches). public bool ShowChips => IsActive || _hasArchives; /// The search box filters the sync rows signed in, and the matches whenever they show. public bool ShowSearch => IsActive || IsMatches; public ICommand UploadAllCommand => _uploadAll; public ICommand OpenAdminCommand { get; } /// "No sequence matches": back to every sequence. public ICommand ClearFiltersCommand { get; } /// "Nothing to compare yet": bring photos in. public ICommand ImportCommand { get; } public string SearchText { get => _search; set { if (!Set(ref _search, value ?? string.Empty)) return; Copies.SearchText = _search; 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; public SyncEmpty Empty => HasRows || IsMatches ? SyncEmpty.None : !IsActive ? SyncEmpty.SignedOut : _entries.Count == 0 ? SyncEmpty.Nothing : SyncEmpty.NoMatch; /// "Not connected to a server", "Nothing to compare yet" or "No sequence matches"; null when rows show. 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, }; /// 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") : SelectUploads(new HashSet()).Skipped.Count is > 0 and var skipping ? Loc.Plural("Tooltips.Server.Sync.UploadAllSkipping", skipping) : Loc.Plural("Tooltips.Server.Sync.UploadAll", 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(AppClock.Shown(s.RefreshedAt)), AppClock.Shown(s.Duration, TimeSpan.FromSeconds(0.4)).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 admits administrators only: the link shows for accounts that manage the archive or users. 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) with { KeepsProjects = Host.HasProjects } : 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; } Copies.Attach(); _ = ReloadAsync(); } /// Selects a chip (the Matches toasts' Review and Show, Library › Compare…), with a search text when given. internal void ShowFilter(SyncFilter filter, string? search = null) { if (search is not null) SearchText = search; Select(filter); } /// 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; } Copies.Changed -= OnCopiesChanged; Copies.Dispose(); } private void Select(SyncFilter filter) { _filter = filter; if (filter != SyncFilter.LocalOnly) _skippedFirst = false; foreach (var chip in _chips) chip.IsSelected = chip.Filter == filter; ApplyFilter(rebuild: true); RaiseLists(); } private void RaiseLists() { OnPropertyChanged(nameof(IsMatches)); OnPropertyChanged(nameof(ShowSyncList)); OnPropertyChanged(nameof(ShowCopyList)); OnPropertyChanged(nameof(ShowCopyEmpty)); OnPropertyChanged(nameof(ShowChips)); OnPropertyChanged(nameof(ShowSearch)); OnPropertyChanged(nameof(Empty)); OnPropertyChanged(nameof(EmptyText)); } /// The copy list reloaded: the Matches chip's count and colour, its visibility, and the rows' marks. private void OnCopiesChanged() { var chip = _chips.Single(c => c.Filter == SyncFilter.FoundCopies); chip.Count = Copies.Count; chip.Attention = Copies.AttentionCount > 0; _ = UpdateArchivesAsync(); ApplyFilter(rebuild: false); OnPropertyChanged(nameof(UploadAllToolTip)); RaiseLists(); } /// Whether this PC has more than one archive (the Matches chip shows signed out then). private async Task UpdateArchivesAsync() { if (_shell.Services.Database is not { } db) return; try { _hasArchives = (await db.Archives.ListAsync()).Count > 1; } catch (Data.DatabaseException) { _hasArchives = false; } UpdateChipVisibility(); OnPropertyChanged(nameof(ShowChips)); } private void UpdateChipVisibility() { foreach (var chip in _chips) chip.IsVisible = chip.Filter == SyncFilter.FoundCopies ? IsActive || _hasArchives : IsActive; } /// What the Matches list adds to the row of : its pair and why Upload all left it out. private SyncMark Mark(SyncEntry entry) => entry.Local is { } local ? new SyncMark(Copies.PairOf(local.Id), _skipped.TryGetValue(local.Id, out var why) ? why : null, _shell.Services.Server.Flow.Info?.Name) : new SyncMark(Copies.PairOf(entry.Id), null, _shell.Services.Server.Flow.Info?.Name); /// The rule of Upload all local (design §6.4): what it sends, and what it leaves out and why. /// The targets of pending Integrate and Merge jobs. /// Every pair of the index (the last reload's when null), never only the ones listed for this server. private (IReadOnlyList Upload, IReadOnlyList<(SyncEntry Entry, UploadSkip Why)> Skipped) SelectUploads(IReadOnlySet busy, IReadOnlyList? pairs = null) => UploadAllRule.Select(LocalOnly, pairs ?? Copies.AllPairs, _shell.Services.Settings.KnownServers.Select(k => k.OriginalsArchiveId).OfType().ToHashSet(), busy); /// Counts, rows, footer and the Library's sync glyphs after a reload. private void Refresh() { foreach (var chip in _chips.Where(c => c.Filter != SyncFilter.FoundCopies)) chip.Count = _entries.Count(e => SyncText.Matches(e, chip.Filter, string.Empty)); UpdateChipVisibility(); ApplyFilter(rebuild: false); RaiseLists(); 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(); // Show on the Upload all toast: the sequences it left out lead Local only. if (_skippedFirst) wanted = [.. wanted.OrderByDescending(e => e.Local is { } l && _skipped.ContainsKey(l.Id))]; 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, Mark(entry)); 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)); } /// 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, Mark(entry)); row.Update(entry, rights, Mark(entry)); 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.Compare: Copies.Compare(entry.Local?.Id ?? entry.Id); return; 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 (await Host.OriginalsForDownloadAsync(entry.Local, (title, message, isError) => _shell.Notify(title, message, isError: isError)) is not { } archive) 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; // Edit opens it as a workspace project of the server: the project opened last, else "Open in workspace" asks (phase 5b). case SyncAction.OpenInWorkspace when Host.HasProjects: _shell.OpenSequence(entry.Id); return; case SyncAction.OpenInWorkspace: return; 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, isError: true); } } /// 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; // Suspected matches, kept-apart sequences, those the server deleted, those an Integrate or Merge holds and those of a // server's originals archive stay, flagged "skipped" with the reason (owner review 6, Q8). var busy = new HashSet(); if (_shell.Services.Database is { } db) { busy.UnionWith(await db.Jobs.ListPendingTargetsAsync(JobKind.Integrate)); busy.UnionWith(await db.Jobs.ListPendingTargetsAsync(JobKind.MergeSequences)); } // The pairs as stored now: one found or answered since the last reload counts too. var pairs = Copies.Engine is { } copies ? await copies.ListAllPairsAsync(CancellationToken.None) : Copies.AllPairs; var (upload, skipped) = SelectUploads(busy, pairs); _skipped.Clear(); foreach (var (entry, why) in skipped) _skipped[entry.Local!.Id] = why; foreach (var entry in upload) await service.EnqueueUploadAsync(engine, server, entry.Local!); if (skipped.Count == 0) _shell.Notify(Loc.Plural("Server.Sync.Queued", upload.Count)); else _shell.Notify(Loc.L("Server.Sync.QueuedSkipped", Formatting.Count(upload.Count), Formatting.Count(skipped.Count)), null, Loc.L("Server.Sync.Show"), Loc.L("Tooltips.Server.Sync.ShowSkipped"), ShowSkipped); await ReloadAsync(); } /// Show on the Upload all toast: Local only, the skipped sequences first. private void ShowSkipped() { _shell.Navigate(SectionKey.Server); Select(SyncFilter.LocalOnly); _skippedFirst = true; ApplyFilter(rebuild: true); } 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 or JobKind.Integrate or JobKind.MergeSequences)) 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); } }