merge: client server mode (sync engine, Server screen sync table and conflicts, Library sync glyphs, render transfers)
Keeps the render node host from the processing branch and disposes the sync host after it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
56 files changed
+6777
-25
No files matched your search
@@ -9,6 +9,8 @@ using Titano.Core.Imaging;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Video;
|
||||
using Titano.Data;
|
||||
using Titano.Data.Jobs;
|
||||
using Titano.Data.Sync;
|
||||
using Titano.Protocol;
|
||||
using Titano.Protocol.Client;
|
||||
|
||||
@@ -17,15 +19,21 @@ namespace Titano.App.DesignTime;
|
||||
/// <summary>
|
||||
/// Synthetic content for <c>--capture</c> screenshots and the screen smoke tests ONLY: a temporary SQLite index
|
||||
/// with an archive of generated JPEGs (one sequence stores its thumbnail as an embedded preview inside a fake RAW
|
||||
/// file), jobs in every state, a fake signed-in server and a fake encoder inventory. Everything lives in the
|
||||
/// file), jobs in every state, a fake signed-in server with sequences to compare (one in conflict) and a fake
|
||||
/// encoder inventory. Everything lives in the
|
||||
/// capture environment's temporary folder; nothing touches the network or the user's data.
|
||||
/// </summary>
|
||||
public sealed class SampleData
|
||||
{
|
||||
public const string ServerFingerprint = "9A:3C:71:E0:5B:12:C4:88:0F:6D:2A:91:E7:44:B3:5C:19:D2:6F:80:A1:3E:57:C9:0B:64:F8:2D:93:A6:71:CE";
|
||||
|
||||
private const string ServerAddress = "https://nas.local:8443";
|
||||
|
||||
private readonly AppServices _services;
|
||||
private readonly SampleSyncRemote _remote = new();
|
||||
private TitanoDatabase? _db;
|
||||
private Guid _sunrise;
|
||||
private Guid _lakeComo;
|
||||
|
||||
private SampleData(AppServices services) => _services = services;
|
||||
|
||||
@@ -38,7 +46,9 @@ public sealed class SampleData
|
||||
services.Server = new ServerSession(settings, services.SaveSettings, new SampleServerApiFactory(), new PlainTokenProtector());
|
||||
services.Encoders = new SampleEncoders();
|
||||
services.CheckForUpdateAsync = _ => Task.FromResult<ReleaseInfo?>(null);
|
||||
return new SampleData(services);
|
||||
var sample = new SampleData(services);
|
||||
services.Sync.RemoteFactory = (_, _, _) => sample._remote;
|
||||
return sample;
|
||||
}
|
||||
|
||||
/// <summary>Opens the empty temporary index (first run: no archive, nothing indexed).</summary>
|
||||
@@ -68,6 +78,7 @@ public sealed class SampleData
|
||||
await db.Sequences.SetTagsAsync(sequences[9].Sequence.Id, ["holy grail"]);
|
||||
|
||||
foreach (var job in Jobs(sequences.Select(s => s.Sequence).ToList(), archive.Id)) await db.Jobs.EnqueueAsync(job);
|
||||
await FillServerAsync(db, sequences.Select(s => s.Sequence).ToList());
|
||||
|
||||
settings.LastArchivePath = @"D:\TitanoArchive";
|
||||
settings.ServerUrl = "https://nas.local:8443";
|
||||
@@ -79,6 +90,111 @@ public sealed class SampleData
|
||||
settings.FirstRunCompleted = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Transfers for the sync table: an upload at 46 % (Comet over the ridge), an upload waiting (Fog lifting, Asti), a
|
||||
/// download of originals running (Sunrise over Superga) and one paused (Lake Como storm).
|
||||
/// </summary>
|
||||
public async Task FillSyncAsync()
|
||||
{
|
||||
var db = _db ?? throw new InvalidOperationException("FillAsync first.");
|
||||
async Task<Sequence> LocalAsync(string text) => (await db.Sequences.ListAsync(new Data.Repositories.SequenceQuery { Text = text, Limit = 1 })).Items[0];
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
Job Transfer(JobKind kind, Guid target, string label, string parameters, JobState state, long done, long total) => new()
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Kind = kind,
|
||||
TargetIds = [target],
|
||||
TargetLabel = label,
|
||||
ParametersJson = parameters,
|
||||
State = state,
|
||||
Priority = JobPriority.User,
|
||||
ProgressDone = done,
|
||||
ProgressTotal = total,
|
||||
ItemsPerSecond = state == JobState.Running ? 1.6 : null,
|
||||
Eta = state == JobState.Running ? TimeSpan.FromMinutes(4) : null,
|
||||
NodeId = state == JobState.Queued ? null : _services.WorkerId,
|
||||
Attempts = state == JobState.Queued ? 0 : 1,
|
||||
Created = now.AddMinutes(-5),
|
||||
Started = state == JobState.Queued ? null : now.AddMinutes(-5),
|
||||
};
|
||||
var upload = $$"""{"server":"{{ServerAddress}}"}""";
|
||||
var originals = $$"""{"server":"{{ServerAddress}}","mode":"Originals"}""";
|
||||
var comet = await LocalAsync("Comet");
|
||||
var fog = await LocalAsync("Fog lifting");
|
||||
await db.Jobs.EnqueueAsync(Transfer(JobKind.UploadCommit, comet.Id, comet.DisplayTitle, upload, JobState.Running, 462, 1_005));
|
||||
await db.Jobs.EnqueueAsync(Transfer(JobKind.UploadCommit, fog.Id, fog.DisplayTitle, upload, JobState.Queued, 0, 0));
|
||||
await db.Jobs.EnqueueAsync(Transfer(JobKind.Download, _sunrise, "Sunrise over Superga", originals, JobState.Running, 1_210, 2_880));
|
||||
await db.Jobs.EnqueueAsync(Transfer(JobKind.Download, _lakeComo, "Lake Como storm", originals, JobState.Paused, 300, 1_450));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fetches the proxies of Sunrise over Superga into the proxy cache through a download job on a one-off engine (the
|
||||
/// capture's engine does not run jobs), so the sync table shows a sequence kept with proxies only.
|
||||
/// </summary>
|
||||
public async Task CacheProxiesAsync()
|
||||
{
|
||||
var db = _db ?? throw new InvalidOperationException("FillAsync first.");
|
||||
var service = _services.Sync.Service ?? throw new InvalidOperationException("The index is not open.");
|
||||
await using var engine = new JobEngine(db, service.CreateJobHandlers(_services.Sync),
|
||||
new JobEngineOptions { Workers = 1, WorkerId = "sample-proxies", Kinds = [JobKind.Download], PollInterval = TimeSpan.FromMilliseconds(50) });
|
||||
await engine.StartAsync();
|
||||
var job = await service.EnqueueDownloadAsync(engine, ServerAddress, _sunrise, "Sunrise over Superga", SyncDownloadMode.Proxies, null);
|
||||
for (var i = 0; i < 200 && await db.Jobs.GetAsync(job.Id) is { State: JobState.Queued or JobState.Running }; i++) await Task.Delay(50);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The server's side: six sequences this PC also holds (two the same, one with settings changed on both sides, one
|
||||
/// with more originals on the server, one with more here, one with renders this PC lacks) and two only on the server;
|
||||
/// the others are only here.
|
||||
/// </summary>
|
||||
private async Task FillServerAsync(TitanoDatabase db, IReadOnlyList<Sequence> local)
|
||||
{
|
||||
Guid Id(string title) => local.First(s => s.Title == title).Id;
|
||||
await db.Sequences.EditAsync(Id("Holy grail · Monviso"), new Data.Repositories.SequenceEdit { SettingsJson = DeflickerWindow(41) }, null);
|
||||
var linked = new (string Title, int Frames, string? Settings, int Renders)[]
|
||||
{
|
||||
("Harbour sunset", 3, null, 0),
|
||||
("Aurora, Tromsø", 3, null, 0),
|
||||
("Holy grail · Monviso", 3, DeflickerWindow(33), 0),
|
||||
("Construction cam · week 38", 8, null, 0),
|
||||
("Milan skyline dusk", 1, null, 0),
|
||||
("Star trails, Colle del Nivolet", 3, null, 3),
|
||||
};
|
||||
foreach (var (title, frames, settings, renders) in linked)
|
||||
{
|
||||
// The server's copy carries the same title, tags and rating as this PC's.
|
||||
var sequence = (await db.Sequences.GetAsync(Id(title)))!;
|
||||
var remote = _remote.Add(SampleSyncRemote.Dto(sequence) with { RenderedCount = renders }, settings, frames);
|
||||
await _services.Sync.Service!.LinkAsync(ServerAddress, remote, sequence.Id);
|
||||
}
|
||||
_sunrise = _remote.Add(SampleSyncRemote.Dto(new Sequence
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
ArchiveId = Guid.Empty,
|
||||
Title = "Sunrise over Superga",
|
||||
Folder = "2026/2026-07-02 Sony ILCE-7M4",
|
||||
FrameCount = 2_880,
|
||||
TotalBytes = 2_880 * 21_000_000L,
|
||||
Status = SequenceStatus.ProxiesBuilt | SequenceStatus.ThumbsBuilt,
|
||||
RenderedCount = 1,
|
||||
UpdatedAt = DateTimeOffset.UtcNow,
|
||||
}), null, 3);
|
||||
_lakeComo = _remote.Add(SampleSyncRemote.Dto(new Sequence
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
ArchiveId = Guid.Empty,
|
||||
Title = "Lake Como storm",
|
||||
Folder = "2026/2026-08-21 Canon EOS R5",
|
||||
FrameCount = 1_450,
|
||||
TotalBytes = 1_450 * 45_000_000L,
|
||||
Status = SequenceStatus.ThumbsBuilt,
|
||||
UpdatedAt = DateTimeOffset.UtcNow,
|
||||
}), null, 3);
|
||||
|
||||
static string DeflickerWindow(int frames) =>
|
||||
"""{"exposure":{"deflickerWindow":{"isAuto":false,"manual":""" + frames.ToString(System.Globalization.CultureInfo.InvariantCulture) + "}}}";
|
||||
}
|
||||
|
||||
private IEnumerable<(Sequence Sequence, string[] Colours, bool Raw)> Sequences(Guid archiveId)
|
||||
{
|
||||
var now = new DateTime(2026, 9, 28, 18, 2, 11);
|
||||
@@ -278,7 +394,8 @@ public sealed class SampleData
|
||||
|
||||
private sealed class SampleServerApi(Uri baseAddress, IReadOnlyCollection<string> trusted) : IServerApi
|
||||
{
|
||||
private static readonly UserDto User = new(Guid.Empty, "alberto", "Alberto", "editor", 0, 5_000_000_000_000, 2_100_000_000_000, false, false,
|
||||
private static readonly UserDto User = new(Guid.Empty, "alberto", "Alberto", "editor", (long)RolePermissions.Default(UserRole.Editor), 5_000_000_000_000,
|
||||
2_100_000_000_000, false, false,
|
||||
new DateTimeOffset(2025, 1, 1, 0, 0, 0, TimeSpan.Zero), DateTimeOffset.UtcNow);
|
||||
|
||||
public Uri BaseAddress { get; } = baseAddress;
|
||||
@@ -308,6 +425,102 @@ public sealed class SampleData
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sample server's sequences for the sync table: listings, manifests (frames hashed from their index, so
|
||||
/// unhashed sample frames match them by count; renders as many as the listing says), settings edits and proxies
|
||||
/// (generated JPEGs); uploads and originals are not part of the screenshots.
|
||||
/// </summary>
|
||||
private sealed class SampleSyncRemote : ISyncRemote
|
||||
{
|
||||
private readonly Dictionary<Guid, (SequenceDto Dto, string? Settings, Guid[] Frames)> _sequences = [];
|
||||
|
||||
public string Server => ServerAddress;
|
||||
|
||||
public static SequenceDto Dto(Sequence s) => new(Guid.CreateVersion7(), s.Title, s.DisplayTitle, s.Folder, s.CameraMake, s.CameraModel, s.Lens,
|
||||
s.FirstCapture, s.LastCapture, s.FrameCount, s.MedianInterval, s.TotalBytes, (long)s.Status, s.RenderedCount, null, s.Tags, s.Rating, s.Notes, 2, 1,
|
||||
0, null, s.UpdatedAt);
|
||||
|
||||
public Guid Add(SequenceDto dto, string? settings, int frames)
|
||||
{
|
||||
lock (_sequences) _sequences[dto.Id] = (dto, settings, [.. Enumerable.Range(0, frames).Select(_ => Guid.CreateVersion7())]);
|
||||
return dto.Id;
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<SequenceDto>> ListSequencesAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
lock (_sequences) return Task.FromResult<IReadOnlyList<SequenceDto>>([.. _sequences.Values.Select(s => s.Dto)]);
|
||||
}
|
||||
|
||||
public Task<SequenceDto> GetSequenceAsync(Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
lock (_sequences) return Task.FromResult(_sequences[id].Dto);
|
||||
}
|
||||
|
||||
public Task<SequenceManifest> GetManifestAsync(Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
lock (_sequences)
|
||||
{
|
||||
var (dto, settings, frames) = _sequences[id];
|
||||
var hasProxy = (dto.Status & (long)SequenceStatus.ProxiesBuilt) != 0;
|
||||
var created = new DateTimeOffset(2026, 9, 20, 21, 0, 0, TimeSpan.Zero);
|
||||
return Task.FromResult(new SequenceManifest(id, dto.FramesVersion, dto.SettingsVersion, settings, dto.Tags,
|
||||
[.. frames.Select((frame, i) => new ManifestFrame(frame, i, $"IMG_{i + 1:0000}.JPG", 24_000_000,
|
||||
Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(BitConverter.GetBytes(i))), hasProxy, true))],
|
||||
[.. Enumerable.Range(0, dto.RenderedCount).Select(i => new RenderDto(Guid.CreateVersion7(), i == 0 ? "4K HEVC" : "1080p H.264", "hevc",
|
||||
3840, 2160, 30, 21.3, 640_000_000, created.AddHours(i), "Studio NAS"))]));
|
||||
}
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<FrameDto>> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken)
|
||||
{
|
||||
lock (_sequences)
|
||||
{
|
||||
return Task.FromResult<IReadOnlyList<FrameDto>>([.. _sequences[sequenceId].Frames.Select((frame, i) => new FrameDto(frame, sequenceId, i,
|
||||
$"IMG_{i + 1:0000}.JPG", 24_000_000, null, new DateTime(2026, 7, 2, 5, 40, 0).AddSeconds(30 * i), null, 1.0 / 250, 8, 100, 24, 1, 320, 180,
|
||||
"jpeg", 0))]);
|
||||
}
|
||||
}
|
||||
|
||||
public Task<SequenceDto> UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
lock (_sequences)
|
||||
{
|
||||
var (dto, _, frames) = _sequences[id];
|
||||
var updated = dto with { SettingsVersion = dto.SettingsVersion + 1, UpdatedAt = DateTimeOffset.UtcNow };
|
||||
_sequences[id] = (updated, request.SettingsJson, frames);
|
||||
return Task.FromResult(updated);
|
||||
}
|
||||
}
|
||||
|
||||
public Task<CompleteUploadResponse?> UploadFileAsync(string path, Guid? sequenceId, string? sessionKey, string sha256, DateTime? capturedAt,
|
||||
CancellationToken cancellationToken) => throw new NotSupportedException("The sample server takes no uploads.");
|
||||
|
||||
/// <summary>Proxies and thumbnails: a dawn gradient whose sun rises with the frame.</summary>
|
||||
public async Task DownloadFrameAsync(Guid frameId, string kind, Stream destination, CancellationToken cancellationToken)
|
||||
{
|
||||
if (kind == "original") throw new NotSupportedException("The sample server serves no originals.");
|
||||
int index;
|
||||
lock (_sequences) index = _sequences.Values.Select(s => Array.IndexOf(s.Frames, frameId)).Max();
|
||||
await destination.WriteAsync(Gradient(["#1B2A4A", "#E8925A", "#F6D28B"], 320, 180, index / 3.0), cancellationToken);
|
||||
}
|
||||
|
||||
public Task<string?> DownloadRenderAsync(Guid renderId, Stream destination, CancellationToken cancellationToken) =>
|
||||
throw new NotSupportedException("The sample server serves no renders.");
|
||||
|
||||
public Task<RenderDto?> UploadRenderAsync(Guid sequenceId, string path, RenderUploadRequest request, CancellationToken cancellationToken) =>
|
||||
throw new NotSupportedException("The sample server takes no renders.");
|
||||
|
||||
public async IAsyncEnumerable<ServerEvent> EventsAsync([System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
{
|
||||
await Task.Delay(Timeout.Infinite, cancellationToken);
|
||||
yield break;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>No encryption: the capture environment is thrown away.</summary>
|
||||
private sealed class PlainTokenProtector : ITokenProtector
|
||||
{
|
||||
|
||||
@@ -28,8 +28,9 @@ namespace Titano.App.Infrastructure;
|
||||
/// Composition root of local mode (BRIEF §4.4): the SQLite index under the data folder (migrated on open), the
|
||||
/// archive engine (WIC first, then managed decoders), the analysis and render engine (the same decoders; Media
|
||||
/// Foundation, then managed encoders), the one <see cref="JobEngine"/> of this PC with the handlers of
|
||||
/// <see cref="CreateJobHandlers"/>, thumbnails, the server session, the render node, the encoder inventory and the
|
||||
/// update check. Started after the window shows, stopped when the app exits. The last archive is reopened at start and
|
||||
/// <see cref="CreateJobHandlers"/>, thumbnails, the server session, the render node, the encoder inventory, the
|
||||
/// update check and the sync with the signed-in server (<see cref="SyncHost"/>). Started after the window shows,
|
||||
/// stopped when the app exits. The last archive is reopened at start and
|
||||
/// rescanned every <see cref="ScanInterval"/> (BRIEF §7: polling, no file-system watchers). The render node runs while
|
||||
/// the user offers this PC (<see cref="AppSettings.RenderNodeOptIn"/>) and a server session is open (never in capture
|
||||
/// mode). Renders and the render node use hardware encoders as Settings › Rendering allows
|
||||
@@ -60,6 +61,7 @@ public sealed class AppServices : IAsyncDisposable
|
||||
Dialogs = dialogs;
|
||||
_renderNode = new RenderNodeHost(StartRenderNode);
|
||||
ArchiveSetup = new EngineArchiveSetup(this);
|
||||
Sync = new SyncHost(this);
|
||||
Server = new ServerSession(settings, saveSettings, new TitanoServerApiFactory(), new DpapiTokenProtector());
|
||||
Encoders = new MediaFoundationInventory();
|
||||
CheckForUpdateAsync = ct => UpdateCheck.FetchAsync(Http.Value, ProductLinks.LatestReleaseApi, VersionText, ct);
|
||||
@@ -92,9 +94,13 @@ public sealed class AppServices : IAsyncDisposable
|
||||
_server = value;
|
||||
_server.PropertyChanged += OnServerChanged;
|
||||
UpdateRenderNode();
|
||||
Sync.Update();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Sync with the signed-in server: engine, job connection, background comparison.</summary>
|
||||
public SyncHost Sync { get; }
|
||||
|
||||
public IEncoderInventory Encoders { get; set; }
|
||||
|
||||
/// <summary>Latest public release (GitHub Releases API of the releases repository, BRIEF §18).</summary>
|
||||
@@ -125,7 +131,10 @@ public sealed class AppServices : IAsyncDisposable
|
||||
/// <summary>The job handlers of this PC's engine — the single registration list; a kind without a handler stays
|
||||
/// queued (it is never claimed here).</summary>
|
||||
public static IReadOnlyList<IJobHandler> CreateJobHandlers(AppServices services) =>
|
||||
[.. services.Archives?.CreateJobHandlers() ?? [], .. services.Processing?.CreateJobHandlers() ?? []];
|
||||
[
|
||||
.. services.Archives?.CreateJobHandlers() ?? [], .. services.Processing?.CreateJobHandlers() ?? [],
|
||||
.. services.Sync.Service?.CreateJobHandlers(services.Sync) ?? [],
|
||||
];
|
||||
|
||||
/// <summary>Queues a scan of <paramref name="archive"/> unless one is already waiting or running.</summary>
|
||||
public async Task QueueScanAsync(Archive archive, bool full, CancellationToken ct = default)
|
||||
@@ -199,6 +208,7 @@ public sealed class AppServices : IAsyncDisposable
|
||||
_stopping.Dispose();
|
||||
_server.PropertyChanged -= OnServerChanged;
|
||||
await _renderNode.DisposeAsync().ConfigureAwait(false);
|
||||
await Sync.DisposeAsync().ConfigureAwait(false);
|
||||
(Jobs as IDisposable)?.Dispose();
|
||||
if (Engine is not null) await Engine.DisposeAsync().ConfigureAwait(false);
|
||||
Thumbnails?.Dispose();
|
||||
@@ -235,6 +245,7 @@ public sealed class AppServices : IAsyncDisposable
|
||||
var archive = new ArchiveServiceOptions { Decoder = DecoderFactory.CreateClient(new WicDecoderProvider()) };
|
||||
Archives = new ArchiveService(database, archive);
|
||||
Processing = new ProcessingService(database, ProcessingOptions(archive));
|
||||
Sync.Open(database, Archives, archive);
|
||||
var handlers = CreateJobHandlers(this);
|
||||
var kinds = handlers.Select(h => h.Kind).Distinct().ToArray();
|
||||
Engine = new JobEngine(database, handlers, new JobEngineOptions { WorkerId = WorkerId, Kinds = kinds });
|
||||
@@ -244,6 +255,7 @@ public sealed class AppServices : IAsyncDisposable
|
||||
Jobs = new EngineJobQueue(database, Engine, started);
|
||||
Log.Info("jobs", started ? $"Job engine started with {Engine.Options.Workers} worker(s) for {string.Join(", ", kinds)}" : "No job handlers registered; jobs stay queued");
|
||||
UpdateRenderNode();
|
||||
Sync.Update();
|
||||
}
|
||||
|
||||
/// <summary>Media Foundation (hardware first, software H.264; hardware as Settings › Rendering allows) then managed
|
||||
@@ -263,7 +275,11 @@ public sealed class AppServices : IAsyncDisposable
|
||||
},
|
||||
};
|
||||
|
||||
private void OnServerChanged(object? sender, PropertyChangedEventArgs e) => UpdateRenderNode();
|
||||
private void OnServerChanged(object? sender, PropertyChangedEventArgs e)
|
||||
{
|
||||
UpdateRenderNode();
|
||||
Sync.Update();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The render node of <paramref name="session"/>: this PC's encoders (Media Foundation, then managed), downloads and
|
||||
|
||||
@@ -111,6 +111,15 @@ public sealed class AppSettings
|
||||
/// <summary>Let the server send render jobs to this PC (BRIEF §14.7).</summary>
|
||||
public bool RenderNodeOptIn { get; set; }
|
||||
|
||||
/// <summary>Keep the proxy caches of the server sequences this PC opened with proxies up to date (BRIEF §12.7).</summary>
|
||||
public bool KeepProxiesOffline { get; set; }
|
||||
|
||||
/// <summary>Send and take project settings changed on one side without asking (Server.html).</summary>
|
||||
public bool SyncSettingsAutomatically { get; set; } = true;
|
||||
|
||||
/// <summary>Pause upload jobs while Windows reports the connection as metered (Server.html).</summary>
|
||||
public bool PauseUploadsOnMetered { get; set; }
|
||||
|
||||
// ---- Jobs ----
|
||||
/// <summary>"Clear done": finished jobs older than this are hidden from the Jobs list (they stay in the history).</summary>
|
||||
public DateTimeOffset? JobsClearedAt { get; set; }
|
||||
|
||||
@@ -147,7 +147,20 @@ public sealed class SequenceItem : ObservableObject
|
||||
OnPropertyChanged(nameof(PrimaryStatus));
|
||||
}
|
||||
|
||||
/// <summary>Card status row: analysed, proxies, renders, sync, warnings (Main.html).</summary>
|
||||
/// <summary>
|
||||
/// Where a local copy stands against the server (the sync engine writes the state), in one word as DESIGN §4 draws
|
||||
/// it ("● Synced", "● Remote", "▲ Conflict") with the detail in the tooltip; null while it is only here.
|
||||
/// </summary>
|
||||
public static CardStatus? SyncStatus(SyncState state) => state switch
|
||||
{
|
||||
SyncState.InSync => new CardStatus(StatusKind.Synced, Loc.L("Library.Status.Synced"), Loc.L("Tooltips.Library.Status.Synced")),
|
||||
SyncState.LocalAhead => new CardStatus(StatusKind.Synced, Loc.L("Library.Status.Synced"), Loc.L("Tooltips.Library.Status.LocalAhead")),
|
||||
SyncState.ServerAhead => new CardStatus(StatusKind.Remote, Loc.L("Library.Status.Remote"), Loc.L("Tooltips.Library.Status.ServerAhead")),
|
||||
SyncState.Conflict => new CardStatus(StatusKind.Warning, Loc.L("Library.Status.Conflict"), Loc.L("Tooltips.Library.Status.Conflict")),
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <summary>Card status row: analysed, proxies, renders, errors or warnings, sync (Main.html); the sync glyph is last so a narrow card cuts it first.</summary>
|
||||
public static IReadOnlyList<CardStatus> BuildStatuses(Sequence s, bool analysing)
|
||||
{
|
||||
var list = new List<CardStatus>(5);
|
||||
@@ -168,12 +181,11 @@ public sealed class SequenceItem : ObservableObject
|
||||
|
||||
if (s.RenderedCount > 0)
|
||||
list.Add(new CardStatus(StatusKind.Rendered, Formatting.Count(s.RenderedCount), Loc.Plural("Tooltips.Library.Status.Rendered", s.RenderedCount)));
|
||||
if (s.SyncState == SyncState.InSync)
|
||||
list.Add(new CardStatus(StatusKind.Synced, Loc.L("Library.Status.Synced"), Loc.L("Tooltips.Library.Status.Synced")));
|
||||
if ((s.Status & SequenceStatus.HasErrors) != 0)
|
||||
list.Add(new CardStatus(StatusKind.Error, Formatting.Count(Math.Max(1, s.WarningCount)), Loc.L("Tooltips.Library.Status.Errors")));
|
||||
else if (s.WarningCount > 0 || (s.Status & SequenceStatus.HasWarnings) != 0)
|
||||
list.Add(new CardStatus(StatusKind.Warning, Formatting.Count(Math.Max(1, s.WarningCount)), Loc.Plural("Tooltips.Library.Status.Warnings", Math.Max(1, s.WarningCount))));
|
||||
if (SyncStatus(s.SyncState) is { } sync) list.Add(sync);
|
||||
return list;
|
||||
}
|
||||
}
|
||||
@@ -497,7 +497,10 @@ public sealed class LibraryViewModel : SectionViewModel
|
||||
{
|
||||
if (await _db.Sequences.GetAsync(item.Id) is { } fresh) item.Update(fresh);
|
||||
}
|
||||
if (job.Kind is JobKind.Scan or JobKind.Rebuild or JobKind.Import or JobKind.Adopt or JobKind.Move or JobKind.UploadCommit) await RefreshAsync();
|
||||
// Downloads of proxies only fill the proxy cache, so the Library is read again for originals and exports only.
|
||||
if (job.Kind is JobKind.Scan or JobKind.Rebuild or JobKind.Import or JobKind.Adopt or JobKind.Move or JobKind.UploadCommit
|
||||
|| Data.Sync.SyncService.TransferKind(job) is Data.Sync.SyncTransferKind.DownloadOriginals or Data.Sync.SyncTransferKind.GetExports)
|
||||
await RefreshAsync();
|
||||
}
|
||||
catch (DatabaseException ex)
|
||||
{
|
||||
|
||||
@@ -15,9 +15,12 @@
|
||||
<Setter Property="Margin" Value="8,0" />
|
||||
<Setter Property="VerticalAlignment" Value="Center" />
|
||||
</Style>
|
||||
<ItemsPanelTemplate x:Key="Panel.Row">
|
||||
<StackPanel Orientation="Horizontal" />
|
||||
</ItemsPanelTemplate>
|
||||
</UserControl.Resources>
|
||||
|
||||
<!-- Server.html: the connection panel; the render-node panel (right) and the sync table (below) join later. -->
|
||||
<!-- Server.html: the connection panel, then the sync table; the render-node panel joins the connection panel. -->
|
||||
<Grid Margin="20,16,20,12">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
@@ -112,9 +115,140 @@
|
||||
<Border Grid.Row="3" Grid.ColumnSpan="2" Margin="0,14,0,0" Padding="0,10,0,0" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,1,0,0">
|
||||
<WrapPanel>
|
||||
<CheckBox Content="{l:Loc Server.RenderNode}" IsChecked="{Binding RenderNodeOptIn}" ToolTip="{l:Loc Tooltips.Server.RenderNode}" Margin="0,0,22,0" />
|
||||
<CheckBox Content="{l:Loc Server.KeepProxies}" IsChecked="{Binding KeepProxiesOffline}" ToolTip="{l:Loc Tooltips.Server.KeepProxies}" Margin="0,0,22,0" />
|
||||
<CheckBox Content="{l:Loc Server.AutoSync}" IsChecked="{Binding SyncSettingsAutomatically}" ToolTip="{l:Loc Tooltips.Server.AutoSync}" Margin="0,0,22,0" />
|
||||
<CheckBox Content="{l:Loc Server.PauseMetered}" IsChecked="{Binding PauseUploadsOnMetered}" ToolTip="{l:Loc Tooltips.Server.PauseMetered}" Margin="0,0,22,0" />
|
||||
</WrapPanel>
|
||||
</Border>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Sequences of this PC and of the server: chips, search, Upload all local; table; footer. -->
|
||||
<Border Grid.Row="1" Style="{StaticResource Border.Panel}" Margin="0,14,0,0" DataContext="{Binding Sync}">
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- Toolbar in visual (and Tab) order: title, chips, search, Upload all local. -->
|
||||
<Grid Margin="14,10">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{l:Loc Server.Sync.Title}" FontWeight="SemiBold" VerticalAlignment="Center" Margin="0,0,10,0" />
|
||||
<ItemsControl Grid.Column="1" ItemsSource="{Binding Chips}" ItemsPanel="{StaticResource Panel.Row}" Focusable="False" VerticalAlignment="Center">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type srv:SyncFilterChip}">
|
||||
<Button x:Name="Chip" Style="{StaticResource Button.Chip}" Content="{Binding Text}" Tag="{Binding IsSelected}" Command="{Binding SelectCommand}"
|
||||
ToolTip="{Binding ToolTip}" Height="28" FontSize="12" Margin="0,0,10,0" Typography.NumeralAlignment="Tabular" />
|
||||
<DataTemplate.Triggers>
|
||||
<!-- Conflicts waiting are drawn in warning colours, unless the chip is the chosen one (then Accent, DESIGN §4). -->
|
||||
<MultiDataTrigger>
|
||||
<MultiDataTrigger.Conditions>
|
||||
<Condition Binding="{Binding NeedsAttention}" Value="True" />
|
||||
<Condition Binding="{Binding IsSelected}" Value="False" />
|
||||
</MultiDataTrigger.Conditions>
|
||||
<Setter TargetName="Chip" Property="BorderBrush" Value="{DynamicResource Brush.Warning}" />
|
||||
<Setter TargetName="Chip" Property="Foreground" Value="{DynamicResource Brush.Warning}" />
|
||||
</MultiDataTrigger>
|
||||
</DataTemplate.Triggers>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
<TextBox Grid.Column="3" Width="200" Height="30" Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}" ui:Field.Glyph="{StaticResource Icon.Search}"
|
||||
ui:Field.Placeholder="{l:Loc Server.Sync.Search}" ToolTip="{l:Loc Tooltips.Server.Sync.Search}" AutomationProperties.Name="{l:Loc Server.Sync.Search}" />
|
||||
<Button Grid.Column="4" Content="{l:Loc Server.Sync.UploadAll}" Command="{Binding UploadAllCommand}" ToolTip="{Binding UploadAllToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True" Height="30" Margin="10,0,0,0" />
|
||||
</Grid>
|
||||
|
||||
<!-- Header; the rows repeat its columns (Server.html: 1.6fr 150px 150px 150px 1.4fr with 10 px gaps). The right padding
|
||||
keeps the space of the rows' scroll bar, so the columns line up. -->
|
||||
<Border Grid.Row="1" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,1,0,1" Padding="14,8,24,8">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="1.6*" MinWidth="140" />
|
||||
<ColumnDefinition Width="160" />
|
||||
<ColumnDefinition Width="160" />
|
||||
<ColumnDefinition Width="160" />
|
||||
<ColumnDefinition Width="1.4*" MinWidth="280" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Style="{StaticResource Text.Header}" Text="{l:Loc Server.Sync.Column.Sequence}" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Header}" Text="{l:Loc Server.Sync.Column.Local}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="2" Style="{StaticResource Text.Header}" Text="{l:Loc Server.Sync.Column.Server}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="3" Style="{StaticResource Text.Header}" Text="{l:Loc Server.Sync.Column.State}" Margin="10,0,0,0" />
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Rows (virtualised): this PC, the server, the state and the actions that apply; conflicts on the card colour.
|
||||
Tab walks every row button (the rows themselves take no focus). Actions wrap when longer labels need it. -->
|
||||
<ListBox x:Name="SyncList" Grid.Row="2" ItemsSource="{Binding Rows}" ItemContainerStyle="{StaticResource ListBoxItem.PlainRow}"
|
||||
VirtualizingPanel.IsVirtualizing="True" VirtualizingPanel.VirtualizationMode="Recycling" VirtualizingPanel.ScrollUnit="Pixel"
|
||||
ScrollViewer.HorizontalScrollBarVisibility="Disabled" KeyboardNavigation.TabNavigation="Continue"
|
||||
AutomationProperties.Name="{l:Loc Server.Sync.Title}" Visibility="{Binding HasRows, Converter={StaticResource BoolToVisibility}}">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type srv:SyncRow}">
|
||||
<Border x:Name="RowBorder" Background="Transparent" Padding="14,0">
|
||||
<Grid MinHeight="40">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="1.6*" MinWidth="140" />
|
||||
<ColumnDefinition Width="160" />
|
||||
<ColumnDefinition Width="160" />
|
||||
<ColumnDefinition Width="160" />
|
||||
<ColumnDefinition Width="1.4*" MinWidth="280" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Style="{StaticResource Text.Cell}" Text="{Binding Title}" ToolTip="{Binding Title}" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding LocalText}" ToolTip="{Binding LocalText}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding ServerText}" ToolTip="{Binding ServerText}" Margin="10,0,0,0" />
|
||||
<ui:StatusGlyph Grid.Column="3" Kind="{Binding StateKind}" Text="{Binding StateText}" ToolTip="{Binding StateToolTip}"
|
||||
FontSize="13" VerticalAlignment="Center" Margin="10,0,0,0" />
|
||||
<ItemsControl Grid.Column="4" ItemsSource="{Binding Actions}" Focusable="False" VerticalAlignment="Center" Margin="10,4,0,4">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<WrapPanel />
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type srv:SyncRowAction}">
|
||||
<Button Style="{StaticResource Button.Row}" Content="{Binding Text}" Command="{Binding Command}" ToolTip="{Binding ToolTip}"
|
||||
FontSize="12" Margin="0,2,6,2" />
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</Grid>
|
||||
</Border>
|
||||
<DataTemplate.Triggers>
|
||||
<DataTrigger Binding="{Binding IsConflict}" Value="True">
|
||||
<Setter TargetName="RowBorder" Property="Background" Value="{DynamicResource Brush.Card}" />
|
||||
</DataTrigger>
|
||||
</DataTemplate.Triggers>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
<ui:EmptyState Grid.Row="2" Message="{Binding EmptyText}" Visibility="{Binding EmptyText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}" />
|
||||
|
||||
<!-- Footer: last comparison · server archive · retry state · admin panel. -->
|
||||
<Border Grid.Row="3" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,1,0,0" Padding="14,8">
|
||||
<DockPanel LastChildFill="False" TextElement.FontSize="12">
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Link}" Content="{l:Loc Server.Sync.OpenAdmin}" Command="{Binding OpenAdminCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Server.Sync.OpenAdmin}" Visibility="{Binding CanOpenAdmin, Converter={StaticResource BoolToVisibility}}" />
|
||||
<TextBlock Text="{Binding LastSyncText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,0,16,0" VerticalAlignment="Center"
|
||||
Typography.NumeralAlignment="Tabular" ToolTip="{l:Loc Tooltips.Server.Sync.LastSync}"
|
||||
Visibility="{Binding LastSyncText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}" />
|
||||
<TextBlock Text="{Binding ArchiveText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,0,16,0" VerticalAlignment="Center"
|
||||
Typography.NumeralAlignment="Tabular" ToolTip="{l:Loc Tooltips.Server.Sync.Archive}"
|
||||
Visibility="{Binding ArchiveText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}" />
|
||||
<ui:StatusGlyph Kind="Warning" Text="{Binding ErrorText}" ToolTip="{Binding ErrorToolTip}" FontSize="12" VerticalAlignment="Center"
|
||||
Visibility="{Binding ErrorText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}" />
|
||||
</DockPanel>
|
||||
</Border>
|
||||
</Grid>
|
||||
</Border>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -10,9 +10,9 @@ using Titano.Ui.Mvvm;
|
||||
namespace Titano.App.Sections;
|
||||
|
||||
/// <summary>
|
||||
/// Server, connection part (BRIEF §12.7, Server.html): address with LAN-discovered servers, connect with
|
||||
/// trust-on-first-use and login, status (name, version, latency, certificate), account and quota, sign out, and
|
||||
/// the render-node opt-in. The sync table and render-node panel join this screen later.
|
||||
/// Server (BRIEF §12.7, Server.html): address with LAN-discovered servers, connect with trust-on-first-use and login,
|
||||
/// status (name, version, latency, certificate), account and quota, sign out, the options of this PC (render node,
|
||||
/// proxies kept offline, automatic project sync, uploads paused on metered networks) and the sync table (<see cref="Sync"/>).
|
||||
/// </summary>
|
||||
public sealed class ServerViewModel : SectionViewModel
|
||||
{
|
||||
@@ -34,8 +34,12 @@ public sealed class ServerViewModel : SectionViewModel
|
||||
else if (p is string text) Address = text;
|
||||
});
|
||||
CertificateCommand = new RelayCommand(ShowCertificate, () => Fingerprint is not null);
|
||||
Sync = new SyncTableViewModel(shell);
|
||||
}
|
||||
|
||||
/// <summary>Sequences of this PC and of the server, where they stand and what can be done.</summary>
|
||||
public SyncTableViewModel Sync { get; }
|
||||
|
||||
public ShellViewModel Shell { get; }
|
||||
|
||||
private ServerSession Session => _session ?? Shell.Services.Server;
|
||||
@@ -134,6 +138,34 @@ public sealed class ServerViewModel : SectionViewModel
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Keep the proxy caches of server sequences opened with proxies up to date on this PC.</summary>
|
||||
public bool KeepProxiesOffline
|
||||
{
|
||||
get => Shell.Services.Settings.KeepProxiesOffline;
|
||||
set => SetSyncOption(value, Shell.Services.Settings.KeepProxiesOffline, v => Shell.Services.Settings.KeepProxiesOffline = v);
|
||||
}
|
||||
|
||||
/// <summary>Send and take project settings changed on one side without asking.</summary>
|
||||
public bool SyncSettingsAutomatically
|
||||
{
|
||||
get => Shell.Services.Settings.SyncSettingsAutomatically;
|
||||
set => SetSyncOption(value, Shell.Services.Settings.SyncSettingsAutomatically, v => Shell.Services.Settings.SyncSettingsAutomatically = v);
|
||||
}
|
||||
|
||||
/// <summary>Pause uploads while the connection is metered.</summary>
|
||||
public bool PauseUploadsOnMetered
|
||||
{
|
||||
get => Shell.Services.Settings.PauseUploadsOnMetered;
|
||||
set
|
||||
{
|
||||
if (Shell.Services.Settings.PauseUploadsOnMetered == value) return;
|
||||
Shell.Services.Settings.PauseUploadsOnMetered = value;
|
||||
Shell.Services.SaveSettings();
|
||||
Shell.Services.Sync.Uploads.Request();
|
||||
OnPropertyChanged();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Re-reads values another screen changed (Settings › Server).</summary>
|
||||
public void Refresh() => OnPropertyChanged(nameof(RenderNodeOptIn));
|
||||
|
||||
@@ -149,6 +181,7 @@ public sealed class ServerViewModel : SectionViewModel
|
||||
if (Address.Length == 0 && Session.Discovered.Count > 0) Address = Session.Discovered[0].Address;
|
||||
};
|
||||
if (!Shell.Services.Environment.IsCapture) _session.StartDiscovery();
|
||||
Sync.Attach();
|
||||
await _session.RestoreAsync();
|
||||
if (_session.Flow.Error is not ConnectError.None and var error && !_session.IsConnected) ErrorText = ServerSession.ErrorText(error);
|
||||
}
|
||||
@@ -156,9 +189,19 @@ public sealed class ServerViewModel : SectionViewModel
|
||||
public override void Dispose()
|
||||
{
|
||||
if (_session is not null) _session.PropertyChanged -= OnSessionChanged;
|
||||
Sync.Dispose();
|
||||
base.Dispose();
|
||||
}
|
||||
|
||||
private void SetSyncOption(bool value, bool current, Action<bool> store, [System.Runtime.CompilerServices.CallerMemberName] string? name = null)
|
||||
{
|
||||
if (value == current) return;
|
||||
store(value);
|
||||
Shell.Services.SaveSettings();
|
||||
Shell.Services.Sync.RequestRefresh();
|
||||
OnPropertyChanged(name);
|
||||
}
|
||||
|
||||
private async Task ConnectAsync()
|
||||
{
|
||||
ErrorText = null;
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
using System.IO;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data;
|
||||
using Titano.Data.Sync;
|
||||
using Titano.Protocol.Client;
|
||||
|
||||
namespace Titano.App.Server;
|
||||
|
||||
/// <summary>Makes the sync connection of a signed-in session.</summary>
|
||||
public delegate ISyncRemote SyncRemoteFactory(Uri address, string token, IReadOnlyCollection<string> trustedFingerprints);
|
||||
|
||||
/// <summary>
|
||||
/// This PC's sync with the signed-in server (BRIEF §4.4, §14.5): the <see cref="SyncService"/> of the index, the
|
||||
/// connection of upload and download jobs (<see cref="ISyncConnector"/>), 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
|
||||
{
|
||||
/// <summary>How long a job resumed at start waits for the saved session to be restored.</summary>
|
||||
private static readonly TimeSpan RestoreWait = TimeSpan.FromSeconds(30);
|
||||
|
||||
private Task _switch = Task.CompletedTask;
|
||||
private Credentials? _credentials;
|
||||
private (SyncAgent Agent, ISyncRemote Remote, Credentials Credentials)? _running;
|
||||
|
||||
/// <summary>Connections over <see cref="TitanoClient"/>; screenshots substitute a fake server.</summary>
|
||||
public SyncRemoteFactory RemoteFactory { get; set; } = (address, token, trusted) =>
|
||||
new TitanoSyncRemote(new TitanoClient(address, new CertificatePinning(trusted), $"Titano ({Environment.MachineName})") { Token = token }, ownsClient: true);
|
||||
|
||||
/// <summary>The engine; null until the index is open.</summary>
|
||||
public SyncService? Service { get; private set; }
|
||||
|
||||
/// <summary>The background comparison of the signed-in server; null while signed out.</summary>
|
||||
public SyncAgent? Agent => _running?.Agent;
|
||||
|
||||
/// <summary>The agent's connection, for the table's own calls (conflict resolution); null while signed out.</summary>
|
||||
public ISyncRemote? Remote => _running?.Remote;
|
||||
|
||||
/// <summary>Key of the signed-in server (<see cref="SyncService.ServerKey"/>); null while signed out.</summary>
|
||||
public string? Server => Volatile.Read(ref _credentials) is { } c ? SyncService.ServerKey(c.Address) : null;
|
||||
|
||||
/// <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;
|
||||
|
||||
/// <summary>Creates the engine over the open index; the proxy cache lives in the client's cache folder.</summary>
|
||||
public SyncService Open(TitanoDatabase database, Titano.Data.Archiving.ArchiveService archives, Titano.Data.Archiving.ArchiveServiceOptions options)
|
||||
{
|
||||
var cache = CacheStore.Folder(services.Environment, services.Settings);
|
||||
Service = new SyncService(database, archives, new SyncOptions { Archive = options, ProxyCacheDirectory = Path.Combine(cache, "proxies") });
|
||||
Service.Changed += server =>
|
||||
{
|
||||
if (server == Server) Changed?.Invoke();
|
||||
};
|
||||
return Service;
|
||||
}
|
||||
|
||||
/// <summary>Follows the server session (UI thread): starts the agent for a new sign-in, stops it on sign-out.</summary>
|
||||
public void Update()
|
||||
{
|
||||
var session = services.Server;
|
||||
Credentials? wanted = session.IsConnected && session.Flow is { Address: { } address, Token: { } token }
|
||||
? new Credentials(address, token, session.Fingerprints)
|
||||
: null;
|
||||
Volatile.Write(ref _credentials, wanted);
|
||||
_switch = SwitchAsync(_switch, wanted);
|
||||
if (services.Engine is { } engine) Uploads.Attach(engine);
|
||||
}
|
||||
|
||||
/// <summary>Compares now, once the session switch in progress settled; null while signed out.</summary>
|
||||
public async Task<SyncSnapshot?> RefreshAsync(CancellationToken ct = default)
|
||||
{
|
||||
await _switch;
|
||||
return Agent is { } agent ? await agent.RefreshAsync(ct) : null;
|
||||
}
|
||||
|
||||
/// <summary>Compares again soon (an option changed, an edit on this PC).</summary>
|
||||
public void RequestRefresh() => Agent?.RequestRefresh();
|
||||
|
||||
/// <summary>The archive downloaded originals go to when a sequence has no local copy: the one this PC works with.</summary>
|
||||
public async Task<Archive?> CurrentArchiveAsync(CancellationToken ct = default)
|
||||
{
|
||||
if (services.Database is not { } db) return null;
|
||||
var archives = await db.Archives.ListAsync(ct);
|
||||
if (services.Settings.LastArchivePath is { Length: > 0 } root)
|
||||
{
|
||||
var full = Path.GetFullPath(root).TrimEnd(Path.DirectorySeparatorChar);
|
||||
if (archives.FirstOrDefault(a => string.Equals(Path.GetFullPath(a.RootPath).TrimEnd(Path.DirectorySeparatorChar), full, StringComparison.OrdinalIgnoreCase))
|
||||
is { } current) return current;
|
||||
}
|
||||
return archives.Count == 1 ? archives[0] : null;
|
||||
}
|
||||
|
||||
public async ValueTask<ISyncRemote?> ConnectAsync(string server, CancellationToken cancellationToken)
|
||||
{
|
||||
// A job resumed at start runs before the saved session is restored: give the restore a moment.
|
||||
var until = DateTime.UtcNow + RestoreWait;
|
||||
while (Volatile.Read(ref _credentials) is null && services.Settings.ProtectedToken is not null && DateTime.UtcNow < until)
|
||||
await Task.Delay(500, cancellationToken);
|
||||
if (Volatile.Read(ref _credentials) is not { } c || SyncService.ServerKey(c.Address) != server) return null;
|
||||
CacheStore.Prepare(CacheStore.Folder(services.Environment, services.Settings));
|
||||
return RemoteFactory(c.Address, c.Token, c.Fingerprints);
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
Volatile.Write(ref _credentials, null);
|
||||
Uploads.Dispose();
|
||||
await _switch;
|
||||
await StopAsync();
|
||||
}
|
||||
|
||||
private async Task SwitchAsync(Task previous, Credentials? wanted)
|
||||
{
|
||||
await previous;
|
||||
if (_running is { } running && wanted is { } same && running.Credentials.Address == same.Address && running.Credentials.Token == same.Token) return;
|
||||
await StopAsync();
|
||||
if (wanted is not { } start || Service is not { } service)
|
||||
{
|
||||
Changed?.Invoke();
|
||||
return;
|
||||
}
|
||||
var remote = RemoteFactory(start.Address, start.Token, start.Fingerprints);
|
||||
var agent = new SyncAgent(service, remote, () => Policy, services.Engine);
|
||||
agent.Changed += () => Changed?.Invoke();
|
||||
agent.Start();
|
||||
_running = (agent, remote, start);
|
||||
Log.Info("sync", $"Comparing with {remote.Server}");
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
private async Task StopAsync()
|
||||
{
|
||||
if (_running is not { } running) return;
|
||||
_running = null;
|
||||
await running.Agent.DisposeAsync();
|
||||
running.Remote.Dispose();
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
private sealed record Credentials(Uri Address, string Token, IReadOnlyCollection<string> Fingerprints);
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
using System.Windows.Input;
|
||||
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", …; 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 IReadOnlyList<SyncRowAction> _actions = [];
|
||||
|
||||
public SyncRow(SyncEntry entry, SyncRights rights, Func<SyncRow, SyncAction, Task> act)
|
||||
{
|
||||
_entry = entry;
|
||||
_act = act;
|
||||
UpdateActions(rights);
|
||||
}
|
||||
|
||||
public SyncEntry Entry => _entry;
|
||||
public Guid Id => _entry.Id;
|
||||
public string Title => _entry.Title;
|
||||
public string LocalText => SyncText.Local(_entry);
|
||||
public string ServerText => SyncText.Server(_entry);
|
||||
public StatusKind StateKind => SyncText.State(_entry).Kind;
|
||||
public string StateText => SyncText.State(_entry).Text;
|
||||
public string StateToolTip => SyncText.State(_entry).ToolTip;
|
||||
|
||||
/// <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;
|
||||
UpdateActions(rights);
|
||||
RaiseTexts();
|
||||
}
|
||||
|
||||
/// <summary>Takes the progress of the row's transfer ("46 % received") without touching its buttons.</summary>
|
||||
public void UpdateProgress(long done, long total)
|
||||
{
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,428 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.IO;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Threading;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.App.Shell;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Jobs;
|
||||
using Titano.Data.Sync;
|
||||
using Titano.Ui.Mvvm;
|
||||
|
||||
namespace Titano.App.Server;
|
||||
|
||||
/// <summary>A filter chip of the sync table: "Conflicts · 1".</summary>
|
||||
public sealed class SyncFilterChip(SyncFilter filter, Action<SyncFilter> select) : ObservableObject
|
||||
{
|
||||
private int _count;
|
||||
private bool _isSelected;
|
||||
|
||||
public SyncFilter Filter { get; } = filter;
|
||||
public string Text => Loc.L("Server.Sync.Filter." + Filter, Formatting.Count(_count));
|
||||
public string ToolTip => Loc.L("Tooltips.Server.Sync.Filter." + Filter);
|
||||
public ICommand SelectCommand { get; } = new RelayCommand(() => select(filter));
|
||||
|
||||
/// <summary>Conflicts waiting for a choice: the chip is drawn in the warning colour unless it is the selected one.</summary>
|
||||
public bool NeedsAttention => Filter == SyncFilter.Conflicts && _count > 0;
|
||||
|
||||
public bool IsSelected
|
||||
{
|
||||
get => _isSelected;
|
||||
set => Set(ref _isSelected, value);
|
||||
}
|
||||
|
||||
public int Count
|
||||
{
|
||||
get => _count;
|
||||
set
|
||||
{
|
||||
if (!Set(ref _count, value)) return;
|
||||
OnPropertyChanged(nameof(Text));
|
||||
OnPropertyChanged(nameof(NeedsAttention));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>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, 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;
|
||||
|
||||
public SyncTableViewModel(ShellViewModel shell)
|
||||
{
|
||||
_shell = shell;
|
||||
_chips = [.. Enum.GetValues<SyncFilter>().Select(f => new SyncFilterChip(f, Select) { IsSelected = f == SyncFilter.All })];
|
||||
_uploadAll = new AsyncRelayCommand(UploadAllAsync, () => IsActive && Rights.CanUpload && LocalOnly.Any());
|
||||
OpenAdminCommand = new RelayCommand(() =>
|
||||
{
|
||||
if (Host.Server is { } server) ShellActions.OpenUrl(server + "/admin");
|
||||
});
|
||||
}
|
||||
|
||||
public ObservableCollection<SyncRow> Rows { get; } = [];
|
||||
public IReadOnlyList<SyncFilterChip> Chips => _chips;
|
||||
public ICommand UploadAllCommand => _uploadAll;
|
||||
public ICommand OpenAdminCommand { get; }
|
||||
|
||||
public string SearchText
|
||||
{
|
||||
get => _search;
|
||||
set
|
||||
{
|
||||
if (Set(ref _search, value ?? string.Empty)) ApplyFilter(rebuild: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Signed in: the table compares this PC with that server.</summary>
|
||||
public bool IsActive => Host.Server is not null;
|
||||
|
||||
public bool HasRows => Rows.Count > 0;
|
||||
|
||||
/// <summary>"Not connected to a server", "Nothing to compare yet" or "No sequence matches"; null when rows show.</summary>
|
||||
public string? EmptyText => HasRows ? null
|
||||
: !IsActive ? Loc.L("Server.Empty")
|
||||
: _entries.Count == 0 ? Loc.L("Server.Sync.Empty")
|
||||
: Loc.L("Server.Sync.NoMatch");
|
||||
|
||||
/// <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
|
||||
? Loc.L("Server.Sync.Last", Formatting.TimeOfDay(s.RefreshedAt), s.Duration.TotalSeconds.ToString("0.0", Loc.Culture))
|
||||
: null;
|
||||
|
||||
/// <summary>"Server archive 9.4 TB · 412 sequences".</summary>
|
||||
public string? ArchiveText => Host.Agent?.Snapshot is { } s ? Loc.Plural("Server.Sync.Archive", s.ServerSequences, Formatting.Bytes(s.ServerBytes)) : null;
|
||||
|
||||
/// <summary>The last comparison failed (it is retried with growing pauses); null when it worked.</summary>
|
||||
public string? ErrorText => Host.Agent?.LastError is not null ? Loc.L("Server.Sync.Retrying") : null;
|
||||
|
||||
public string? ErrorToolTip => Host.Agent?.LastError is { } error ? Loc.L("Tooltips.Server.Sync.Retrying", error.Message) : null;
|
||||
|
||||
/// <summary>The server's web admin (it admits administrators only).</summary>
|
||||
public bool CanOpenAdmin => IsActive;
|
||||
|
||||
private SyncHost Host => _shell.Services.Sync;
|
||||
|
||||
private SyncRights Rights => _shell.Services.Server.User is { } user ? SyncRights.Of(user.Permissions) : default;
|
||||
|
||||
private IEnumerable<SyncEntry> LocalOnly => _entries.Where(e => e.Status == SyncStatus.LocalOnly);
|
||||
|
||||
/// <summary>Starts following the sync engine, 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;
|
||||
jobs.Progress += OnProgress;
|
||||
}
|
||||
_ = ReloadAsync();
|
||||
}
|
||||
|
||||
/// <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;
|
||||
Loc.CultureChanged -= OnCultureChanged;
|
||||
if (_shell.Services.Jobs is { } jobs)
|
||||
{
|
||||
jobs.JobChanged -= OnJobChanged;
|
||||
jobs.Progress -= OnProgress;
|
||||
}
|
||||
}
|
||||
|
||||
private void Select(SyncFilter filter)
|
||||
{
|
||||
_filter = filter;
|
||||
foreach (var chip in _chips) chip.IsSelected = chip.Filter == filter;
|
||||
ApplyFilter(rebuild: true);
|
||||
}
|
||||
|
||||
/// <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(rebuild: false);
|
||||
UpdateLibrary();
|
||||
OnPropertyChanged(nameof(IsActive));
|
||||
OnPropertyChanged(nameof(UploadAllToolTip));
|
||||
OnPropertyChanged(nameof(LastSyncText));
|
||||
OnPropertyChanged(nameof(ArchiveText));
|
||||
OnPropertyChanged(nameof(ErrorText));
|
||||
OnPropertyChanged(nameof(ErrorToolTip));
|
||||
OnPropertyChanged(nameof(CanOpenAdmin));
|
||||
_uploadAll.RaiseCanExecuteChanged();
|
||||
}
|
||||
|
||||
/// <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);
|
||||
if (rebuild)
|
||||
{
|
||||
Rows.Clear();
|
||||
foreach (var entry in wanted) Rows.Add(Row(entry, rights, byId));
|
||||
}
|
||||
else
|
||||
{
|
||||
for (var i = 0; i < wanted.Count; i++)
|
||||
{
|
||||
var entry = wanted[i];
|
||||
if (i < Rows.Count && Rows[i].Id == entry.Id)
|
||||
{
|
||||
Rows[i].Update(entry, rights);
|
||||
continue;
|
||||
}
|
||||
var row = Row(entry, rights, byId);
|
||||
var at = byId.ContainsKey(entry.Id) ? Rows.IndexOf(row) : -1;
|
||||
if (at >= 0) Rows.Move(at, i);
|
||||
else Rows.Insert(i, row);
|
||||
}
|
||||
while (Rows.Count > wanted.Count) Rows.RemoveAt(Rows.Count - 1);
|
||||
}
|
||||
OnPropertyChanged(nameof(HasRows));
|
||||
OnPropertyChanged(nameof(EmptyText));
|
||||
}
|
||||
|
||||
/// <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()
|
||||
{
|
||||
var locals = _entries.Where(e => e.Local is not null).ToDictionary(e => e.Local!.Id, e => e.Local!);
|
||||
foreach (var item in _shell.Library.Items)
|
||||
{
|
||||
if (locals.TryGetValue(item.Id, out var fresh) && fresh.SyncState != item.Sequence.SyncState) item.Update(fresh);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ActAsync(SyncRow row, SyncAction action)
|
||||
{
|
||||
if (Host is not { Service: { } service, Server: { } server } || _shell.Services.Engine is not { } engine) return;
|
||||
var entry = row.Entry;
|
||||
switch (action)
|
||||
{
|
||||
case SyncAction.Upload:
|
||||
await service.EnqueueUploadAsync(engine, server, entry.Local!);
|
||||
break;
|
||||
case SyncAction.SendExports:
|
||||
await service.EnqueueSendExportsAsync(engine, server, entry.Local!);
|
||||
break;
|
||||
case SyncAction.DownloadOriginals:
|
||||
if ((entry.Local?.ArchiveId ?? (await Host.CurrentArchiveAsync())?.Id) is not { } archive)
|
||||
{
|
||||
_shell.Notify(Loc.L("Errors.Sync.NoArchive"));
|
||||
return;
|
||||
}
|
||||
await service.EnqueueDownloadAsync(engine, server, entry.Id, entry.Title, SyncDownloadMode.Originals, archive);
|
||||
break;
|
||||
case SyncAction.GetExports:
|
||||
await service.EnqueueDownloadAsync(engine, server, entry.Id, entry.Title, SyncDownloadMode.Exports, null);
|
||||
break;
|
||||
case SyncAction.OpenWithProxies when entry.Status == SyncStatus.ProxiesOnly && service.OpenRemote(server, entry.Id) is not null:
|
||||
_shell.OpenSequence(entry.Id);
|
||||
return;
|
||||
case SyncAction.OpenWithProxies:
|
||||
var job = await service.EnqueueDownloadAsync(engine, server, entry.Id, entry.Title, SyncDownloadMode.Proxies, null);
|
||||
_openWhenCached[entry.Id] = job.Id;
|
||||
// A download that finished before it was recorded here opens at once.
|
||||
if (await _shell.Services.Database!.Jobs.GetAsync(job.Id) is { State: JobState.Done or JobState.Failed or JobState.Cancelled } ended)
|
||||
OpenWhenCached(ended);
|
||||
break;
|
||||
case SyncAction.Pause:
|
||||
await _shell.Services.Jobs!.PauseAsync(entry.Transfer!.Id);
|
||||
break;
|
||||
case SyncAction.Resume:
|
||||
await _shell.Services.Jobs!.ResumeAsync(entry.Transfer!.Id);
|
||||
break;
|
||||
case SyncAction.SyncSettings when Host.Remote is { } remote:
|
||||
await service.SyncSettingsAsync(remote, entry.Id, Host.Policy, CancellationToken.None);
|
||||
break;
|
||||
case SyncAction.KeepMine or SyncAction.TakeServer or SyncAction.SaveBoth when Host.Remote is { } remote:
|
||||
await ResolveAsync(service, remote, entry, action);
|
||||
break;
|
||||
}
|
||||
await ReloadAsync();
|
||||
}
|
||||
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <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;
|
||||
var queued = 0;
|
||||
foreach (var entry in LocalOnly.ToList())
|
||||
{
|
||||
await service.EnqueueUploadAsync(engine, server, entry.Local!);
|
||||
queued++;
|
||||
}
|
||||
_shell.Notify(Loc.Plural("Server.Sync.Queued", queued));
|
||||
await ReloadAsync();
|
||||
}
|
||||
|
||||
private void OnChanged() => Dispatch(() => _ = ReloadAsync());
|
||||
|
||||
private void OnCultureChanged(object? sender, EventArgs e) => Dispatch(() =>
|
||||
{
|
||||
foreach (var chip in _chips) chip.Relabel();
|
||||
foreach (var row in Rows) row.Relabel();
|
||||
OnAllPropertiesChanged();
|
||||
});
|
||||
|
||||
private void OnJobChanged(Job job)
|
||||
{
|
||||
if (job.Kind is not (JobKind.UploadCommit or JobKind.Download)) return;
|
||||
_progress.TryRemove(job.Id, out _);
|
||||
Dispatch(() =>
|
||||
{
|
||||
OpenWhenCached(job);
|
||||
_ = ReloadAsync();
|
||||
});
|
||||
}
|
||||
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Sync;
|
||||
using Titano.Ui.Controls;
|
||||
|
||||
namespace Titano.App.Server;
|
||||
|
||||
/// <summary>Filter chips of the sync table (Server.html).</summary>
|
||||
public enum SyncFilter
|
||||
{
|
||||
All,
|
||||
LocalOnly,
|
||||
Remote,
|
||||
Conflicts,
|
||||
}
|
||||
|
||||
/// <summary>What a row of the sync table offers.</summary>
|
||||
public enum SyncAction
|
||||
{
|
||||
Upload,
|
||||
OpenWithProxies,
|
||||
DownloadOriginals,
|
||||
SyncSettings,
|
||||
KeepMine,
|
||||
TakeServer,
|
||||
SaveBoth,
|
||||
GetExports,
|
||||
SendExports,
|
||||
Pause,
|
||||
Resume,
|
||||
}
|
||||
|
||||
/// <summary>What the signed-in account may do (server permission bits).</summary>
|
||||
/// <param name="CanUpload">Send originals, settings and renders (upload and edit rights).</param>
|
||||
/// <param name="CanFetchOriginals">Download originals (editors and render nodes).</param>
|
||||
/// <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) != 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)
|
||||
{
|
||||
if (entry.HasLocalOriginals)
|
||||
{
|
||||
return (entry.Local!.Status & SequenceStatus.ProxiesBuilt) != 0
|
||||
? Join(Loc.L("Server.Sync.Originals"), Loc.L("Server.Sync.Proxies"))
|
||||
: Loc.L("Server.Sync.Originals");
|
||||
}
|
||||
return entry.Link is { ProxiesCached: > 0 } ? Loc.L("Server.Sync.Proxies") : Loc.L("Server.Sync.None");
|
||||
}
|
||||
|
||||
/// <summary>"originals · proxies · 3 exports", "46 % received" while uploading, or "—".</summary>
|
||||
public static string Server(SyncEntry entry)
|
||||
{
|
||||
if (entry.Transfer is { Kind: JobKind.UploadCommit, State: JobState.Running, ProgressTotal: > 0 } upload)
|
||||
return Loc.L("Server.Sync.Received", Formatting.Percent((double)upload.ProgressDone / upload.ProgressTotal));
|
||||
if (entry.Link is not { } link) return Loc.L("Server.Sync.None");
|
||||
var parts = new List<string>(3) { Loc.L("Server.Sync.Originals") };
|
||||
if (link.ServerHasProxies) parts.Add(Loc.L("Server.Sync.Proxies"));
|
||||
if (link.RenderCount > 0) parts.Add(Loc.Plural("Server.Sync.Exports", link.RenderCount));
|
||||
return Join([.. parts]);
|
||||
}
|
||||
|
||||
/// <summary>The State column: glyph kind, word and tooltip (never colour alone).</summary>
|
||||
public static (StatusKind Kind, string Text, string ToolTip) State(SyncEntry entry)
|
||||
{
|
||||
if (entry.Transfer is { } job)
|
||||
{
|
||||
var upload = job.Kind == JobKind.UploadCommit;
|
||||
return job.State switch
|
||||
{
|
||||
JobState.Paused => (StatusKind.Paused, Loc.L("Server.Sync.State.Paused"), Loc.L("Tooltips.Server.Sync.State.Paused")),
|
||||
JobState.Queued => (StatusKind.Queued, Loc.L("Server.Sync.State.Waiting"), Loc.L("Tooltips.Server.Sync.State.Waiting")),
|
||||
_ => (StatusKind.Running, Loc.L(upload ? "Server.Sync.State.Uploading" : "Server.Sync.State.Downloading"),
|
||||
Loc.L(upload ? "Tooltips.Server.Sync.State.Uploading" : "Tooltips.Server.Sync.State.Downloading")),
|
||||
};
|
||||
}
|
||||
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")),
|
||||
SyncStatus.LocalOnly => (StatusKind.Offline, Loc.L("Server.Sync.State.LocalOnly"), Loc.L("Tooltips.Server.Sync.State.LocalOnly")),
|
||||
SyncStatus.RemoteOnly => (StatusKind.Remote, Loc.L("Server.Sync.State.RemoteOnly"), Loc.L("Tooltips.Server.Sync.State.RemoteOnly")),
|
||||
SyncStatus.ProxiesOnly => (StatusKind.Remote, Loc.L("Server.Sync.State.ProxiesOnly"), Loc.L("Tooltips.Server.Sync.State.ProxiesOnly")),
|
||||
SyncStatus.LocalAhead => (StatusKind.Synced, Loc.L("Server.Sync.State.LocalAhead"), Loc.L("Tooltips.Server.Sync.State.LocalAhead")),
|
||||
SyncStatus.ServerAhead => (StatusKind.Remote, Loc.L("Server.Sync.State.ServerAhead"), Loc.L("Tooltips.Server.Sync.State.ServerAhead")),
|
||||
_ => (StatusKind.Warning, Loc.L("Server.Sync.State.Conflict"), ConflictSummary(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 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>
|
||||
public static IReadOnlyList<SyncAction> Actions(SyncEntry entry, SyncRights rights)
|
||||
{
|
||||
if (entry.Transfer is { } job) return job.State == JobState.Paused ? [SyncAction.Resume] : [SyncAction.Pause];
|
||||
var actions = new List<SyncAction>(3);
|
||||
switch (entry.Status)
|
||||
{
|
||||
case SyncStatus.LocalOnly when rights.CanUpload:
|
||||
actions.Add(SyncAction.Upload);
|
||||
break;
|
||||
case SyncStatus.RemoteOnly or SyncStatus.ProxiesOnly:
|
||||
actions.Add(SyncAction.OpenWithProxies);
|
||||
if (rights.CanFetchOriginals) actions.Add(SyncAction.DownloadOriginals);
|
||||
break;
|
||||
case SyncStatus.LocalAhead when entry.Link is { MissingRemote: > 0 }:
|
||||
if (rights.CanUpload) actions.Add(SyncAction.Upload);
|
||||
break;
|
||||
case SyncStatus.ServerAhead when entry.Link is { MissingLocal: > 0 }:
|
||||
if (rights.CanFetchOriginals) actions.Add(SyncAction.DownloadOriginals);
|
||||
break;
|
||||
case SyncStatus.LocalAhead when rights.CanEdit:
|
||||
case SyncStatus.ServerAhead:
|
||||
actions.Add(SyncAction.SyncSettings);
|
||||
break;
|
||||
case SyncStatus.Conflict:
|
||||
if (rights.CanEdit) actions.Add(SyncAction.KeepMine);
|
||||
actions.AddRange([SyncAction.TakeServer, SyncAction.SaveBoth]);
|
||||
return actions;
|
||||
}
|
||||
// Renders travel on request once no original is waiting to go either way.
|
||||
if (entry is { Local: not null, Link: { MissingRemote: 0, MissingLocal: 0 } 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 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
|
||||
{
|
||||
SyncFilter.LocalOnly => entry.Status == SyncStatus.LocalOnly,
|
||||
SyncFilter.Remote => entry.Status is SyncStatus.RemoteOnly or SyncStatus.ProxiesOnly,
|
||||
SyncFilter.Conflicts => entry.Status == SyncStatus.Conflict,
|
||||
_ => true,
|
||||
}) && (search.Length == 0 || entry.Title.Contains(search, StringComparison.CurrentCultureIgnoreCase));
|
||||
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using System.Windows.Threading;
|
||||
using Titano.App.DesignTime;
|
||||
using Titano.App.Server;
|
||||
using Titano.App.Settings;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Ui.Theming;
|
||||
@@ -13,7 +14,7 @@ namespace Titano.App.Shell;
|
||||
/// <summary>
|
||||
/// <c>Titano.exe --capture <dir></c>: renders every client screen at 1440×900 in the dark and light themes to
|
||||
/// <c><screen>-<theme>.png</c> from <see cref="SampleData"/> (first run on an empty index, then a populated
|
||||
/// one), for visual review and phase reports (BRIEF §20.2), then exits.
|
||||
/// one, then the sync table with transfers, a conflict and its confirmation), for visual review and phase reports (BRIEF §20.2), then exits.
|
||||
/// </summary>
|
||||
public static class ScreenCapture
|
||||
{
|
||||
@@ -55,6 +56,8 @@ public static class ScreenCapture
|
||||
await shell.Library.RefreshAsync();
|
||||
await shell.Jobs.ReloadAsync();
|
||||
await shell.Services.Server.RestoreAsync();
|
||||
await shell.Services.Sync.RefreshAsync();
|
||||
await shell.Server.Sync.ReloadAsync();
|
||||
shell.About.SetResult(null);
|
||||
await shell.Settings.DetectEncodersAsync();
|
||||
await shell.Settings.SelfTestAsync();
|
||||
@@ -97,6 +100,24 @@ public static class ScreenCapture
|
||||
written += await SaveAsync(window, directory, key.ToString().ToLowerInvariant(), theme);
|
||||
}
|
||||
}
|
||||
// The sync table with proxies kept here and transfers in every state, then filtered to the conflict, then the
|
||||
// conflict's confirmation (after the other screens, so the Jobs capture keeps its own sample).
|
||||
await sample.CacheProxiesAsync();
|
||||
await sample.FillSyncAsync();
|
||||
await shell.Server.Sync.ReloadAsync();
|
||||
foreach (var theme in Themes)
|
||||
{
|
||||
ThemeManager.Apply(theme);
|
||||
shell.Navigate(SectionKey.Server);
|
||||
SelectSyncFilter(shell, SyncFilter.All);
|
||||
written += await SaveAsync(window, directory, "server-sync", theme);
|
||||
SelectSyncFilter(shell, SyncFilter.Conflicts);
|
||||
written += await SaveAsync(window, directory, "server-conflict", theme);
|
||||
if (shell.Server.Sync.Rows.FirstOrDefault() is { } conflict)
|
||||
written += await SaveDialogAsync(new ConfirmDialog(SyncTableViewModel.ConflictRequest(conflict.Entry, SyncAction.KeepMine)), directory,
|
||||
"server-conflict-confirm", theme);
|
||||
SelectSyncFilter(shell, SyncFilter.All);
|
||||
}
|
||||
Log.Info("capture", $"{written} screenshot(s) written to {Path.GetFullPath(directory)}");
|
||||
if (written == 0) Environment.ExitCode = 1;
|
||||
}
|
||||
@@ -111,6 +132,28 @@ public static class ScreenCapture
|
||||
}
|
||||
}
|
||||
|
||||
private static void SelectSyncFilter(ShellViewModel shell, SyncFilter filter) =>
|
||||
shell.Server.Sync.Chips.First(c => c.Filter == filter).SelectCommand.Execute(null);
|
||||
|
||||
/// <summary>A dialog shown off screen, saved, then closed.</summary>
|
||||
private static async Task<int> SaveDialogAsync(Window dialog, string directory, string screen, AppTheme theme)
|
||||
{
|
||||
dialog.WindowStartupLocation = WindowStartupLocation.Manual;
|
||||
dialog.Left = -20000;
|
||||
dialog.Top = -20000;
|
||||
dialog.ShowActivated = false;
|
||||
dialog.ShowInTaskbar = false;
|
||||
dialog.Show();
|
||||
try
|
||||
{
|
||||
return await SaveAsync(dialog, directory, screen, theme);
|
||||
}
|
||||
finally
|
||||
{
|
||||
dialog.Close();
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<int> SaveAsync(Window window, string directory, string screen, AppTheme theme, ShellViewModel? waitForThumbnails = null)
|
||||
{
|
||||
await Settle(window);
|
||||
|
||||
Reference in new issue
Block a user