Files
Chronos/src/Chronos.App/Server/SyncTableViewModel.cs
T
Alby96andClaude Opus 5.5 b34b6b6fe0 fix(copies): close the owner review 6 verification findings
A merge could still trash photos it never verified, resume against a
pair the user had answered meanwhile, and take different unhashed
photos for copies; the dialog and the lists worded several facts
wrongly or lost them on refresh.

- Merge: a retry resumes only while the pair is still the job's;
  Verify requires the other archive online and its folder in place,
  stops on an unreadable photo, files a differing unhashed photo as a
  second version and must cover every frame before Trash; the plan
  hashes unmatched unhashed photos first, lists "Deleted in the other"
  and names the relinked servers; second versions stay discoverable
  (CopySides.VersionsAsync).
- Integrate: a retry after a failure before the journal runs again.
- Sync: a sequence back after a 404 stays Linked while its link holds;
  a local cull no longer asks for attention.
- Block lines of both planners name the right sequence, archive,
  server and space through one formatter.
- Compare dialog: one Details row per setting with worded values,
  Projects headings, Choose focuses the kept-sequence radios, the
  photo selection reaches rows outside the viewport, the Replace
  confirmation lists the losers per side, plan lines read as queued.
- Matches and Library: counts first and grouped, integrating shown as
  a share, local matches name the other archive, the Library keeps its
  match and "deleted on server" statuses across a refresh.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:02:39 +01:00

