fix(sync): resolve conflicts against the versions shown, isolate failures, renders on request
- Conflicts are settled against the versions the user was shown; a later change on
either side refuses the choice and compares again. Title, tags, rating and notes
changed differently on both sides are a conflict too (no silent tag union).
- Links are written under the engine's gate and forgotten only after a 404; linked
local copies are read by id; unlinked copies with the same originals are linked
by content.
- A failure on one sequence is recorded on its link; the others are still compared.
- Downloads hash unverified local copies first and restore originals missing here.
- Background proxy downloads give way to the user's requests; "Keep proxies offline"
refreshes the caches of sequences opened with proxies, checks free space and backs
off after a failure.
- Renders travel on request: Send exports (chunked, hash-verified upload keeping the
render id; new POST /sequences/{id}/renders endpoints) and Get exports.
- Server screen: stable row buttons, mockup column grid, Tab through rows, conflict
rows first on the card colour, localised conflict detail, Save both confirmation,
Pause metered uploads, culture switch, Library one-word sync glyphs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
48 files changed
+2498
-465
No files matched your search
@@ -13,9 +13,10 @@ public delegate ISyncRemote SyncRemoteFactory(Uri address, string token, IReadOn
|
||||
|
||||
/// <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"/>.
|
||||
/// connection of upload and download jobs (<see cref="ISyncConnector"/>), a <see cref="SyncAgent"/> that keeps the
|
||||
/// table current while a session is open, started and stopped in order as the session changes, and the
|
||||
/// <see cref="UploadHold"/> for metered connections. Options come from <see cref="AppSettings.SyncSettingsAutomatically"/>,
|
||||
/// <see cref="AppSettings.KeepProxiesOffline"/> and <see cref="AppSettings.PauseUploadsOnMetered"/>.
|
||||
/// </summary>
|
||||
public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDisposable
|
||||
{
|
||||
@@ -42,7 +43,12 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
|
||||
/// <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 options, and whether the account may change server sequences (without it this PC's edits are not sent).</summary>
|
||||
public SyncPolicy Policy => new(services.Settings.SyncSettingsAutomatically, services.Settings.KeepProxiesOffline,
|
||||
services.Server.User is { } user && (user.Permissions & (long)Permissions.Edit) != 0);
|
||||
|
||||
/// <summary>Pauses uploads while the connection is metered and the option is on.</summary>
|
||||
public UploadHold Uploads { get; } = new(services);
|
||||
|
||||
/// <summary>The agent started, stopped or compared, or the table of the signed-in server changed (any thread).</summary>
|
||||
public event Action? Changed;
|
||||
@@ -68,6 +74,7 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
|
||||
: null;
|
||||
Volatile.Write(ref _credentials, wanted);
|
||||
_switch = SwitchAsync(_switch, wanted);
|
||||
if (services.Engine is { } engine) Uploads.Attach(engine);
|
||||
}
|
||||
|
||||
/// <summary>Compares now, once the session switch in progress settled; null while signed out.</summary>
|
||||
@@ -108,6 +115,7 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
Volatile.Write(ref _credentials, null);
|
||||
Uploads.Dispose();
|
||||
await _switch;
|
||||
await StopAsync();
|
||||
}
|
||||
|
||||
@@ -1,28 +1,43 @@
|
||||
using System.Windows.Input;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
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>A row button: "Upload", "Keep mine", …; kept while the row offers it, so focus, tooltips and clicks survive updates.</summary>
|
||||
public sealed class SyncRowAction(SyncAction action, ICommand command) : ObservableObject
|
||||
{
|
||||
private string _toolTip = string.Empty;
|
||||
|
||||
public SyncAction Action { get; } = action;
|
||||
public string Text => Loc.L("Server.Sync.Action." + Action);
|
||||
public ICommand Command { get; } = command;
|
||||
|
||||
public string ToolTip
|
||||
{
|
||||
get => _toolTip;
|
||||
set => Set(ref _toolTip, value);
|
||||
}
|
||||
|
||||
/// <summary>The label in the current language.</summary>
|
||||
public void Relabel() => OnPropertyChanged(nameof(Text));
|
||||
}
|
||||
|
||||
/// <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;
|
||||
private IReadOnlyList<SyncRowAction> _actions = [];
|
||||
|
||||
public SyncRow(SyncEntry entry, SyncRights rights, Func<SyncRow, SyncAction, Task> act)
|
||||
{
|
||||
_entry = entry;
|
||||
_rights = rights;
|
||||
_act = act;
|
||||
Actions = BuildActions();
|
||||
UpdateActions(rights);
|
||||
}
|
||||
|
||||
public SyncEntry Entry => _entry;
|
||||
@@ -33,26 +48,62 @@ public sealed class SyncRow : ObservableObject
|
||||
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>
|
||||
/// <summary>Settings differ on both sides: the row is drawn on the card colour, as in Server.html.</summary>
|
||||
public bool IsConflict => _entry.Status == SyncStatus.Conflict && _entry.Transfer is null;
|
||||
|
||||
public IReadOnlyList<SyncRowAction> Actions
|
||||
{
|
||||
get => _actions;
|
||||
private set => Set(ref _actions, value);
|
||||
}
|
||||
|
||||
/// <summary>Takes a fresher comparison of the same sequence; buttons the row still offers are kept.</summary>
|
||||
public void Update(SyncEntry entry, SyncRights rights)
|
||||
{
|
||||
_entry = entry;
|
||||
_rights = rights;
|
||||
Actions = BuildActions();
|
||||
OnAllPropertiesChanged();
|
||||
UpdateActions(rights);
|
||||
RaiseTexts();
|
||||
}
|
||||
|
||||
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
|
||||
/// <summary>Takes the progress of the row's transfer ("46 % received") without touching its buttons.</summary>
|
||||
public void UpdateProgress(long done, long total)
|
||||
{
|
||||
SyncAction.Upload or SyncAction.DownloadOriginals => Loc.L("Tooltips.Server.Sync." + action, Formatting.Bytes(SyncText.Size(_entry, action))),
|
||||
_ => Loc.L("Tooltips.Server.Sync." + action),
|
||||
};
|
||||
if (_entry.Transfer is not { } job) return;
|
||||
_entry = _entry with { Transfer = job with { ProgressDone = done, ProgressTotal = total } };
|
||||
OnPropertyChanged(nameof(ServerText));
|
||||
}
|
||||
|
||||
/// <summary>Texts in the current language.</summary>
|
||||
public void Relabel()
|
||||
{
|
||||
foreach (var action in _actions)
|
||||
{
|
||||
action.Relabel();
|
||||
action.ToolTip = SyncText.ToolTip(_entry, action.Action);
|
||||
}
|
||||
RaiseTexts();
|
||||
}
|
||||
|
||||
private void UpdateActions(SyncRights rights)
|
||||
{
|
||||
var wanted = SyncText.Actions(_entry, rights);
|
||||
if (!wanted.SequenceEqual(_actions.Select(a => a.Action)))
|
||||
{
|
||||
var kept = _actions.ToDictionary(a => a.Action);
|
||||
Actions = [.. wanted.Select(action => kept.GetValueOrDefault(action) ?? new SyncRowAction(action, new AsyncRelayCommand(() => _act(this, action))))];
|
||||
}
|
||||
foreach (var action in _actions) action.ToolTip = SyncText.ToolTip(_entry, action.Action);
|
||||
}
|
||||
|
||||
private void RaiseTexts()
|
||||
{
|
||||
OnPropertyChanged(nameof(Title));
|
||||
OnPropertyChanged(nameof(LocalText));
|
||||
OnPropertyChanged(nameof(ServerText));
|
||||
OnPropertyChanged(nameof(StateKind));
|
||||
OnPropertyChanged(nameof(StateText));
|
||||
OnPropertyChanged(nameof(StateToolTip));
|
||||
OnPropertyChanged(nameof(IsConflict));
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Net;
|
||||
using System.IO;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Threading;
|
||||
using Titano.App.Infrastructure;
|
||||
@@ -10,7 +10,6 @@ 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;
|
||||
@@ -26,7 +25,7 @@ public sealed class SyncFilterChip(SyncFilter filter, Action<SyncFilter> select)
|
||||
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>
|
||||
/// <summary>Conflicts waiting for a choice: the chip is drawn in the warning colour unless it is the selected one.</summary>
|
||||
public bool NeedsAttention => Filter == SyncFilter.Conflicts && _count > 0;
|
||||
|
||||
public bool IsSelected
|
||||
@@ -45,22 +44,33 @@ public sealed class SyncFilterChip(SyncFilter filter, Action<SyncFilter> select)
|
||||
OnPropertyChanged(nameof(NeedsAttention));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Texts in the current language.</summary>
|
||||
public void Relabel()
|
||||
{
|
||||
OnPropertyChanged(nameof(Text));
|
||||
OnPropertyChanged(nameof(ToolTip));
|
||||
}
|
||||
}
|
||||
|
||||
/// <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.
|
||||
/// 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;
|
||||
private readonly HashSet<Guid> _openWhenCached = [];
|
||||
|
||||
/// <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;
|
||||
@@ -72,7 +82,7 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
|
||||
{
|
||||
_shell = shell;
|
||||
_chips = [.. Enum.GetValues<SyncFilter>().Select(f => new SyncFilterChip(f, Select) { IsSelected = f == SyncFilter.All })];
|
||||
UploadAllCommand = new AsyncRelayCommand(UploadAllAsync, () => Rights.CanUpload && LocalOnly.Any());
|
||||
_uploadAll = new AsyncRelayCommand(UploadAllAsync, () => IsActive && Rights.CanUpload && LocalOnly.Any());
|
||||
OpenAdminCommand = new RelayCommand(() =>
|
||||
{
|
||||
if (Host.Server is { } server) ShellActions.OpenUrl(server + "/admin");
|
||||
@@ -81,7 +91,7 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
|
||||
|
||||
public ObservableCollection<SyncRow> Rows { get; } = [];
|
||||
public IReadOnlyList<SyncFilterChip> Chips => _chips;
|
||||
public ICommand UploadAllCommand { get; }
|
||||
public ICommand UploadAllCommand => _uploadAll;
|
||||
public ICommand OpenAdminCommand { get; }
|
||||
|
||||
public string SearchText
|
||||
@@ -89,7 +99,7 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
|
||||
get => _search;
|
||||
set
|
||||
{
|
||||
if (Set(ref _search, value ?? string.Empty)) ApplyFilter();
|
||||
if (Set(ref _search, value ?? string.Empty)) ApplyFilter(rebuild: true);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,7 +114,12 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
|
||||
: _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>What "Upload all local" sends, or why it is disabled.</summary>
|
||||
public string UploadAllToolTip =>
|
||||
!IsActive ? Loc.L("Tooltips.Server.Sync.UploadAll.NotConnected")
|
||||
: !Rights.CanUpload ? Loc.L("Tooltips.Server.Sync.UploadAll.NoRight")
|
||||
: !LocalOnly.Any() ? Loc.L("Tooltips.Server.Sync.UploadAll.Nothing")
|
||||
: Loc.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
|
||||
@@ -128,12 +143,13 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
|
||||
|
||||
private IEnumerable<SyncEntry> LocalOnly => _entries.Where(e => e.Status == SyncStatus.LocalOnly);
|
||||
|
||||
/// <summary>Starts following the sync engine and the transfer jobs.</summary>
|
||||
/// <summary>Starts following the sync engine, the transfer jobs and the language.</summary>
|
||||
public void Attach()
|
||||
{
|
||||
if (_attached) return;
|
||||
_attached = true;
|
||||
Host.Changed += OnChanged;
|
||||
Loc.CultureChanged += OnCultureChanged;
|
||||
if (_shell.Services.Jobs is { } jobs)
|
||||
{
|
||||
jobs.JobChanged += OnJobChanged;
|
||||
@@ -168,7 +184,9 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
|
||||
public void Dispose()
|
||||
{
|
||||
if (!_attached) return;
|
||||
_attached = false;
|
||||
Host.Changed -= OnChanged;
|
||||
Loc.CultureChanged -= OnCultureChanged;
|
||||
if (_shell.Services.Jobs is { } jobs)
|
||||
{
|
||||
jobs.JobChanged -= OnJobChanged;
|
||||
@@ -180,16 +198,15 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
|
||||
{
|
||||
_filter = filter;
|
||||
foreach (var chip in _chips) chip.IsSelected = chip.Filter == filter;
|
||||
ApplyFilter();
|
||||
ApplyFilter(rebuild: true);
|
||||
}
|
||||
|
||||
/// <summary>Counts, rows, footer and the Library's sync glyphs after a reload.</summary>
|
||||
private void Refresh()
|
||||
{
|
||||
foreach (var chip in _chips) chip.Count = _entries.Count(e => SyncText.Matches(e, chip.Filter, string.Empty));
|
||||
ApplyFilter();
|
||||
ApplyFilter(rebuild: false);
|
||||
UpdateLibrary();
|
||||
OpenCachedProxies();
|
||||
OnPropertyChanged(nameof(IsActive));
|
||||
OnPropertyChanged(nameof(UploadAllToolTip));
|
||||
OnPropertyChanged(nameof(LastSyncText));
|
||||
@@ -197,34 +214,52 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
|
||||
OnPropertyChanged(nameof(ErrorText));
|
||||
OnPropertyChanged(nameof(ErrorToolTip));
|
||||
OnPropertyChanged(nameof(CanOpenAdmin));
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
_uploadAll.RaiseCanExecuteChanged();
|
||||
}
|
||||
|
||||
/// <summary>Updates the rows in place (scroll position and recycled containers survive), adding and removing as needed.</summary>
|
||||
private void ApplyFilter()
|
||||
/// <summary>
|
||||
/// Shows the entries the filter and search keep. A reload updates the rows in place (scroll position, focus and
|
||||
/// recycled containers survive); a new filter or search lays the rows out again.
|
||||
/// </summary>
|
||||
private void ApplyFilter(bool rebuild)
|
||||
{
|
||||
var rights = Rights;
|
||||
var wanted = _entries.Where(e => SyncText.Matches(e, _filter, _search.Trim())).ToList();
|
||||
var byId = Rows.ToDictionary(r => r.Id);
|
||||
for (var i = 0; i < wanted.Count; i++)
|
||||
if (rebuild)
|
||||
{
|
||||
var entry = wanted[i];
|
||||
if (byId.Remove(entry.Id, out var row))
|
||||
Rows.Clear();
|
||||
foreach (var entry in wanted) Rows.Add(Row(entry, rights, byId));
|
||||
}
|
||||
else
|
||||
{
|
||||
for (var i = 0; i < wanted.Count; i++)
|
||||
{
|
||||
row.Update(entry, rights);
|
||||
var at = Rows.IndexOf(row);
|
||||
if (at != i) Rows.Move(at, 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);
|
||||
}
|
||||
else
|
||||
{
|
||||
Rows.Insert(i, new SyncRow(entry, rights, ActAsync));
|
||||
}
|
||||
while (Rows.Count > wanted.Count) Rows.RemoveAt(Rows.Count - 1);
|
||||
}
|
||||
while (Rows.Count > wanted.Count) Rows.RemoveAt(Rows.Count - 1);
|
||||
OnPropertyChanged(nameof(HasRows));
|
||||
OnPropertyChanged(nameof(EmptyText));
|
||||
}
|
||||
|
||||
/// <summary>The existing row of an entry, updated, or a new one.</summary>
|
||||
private SyncRow Row(SyncEntry entry, SyncRights rights, Dictionary<Guid, SyncRow> existing)
|
||||
{
|
||||
if (!existing.TryGetValue(entry.Id, out var row)) return new SyncRow(entry, rights, ActAsync);
|
||||
row.Update(entry, rights);
|
||||
return row;
|
||||
}
|
||||
|
||||
/// <summary>The Library shows each local copy's sync state: rows it has loaded take the fresh state.</summary>
|
||||
private void UpdateLibrary()
|
||||
{
|
||||
@@ -235,15 +270,6 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <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;
|
||||
@@ -253,6 +279,9 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
|
||||
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)
|
||||
{
|
||||
@@ -261,12 +290,18 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
|
||||
}
|
||||
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:
|
||||
_openWhenCached.Add(entry.Id);
|
||||
await service.EnqueueDownloadAsync(engine, server, entry.Id, entry.Title, SyncDownloadMode.Proxies, null);
|
||||
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);
|
||||
@@ -275,7 +310,7 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
|
||||
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);
|
||||
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);
|
||||
@@ -284,40 +319,43 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
|
||||
await ReloadAsync();
|
||||
}
|
||||
|
||||
/// <summary>Settles a conflict; overwriting one side is confirmed first with the settings that differ (the dry run).</summary>
|
||||
/// <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,
|
||||
};
|
||||
if (resolution != SyncResolution.SaveBoth && !_shell.Services.Dialogs.Confirm(OverwriteRequest(entry, action))) return;
|
||||
try
|
||||
{
|
||||
await service.ResolveAsync(remote, entry.Id, resolution, CancellationToken.None);
|
||||
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 (TitanoApiException ex) when (ex.Status == HttpStatusCode.Conflict)
|
||||
catch (SyncConflictChangedException ex)
|
||||
{
|
||||
// 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);
|
||||
// One side changed after the choice was shown: the row now shows the fresh content.
|
||||
_shell.Notify(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"Keep this PC's settings?" with the settings that differ: one side's edits are about to be overwritten.</summary>
|
||||
private static ConfirmRequest OverwriteRequest(SyncEntry entry, SyncAction action) => new()
|
||||
/// <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 = SyncText.Conflict(entry),
|
||||
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 = true,
|
||||
IsDestructive = action != SyncAction.SaveBoth,
|
||||
};
|
||||
|
||||
private async Task UploadAllAsync()
|
||||
@@ -335,11 +373,34 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
|
||||
|
||||
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 _);
|
||||
OnChanged();
|
||||
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>
|
||||
@@ -352,11 +413,9 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
|
||||
{
|
||||
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);
|
||||
if (row.Entry.Transfer is { } job && _progress.TryGetValue(job.Id, out var p)) row.UpdateProgress(p.Done, p.Total);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
@@ -25,23 +28,68 @@ public enum SyncAction
|
||||
KeepMine,
|
||||
TakeServer,
|
||||
SaveBoth,
|
||||
GetExports,
|
||||
SendExports,
|
||||
Pause,
|
||||
Resume,
|
||||
}
|
||||
|
||||
/// <summary>What the signed-in account may do (server permission bits).</summary>
|
||||
/// <param name="CanUpload">Send originals and settings.</param>
|
||||
/// <param name="CanUpload">Send originals, settings and renders (upload and edit rights).</param>
|
||||
/// <param name="CanFetchOriginals">Download originals (editors and render nodes).</param>
|
||||
public readonly record struct SyncRights(bool CanUpload, bool CanFetchOriginals)
|
||||
/// <param name="CanEdit">Change the server's copy of a sequence's settings, title, tags, rating and notes.</param>
|
||||
public readonly record struct SyncRights(bool CanUpload, bool CanFetchOriginals, bool CanEdit)
|
||||
{
|
||||
public static SyncRights Of(long permissions) => new(
|
||||
(permissions & (long)Permissions.Upload) != 0 && (permissions & (long)Permissions.Edit) != 0,
|
||||
(permissions & (long)(Permissions.Edit | Permissions.RenderNode)) != 0);
|
||||
(permissions & (long)(Permissions.Edit | Permissions.RenderNode)) != 0,
|
||||
(permissions & (long)Permissions.Edit) != 0);
|
||||
}
|
||||
|
||||
/// <summary>The words, glyphs and actions of the sync table (BRIEF §12.7): plain functions of a <see cref="SyncEntry"/>.</summary>
|
||||
public static class SyncText
|
||||
{
|
||||
/// <summary>Resource keys of the settings and sequence fields a conflict can show, by JSON path (sections, then members).</summary>
|
||||
private static readonly Dictionary<string, string> SettingKeys = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["sequence.title"] = "Server.Setting.Title",
|
||||
["sequence.tags"] = "Server.Setting.Tags",
|
||||
["sequence.rating"] = "Server.Setting.Rating",
|
||||
["sequence.notes"] = "Server.Setting.Notes",
|
||||
["timing.mode"] = "Server.Setting.TimingMode",
|
||||
["timing.frameRate"] = "Server.Setting.FrameRate",
|
||||
["timing.fitToSeconds"] = "Server.Setting.FitToDuration",
|
||||
["timing.remapCurve"] = "Server.Setting.TimeRemap",
|
||||
["exposure.deflicker"] = "Server.Setting.Deflicker",
|
||||
["exposure.deflickerWindow"] = "Server.Setting.DeflickerWindow",
|
||||
["exposure.deflickerStrength"] = "Server.Setting.DeflickerStrength",
|
||||
["exposure.regions"] = "Server.Setting.Regions",
|
||||
["exposure.holyGrail"] = "Server.Setting.HolyGrail",
|
||||
["exposure.transitionLength"] = "Server.Setting.Transitions",
|
||||
["exposure.whiteBalanceSmoothing"] = "Server.Setting.WhiteBalance",
|
||||
["exposure.exposureOffsetEv"] = "Server.Setting.ExposureOffset",
|
||||
["exposure.highlightKnee"] = "Server.Setting.HighlightKnee",
|
||||
["motion.motionBlur"] = "Server.Setting.MotionBlur",
|
||||
["motion.targetShutterAngle"] = "Server.Setting.ShutterAngle",
|
||||
["motion.flowQuality"] = "Server.Setting.FlowQuality",
|
||||
["motion.stabilize"] = "Server.Setting.Stabilize",
|
||||
["motion.stabilizeSmoothing"] = "Server.Setting.StabilizeSmoothing",
|
||||
["camera.crop"] = "Server.Setting.Crop",
|
||||
["camera.aspect"] = "Server.Setting.Aspect",
|
||||
["camera.offsetX"] = "Server.Setting.CameraOffset",
|
||||
["camera.offsetY"] = "Server.Setting.CameraOffset",
|
||||
["camera.keyframes"] = "Server.Setting.Keyframes",
|
||||
["stack.mode"] = "Server.Setting.Stacking",
|
||||
["stack.length"] = "Server.Setting.TrailLength",
|
||||
["export.preset"] = "Server.Setting.ExportPreset",
|
||||
["export.overrides"] = "Server.Setting.ExportValues",
|
||||
["export.nameTemplate"] = "Server.Setting.OutputName",
|
||||
["export.folder"] = "Server.Setting.ExportFolder",
|
||||
["export.batch"] = "Server.Setting.Batch",
|
||||
["excludedFrames"] = "Server.Setting.ExcludedFrames",
|
||||
["heroFrame"] = "Server.Setting.HeroFrame",
|
||||
};
|
||||
|
||||
/// <summary>"originals · proxies", "proxies" (cached server proxies) or "—".</summary>
|
||||
public static string Local(SyncEntry entry)
|
||||
{
|
||||
@@ -76,6 +124,7 @@ public static class SyncText
|
||||
Loc.L(upload ? "Tooltips.Server.Sync.State.Uploading" : "Tooltips.Server.Sync.State.Downloading")),
|
||||
};
|
||||
}
|
||||
if (entry.Link?.Error is { } error) return (StatusKind.Warning, Loc.L("Server.Sync.State.Failed"), Loc.L("Tooltips.Server.Sync.State.Failed", error));
|
||||
return entry.Status switch
|
||||
{
|
||||
SyncStatus.InSync => (StatusKind.Done, Loc.L("Server.Sync.State.InSync"), Loc.L("Tooltips.Server.Sync.State.InSync")),
|
||||
@@ -84,16 +133,44 @@ public static class SyncText
|
||||
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)),
|
||||
_ => (StatusKind.Warning, Loc.L("Server.Sync.State.Conflict"), ConflictSummary(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)
|
||||
/// <summary>One line for the State tooltip: "Deflicker window 41 here, 33 on the server · +2".</summary>
|
||||
public static string ConflictSummary(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"))));
|
||||
var lines = Conflict(entry, int.MaxValue);
|
||||
return lines.Count switch
|
||||
{
|
||||
0 => Loc.L("Tooltips.Server.Sync.State.Conflict"),
|
||||
1 => lines[0],
|
||||
_ => Loc.L("Server.Conflict.More", lines[0], Formatting.Count(lines.Count - 1)),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What differs, one line per setting or sequence field in project order ("Deflicker window 41 here, 33 on the
|
||||
/// server", "Tags differ"), at most <paramref name="max"/>.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<string> Conflict(SyncEntry entry, int max)
|
||||
{
|
||||
if (entry is not { Local: { } local, Link.ConflictRemote: { } theirs }) return [];
|
||||
var lines = new List<string>();
|
||||
var shown = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var difference in SyncRules.Differences(SyncPayload.Of(local), theirs, 64))
|
||||
{
|
||||
var (key, field) = Setting(difference.Path);
|
||||
if (!shown.Add(key)) continue;
|
||||
var label = Loc.L(key);
|
||||
var metadata = difference.Path.StartsWith(SyncRules.MetadataPath, StringComparison.Ordinal);
|
||||
lines.Add((metadata ? Text(difference.Mine) : Value(difference.Mine, field)) is { } mine
|
||||
&& (metadata ? Text(difference.Theirs) : Value(difference.Theirs, field)) is { } server
|
||||
? Loc.L("Server.Conflict.Difference", label, mine, server)
|
||||
: Loc.L("Server.Conflict.Changed", label));
|
||||
if (lines.Count == max) break;
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
/// <summary>The row's buttons, in the order the mockup shows them.</summary>
|
||||
@@ -116,24 +193,42 @@ public static class SyncText
|
||||
case SyncStatus.ServerAhead when entry.Link is { MissingLocal: > 0 }:
|
||||
if (rights.CanFetchOriginals) actions.Add(SyncAction.DownloadOriginals);
|
||||
break;
|
||||
case SyncStatus.LocalAhead or SyncStatus.ServerAhead:
|
||||
case SyncStatus.LocalAhead when rights.CanEdit:
|
||||
case SyncStatus.ServerAhead:
|
||||
actions.Add(SyncAction.SyncSettings);
|
||||
break;
|
||||
case SyncStatus.Conflict:
|
||||
actions.AddRange([SyncAction.KeepMine, SyncAction.TakeServer, SyncAction.SaveBoth]);
|
||||
break;
|
||||
if (rights.CanEdit) actions.Add(SyncAction.KeepMine);
|
||||
actions.AddRange([SyncAction.TakeServer, SyncAction.SaveBoth]);
|
||||
return actions;
|
||||
}
|
||||
if (entry is { Local: not null, Link: { } link })
|
||||
{
|
||||
if (link.ExportsToGet > 0) actions.Add(SyncAction.GetExports);
|
||||
if (link.ExportsToSend > 0 && rights.CanUpload) actions.Add(SyncAction.SendExports);
|
||||
}
|
||||
return actions;
|
||||
}
|
||||
|
||||
/// <summary>The bytes an upload or download of the row moves (for the tooltips).</summary>
|
||||
/// <summary>The bytes an action moves (for the tooltips).</summary>
|
||||
public static long Size(SyncEntry entry, SyncAction action) => action switch
|
||||
{
|
||||
SyncAction.Upload => entry.Local?.TotalBytes ?? 0,
|
||||
SyncAction.DownloadOriginals => entry.Link?.TotalBytes ?? 0,
|
||||
SyncAction.GetExports => entry.Link?.ExportsToGetBytes ?? 0,
|
||||
SyncAction.SendExports => entry.Link?.ExportsToSendBytes ?? 0,
|
||||
_ => 0,
|
||||
};
|
||||
|
||||
/// <summary>The tooltip of a row button: what it does and, for transfers, what it moves.</summary>
|
||||
public static string ToolTip(SyncEntry entry, SyncAction action) => action switch
|
||||
{
|
||||
SyncAction.Upload or SyncAction.DownloadOriginals => Loc.L("Tooltips.Server.Sync." + action, Formatting.Bytes(Size(entry, action))),
|
||||
SyncAction.GetExports => Loc.Plural("Tooltips.Server.Sync.GetExports", entry.Link!.ExportsToGet, Formatting.Bytes(Size(entry, action))),
|
||||
SyncAction.SendExports => Loc.Plural("Tooltips.Server.Sync.SendExports", entry.Link!.ExportsToSend, Formatting.Bytes(Size(entry, action))),
|
||||
_ => Loc.L("Tooltips.Server.Sync." + action),
|
||||
};
|
||||
|
||||
public static bool Matches(SyncEntry entry, SyncFilter filter, string search) =>
|
||||
(filter switch
|
||||
{
|
||||
@@ -143,5 +238,49 @@ public static class SyncText
|
||||
_ => true,
|
||||
}) && (search.Length == 0 || entry.Title.Contains(search, StringComparison.CurrentCultureIgnoreCase));
|
||||
|
||||
/// <summary>
|
||||
/// The label key of a difference path and the member below the setting it reaches ("isAuto", "manual", … of an
|
||||
/// Auto parameter; null for the setting itself): "exposure.deflickerWindow.manual" is the deflicker window's manual value.
|
||||
/// </summary>
|
||||
private static (string Key, string? Field) Setting(string path)
|
||||
{
|
||||
var segments = path.Split('.');
|
||||
for (var length = segments.Length; length > 0; length--)
|
||||
{
|
||||
if (SettingKeys.TryGetValue(string.Join('.', segments[..length]), out var key)) return (key, length < segments.Length ? segments[length] : null);
|
||||
}
|
||||
return ("Server.Setting.Other", segments[^1]);
|
||||
}
|
||||
|
||||
/// <summary>A title, tags, rating or notes value as shown ("—" when empty).</summary>
|
||||
private static string Text(string? value) => string.IsNullOrWhiteSpace(value) ? Loc.L("Server.Sync.None") : Shorten(value);
|
||||
|
||||
/// <summary>A side's value as shown ("41", "on", "auto"); null when it is not a single value worth printing.</summary>
|
||||
private static string? Value(string? json, string? field)
|
||||
{
|
||||
if (json is null) return field is null or "manual" ? Loc.L("Server.Sync.None") : null;
|
||||
if (field is not (null or "manual" or "autoValue" or "isAuto")) return null;
|
||||
JsonNode? node;
|
||||
try
|
||||
{
|
||||
node = JsonNode.Parse(json);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
if (field == "isAuto") return node is JsonValue v && v.TryGetValue<bool>(out var auto) ? Loc.L(auto ? "Server.Setting.Auto" : "Server.Setting.Manual") : null;
|
||||
return node switch
|
||||
{
|
||||
null => Loc.L("Server.Sync.None"),
|
||||
JsonValue value when value.TryGetValue<bool>(out var flag) => Loc.L(flag ? "Server.Setting.On" : "Server.Setting.Off"),
|
||||
JsonValue value when value.TryGetValue<double>(out var number) => number.ToString("0.###", Loc.Culture),
|
||||
JsonValue value when value.TryGetValue<string>(out var text) => Shorten(text),
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
private static string Shorten(string text) => text.Length <= 40 ? text : string.Concat(text.AsSpan(0, 39), "…");
|
||||
|
||||
private static string Join(params string[] parts) => string.Join(" · ", parts);
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
using System.Net.NetworkInformation;
|
||||
using System.Runtime.InteropServices;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Jobs;
|
||||
|
||||
namespace Titano.App.Server;
|
||||
|
||||
/// <summary>
|
||||
/// "Pause uploads on metered networks" (Server.html): while <see cref="AppSettings.PauseUploadsOnMetered"/> is on and
|
||||
/// Windows reports the connection as metered, upload jobs are paused (a running one stops after its current chunk and
|
||||
/// keeps its checkpoint); they are resumed when the connection is no longer metered or the option goes off. Only the
|
||||
/// uploads it paused are resumed. Checked when the network or an upload job changes, and every minute.
|
||||
/// </summary>
|
||||
public sealed class UploadHold : IDisposable
|
||||
{
|
||||
private static readonly TimeSpan Interval = TimeSpan.FromMinutes(1);
|
||||
|
||||
private readonly AppServices _services;
|
||||
private readonly HashSet<Guid> _held = [];
|
||||
private readonly SemaphoreSlim _gate = new(1, 1);
|
||||
private readonly Timer _timer;
|
||||
private JobEngine? _engine;
|
||||
|
||||
public UploadHold(AppServices services)
|
||||
{
|
||||
_services = services;
|
||||
_timer = new Timer(_ => Request(), null, Interval, Interval);
|
||||
NetworkChange.NetworkAddressChanged += OnNetworkChanged;
|
||||
NetworkChange.NetworkAvailabilityChanged += OnNetworkChanged;
|
||||
}
|
||||
|
||||
/// <summary>Follows the jobs of <paramref name="engine"/> (once the index is open).</summary>
|
||||
public void Attach(JobEngine engine)
|
||||
{
|
||||
if (ReferenceEquals(_engine, engine)) return;
|
||||
if (_engine is not null) _engine.JobChanged -= OnJobChanged;
|
||||
_engine = engine;
|
||||
engine.JobChanged += OnJobChanged;
|
||||
Request();
|
||||
}
|
||||
|
||||
/// <summary>Applies the option and the connection's cost now (the option changed).</summary>
|
||||
public void Request() => _ = ApplyAsync();
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_timer.Dispose();
|
||||
NetworkChange.NetworkAddressChanged -= OnNetworkChanged;
|
||||
NetworkChange.NetworkAvailabilityChanged -= OnNetworkChanged;
|
||||
if (_engine is not null) _engine.JobChanged -= OnJobChanged;
|
||||
}
|
||||
|
||||
private bool Holding => _services.Settings.PauseUploadsOnMetered && MeteredNetwork.IsMetered();
|
||||
|
||||
private void OnNetworkChanged(object? sender, EventArgs e) => Request();
|
||||
|
||||
private void OnJobChanged(Job job)
|
||||
{
|
||||
if (job is { Kind: JobKind.UploadCommit, State: JobState.Queued or JobState.Running }) Request();
|
||||
}
|
||||
|
||||
private async Task ApplyAsync()
|
||||
{
|
||||
if (_engine is not { } engine || _services.Database is not { } db) return;
|
||||
await _gate.WaitAsync();
|
||||
try
|
||||
{
|
||||
if (Holding)
|
||||
{
|
||||
foreach (var state in new[] { JobState.Queued, JobState.Running })
|
||||
{
|
||||
foreach (var job in (await db.Jobs.ListAsync(state, JobKind.UploadCommit, 500)).Items)
|
||||
{
|
||||
await engine.PauseAsync(job.Id);
|
||||
_held.Add(job.Id);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
foreach (var id in _held)
|
||||
{
|
||||
if (await db.Jobs.GetAsync(id) is { State: JobState.Paused }) await engine.ResumeAsync(id);
|
||||
}
|
||||
_held.Clear();
|
||||
}
|
||||
catch (Data.DatabaseException ex)
|
||||
{
|
||||
Log.Warning("sync", "Uploads could not be paused or resumed for the metered connection", ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The connection cost Windows reports (Settings › Network › Metered connection) through <c>INetworkCostManager</c>.</summary>
|
||||
internal static class MeteredNetwork
|
||||
{
|
||||
private const uint Fixed = 0x2;
|
||||
private const uint Variable = 0x4;
|
||||
private const uint OverDataLimit = 0x10000;
|
||||
private const uint Roaming = 0x40000;
|
||||
|
||||
/// <summary>True when the machine's connection is metered (fixed or variable cost, over its data limit, or roaming); false when unknown.</summary>
|
||||
public static bool IsMetered()
|
||||
{
|
||||
try
|
||||
{
|
||||
var manager = (INetworkCostManager)new NetworkListManagerClass();
|
||||
try
|
||||
{
|
||||
return manager.GetCost(out var cost, IntPtr.Zero) == 0 && (cost & (Fixed | Variable | OverDataLimit | Roaming)) != 0;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Marshal.ReleaseComObject(manager);
|
||||
}
|
||||
}
|
||||
catch (COMException ex)
|
||||
{
|
||||
Log.Warning("sync", "The connection cost could not be read", ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
[ComImport]
|
||||
[Guid("DCB00C01-570F-4A9B-8D69-199FDBA5723B")]
|
||||
private class NetworkListManagerClass;
|
||||
|
||||
[ComImport]
|
||||
[Guid("DCB00008-570F-4A9B-8D69-199FDBA5723B")]
|
||||
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
private interface INetworkCostManager
|
||||
{
|
||||
[PreserveSig]
|
||||
int GetCost(out uint cost, IntPtr destination);
|
||||
|
||||
[PreserveSig]
|
||||
int GetDataPlanStatus(IntPtr status, IntPtr destination);
|
||||
|
||||
[PreserveSig]
|
||||
int SetDestinationAddresses(uint length, IntPtr addresses, short append);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user