640 lines
28 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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;
/// <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;
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));
/// <summary>Conflicts, or matches, 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 : Filter == SyncFilter.FoundCopies && _attention;
/// <summary>Matches: some pair asks for a choice (set by the sync table from the copy list).</summary>
public bool Attention
{
get => _attention;
set
{
if (Set(ref _attention, value)) OnPropertyChanged(nameof(NeedsAttention));
}
}
/// <summary>The Matches chip shows signed out too while this PC has more than one archive; the others only signed in.</summary>
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));
}
}
/// <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;
private bool _hasArchives;
/// <summary>The local-only sequences the last Upload all local left out, and why (owner review 6, Q8).</summary>
private readonly Dictionary<Guid, UploadSkip> _skipped = [];
/// <summary>Show was pressed on the Upload all toast: Local only lists the skipped sequences first.</summary>
private bool _skippedFirst;
public SyncTableViewModel(ShellViewModel shell)
{
_shell = shell;
_chips = [.. Enum.GetValues<SyncFilter>().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<SyncRow> Rows { get; } = [];
public IReadOnlyList<SyncFilterChip> Chips => _chips;
/// <summary>Server › Matches (owner review 6, #73): shown in place of the rows while its chip is selected.</summary>
public CopyListViewModel Copies { get; }
/// <summary>The Matches chip is selected: the copy list, its header and Find matches replace the sync rows.</summary>
public bool IsMatches => _filter == SyncFilter.FoundCopies;
public bool ShowSyncList => !IsMatches && HasRows;
public bool ShowCopyList => IsMatches && Copies.HasRows;
public bool ShowCopyEmpty => IsMatches && Copies.IsEmpty;
/// <summary>The chips show while signed in, and signed out while this PC has more than one archive (local matches).</summary>
public bool ShowChips => IsActive || _hasArchives;
/// <summary>The search box filters the sync rows signed in, and the matches whenever they show.</summary>
public bool ShowSearch => IsActive || IsMatches;
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)) return;
Copies.SearchText = _search;
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 || IsMatches ? 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")
: SelectUploads(new HashSet<Guid>()).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)));
/// <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(AppClock.Shown(s.RefreshedAt)),
AppClock.Shown(s.Duration, TimeSpan.FromSeconds(0.4)).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) with { KeepsProjects = Host.HasProjects } : 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;
Host.PhotosNotSent += OnPhotosNotSent;
Loc.CultureChanged += OnCultureChanged;
if (_shell.Services.Jobs is { } jobs)
{
jobs.JobChanged += OnJobChanged;
jobs.Progress += OnProgress;
}
Copies.Attach();
_ = ReloadAsync();
}
/// <summary>Selects a chip (the Matches toasts' Review and Show, Library › Compare…), with a search text when given.</summary>
internal void ShowFilter(SyncFilter filter, string? search = null)
{
if (search is not null) SearchText = search;
Select(filter);
}
/// <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;
Host.PhotosNotSent -= OnPhotosNotSent;
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));
}
/// <summary>The copy list reloaded: the Matches chip's count and colour, its visibility, and the rows' marks.</summary>
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();
}
/// <summary>Whether this PC has more than one archive (the Matches chip shows signed out then).</summary>
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;
}
/// <summary>What the Matches list adds to the row of <paramref name="entry"/>: its pair and why Upload all left it out.</summary>
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,
Host.PhotoFailures.TryGetValue(local.Id, out var failure) && failure.Count >= SyncAgent.NotSentAfter ? failure : null,
Copies.OtherWhere(local.Id))
: new SyncMark(Copies.PairOf(entry.Id), null, _shell.Services.Server.Flow.Info?.Name, OtherWhere: Copies.OtherWhere(entry.Id));
/// <summary>The rule of Upload all local (design §6.4): what it sends, and what it leaves out and why.</summary>
/// <param name="busy">The targets of pending Integrate and Merge jobs.</param>
/// <param name="pairs">Every pair of the index (the last reload's when null), never only the ones listed for this server.</param>
private (IReadOnlyList<SyncEntry> Upload, IReadOnlyList<(SyncEntry Entry, UploadSkip Why)> Skipped) SelectUploads(IReadOnlySet<Guid> busy,
IReadOnlyList<FoundCopy>? pairs = null) =>
UploadAllRule.Select(LocalOnly, pairs ?? Copies.AllPairs,
_shell.Services.Settings.KnownServers.Select(k => k.OriginalsArchiveId).OfType<Guid>().ToHashSet(), busy);
/// <summary>Counts, rows, footer and the Library's sync glyphs after a reload.</summary>
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();
}
/// <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();
// 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));
}
/// <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, Mark(entry));
row.Update(entry, rights, Mark(entry));
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.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();
}
/// <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;
// 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<Guid>();
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();
}
/// <summary>Show on the Upload all toast: Local only, the skipped sequences first.</summary>
private void ShowSkipped()
{
_shell.Navigate(SectionKey.Server);
Select(SyncFilter.LocalOnly);
_skippedFirst = true;
ApplyFilter(rebuild: true);
}
private void OnChanged() => Dispatch(() => _ = ReloadAsync());
private void OnPhotosNotSent(string server, Guid localId, AutoPhotoFailure failure) => Dispatch(() => _ = TellNotSentAsync(localId));
/// <summary>
/// The new photos of an integrated pair failed to move by themselves three times in a row (design §6.1): "{title}: photos
/// not sent" · Show, which shows the sequence's row (it reads "not sent", the reason in its tooltip).
/// </summary>
internal async Task TellNotSentAsync(Guid localId)
{
var title = _entries.FirstOrDefault(e => e.Local?.Id == localId)?.Title;
if (title is null && _shell.Services.Database is { } db)
{
try
{
title = (await db.Sequences.GetAsync(localId))?.DisplayTitle;
}
catch (Data.DatabaseException ex)
{
Log.Warning("sync", "The sequence whose photos were not sent could not be read", ex);
}
}
if (title is null) return;
var shown = title;
_shell.Notify(Loc.L("Server.Sync.NotSentToast", title), null, Loc.L("Server.Sync.Show"), Loc.L("Tooltips.Server.Sync.ShowNotSent"), () =>
{
_shell.Navigate(SectionKey.Server);
ShowFilter(SyncFilter.All, shown);
}, isError: true, runsFromNotification: true);
await 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();
});
}
/// <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);
}
}