diff --git a/i18n/en/Errors.resx b/i18n/en/Errors.resx
index 13da03d2..9caf8a3a 100644
--- a/i18n/en/Errors.resx
+++ b/i18n/en/Errors.resx
@@ -20,6 +20,18 @@
The sequence to render is no longer in the archive.Enter a server address such as nas.local:8443 or https://titano.example.com.This file does not contain Titano settings.
+ This PC or the server changed the sequence again; compare and choose again.
+ The disk needs {0} GB more for this download.{0} gigabytes missing
+ {0} render is no longer on this PC; the others were sent.{0} count
+ {0} renders are no longer on this PC; the others were sent.{0} count
+ {0} did not arrive intact; download it again.{0} file name
+ The sequence is no longer in this PC's archive index.
+ Open or create an archive on this PC to receive the originals.
+ Not connected to this server; connect and retry the job.
+ This sequence is not on the server yet; upload it first.
+ No original reached the server: they are missing here or already in another server sequence.
+ {0} original is missing or changed since it was archived; verify the archive.{0} count
+ {0} originals are missing or changed since they were archived; verify the archive.{0} countThe template is empty.Empty token at position {1}: write a name between the braces.File names cannot contain a slash; put folders in the folder template.
diff --git a/i18n/en/Jobs.resx b/i18n/en/Jobs.resx
index a165f36d..723aaee7 100644
--- a/i18n/en/Jobs.resx
+++ b/i18n/en/Jobs.resx
@@ -33,6 +33,7 @@
History keeps {0} daysAdopt folderDeep analysis
+ DownloadDuplicatesImportLight analysis
diff --git a/i18n/en/Library.resx b/i18n/en/Library.resx
index 8d365087..cc92b057 100644
--- a/i18n/en/Library.resx
+++ b/i18n/en/Library.resx
@@ -61,6 +61,7 @@
TitleAnalysedAnalysing
+ ConflictProxiesRemoteSynced
diff --git a/i18n/en/Server.resx b/i18n/en/Server.resx
index 512ef763..3d9acadf 100644
--- a/i18n/en/Server.resx
+++ b/i18n/en/Server.resx
@@ -5,12 +5,23 @@
System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089nas.local:8443invariant
+ Sync projects automaticallyCertificateForgetKeepTitano trusts this certificate for this server. Forgetting it disconnects, and the next connection asks again.longServer certificateTLS {0} trusted {1}
+ Cancel
+ {0} differs{0} setting name
+ {0} {1} here, {2} on the serverlong; {0} setting name, {1} value on this PC, {2} value on the server
+ The server copy of {0} will be replaced by this PC's settings.long; {0} sequence title
+ Keep this PC's settings?
+ {0} · +{1}invariant; {0} first difference, {1} count of the others
+ This PC takes the server's version of {0} and keeps its own settings as a dated copy next to the project.long; {0} sequence title
+ Save both versions?
+ This PC's settings of {0} will be replaced by the server copy.long; {0} sequence title
+ Take the server's settings?ConnectDisconnectNot connected to a server
@@ -71,6 +82,7 @@
The current password is wrong.longThis upload belongs to a render job.longServers found
+ Keep proxies offlineAccountServerStatus
@@ -80,6 +92,7 @@
Sign inSign inUser
+ Pause metered uploads{0} of {1}{0} usedOffer this PC as render node
@@ -88,11 +101,102 @@
UploaderViewerTitano time-lapse archive, uploads, jobs and rendering server.long
+ Aspect
+ auto
+ Batch list
+ Camera offset
+ Crop
+ Deflicker
+ Deflicker strength
+ Deflicker window
+ Excluded frames
+ Export folder
+ Export preset
+ Export values
+ Exposure offset
+ Fit to duration
+ Flow quality
+ Frame rate
+ Hero frame
+ Highlight knee
+ Holy grail
+ Camera keyframes
+ manual
+ Motion blur
+ Notes
+ off
+ on
+ Other setting
+ Output name
+ Rating
+ Regions
+ Shutter angle
+ Stabilisation
+ Stabilisation smoothing
+ Stacking
+ Tags
+ Time remap
+ Timing mode
+ Title
+ Trail length
+ Transitions
+ WB smoothingSign outConnectedConnecting…DisconnectedNot connected
+ Download originals
+ Get exports
+ Keep mine
+ Open with proxies
+ Pause
+ Resume
+ Save both
+ Send exports
+ Sync settings
+ Take server
+ Upload
+ Server archive {1} · {0} sequencelong; {0} sequence count, {1} archive size
+ Server archive {1} · {0} sequenceslong; {0} sequence count, {1} archive size
+ This PC
+ Sequence
+ Server
+ State
+ Nothing to compare yet
+ {0} export{0} count
+ {0} exports{0} count
+ All · {0}{0} count
+ Conflicts · {0}{0} count
+ Local only · {0}{0} count
+ Remote · {0}{0} count
+ Last sync {0} · manifest diff {1} slong; {0} time of day, {1} seconds
+ No sequence matches
+ —invariant
+ Open admin panel
+ originals
+ proxies
+ {0} upload queued{0} count
+ {0} uploads queued{0} count
+ {0} received{0} percent
+ Not compared · retrying
+ This PC's settings savedlong
+ Search
+ Show file
+ settings differ
+ downloading
+ not compared
+ in sync
+ newer here
+ local only
+ paused
+ proxies only
+ remote
+ newer on server
+ uploading
+ waiting
+ Sequences
+ Upload all localTrustCancel{0} uses a certificate Titano does not know yet. Compare the fingerprint with the one in the server's admin panel before you trust it.long
diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx
index 6ece7aea..ba7e3fda 100644
--- a/i18n/en/Tooltips.resx
+++ b/i18n/en/Tooltips.resx
@@ -79,13 +79,16 @@
Filter by analysis, proxies, verification or warningsAnalysed: exposure, flicker and motion are measuredAn analysis job is running on this sequence
+ Settings changed here and on the server; choose on the Server screenSome frames are missing or unreadable; open the sequence for details
+ This PC has originals or settings the server does not have yetNo proxies yet; editing reads the originalsNot analysed yetJPEG proxies built for fast editingLives on the server; this PC has proxies at mostRendered onceRendered {0:N0} times
+ The server has originals or settings this PC does not have yetThe same on this PC and on the server{0:N0} warning; open the sequence for details{0:N0} warnings; open the sequence for details
@@ -102,18 +105,23 @@
Connection, sync and render node · Ctrl+6Preferences of this PC · Ctrl+,Address of the Titano Server; https is assumed · Enter connects
+ Send and take project settings as they change; settings changed on both sides wait for your choice in the table belowShow the full fingerprint, or forget the trustFingerprint trusted on first use; a change blocks the connection and asks you again
+ Close without changing either copy
+ The settings that differ: this PC's value, then the server'sIdentify the server, confirm a new certificate, then sign in · EnterClose the session and work with the local archive only; you stay signed inDo not connect; nothing is sent to this serverSHA-256 fingerprint of the server certificateForget this certificate; the next connection asks againServers found on this network and used before
+ Keep the proxies of the server sequences you opened with proxies up to date on this PC, to edit without the originals; uses space in the cache folderlongKeep trusting this certificateClose without signing in · EscSent only to this server; Titano keeps a session token, never the passwordYour user name on the server
+ Pause uploads while Windows reports this connection as metered; they resume by themselves when it is notlongSpace you use on the server out of your quotaLet the server send render jobs to this PC when it is idle; uses your GPU encodersAdmins manage users, the archive and the server
@@ -123,6 +131,45 @@
Sign in; the token is stored encrypted for this Windows user · EnterSign out; the token is removed from this PCConnection to the server
+ Size and sequences of the server archive
+ Fetch the originals to this PC, verified by hash ({0}){0} size
+ All sequences on this PC and on the server
+ Settings differ between this PC and the server
+ Only on this PC
+ Only on the server
+ Copy the server's render to this PC ({1}){0} count, {1} size
+ Copy the {0} server renders to this PC ({1}){0} count, {1} size
+ Overwrite the server copy with this PC's settings
+ When this PC last compared every sequence with the server, and how long it took
+ Open the web admin in your browser (admins only)
+ Open the editor on the proxies; the render runs on the server
+ Pause this transfer; it resumes where it stopped
+ Resume this transfer where it stopped
+ The last comparison failed: {0}. It is retried automatically.{0} reason
+ Take the server copy and keep this PC's settings as a dated copy of the project
+ Filter the table by sequence title
+ Send this PC's render to the server, verified by hash ({1}){0} count, {1} size
+ Send this PC's {0} renders to the server, verified by hash ({1}){0} count, {1} size
+ Show the saved copy of this PC's settings in File Explorer
+ Settings changed both here and on the server; choose which to keep
+ Originals or proxies are arriving from the server
+ This sequence could not be compared: {0}. It is compared again automatically.long; {0} reason
+ Same originals and settings on this PC and on the server
+ This PC has originals or settings the server does not have yet
+ Only on this PC; upload it to keep it on the server too
+ The transfer is paused; resume it to continue
+ On the server; this PC keeps its proxies for editing
+ Only on the server
+ The server has originals or settings this PC does not have yet
+ Originals are being sent to the server
+ The transfer waits for its turn in the job queue
+ Send or take the settings changed on one side
+ Replace this PC's settings with the server copy
+ Copy originals and settings to the server ({0}){0} size
+ Send every local-only sequence to the server ({0} sequences, {1}){0} count, {1} size
+ Your account cannot upload to this server
+ Connect to a server to upload
+ No sequence is only on this PCTrust this certificate for this server and continue to sign inUse this addressGraphics adapter and Media Foundation encoders found
diff --git a/i18n/it/Errors.it.resx b/i18n/it/Errors.it.resx
index a973d15d..f90ce140 100644
--- a/i18n/it/Errors.it.resx
+++ b/i18n/it/Errors.it.resx
@@ -20,6 +20,18 @@
La sequenza da renderizzare non è più nell'archivio.Inserisci l'indirizzo di un server, ad esempio nas.local:8443 o https://titano.example.com.Questo file non contiene impostazioni di Titano.
+ La sequenza è cambiata di nuovo su questo PC o sul server; confronta e scegli di nuovo.
+ Al disco servono altri {0} GB per questo scaricamento.
+ {0} render non è più su questo PC; gli altri sono stati inviati.
+ {0} render non sono più su questo PC; gli altri sono stati inviati.
+ {0} non è arrivato integro; scaricalo di nuovo.
+ La sequenza non è più nell'indice dell'archivio di questo PC.
+ Apri o crea un archivio su questo PC per ricevere gli originali.
+ Non connesso a questo server; collegati e riprova l'attività.
+ Questa sequenza non è ancora sul server; caricala prima.
+ Nessun originale è arrivato al server: mancano qui o sono già in un'altra sequenza del server.
+ {0} originale manca o è cambiato dopo l'archiviazione; verifica l'archivio.
+ {0} originali mancano o sono cambiati dopo l'archiviazione; verifica l'archivio.Il modello è vuoto.Segnaposto vuoto alla posizione {1}: scrivi un nome tra le parentesi graffe.I nomi dei file non possono contenere la barra; metti le cartelle nel modello delle cartelle.
diff --git a/i18n/it/Jobs.it.resx b/i18n/it/Jobs.it.resx
index 29507c5b..58ed4e7c 100644
--- a/i18n/it/Jobs.it.resx
+++ b/i18n/it/Jobs.it.resx
@@ -33,6 +33,7 @@
Cronologia di {0} giorniAdozione cartellaAnalisi approfondita
+ ScaricamentoDuplicatiImportazioneAnalisi rapida
diff --git a/i18n/it/Library.it.resx b/i18n/it/Library.it.resx
index cbf7ca1a..5d75b9af 100644
--- a/i18n/it/Library.it.resx
+++ b/i18n/it/Library.it.resx
@@ -61,6 +61,7 @@
TitoloAnalizzataIn analisi
+ ConflittoProxyRemotaSincronizzata
diff --git a/i18n/it/Server.it.resx b/i18n/it/Server.it.resx
index fb5bdb68..ab68efee 100644
--- a/i18n/it/Server.it.resx
+++ b/i18n/it/Server.it.resx
@@ -4,12 +4,22 @@
2.0System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ Sincronizza progetti automaticamenteCertificatoDimenticaMantieniTitano considera attendibile questo certificato per questo server. Se lo dimentichi la connessione si chiude e la prossima volta te lo chiederà di nuovo.Certificato del serverTLS {0} attendibile dal {1}
+ Annulla
+ {0}: valori diversi
+ {0} {1} qui, {2} sul server
+ La copia sul server di {0} sarà sostituita dalle impostazioni di questo PC.
+ Tenere le impostazioni di questo PC?
+ Questo PC prende la versione del server di {0} e conserva le proprie impostazioni come copia datata accanto al progetto.
+ Salvare entrambe le versioni?
+ Le impostazioni di {0} su questo PC saranno sostituite dalla copia del server.
+ Usare le impostazioni del server?ConnettiDisconnettiNon connesso a un server
@@ -70,6 +80,7 @@
La password attuale è errata.Questo caricamento appartiene a un job di rendering.Server trovati
+ Proxy disponibili offlineAccountServerStato
@@ -79,6 +90,7 @@
AccediAccediUtente
+ Pausa su reti a consumo{0} di {1}{0} usatiOffri questo PC per il rendering
@@ -87,11 +99,101 @@
CaricatoreVisualizzatoreServer Titano per archivio time-lapse, caricamenti, job e rendering.
+ Proporzioni
+ auto
+ Elenco batch
+ Spostamento camera
+ Ritaglio
+ Deflicker
+ Intensità deflicker
+ Finestra deflicker
+ Fotogrammi esclusi
+ Cartella di esportazione
+ Preset di esportazione
+ Valori di esportazione
+ Correzione esposizione
+ Adatta alla durata
+ Qualità del flusso
+ Frequenza fotogrammi
+ Fotogramma copertina
+ Compressione alte luci
+ Holy grail
+ Keyframe camera
+ manuale
+ Sfocatura di movimento
+ Note
+ disattivo
+ attivo
+ Altra impostazione
+ Nome del file
+ Valutazione
+ Regioni
+ Angolo otturatore
+ Stabilizzazione
+ Morbidezza stabilizzazione
+ Stacking
+ Tag
+ Rimappatura del tempo
+ Modalità dei tempi
+ Titolo
+ Lunghezza scie
+ Transizioni
+ Livellamento WBEsciConnessoConnessione…DisconnessoNon connesso
+ Scarica originali
+ Ricevi esportazioni
+ Tieni le mie
+ Apri con i proxy
+ Pausa
+ Riprendi
+ Salva entrambe
+ Invia esportazioni
+ Sincronizza
+ Usa il server
+ Carica
+ Archivio del server {1} · {0} sequenza
+ Archivio del server {1} · {0} sequenze
+ Questo PC
+ Sequenza
+ Server
+ Stato
+ Ancora nulla da confrontare
+ {0} esportazione
+ {0} esportazioni
+ Tutte · {0}
+ Conflitti · {0}
+ Solo locali · {0}
+ Sul server · {0}
+ Ultima sincronizzazione {0} · confronto {1} s
+ Nessuna sequenza corrisponde
+ Apri pannello admin
+ originali
+ proxy
+ {0} caricamento in coda
+ {0} caricamenti in coda
+ {0} ricevuto
+ Confronto fallito · riprovo
+ Impostazioni di questo PC salvate
+ Cerca
+ Mostra file
+ impostazioni diverse
+ in scaricamento
+ non confrontata
+ sincronizzata
+ più recente qui
+ solo locale
+ in pausa
+ solo proxy
+ sul server
+ server più recente
+ in caricamento
+ in attesa
+ Sequenze
+ Carica le localiConsidera attendibileAnnulla{0} usa un certificato che Titano non conosce ancora. Confronta l'impronta con quella del pannello di amministrazione del server prima di considerarlo attendibile.
diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx
index 4246176c..ab58c062 100644
--- a/i18n/it/Tooltips.it.resx
+++ b/i18n/it/Tooltips.it.resx
@@ -79,13 +79,16 @@
Filtra per analisi, proxy, verifica o avvisiAnalizzata: esposizione, flicker e movimento sono misuratiUn'attività di analisi è in corso su questa sequenza
+ Impostazioni cambiate qui e sul server; scegli nella schermata ServerAlcuni fotogrammi mancano o sono illeggibili; apri la sequenza per i dettagli
+ Questo PC ha originali o impostazioni che il server non ha ancoraAncora nessun proxy; la modifica legge gli originaliNon ancora analizzataProxy JPEG pronti per una modifica veloceSi trova sul server; questo PC ne ha al massimo i proxyEsportata una voltaEsportata {0:N0} volte
+ Il server ha originali o impostazioni che questo PC non ha ancoraUguale su questo PC e sul server{0:N0} avviso; apri la sequenza per i dettagli{0:N0} avvisi; apri la sequenza per i dettagli
@@ -102,18 +105,23 @@
Connessione, sincronizzazione e nodo di rendering · Ctrl+6Preferenze di questo PC · Ctrl+,Indirizzo del Titano Server; si presume https · Invio per connettersi
+ Invia e ricevi le impostazioni dei progetti quando cambiano; quelle cambiate da entrambe le parti attendono la tua scelta nella tabella sottoMostra l'impronta completa o revoca la fiduciaImpronta accettata al primo utilizzo; se cambia, la connessione si blocca e te lo chiede di nuovo
+ Chiudi senza modificare nessuna delle due copie
+ Le impostazioni diverse: il valore di questo PC, poi quello del serverIdentifica il server, conferma un certificato nuovo e poi accedi · InvioChiude la sessione e lavora solo con l'archivio locale; l'accesso resta salvatoNon connetterti; a questo server non viene inviato nullaImpronta SHA-256 del certificato del serverDimentica questo certificato; alla prossima connessione verrà chiesto di nuovoServer trovati in questa rete e usati in precedenza
+ Mantieni aggiornati su questo PC i proxy delle sequenze del server aperte con i proxy, per lavorare senza gli originali; usa spazio nella cartella cacheContinua a considerare attendibile questo certificatoChiude senza accedere · EscInviata solo a questo server; Titano conserva un token di sessione, mai la passwordIl tuo nome utente sul server
+ Mette in pausa i caricamenti mentre Windows segnala questa connessione come a consumo; riprendono da soli quando non lo èSpazio che usi sul server rispetto alla tua quotaPermette al server di inviare rendering a questo PC quando è inattivo; usa gli encoder della tua GPUGli amministratori gestiscono utenti, archivio e server
@@ -123,6 +131,45 @@
Accedi; il token viene salvato cifrato per questo utente di Windows · InvioEsci; il token viene rimosso da questo PCConnessione al server
+ Dimensione e sequenze dell'archivio del server
+ Scarica gli originali su questo PC, verificati con l'hash ({0})
+ Tutte le sequenze di questo PC e del server
+ Le impostazioni differiscono tra questo PC e il server
+ Solo su questo PC
+ Solo sul server
+ Copia su questo PC il render del server ({1})
+ Copia su questo PC i {0} render del server ({1})
+ Sovrascrivi la copia del server con le impostazioni di questo PC
+ Quando questo PC ha confrontato per l'ultima volta tutte le sequenze con il server, e quanto ha impiegato
+ Apri l'amministrazione web nel browser (solo amministratori)
+ Apri l'editor sui proxy; il rendering avviene sul server
+ Metti in pausa questo trasferimento; riprende da dove si è fermato
+ Riprendi questo trasferimento da dove si è fermato
+ L'ultimo confronto non è riuscito: {0}. Viene ripetuto automaticamente.
+ Usa la copia del server e conserva le impostazioni di questo PC come copia datata del progetto
+ Filtra la tabella per titolo della sequenza
+ Invia al server il render di questo PC, verificato con l'hash ({1})
+ Invia al server i {0} render di questo PC, verificati con l'hash ({1})
+ Mostra in Esplora file la copia salvata delle impostazioni di questo PC
+ Le impostazioni sono cambiate sia qui sia sul server; scegli quali tenere
+ Originali o proxy in arrivo dal server
+ Questa sequenza non è stata confrontata: {0}. Il confronto viene ripetuto automaticamente.
+ Stessi originali e impostazioni su questo PC e sul server
+ Questo PC ha originali o impostazioni che il server non ha ancora
+ Solo su questo PC; caricala per averla anche sul server
+ Il trasferimento è in pausa; riprendilo per continuare
+ Sul server; questo PC ne conserva i proxy per modificarla
+ Solo sul server
+ Il server ha originali o impostazioni che questo PC non ha ancora
+ Originali in invio al server
+ Il trasferimento attende il suo turno nella coda delle attività
+ Invia o ricevi le impostazioni cambiate da una sola parte
+ Sostituisci le impostazioni di questo PC con la copia del server
+ Copia originali e impostazioni sul server ({0})
+ Invia al server ogni sequenza solo locale ({0} sequenze, {1})
+ Il tuo account non può caricare su questo server
+ Collegati a un server per caricare
+ Nessuna sequenza è solo su questo PCConsidera attendibile questo certificato per questo server e prosegui con l'accessoUsa questo indirizzoScheda grafica ed encoder Media Foundation trovati
diff --git a/src/Titano.App/DesignTime/SampleData.cs b/src/Titano.App/DesignTime/SampleData.cs
index 105b4f1a..348785f7 100644
--- a/src/Titano.App/DesignTime/SampleData.cs
+++ b/src/Titano.App/DesignTime/SampleData.cs
@@ -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;
///
/// Synthetic content for --capture 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.
///
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(null);
- return new SampleData(services);
+ var sample = new SampleData(services);
+ services.Sync.RemoteFactory = (_, _, _) => sample._remote;
+ return sample;
}
/// Opens the empty temporary index (first run: no archive, nothing indexed).
@@ -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;
}
+ ///
+ /// 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).
+ ///
+ public async Task FillSyncAsync()
+ {
+ var db = _db ?? throw new InvalidOperationException("FillAsync first.");
+ async Task 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));
+ }
+
+ ///
+ /// 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.
+ ///
+ 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);
+ }
+
+ ///
+ /// 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.
+ ///
+ private async Task FillServerAsync(TitanoDatabase db, IReadOnlyList 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 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
}
}
+ ///
+ /// 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.
+ ///
+ private sealed class SampleSyncRemote : ISyncRemote
+ {
+ private readonly Dictionary _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> ListSequencesAsync(CancellationToken cancellationToken)
+ {
+ lock (_sequences) return Task.FromResult>([.. _sequences.Values.Select(s => s.Dto)]);
+ }
+
+ public Task GetSequenceAsync(Guid id, CancellationToken cancellationToken)
+ {
+ lock (_sequences) return Task.FromResult(_sequences[id].Dto);
+ }
+
+ public Task 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> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken)
+ {
+ lock (_sequences)
+ {
+ return Task.FromResult>([.. _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 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 UploadFileAsync(string path, Guid? sequenceId, string? sessionKey, string sha256, DateTime? capturedAt,
+ CancellationToken cancellationToken) => throw new NotSupportedException("The sample server takes no uploads.");
+
+ /// Proxies and thumbnails: a dawn gradient whose sun rises with the frame.
+ 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 DownloadRenderAsync(Guid renderId, Stream destination, CancellationToken cancellationToken) =>
+ throw new NotSupportedException("The sample server serves no renders.");
+
+ public Task UploadRenderAsync(Guid sequenceId, string path, RenderUploadRequest request, CancellationToken cancellationToken) =>
+ throw new NotSupportedException("The sample server takes no renders.");
+
+ public async IAsyncEnumerable EventsAsync([System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken)
+ {
+ await Task.Delay(Timeout.Infinite, cancellationToken);
+ yield break;
+ }
+
+ public void Dispose()
+ {
+ }
+ }
+
/// No encryption: the capture environment is thrown away.
private sealed class PlainTokenProtector : ITokenProtector
{
diff --git a/src/Titano.App/Infrastructure/AppServices.cs b/src/Titano.App/Infrastructure/AppServices.cs
index 55f956e0..edf2b567 100644
--- a/src/Titano.App/Infrastructure/AppServices.cs
+++ b/src/Titano.App/Infrastructure/AppServices.cs
@@ -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 of this PC with the handlers of
-/// , 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
+/// , thumbnails, the server session, the render node, the encoder inventory, the
+/// update check and the sync with the signed-in server (). Started after the window shows,
+/// stopped when the app exits. The last archive is reopened at start and
/// rescanned every (BRIEF §7: polling, no file-system watchers). The render node runs while
/// the user offers this PC () 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();
}
}
+ /// Sync with the signed-in server: engine, job connection, background comparison.
+ public SyncHost Sync { get; }
+
public IEncoderInventory Encoders { get; set; }
/// Latest public release (GitHub Releases API of the releases repository, BRIEF §18).
@@ -125,7 +131,10 @@ public sealed class AppServices : IAsyncDisposable
/// The job handlers of this PC's engine — the single registration list; a kind without a handler stays
/// queued (it is never claimed here).
public static IReadOnlyList CreateJobHandlers(AppServices services) =>
- [.. services.Archives?.CreateJobHandlers() ?? [], .. services.Processing?.CreateJobHandlers() ?? []];
+ [
+ .. services.Archives?.CreateJobHandlers() ?? [], .. services.Processing?.CreateJobHandlers() ?? [],
+ .. services.Sync.Service?.CreateJobHandlers(services.Sync) ?? [],
+ ];
/// Queues a scan of unless one is already waiting or running.
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();
}
/// 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();
+ }
///
/// The render node of : this PC's encoders (Media Foundation, then managed), downloads and
diff --git a/src/Titano.App/Infrastructure/AppSettings.cs b/src/Titano.App/Infrastructure/AppSettings.cs
index 59385ce1..31514da3 100644
--- a/src/Titano.App/Infrastructure/AppSettings.cs
+++ b/src/Titano.App/Infrastructure/AppSettings.cs
@@ -111,6 +111,15 @@ public sealed class AppSettings
/// Let the server send render jobs to this PC (BRIEF §14.7).
public bool RenderNodeOptIn { get; set; }
+ /// Keep the proxy caches of the server sequences this PC opened with proxies up to date (BRIEF §12.7).
+ public bool KeepProxiesOffline { get; set; }
+
+ /// Send and take project settings changed on one side without asking (Server.html).
+ public bool SyncSettingsAutomatically { get; set; } = true;
+
+ /// Pause upload jobs while Windows reports the connection as metered (Server.html).
+ public bool PauseUploadsOnMetered { get; set; }
+
// ---- Jobs ----
/// "Clear done": finished jobs older than this are hidden from the Jobs list (they stay in the history).
public DateTimeOffset? JobsClearedAt { get; set; }
diff --git a/src/Titano.App/Library/SequenceItem.cs b/src/Titano.App/Library/SequenceItem.cs
index f1ed8d64..28771425 100644
--- a/src/Titano.App/Library/SequenceItem.cs
+++ b/src/Titano.App/Library/SequenceItem.cs
@@ -147,7 +147,20 @@ public sealed class SequenceItem : ObservableObject
OnPropertyChanged(nameof(PrimaryStatus));
}
- /// Card status row: analysed, proxies, renders, sync, warnings (Main.html).
+ ///
+ /// 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.
+ ///
+ 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,
+ };
+
+ /// Card status row: analysed, proxies, renders, errors or warnings, sync (Main.html); the sync glyph is last so a narrow card cuts it first.
public static IReadOnlyList BuildStatuses(Sequence s, bool analysing)
{
var list = new List(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;
}
}
diff --git a/src/Titano.App/Sections/LibraryViewModel.cs b/src/Titano.App/Sections/LibraryViewModel.cs
index f1072311..b4a185a1 100644
--- a/src/Titano.App/Sections/LibraryViewModel.cs
+++ b/src/Titano.App/Sections/LibraryViewModel.cs
@@ -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)
{
diff --git a/src/Titano.App/Sections/ServerView.xaml b/src/Titano.App/Sections/ServerView.xaml
index 4ad2e471..a6bdfcd5 100644
--- a/src/Titano.App/Sections/ServerView.xaml
+++ b/src/Titano.App/Sections/ServerView.xaml
@@ -15,9 +15,12 @@
+
+
+
-
+
@@ -112,9 +115,140 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Titano.App/Sections/ServerViewModel.cs b/src/Titano.App/Sections/ServerViewModel.cs
index b50d7a70..b3f01f5b 100644
--- a/src/Titano.App/Sections/ServerViewModel.cs
+++ b/src/Titano.App/Sections/ServerViewModel.cs
@@ -10,9 +10,9 @@ using Titano.Ui.Mvvm;
namespace Titano.App.Sections;
///
-/// 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 ().
///
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);
}
+ /// Sequences of this PC and of the server, where they stand and what can be done.
+ public SyncTableViewModel Sync { get; }
+
public ShellViewModel Shell { get; }
private ServerSession Session => _session ?? Shell.Services.Server;
@@ -134,6 +138,34 @@ public sealed class ServerViewModel : SectionViewModel
}
}
+ /// Keep the proxy caches of server sequences opened with proxies up to date on this PC.
+ public bool KeepProxiesOffline
+ {
+ get => Shell.Services.Settings.KeepProxiesOffline;
+ set => SetSyncOption(value, Shell.Services.Settings.KeepProxiesOffline, v => Shell.Services.Settings.KeepProxiesOffline = v);
+ }
+
+ /// Send and take project settings changed on one side without asking.
+ public bool SyncSettingsAutomatically
+ {
+ get => Shell.Services.Settings.SyncSettingsAutomatically;
+ set => SetSyncOption(value, Shell.Services.Settings.SyncSettingsAutomatically, v => Shell.Services.Settings.SyncSettingsAutomatically = v);
+ }
+
+ /// Pause uploads while the connection is metered.
+ 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();
+ }
+ }
+
/// Re-reads values another screen changed (Settings › Server).
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 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;
diff --git a/src/Titano.App/Server/SyncHost.cs b/src/Titano.App/Server/SyncHost.cs
new file mode 100644
index 00000000..445cb56a
--- /dev/null
+++ b/src/Titano.App/Server/SyncHost.cs
@@ -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;
+
+/// Makes the sync connection of a signed-in session.
+public delegate ISyncRemote SyncRemoteFactory(Uri address, string token, IReadOnlyCollection trustedFingerprints);
+
+///
+/// This PC's sync with the signed-in server (BRIEF §4.4, §14.5): the of the index, the
+/// connection of upload and download jobs (), a that keeps the
+/// table current while a session is open, started and stopped in order as the session changes, and the
+/// for metered connections. Options come from ,
+/// and .
+///
+public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDisposable
+{
+ /// How long a job resumed at start waits for the saved session to be restored.
+ private static readonly TimeSpan RestoreWait = TimeSpan.FromSeconds(30);
+
+ private Task _switch = Task.CompletedTask;
+ private Credentials? _credentials;
+ private (SyncAgent Agent, ISyncRemote Remote, Credentials Credentials)? _running;
+
+ /// Connections over ; screenshots substitute a fake server.
+ public SyncRemoteFactory RemoteFactory { get; set; } = (address, token, trusted) =>
+ new TitanoSyncRemote(new TitanoClient(address, new CertificatePinning(trusted), $"Titano ({Environment.MachineName})") { Token = token }, ownsClient: true);
+
+ /// The engine; null until the index is open.
+ public SyncService? Service { get; private set; }
+
+ /// The background comparison of the signed-in server; null while signed out.
+ public SyncAgent? Agent => _running?.Agent;
+
+ /// The agent's connection, for the table's own calls (conflict resolution); null while signed out.
+ public ISyncRemote? Remote => _running?.Remote;
+
+ /// Key of the signed-in server (); null while signed out.
+ public string? Server => Volatile.Read(ref _credentials) is { } c ? SyncService.ServerKey(c.Address) : null;
+
+ /// The options, and whether the account may change server sequences (without it this PC's edits are not sent).
+ public SyncPolicy Policy => new(services.Settings.SyncSettingsAutomatically, services.Settings.KeepProxiesOffline,
+ services.Server.User is { } user && (user.Permissions & (long)Permissions.Edit) != 0);
+
+ /// Pauses uploads while the connection is metered and the option is on.
+ public UploadHold Uploads { get; } = new(services);
+
+ /// The agent started, stopped or compared, or the table of the signed-in server changed (any thread).
+ public event Action? Changed;
+
+ /// Creates the engine over the open index; the proxy cache lives in the client's cache folder.
+ 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;
+ }
+
+ /// Follows the server session (UI thread): starts the agent for a new sign-in, stops it on sign-out.
+ 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);
+ }
+
+ /// Compares now, once the session switch in progress settled; null while signed out.
+ public async Task RefreshAsync(CancellationToken ct = default)
+ {
+ await _switch;
+ return Agent is { } agent ? await agent.RefreshAsync(ct) : null;
+ }
+
+ /// Compares again soon (an option changed, an edit on this PC).
+ public void RequestRefresh() => Agent?.RequestRefresh();
+
+ /// The archive downloaded originals go to when a sequence has no local copy: the one this PC works with.
+ public async Task 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 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 Fingerprints);
+}
diff --git a/src/Titano.App/Server/SyncRow.cs b/src/Titano.App/Server/SyncRow.cs
new file mode 100644
index 00000000..a5647aa7
--- /dev/null
+++ b/src/Titano.App/Server/SyncRow.cs
@@ -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;
+
+/// A row button: "Upload", "Keep mine", …; kept while the row offers it, so focus, tooltips and clicks survive updates.
+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);
+ }
+
+ /// The label in the current language.
+ public void Relabel() => OnPropertyChanged(nameof(Text));
+}
+
+/// One row of the sync table (Server.html): sequence, this PC, server, state and the actions that apply.
+public sealed class SyncRow : ObservableObject
+{
+ private readonly Func _act;
+ private SyncEntry _entry;
+ private IReadOnlyList _actions = [];
+
+ public SyncRow(SyncEntry entry, SyncRights rights, Func 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;
+
+ /// Settings differ on both sides: the row is drawn on the card colour, as in Server.html.
+ public bool IsConflict => _entry.Status == SyncStatus.Conflict && _entry.Transfer is null;
+
+ public IReadOnlyList Actions
+ {
+ get => _actions;
+ private set => Set(ref _actions, value);
+ }
+
+ /// Takes a fresher comparison of the same sequence; buttons the row still offers are kept.
+ public void Update(SyncEntry entry, SyncRights rights)
+ {
+ _entry = entry;
+ UpdateActions(rights);
+ RaiseTexts();
+ }
+
+ /// Takes the progress of the row's transfer ("46 % received") without touching its buttons.
+ 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));
+ }
+
+ /// Texts in the current language.
+ 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));
+ }
+}
diff --git a/src/Titano.App/Server/SyncTableViewModel.cs b/src/Titano.App/Server/SyncTableViewModel.cs
new file mode 100644
index 00000000..88fb2f8f
--- /dev/null
+++ b/src/Titano.App/Server/SyncTableViewModel.cs
@@ -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;
+
+/// A filter chip of the sync table: "Conflicts · 1".
+public sealed class SyncFilterChip(SyncFilter filter, Action select) : ObservableObject
+{
+ private int _count;
+ private bool _isSelected;
+
+ public SyncFilter Filter { get; } = filter;
+ public string Text => Loc.L("Server.Sync.Filter." + Filter, Formatting.Count(_count));
+ public string ToolTip => Loc.L("Tooltips.Server.Sync.Filter." + Filter);
+ public ICommand SelectCommand { get; } = new RelayCommand(() => select(filter));
+
+ /// Conflicts waiting for a choice: the chip is drawn in the warning colour unless it is the selected one.
+ public bool NeedsAttention => Filter == SyncFilter.Conflicts && _count > 0;
+
+ public bool IsSelected
+ {
+ get => _isSelected;
+ set => Set(ref _isSelected, value);
+ }
+
+ public int Count
+ {
+ get => _count;
+ set
+ {
+ if (!Set(ref _count, value)) return;
+ OnPropertyChanged(nameof(Text));
+ OnPropertyChanged(nameof(NeedsAttention));
+ }
+ }
+
+ /// Texts in the current language.
+ public void Relabel()
+ {
+ OnPropertyChanged(nameof(Text));
+ OnPropertyChanged(nameof(ToolTip));
+ }
+}
+
+///
+/// The sync table of the Server screen (BRIEF §12.7, Server.html): every sequence of this PC and of the signed-in
+/// server with what each side holds, where it stands and what can be done (upload, download originals, open with
+/// proxies, get or send exports, settle a conflict, pause or resume a transfer), filter chips, search, "Upload all
+/// local" and the footer (last comparison, server archive, admin panel). Reloads when the sync engine reports a change;
+/// transfer progress is applied at most a few times a second. Runs on the UI thread.
+///
+public sealed class SyncTableViewModel : ObservableObject, IDisposable
+{
+ private readonly ShellViewModel _shell;
+ private readonly IReadOnlyList _chips;
+
+ /// "Open with proxies" waiting for its proxy download: server id → the job that fills the cache.
+ private readonly Dictionary _openWhenCached = [];
+
+ private readonly ConcurrentDictionary _progress = new();
+ private readonly SemaphoreSlim _reloading = new(1, 1);
+ private readonly AsyncRelayCommand _uploadAll;
+ private IReadOnlyList _entries = [];
+ private SyncFilter _filter = SyncFilter.All;
+ private string _search = string.Empty;
+ private int _progressQueued;
+ private int _reloadQueued;
+ private bool _attached;
+
+ public SyncTableViewModel(ShellViewModel shell)
+ {
+ _shell = shell;
+ _chips = [.. Enum.GetValues().Select(f => new SyncFilterChip(f, Select) { IsSelected = f == SyncFilter.All })];
+ _uploadAll = new AsyncRelayCommand(UploadAllAsync, () => IsActive && Rights.CanUpload && LocalOnly.Any());
+ OpenAdminCommand = new RelayCommand(() =>
+ {
+ if (Host.Server is { } server) ShellActions.OpenUrl(server + "/admin");
+ });
+ }
+
+ public ObservableCollection Rows { get; } = [];
+ public IReadOnlyList Chips => _chips;
+ public ICommand UploadAllCommand => _uploadAll;
+ public ICommand OpenAdminCommand { get; }
+
+ public string SearchText
+ {
+ get => _search;
+ set
+ {
+ if (Set(ref _search, value ?? string.Empty)) ApplyFilter(rebuild: true);
+ }
+ }
+
+ /// Signed in: the table compares this PC with that server.
+ public bool IsActive => Host.Server is not null;
+
+ public bool HasRows => Rows.Count > 0;
+
+ /// "Not connected to a server", "Nothing to compare yet" or "No sequence matches"; null when rows show.
+ public string? EmptyText => HasRows ? null
+ : !IsActive ? Loc.L("Server.Empty")
+ : _entries.Count == 0 ? Loc.L("Server.Sync.Empty")
+ : Loc.L("Server.Sync.NoMatch");
+
+ /// What "Upload all local" sends, or why it is disabled.
+ public string UploadAllToolTip =>
+ !IsActive ? Loc.L("Tooltips.Server.Sync.UploadAll.NotConnected")
+ : !Rights.CanUpload ? Loc.L("Tooltips.Server.Sync.UploadAll.NoRight")
+ : !LocalOnly.Any() ? Loc.L("Tooltips.Server.Sync.UploadAll.Nothing")
+ : Loc.L("Tooltips.Server.Sync.UploadAll", Formatting.Count(LocalOnly.Count()), Formatting.Bytes(LocalOnly.Sum(e => e.Local!.TotalBytes)));
+
+ /// "Last sync 10:15 · manifest diff 0.4 s"; null before the first comparison.
+ public string? LastSyncText => Host.Agent?.Snapshot is { } s
+ ? Loc.L("Server.Sync.Last", Formatting.TimeOfDay(s.RefreshedAt), s.Duration.TotalSeconds.ToString("0.0", Loc.Culture))
+ : null;
+
+ /// "Server archive 9.4 TB · 412 sequences".
+ public string? ArchiveText => Host.Agent?.Snapshot is { } s ? Loc.Plural("Server.Sync.Archive", s.ServerSequences, Formatting.Bytes(s.ServerBytes)) : null;
+
+ /// The last comparison failed (it is retried with growing pauses); null when it worked.
+ public string? ErrorText => Host.Agent?.LastError is not null ? Loc.L("Server.Sync.Retrying") : null;
+
+ public string? ErrorToolTip => Host.Agent?.LastError is { } error ? Loc.L("Tooltips.Server.Sync.Retrying", error.Message) : null;
+
+ /// The server's web admin (it admits administrators only).
+ public bool CanOpenAdmin => IsActive;
+
+ private SyncHost Host => _shell.Services.Sync;
+
+ private SyncRights Rights => _shell.Services.Server.User is { } user ? SyncRights.Of(user.Permissions) : default;
+
+ private IEnumerable LocalOnly => _entries.Where(e => e.Status == SyncStatus.LocalOnly);
+
+ /// Starts following the sync engine, the transfer jobs and the language.
+ public void Attach()
+ {
+ if (_attached) return;
+ _attached = true;
+ Host.Changed += OnChanged;
+ Loc.CultureChanged += OnCultureChanged;
+ if (_shell.Services.Jobs is { } jobs)
+ {
+ jobs.JobChanged += OnJobChanged;
+ jobs.Progress += OnProgress;
+ }
+ _ = ReloadAsync();
+ }
+
+ /// Reads the table again; requests made while a pass runs share the next one, which they wait for.
+ public async Task ReloadAsync()
+ {
+ Interlocked.Exchange(ref _reloadQueued, 1);
+ await _reloading.WaitAsync();
+ try
+ {
+ while (Interlocked.Exchange(ref _reloadQueued, 0) == 1)
+ {
+ _entries = Host is { Service: { } service, Server: { } server } ? await service.ListAsync(server, CancellationToken.None) : [];
+ Refresh();
+ }
+ }
+ catch (Exception ex) when (ex is Data.DatabaseException or InvalidOperationException)
+ {
+ Log.Warning("sync", "The sync table could not be read", ex);
+ }
+ finally
+ {
+ _reloading.Release();
+ }
+ }
+
+ public void Dispose()
+ {
+ if (!_attached) return;
+ _attached = false;
+ Host.Changed -= OnChanged;
+ Loc.CultureChanged -= OnCultureChanged;
+ if (_shell.Services.Jobs is { } jobs)
+ {
+ jobs.JobChanged -= OnJobChanged;
+ jobs.Progress -= OnProgress;
+ }
+ }
+
+ private void Select(SyncFilter filter)
+ {
+ _filter = filter;
+ foreach (var chip in _chips) chip.IsSelected = chip.Filter == filter;
+ ApplyFilter(rebuild: true);
+ }
+
+ /// Counts, rows, footer and the Library's sync glyphs after a reload.
+ private void Refresh()
+ {
+ foreach (var chip in _chips) chip.Count = _entries.Count(e => SyncText.Matches(e, chip.Filter, string.Empty));
+ ApplyFilter(rebuild: false);
+ UpdateLibrary();
+ OnPropertyChanged(nameof(IsActive));
+ OnPropertyChanged(nameof(UploadAllToolTip));
+ OnPropertyChanged(nameof(LastSyncText));
+ OnPropertyChanged(nameof(ArchiveText));
+ OnPropertyChanged(nameof(ErrorText));
+ OnPropertyChanged(nameof(ErrorToolTip));
+ OnPropertyChanged(nameof(CanOpenAdmin));
+ _uploadAll.RaiseCanExecuteChanged();
+ }
+
+ ///
+ /// Shows the entries the filter and search keep. A reload updates the rows in place (scroll position, focus and
+ /// recycled containers survive); a new filter or search lays the rows out again.
+ ///
+ private void ApplyFilter(bool rebuild)
+ {
+ var rights = Rights;
+ var wanted = _entries.Where(e => SyncText.Matches(e, _filter, _search.Trim())).ToList();
+ var byId = Rows.ToDictionary(r => r.Id);
+ if (rebuild)
+ {
+ Rows.Clear();
+ foreach (var entry in wanted) Rows.Add(Row(entry, rights, byId));
+ }
+ else
+ {
+ for (var i = 0; i < wanted.Count; i++)
+ {
+ var entry = wanted[i];
+ if (i < Rows.Count && Rows[i].Id == entry.Id)
+ {
+ Rows[i].Update(entry, rights);
+ continue;
+ }
+ var row = Row(entry, rights, byId);
+ var at = byId.ContainsKey(entry.Id) ? Rows.IndexOf(row) : -1;
+ if (at >= 0) Rows.Move(at, i);
+ else Rows.Insert(i, row);
+ }
+ while (Rows.Count > wanted.Count) Rows.RemoveAt(Rows.Count - 1);
+ }
+ OnPropertyChanged(nameof(HasRows));
+ OnPropertyChanged(nameof(EmptyText));
+ }
+
+ /// The existing row of an entry, updated, or a new one.
+ private SyncRow Row(SyncEntry entry, SyncRights rights, Dictionary existing)
+ {
+ if (!existing.TryGetValue(entry.Id, out var row)) return new SyncRow(entry, rights, ActAsync);
+ row.Update(entry, rights);
+ return row;
+ }
+
+ /// The Library shows each local copy's sync state: rows it has loaded take the fresh state.
+ private void UpdateLibrary()
+ {
+ var locals = _entries.Where(e => e.Local is not null).ToDictionary(e => e.Local!.Id, e => e.Local!);
+ foreach (var item in _shell.Library.Items)
+ {
+ if (locals.TryGetValue(item.Id, out var fresh) && fresh.SyncState != item.Sequence.SyncState) item.Update(fresh);
+ }
+ }
+
+ private async Task ActAsync(SyncRow row, SyncAction action)
+ {
+ if (Host is not { Service: { } service, Server: { } server } || _shell.Services.Engine is not { } engine) return;
+ var entry = row.Entry;
+ switch (action)
+ {
+ case SyncAction.Upload:
+ await service.EnqueueUploadAsync(engine, server, entry.Local!);
+ break;
+ case SyncAction.SendExports:
+ await service.EnqueueSendExportsAsync(engine, server, entry.Local!);
+ break;
+ case SyncAction.DownloadOriginals:
+ if ((entry.Local?.ArchiveId ?? (await Host.CurrentArchiveAsync())?.Id) is not { } archive)
+ {
+ _shell.Notify(Loc.L("Errors.Sync.NoArchive"));
+ return;
+ }
+ await service.EnqueueDownloadAsync(engine, server, entry.Id, entry.Title, SyncDownloadMode.Originals, archive);
+ break;
+ case SyncAction.GetExports:
+ await service.EnqueueDownloadAsync(engine, server, entry.Id, entry.Title, SyncDownloadMode.Exports, null);
+ break;
+ case SyncAction.OpenWithProxies when entry.Status == SyncStatus.ProxiesOnly && service.OpenRemote(server, entry.Id) is not null:
+ _shell.OpenSequence(entry.Id);
+ return;
+ case SyncAction.OpenWithProxies:
+ var job = await service.EnqueueDownloadAsync(engine, server, entry.Id, entry.Title, SyncDownloadMode.Proxies, null);
+ _openWhenCached[entry.Id] = job.Id;
+ // A download that finished before it was recorded here opens at once.
+ if (await _shell.Services.Database!.Jobs.GetAsync(job.Id) is { State: JobState.Done or JobState.Failed or JobState.Cancelled } ended)
+ OpenWhenCached(ended);
+ break;
+ case SyncAction.Pause:
+ await _shell.Services.Jobs!.PauseAsync(entry.Transfer!.Id);
+ break;
+ case SyncAction.Resume:
+ await _shell.Services.Jobs!.ResumeAsync(entry.Transfer!.Id);
+ break;
+ case SyncAction.SyncSettings when Host.Remote is { } remote:
+ await service.SyncSettingsAsync(remote, entry.Id, Host.Policy, CancellationToken.None);
+ break;
+ case SyncAction.KeepMine or SyncAction.TakeServer or SyncAction.SaveBoth when Host.Remote is { } remote:
+ await ResolveAsync(service, remote, entry, action);
+ break;
+ }
+ await ReloadAsync();
+ }
+
+ /// Settles a conflict once the user confirmed the plan: the settings that differ and what each choice overwrites.
+ private async Task ResolveAsync(SyncService service, ISyncRemote remote, SyncEntry entry, SyncAction action)
+ {
+ if (!_shell.Services.Dialogs.Confirm(ConflictRequest(entry, action))) return;
+ var resolution = action switch
+ {
+ SyncAction.KeepMine => SyncResolution.KeepMine,
+ SyncAction.TakeServer => SyncResolution.TakeServer,
+ _ => SyncResolution.SaveBoth,
+ };
+ try
+ {
+ if (await service.ResolveAsync(remote, entry.Id, resolution, CancellationToken.None) is { } saved)
+ {
+ _shell.Notify(Loc.L("Server.Sync.SavedBoth"), Path.GetFileName(saved), Loc.L("Server.Sync.ShowCopy"), Loc.L("Tooltips.Server.Sync.ShowCopy"),
+ () => ShellActions.Reveal(saved));
+ }
+ }
+ catch (SyncConflictChangedException ex)
+ {
+ // One side changed after the choice was shown: the row now shows the fresh content.
+ _shell.Notify(ex.Message);
+ }
+ }
+
+ /// The dry run of a resolution: what is replaced, by which side's values, and where "Save both" keeps this PC's.
+ internal static ConfirmRequest ConflictRequest(SyncEntry entry, SyncAction action) => new()
+ {
+ Heading = Loc.L("Server.Conflict." + action + ".Title"),
+ Message = Loc.L("Server.Conflict." + action + ".Message", entry.Title),
+ Detail = string.Join(Environment.NewLine, SyncText.Conflict(entry, 10)),
+ DetailToolTip = Loc.L("Tooltips.Server.Conflict.Detail"),
+ SafeText = Loc.L("Server.Conflict.Cancel"),
+ SafeToolTip = Loc.L("Tooltips.Server.Conflict.Cancel"),
+ ActionText = Loc.L("Server.Sync.Action." + action),
+ ActionToolTip = Loc.L("Tooltips.Server.Sync." + action),
+ IsDestructive = action != SyncAction.SaveBoth,
+ };
+
+ private async Task UploadAllAsync()
+ {
+ if (Host is not { Service: { } service, Server: { } server } || _shell.Services.Engine is not { } engine) return;
+ var queued = 0;
+ foreach (var entry in LocalOnly.ToList())
+ {
+ await service.EnqueueUploadAsync(engine, server, entry.Local!);
+ queued++;
+ }
+ _shell.Notify(Loc.Plural("Server.Sync.Queued", queued));
+ await ReloadAsync();
+ }
+
+ private void OnChanged() => Dispatch(() => _ = ReloadAsync());
+
+ private void OnCultureChanged(object? sender, EventArgs e) => Dispatch(() =>
+ {
+ foreach (var chip in _chips) chip.Relabel();
+ foreach (var row in Rows) row.Relabel();
+ OnAllPropertiesChanged();
+ });
+
+ private void OnJobChanged(Job job)
+ {
+ if (job.Kind is not (JobKind.UploadCommit or JobKind.Download)) return;
+ _progress.TryRemove(job.Id, out _);
+ Dispatch(() =>
+ {
+ OpenWhenCached(job);
+ _ = ReloadAsync();
+ });
+ }
+
+ ///
+ /// "Open with proxies" opens the editor when the download it queued is done, if the Server screen is still the one
+ /// in front; a failed or cancelled download drops the request.
+ ///
+ private void OpenWhenCached(Job job)
+ {
+ if (job.State is not (JobState.Done or JobState.Failed or JobState.Cancelled)) return;
+ var remoteId = _openWhenCached.FirstOrDefault(p => p.Value == job.Id).Key;
+ if (!_openWhenCached.Remove(remoteId)) return;
+ if (job.State == JobState.Done && ReferenceEquals(_shell.Current, _shell.Server)) _shell.OpenSequence(remoteId);
+ }
+
+ /// Transfer progress ("46 % received") without reading the table again, at most a few times a second.
+ private void OnProgress(JobProgressInfo info)
+ {
+ if (info.Kind is not (JobKind.UploadCommit or JobKind.Download)) return;
+ _progress[info.JobId] = info;
+ if (Interlocked.Exchange(ref _progressQueued, 1) == 1) return;
+ System.Windows.Application.Current?.Dispatcher.BeginInvoke(DispatcherPriority.Background, async () =>
+ {
+ await Task.Delay(250);
+ Interlocked.Exchange(ref _progressQueued, 0);
+ foreach (var row in Rows)
+ {
+ if (row.Entry.Transfer is { } job && _progress.TryGetValue(job.Id, out var p)) row.UpdateProgress(p.Done, p.Total);
+ }
+ });
+ }
+
+ private static void Dispatch(Action action)
+ {
+ if (System.Windows.Application.Current?.Dispatcher is not { } dispatcher || dispatcher.CheckAccess()) action();
+ else dispatcher.BeginInvoke(action);
+ }
+}
diff --git a/src/Titano.App/Server/SyncText.cs b/src/Titano.App/Server/SyncText.cs
new file mode 100644
index 00000000..f55ab693
--- /dev/null
+++ b/src/Titano.App/Server/SyncText.cs
@@ -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;
+
+/// Filter chips of the sync table (Server.html).
+public enum SyncFilter
+{
+ All,
+ LocalOnly,
+ Remote,
+ Conflicts,
+}
+
+/// What a row of the sync table offers.
+public enum SyncAction
+{
+ Upload,
+ OpenWithProxies,
+ DownloadOriginals,
+ SyncSettings,
+ KeepMine,
+ TakeServer,
+ SaveBoth,
+ GetExports,
+ SendExports,
+ Pause,
+ Resume,
+}
+
+/// What the signed-in account may do (server permission bits).
+/// Send originals, settings and renders (upload and edit rights).
+/// Download originals (editors and render nodes).
+/// Change the server's copy of a sequence's settings, title, tags, rating and notes.
+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);
+}
+
+/// The words, glyphs and actions of the sync table (BRIEF §12.7): plain functions of a .
+public static class SyncText
+{
+ /// Resource keys of the settings and sequence fields a conflict can show, by JSON path (sections, then members).
+ private static readonly Dictionary 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",
+ };
+
+ /// "originals · proxies", "proxies" (cached server proxies) or "—".
+ 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");
+ }
+
+ /// "originals · proxies · 3 exports", "46 % received" while uploading, or "—".
+ 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(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]);
+ }
+
+ /// The State column: glyph kind, word and tooltip (never colour alone).
+ 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)),
+ };
+ }
+
+ /// One line for the State tooltip: "Deflicker window 41 here, 33 on the server · +2".
+ 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)),
+ };
+ }
+
+ ///
+ /// What differs, one line per setting or sequence field in project order ("Deflicker window 41 here, 33 on the
+ /// server", "Tags differ"), at most .
+ ///
+ public static IReadOnlyList Conflict(SyncEntry entry, int max)
+ {
+ if (entry is not { Local: { } local, Link.ConflictRemote: { } theirs }) return [];
+ var lines = new List();
+ var shown = new HashSet(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;
+ }
+
+ /// The row's buttons, in the order the mockup shows them.
+ public static IReadOnlyList Actions(SyncEntry entry, SyncRights rights)
+ {
+ if (entry.Transfer is { } job) return job.State == JobState.Paused ? [SyncAction.Resume] : [SyncAction.Pause];
+ var actions = new List(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;
+ }
+
+ /// The bytes an action moves (for the tooltips).
+ 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,
+ };
+
+ /// The tooltip of a row button: what it does and, for transfers, what it moves.
+ 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));
+
+ ///
+ /// 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.
+ ///
+ 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]);
+ }
+
+ /// A title, tags, rating or notes value as shown ("—" when empty).
+ private static string Text(string? value) => string.IsNullOrWhiteSpace(value) ? Loc.L("Server.Sync.None") : Shorten(value);
+
+ /// A side's value as shown ("41", "on", "auto"); null when it is not a single value worth printing.
+ 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(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(out var flag) => Loc.L(flag ? "Server.Setting.On" : "Server.Setting.Off"),
+ JsonValue value when value.TryGetValue(out var number) => number.ToString("0.###", Loc.Culture),
+ JsonValue value when value.TryGetValue(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);
+}
diff --git a/src/Titano.App/Server/UploadHold.cs b/src/Titano.App/Server/UploadHold.cs
new file mode 100644
index 00000000..df5735b9
--- /dev/null
+++ b/src/Titano.App/Server/UploadHold.cs
@@ -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;
+
+///
+/// "Pause uploads on metered networks" (Server.html): while 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.
+///
+public sealed class UploadHold : IDisposable
+{
+ private static readonly TimeSpan Interval = TimeSpan.FromMinutes(1);
+
+ private readonly AppServices _services;
+ private readonly HashSet _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;
+ }
+
+ /// Follows the jobs of (once the index is open).
+ public void Attach(JobEngine engine)
+ {
+ if (ReferenceEquals(_engine, engine)) return;
+ if (_engine is not null) _engine.JobChanged -= OnJobChanged;
+ _engine = engine;
+ engine.JobChanged += OnJobChanged;
+ Request();
+ }
+
+ /// Applies the option and the connection's cost now (the option changed).
+ 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();
+ }
+ }
+}
+
+/// The connection cost Windows reports (Settings › Network › Metered connection) through INetworkCostManager.
+internal static class MeteredNetwork
+{
+ private const uint Fixed = 0x2;
+ private const uint Variable = 0x4;
+ private const uint OverDataLimit = 0x10000;
+ private const uint Roaming = 0x40000;
+
+ /// True when the machine's connection is metered (fixed or variable cost, over its data limit, or roaming); false when unknown.
+ 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);
+ }
+}
diff --git a/src/Titano.App/Shell/ScreenCapture.cs b/src/Titano.App/Shell/ScreenCapture.cs
index 6a406d5a..c4fa8290 100644
--- a/src/Titano.App/Shell/ScreenCapture.cs
+++ b/src/Titano.App/Shell/ScreenCapture.cs
@@ -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;
///
/// Titano.exe --capture <dir>: renders every client screen at 1440×900 in the dark and light themes to
/// <screen>-<theme>.png from (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.
///
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);
+
+ /// A dialog shown off screen, saved, then closed.
+ private static async Task 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 SaveAsync(Window window, string directory, string screen, AppTheme theme, ShellViewModel? waitForThumbnails = null)
{
await Settle(window);
diff --git a/src/Titano.Core/Model/Enums.cs b/src/Titano.Core/Model/Enums.cs
index 09627a48..2bb39f50 100644
--- a/src/Titano.Core/Model/Enums.cs
+++ b/src/Titano.Core/Model/Enums.cs
@@ -72,6 +72,9 @@ public enum JobKind
Orphans,
Adopt,
Move,
+
+ /// Client: originals or proxies of a server sequence fetched into this PC (BRIEF §14.5).
+ Download,
}
public enum JobState
diff --git a/src/Titano.Data/Migrations/postgres/0004_sync.sql b/src/Titano.Data/Migrations/postgres/0004_sync.sql
new file mode 100644
index 00000000..88aff90a
--- /dev/null
+++ b/src/Titano.Data/Migrations/postgres/0004_sync.sql
@@ -0,0 +1,38 @@
+-- Client sync state (BRIEF §4.4, §14.5): one row per sequence of a server this client has listed, linked to the local
+-- copy when there is one. Versions are the counters both sides agreed on at the last sync; conflict_remote is the
+-- server's side (title, tags, rating, notes, settings) of an unresolved conflict as JSON. Mirrors sqlite/0004_sync.sql.
+
+CREATE TABLE sync_links (
+ server text COLLATE "C" NOT NULL,
+ remote_id uuid NOT NULL,
+ local_id uuid REFERENCES sequences (id) ON DELETE SET NULL,
+ title text NOT NULL,
+ frame_count integer NOT NULL DEFAULT 0,
+ total_bytes bigint NOT NULL DEFAULT 0,
+ render_count integer NOT NULL DEFAULT 0,
+ remote_status integer NOT NULL DEFAULT 0,
+ remote_settings_version integer NOT NULL DEFAULT 0,
+ remote_frames_version integer NOT NULL DEFAULT 0,
+ remote_updated_at timestamptz NOT NULL,
+ base_local_settings integer,
+ base_remote_settings integer,
+ diff_local_frames integer,
+ diff_remote_frames integer,
+ diff_local_renders integer,
+ diff_remote_renders integer,
+ missing_remote integer NOT NULL DEFAULT 0,
+ missing_local integer NOT NULL DEFAULT 0,
+ exports_to_get integer NOT NULL DEFAULT 0,
+ exports_to_get_bytes bigint NOT NULL DEFAULT 0,
+ exports_to_send integer NOT NULL DEFAULT 0,
+ exports_to_send_bytes bigint NOT NULL DEFAULT 0,
+ conflict_local_settings integer,
+ conflict_remote_settings integer,
+ conflict_remote text,
+ proxies_cached integer NOT NULL DEFAULT 0,
+ proxies_frames_version integer,
+ error text,
+ synced_at timestamptz,
+ PRIMARY KEY (server, remote_id)
+);
+CREATE UNIQUE INDEX ix_sync_links_local ON sync_links (server, local_id);
diff --git a/src/Titano.Data/Migrations/sqlite/0004_sync.sql b/src/Titano.Data/Migrations/sqlite/0004_sync.sql
new file mode 100644
index 00000000..ddc67059
--- /dev/null
+++ b/src/Titano.Data/Migrations/sqlite/0004_sync.sql
@@ -0,0 +1,38 @@
+-- Client sync state (BRIEF §4.4, §14.5): one row per sequence of a server this client has listed, linked to the local
+-- copy when there is one. Versions are the counters both sides agreed on at the last sync; conflict_remote is the
+-- server's side (title, tags, rating, notes, settings) of an unresolved conflict as JSON. Mirrors postgres/0004_sync.sql.
+
+CREATE TABLE sync_links (
+ server TEXT NOT NULL,
+ remote_id TEXT NOT NULL,
+ local_id TEXT REFERENCES sequences (id) ON DELETE SET NULL,
+ title TEXT NOT NULL,
+ frame_count INTEGER NOT NULL DEFAULT 0,
+ total_bytes INTEGER NOT NULL DEFAULT 0,
+ render_count INTEGER NOT NULL DEFAULT 0,
+ remote_status INTEGER NOT NULL DEFAULT 0,
+ remote_settings_version INTEGER NOT NULL DEFAULT 0,
+ remote_frames_version INTEGER NOT NULL DEFAULT 0,
+ remote_updated_at TEXT NOT NULL,
+ base_local_settings INTEGER,
+ base_remote_settings INTEGER,
+ diff_local_frames INTEGER,
+ diff_remote_frames INTEGER,
+ diff_local_renders INTEGER,
+ diff_remote_renders INTEGER,
+ missing_remote INTEGER NOT NULL DEFAULT 0,
+ missing_local INTEGER NOT NULL DEFAULT 0,
+ exports_to_get INTEGER NOT NULL DEFAULT 0,
+ exports_to_get_bytes INTEGER NOT NULL DEFAULT 0,
+ exports_to_send INTEGER NOT NULL DEFAULT 0,
+ exports_to_send_bytes INTEGER NOT NULL DEFAULT 0,
+ conflict_local_settings INTEGER,
+ conflict_remote_settings INTEGER,
+ conflict_remote TEXT,
+ proxies_cached INTEGER NOT NULL DEFAULT 0,
+ proxies_frames_version INTEGER,
+ error TEXT,
+ synced_at TEXT,
+ PRIMARY KEY (server, remote_id)
+);
+CREATE UNIQUE INDEX ix_sync_links_local ON sync_links (server, local_id);
diff --git a/src/Titano.Data/Processing/RenderNodeClient.cs b/src/Titano.Data/Processing/RenderNodeClient.cs
index aa53c5df..c8938ad7 100644
--- a/src/Titano.Data/Processing/RenderNodeClient.cs
+++ b/src/Titano.Data/Processing/RenderNodeClient.cs
@@ -430,7 +430,7 @@ public sealed class RenderNodeClient : IAsyncDisposable
}
}
- private static Sequence ToSequence(SequenceDto s) => new()
+ internal static Sequence ToSequence(SequenceDto s) => new()
{
Id = s.Id,
ArchiveId = Guid.Empty,
@@ -444,7 +444,7 @@ public sealed class RenderNodeClient : IAsyncDisposable
FrameCount = s.FrameCount,
};
- private static Frame ToFrame(FrameDto f) => new()
+ internal static Frame ToFrame(FrameDto f) => new()
{
Id = f.Id,
SequenceId = f.SequenceId,
diff --git a/src/Titano.Data/Sync/ProxyCache.cs b/src/Titano.Data/Sync/ProxyCache.cs
new file mode 100644
index 00000000..09c3de2d
--- /dev/null
+++ b/src/Titano.Data/Sync/ProxyCache.cs
@@ -0,0 +1,157 @@
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using Titano.Core.Diagnostics;
+using Titano.Core.Imaging;
+using Titano.Core.IO;
+using Titano.Core.Model;
+using Titano.Core.Render;
+using Titano.Data.Processing;
+using Titano.Protocol;
+
+namespace Titano.Data.Sync;
+
+///
+/// A server sequence opened with proxies (BRIEF §14.5 "edit with proxies, render where the originals are"): the
+/// sequence and frame rows as the server lists them, and for each frame its cached proxy (a thumbnail when the server
+/// had no proxy). Frames without a cached file are flagged , so analysis and renders
+/// skip them. Not part of the local index.
+///
+public sealed class RemoteSequence
+{
+ internal RemoteSequence(string server, Sequence sequence, IReadOnlyList frames, IReadOnlyList files)
+ {
+ Server = server;
+ Sequence = sequence;
+ Frames = frames;
+ Files = files;
+ }
+
+ /// The server it belongs to ().
+ public string Server { get; }
+
+ /// The server's sequence: its id, , its settings JSON and versions; no archive.
+ public Sequence Sequence { get; }
+
+ public IReadOnlyList Frames { get; }
+
+ /// Absolute path of each frame's cached proxy, in frame order; null when it is not cached.
+ public IReadOnlyList Files { get; }
+
+ public int CachedCount => Files.Count(f => f is not null);
+
+ ///
+ /// The editor's frame source over the cached proxies, decoded by through the same
+ /// read-ahead window as archive renders. The result also implements
+ /// and ; dispose it when done. Frames are proxy-sized while the source reports the
+ /// originals' size, which allows.
+ ///
+ public IRenderFrameSource OpenFrames(ImageDecoder decoder, FrameWindowOptions? window = null)
+ {
+ var frames = new SequenceFrames(Sequence, Frames, Files);
+ return new SequenceFrameSource(frames, frames.LightFrames(), decoder, window);
+ }
+}
+
+/// What the proxy cache keeps next to the files of one server sequence.
+internal sealed record ProxyCacheIndex(SequenceDto Sequence, string? SettingsJson, int FramesVersion, IReadOnlyList Frames, IReadOnlyList Files);
+
+[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
+[JsonSerializable(typeof(ProxyCacheIndex))]
+internal sealed partial class ProxyCacheJson : JsonSerializerContext;
+
+///
+/// Proxies of server sequences on this PC: <root>/<server hash>/<sequence id>/ with one JPEG per
+/// frame (named by frame id, so renumbering never mixes them up) and remote.json. Everything here can be
+/// downloaded again, so the folder lives in the client's cache.
+///
+internal sealed class ProxyCache(string root)
+{
+ private const string IndexFile = "remote.json";
+
+ public string Folder(string server, Guid remoteId) =>
+ Path.Combine(root, Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(server)))[..16], remoteId.ToString("N"));
+
+ public static string FileName(Guid frameId) => frameId.ToString("N") + ".jpg";
+
+ public bool Exists(string server, Guid remoteId) => File.Exists(Path.Combine(Folder(server, remoteId), IndexFile));
+
+ public void Save(string server, Guid remoteId, ProxyCacheIndex index) =>
+ AtomicFile.WriteAllText(Path.Combine(Folder(server, remoteId), IndexFile), JsonSerializer.Serialize(index, ProxyCacheJson.Default.ProxyCacheIndex));
+
+ /// The cached sequence, or null when it was never cached or the cache was cleared.
+ public RemoteSequence? Load(string server, Guid remoteId)
+ {
+ var folder = Folder(server, remoteId);
+ var path = Path.Combine(folder, IndexFile);
+ if (!File.Exists(path)) return null;
+ ProxyCacheIndex? index;
+ try
+ {
+ index = JsonSerializer.Deserialize(File.ReadAllText(path), ProxyCacheJson.Default.ProxyCacheIndex);
+ }
+ catch (Exception ex) when (ex is JsonException or IOException)
+ {
+ Log.Warning("sync", $"Proxy cache of {remoteId} is unreadable", ex);
+ return null;
+ }
+ if (index is null || index.Files.Count != index.Frames.Count) return null;
+ var dto = index.Sequence;
+ var sequence = RenderNodeClient.ToSequence(dto) with
+ {
+ Tags = dto.Tags,
+ Rating = dto.Rating,
+ Notes = dto.Notes,
+ MedianInterval = dto.MedianInterval,
+ TotalBytes = dto.TotalBytes,
+ Status = (SequenceStatus)dto.Status,
+ HeroFrameId = dto.HeroFrameId,
+ SettingsJson = index.SettingsJson,
+ SettingsVersion = dto.SettingsVersion,
+ FramesVersion = index.FramesVersion,
+ Origin = SequenceOrigin.Server,
+ SyncState = SyncState.RemoteOnly,
+ OwnerUserId = dto.OwnerUserId,
+ UpdatedAt = dto.UpdatedAt,
+ };
+ var files = index.Files.Select(f => f is not null && File.Exists(Path.Combine(folder, f)) ? Path.Combine(folder, f) : null).ToList();
+ var frames = index.Frames.Select((f, i) =>
+ {
+ var frame = RenderNodeClient.ToFrame(f);
+ return files[i] is null ? frame with { Flags = frame.Flags | FrameFlags.Missing } : frame;
+ }).ToList();
+ return new RemoteSequence(server, sequence, frames, files);
+ }
+
+ /// Removes the files of a sequence the server no longer has.
+ public void Delete(string server, Guid remoteId)
+ {
+ var folder = Folder(server, remoteId);
+ try
+ {
+ if (Directory.Exists(folder)) Directory.Delete(folder, recursive: true);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Log.Warning("sync", $"Proxy cache {folder} could not be removed", ex);
+ }
+ }
+
+ /// Deletes proxies of frames does not name (frames removed on the server).
+ public static void Prune(string folder, IReadOnlySet keep)
+ {
+ foreach (var file in Directory.EnumerateFiles(folder, "*.jpg"))
+ {
+ if (keep.Contains(Path.GetFileName(file))) continue;
+ try
+ {
+ File.Delete(file);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Log.Warning("sync", $"Stale proxy {file} could not be removed", ex);
+ }
+ }
+ }
+}
diff --git a/src/Titano.Data/Sync/SyncAgent.cs b/src/Titano.Data/Sync/SyncAgent.cs
new file mode 100644
index 00000000..1d47748d
--- /dev/null
+++ b/src/Titano.Data/Sync/SyncAgent.cs
@@ -0,0 +1,271 @@
+using System.Collections.Concurrent;
+using System.Threading.Channels;
+using Titano.Core.Diagnostics;
+using Titano.Core.Model;
+using Titano.Data.Jobs;
+using Titano.Protocol;
+
+namespace Titano.Data.Sync;
+
+/// Timing of a .
+public sealed record SyncAgentOptions
+{
+ /// Full comparison while nothing asks for one sooner (catches edits on this PC and missed events).
+ public TimeSpan RefreshInterval { get; init; } = TimeSpan.FromMinutes(2);
+
+ /// Server events are collected this long, then their sequences are compared in one pass.
+ public TimeSpan EventDelay { get; init; } = TimeSpan.FromSeconds(1);
+
+ /// First wait after a failed refresh or a lost event socket; doubles up to .
+ public TimeSpan MinBackoff { get; init; } = TimeSpan.FromSeconds(5);
+
+ public TimeSpan MaxBackoff { get; init; } = TimeSpan.FromMinutes(5);
+}
+
+///
+/// Keeps the sync table of one signed-in server current in the background: a full comparison at start, on request
+/// and every ; the sequences named by the server's sequenceChanged
+/// events (WebSocket) compared again within a second, except those an upload or download is working on (it compares
+/// them when it ends); failures retried with exponential backoff; and, with
+/// , background downloads that bring stale proxy caches of the sequences
+/// this PC opened with proxies up to date (a failed one waits with the same backoff). Dispose to stop.
+///
+public sealed class SyncAgent : IAsyncDisposable
+{
+ private const string LogCategory = "sync";
+
+ private readonly SyncService _sync;
+ private readonly ISyncRemote _remote;
+ private readonly Func _policy;
+ private readonly JobEngine? _engine;
+ private readonly SyncAgentOptions _options;
+ private readonly CancellationTokenSource _stopping = new();
+ private readonly Channel _refreshWake = Channel.CreateBounded(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite });
+ private readonly Channel _eventWake = Channel.CreateBounded(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite });
+ private readonly ConcurrentDictionary _changed = new();
+
+ /// Proxy downloads this agent queued, by server id, and the failures of each sequence's last ones.
+ private readonly Dictionary _proxyJobs = [];
+
+ private readonly Dictionary _proxyFailures = [];
+ private readonly SemaphoreSlim _refreshing = new(1, 1);
+ private Task _running = Task.CompletedTask;
+ private SyncSnapshot? _snapshot;
+ private Exception? _lastError;
+
+ /// Read before every comparison, so option changes apply at once.
+ /// Queue for proxy downloads; null keeps no proxies offline.
+ public SyncAgent(SyncService sync, ISyncRemote remote, Func policy, JobEngine? engine, SyncAgentOptions? options = null)
+ {
+ _sync = sync;
+ _remote = remote;
+ _policy = policy;
+ _engine = engine;
+ _options = options ?? new SyncAgentOptions();
+ }
+
+ public string Server => _remote.Server;
+
+ /// The last full comparison; null until the first one finished.
+ public SyncSnapshot? Snapshot => Volatile.Read(ref _snapshot);
+
+ /// Why the last full comparison failed; null after a successful one.
+ public Exception? LastError => Volatile.Read(ref _lastError);
+
+ /// or changed (any thread).
+ public event Action? Changed;
+
+ /// Starts the comparison and event loops.
+ public void Start()
+ {
+ var token = _stopping.Token;
+ _running = Task.WhenAll(
+ Task.Run(() => RefreshLoopAsync(token), CancellationToken.None),
+ Task.Run(() => EventLoopAsync(token), CancellationToken.None),
+ Task.Run(() => ChangedLoopAsync(token), CancellationToken.None));
+ }
+
+ /// Asks for a full comparison soon (after an edit on this PC, an option change, a reconnect).
+ public void RequestRefresh() => _refreshWake.Writer.TryWrite(true);
+
+ /// Compares everything now; concurrent calls run one after the other.
+ public async Task RefreshAsync(CancellationToken cancellationToken = default)
+ {
+ using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _stopping.Token);
+ await _refreshing.WaitAsync(linked.Token).ConfigureAwait(false);
+ try
+ {
+ var policy = _policy();
+ var snapshot = await _sync.RefreshAsync(_remote, policy, linked.Token).ConfigureAwait(false);
+ Volatile.Write(ref _snapshot, snapshot);
+ Volatile.Write(ref _lastError, null);
+ if (policy.KeepProxiesOffline && _engine is not null) await QueueProxiesAsync(snapshot, linked.Token).ConfigureAwait(false);
+ Changed?.Invoke();
+ return snapshot;
+ }
+ finally
+ {
+ _refreshing.Release();
+ }
+ }
+
+ public async ValueTask DisposeAsync()
+ {
+ await _stopping.CancelAsync().ConfigureAwait(false);
+ try
+ {
+ await _running.ConfigureAwait(false);
+ }
+ catch (OperationCanceledException)
+ {
+ }
+ _stopping.Dispose();
+ }
+
+ private TimeSpan Backoff(int failures) =>
+ TimeSpan.FromTicks(Math.Min(_options.MaxBackoff.Ticks, _options.MinBackoff.Ticks << Math.Min(failures, 20)));
+
+ private async Task RefreshLoopAsync(CancellationToken cancellationToken)
+ {
+ var failures = 0;
+ while (!cancellationToken.IsCancellationRequested)
+ {
+ TimeSpan wait;
+ try
+ {
+ await RefreshAsync(cancellationToken).ConfigureAwait(false);
+ failures = 0;
+ wait = _options.RefreshInterval;
+ }
+ catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
+ {
+ return;
+ }
+ catch (Exception ex)
+ {
+ Log.Warning(LogCategory, $"Comparing with {Server} failed", ex);
+ Volatile.Write(ref _lastError, ex);
+ Changed?.Invoke();
+ wait = Backoff(failures++);
+ }
+ if (!await WaitAsync(_refreshWake.Reader, wait, cancellationToken).ConfigureAwait(false)) return;
+ }
+ }
+
+ /// Listens to the server's events; a lost socket reconnects with backoff and asks for a full comparison (events were missed).
+ private async Task EventLoopAsync(CancellationToken cancellationToken)
+ {
+ var failures = 0;
+ while (!cancellationToken.IsCancellationRequested)
+ {
+ try
+ {
+ await foreach (var e in _remote.EventsAsync(cancellationToken).ConfigureAwait(false))
+ {
+ failures = 0;
+ if (e is not SequenceChangedEvent changed) continue;
+ _changed[changed.SequenceId] = 0;
+ _eventWake.Writer.TryWrite(true);
+ }
+ }
+ catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
+ {
+ return;
+ }
+ catch (Exception ex)
+ {
+ Log.Info(LogCategory, $"Event stream of {Server} lost: {ex.Message}");
+ }
+ try
+ {
+ await Task.Delay(Backoff(failures++), cancellationToken).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException)
+ {
+ return;
+ }
+ RequestRefresh();
+ }
+ }
+
+ /// Compares the sequences named by events, a short while after the first one arrived.
+ private async Task ChangedLoopAsync(CancellationToken cancellationToken)
+ {
+ try
+ {
+ while (await _eventWake.Reader.WaitToReadAsync(cancellationToken).ConfigureAwait(false))
+ {
+ _eventWake.Reader.TryRead(out _);
+ await Task.Delay(_options.EventDelay, cancellationToken).ConfigureAwait(false);
+ var ids = _changed.Keys.ToList();
+ foreach (var id in ids) _changed.TryRemove(id, out _);
+ try
+ {
+ var busy = await _sync.TransferringAsync(Server, cancellationToken).ConfigureAwait(false);
+ var due = ids.Where(id => !busy.Contains(id)).ToList();
+ if (due.Count > 0) await _sync.RefreshSequencesAsync(_remote, due, _policy(), cancellationToken).ConfigureAwait(false);
+ }
+ catch (Exception ex) when (!cancellationToken.IsCancellationRequested)
+ {
+ // Includes timeouts reported as cancellation: the loop goes on and a full comparison catches up.
+ Log.Warning(LogCategory, $"Comparing changed sequences of {Server} failed", ex);
+ RequestRefresh();
+ }
+ }
+ }
+ catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
+ {
+ }
+ }
+
+ ///
+ /// Queues (background priority) the proxies of server sequences this PC keeps proxies of, without local originals,
+ /// whose cache is stale; a sequence whose last download failed waits for its backoff.
+ ///
+ private async Task QueueProxiesAsync(SyncSnapshot snapshot, CancellationToken cancellationToken)
+ {
+ foreach (var (remoteId, jobId) in _proxyJobs.ToList())
+ {
+ var job = await _sync.Database.Jobs.GetAsync(jobId, cancellationToken).ConfigureAwait(false);
+ if (job?.State is JobState.Queued or JobState.Running or JobState.Paused) continue;
+ _proxyJobs.Remove(remoteId);
+ if (job?.State == JobState.Failed)
+ {
+ var failures = _proxyFailures.GetValueOrDefault(remoteId).Failures + 1;
+ _proxyFailures[remoteId] = (failures, DateTime.UtcNow + Backoff(failures));
+ }
+ else
+ {
+ _proxyFailures.Remove(remoteId);
+ }
+ }
+ foreach (var entry in snapshot.Entries)
+ {
+ if (entry is not { Local: null, Transfer: null, Link: { ProxiesCached: > 0, ServerHasProxies: true, ProxiesStale: true } link }) continue;
+ if (_proxyFailures.TryGetValue(link.RemoteId, out var failed) && DateTime.UtcNow < failed.NotBefore) continue;
+ var job = await _sync.EnqueueDownloadAsync(_engine!, Server, link.RemoteId, link.Title, SyncDownloadMode.Proxies, null, JobPriority.Background,
+ cancellationToken).ConfigureAwait(false);
+ _proxyJobs[link.RemoteId] = job.Id;
+ }
+ }
+
+ /// Waits for a wake-up or the delay; false when stopping.
+ private static async Task WaitAsync(ChannelReader wake, TimeSpan delay, CancellationToken cancellationToken)
+ {
+ using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+ timeout.CancelAfter(delay);
+ try
+ {
+ await wake.ReadAsync(timeout.Token).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
+ {
+ // The delay elapsed.
+ }
+ catch (OperationCanceledException)
+ {
+ return false;
+ }
+ return true;
+ }
+}
diff --git a/src/Titano.Data/Sync/SyncJobHandler.cs b/src/Titano.Data/Sync/SyncJobHandler.cs
new file mode 100644
index 00000000..be602d4b
--- /dev/null
+++ b/src/Titano.Data/Sync/SyncJobHandler.cs
@@ -0,0 +1,93 @@
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using Titano.Core.Localization;
+using Titano.Core.Model;
+using Titano.Data.Jobs;
+
+namespace Titano.Data.Sync;
+
+/// What an upload or download job moves.
+public enum SyncTransferKind
+{
+ /// Originals and settings of a local sequence to the server.
+ Upload,
+
+ /// Renders of a local copy to the server.
+ SendExports,
+
+ /// Originals of a server sequence into the local archive.
+ DownloadOriginals,
+
+ /// Proxies of a server sequence into the proxy cache.
+ DownloadProxies,
+
+ /// Renders of a server sequence into the local copy's exports.
+ GetExports,
+}
+
+///
+/// Parameters of upload and download jobs. The job's target is the local sequence for an upload and the server
+/// sequence for a download.
+///
+/// Archive that receives downloaded originals when the sequence has no local copy yet.
+internal sealed record SyncJobParameters(string Server, SyncDownloadMode? Mode = null, Guid? ArchiveId = null, SyncUploadMode? Upload = null)
+{
+ public static SyncJobParameters? Read(Job job)
+ {
+ if (job.Kind is not (JobKind.UploadCommit or JobKind.Download) || job.ParametersJson is not { } json) return null;
+ try
+ {
+ return JsonSerializer.Deserialize(json, SyncJobJson.Default.SyncJobParameters);
+ }
+ catch (JsonException)
+ {
+ return null;
+ }
+ }
+
+ public SyncTransferKind Kind(JobKind kind) => (kind, Mode, Upload) switch
+ {
+ (JobKind.UploadCommit, _, SyncUploadMode.Exports) => SyncTransferKind.SendExports,
+ (JobKind.UploadCommit, _, _) => SyncTransferKind.Upload,
+ (_, SyncDownloadMode.Proxies, _) => SyncTransferKind.DownloadProxies,
+ (_, SyncDownloadMode.Exports, _) => SyncTransferKind.GetExports,
+ _ => SyncTransferKind.DownloadOriginals,
+ };
+}
+
+[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, UseStringEnumConverter = true,
+ DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
+[JsonSerializable(typeof(SyncJobParameters))]
+internal sealed partial class SyncJobJson : JsonSerializerContext;
+
+/// Runs upload and download jobs with a connection to their server; the job fails with a reason when this PC is not connected to it.
+internal sealed class SyncJobHandler(JobKind kind, SyncTransfers transfers, ISyncConnector connector) : IJobHandler
+{
+ public JobKind Kind => kind;
+
+ public async Task RunAsync(JobContext context)
+ {
+ var parameters = SyncJobParameters.Read(context.Job) ?? throw new InvalidDataException("The job has no sync parameters.");
+ if (context.Job.TargetIds is not [var target, ..]) throw new InvalidDataException("The job has no target sequence.");
+ using var remote = await connector.ConnectAsync(parameters.Server, context.Cancellation).ConfigureAwait(false)
+ ?? throw new InvalidOperationException(Loc.L("Errors.Sync.NotConnected"));
+ switch (parameters.Kind(kind))
+ {
+ case SyncTransferKind.Upload:
+ await transfers.UploadAsync(context, remote, target).ConfigureAwait(false);
+ break;
+ case SyncTransferKind.SendExports:
+ await transfers.SendExportsAsync(context, remote, target).ConfigureAwait(false);
+ break;
+ case SyncTransferKind.DownloadProxies:
+ await transfers.DownloadProxiesAsync(context, remote, target).ConfigureAwait(false);
+ break;
+ case SyncTransferKind.GetExports:
+ await transfers.GetExportsAsync(context, remote, target).ConfigureAwait(false);
+ break;
+ default:
+ await transfers.DownloadOriginalsAsync(context, remote, target, parameters.ArchiveId).ConfigureAwait(false);
+ break;
+ }
+ }
+}
diff --git a/src/Titano.Data/Sync/SyncLinkStore.cs b/src/Titano.Data/Sync/SyncLinkStore.cs
new file mode 100644
index 00000000..1d28e3f4
--- /dev/null
+++ b/src/Titano.Data/Sync/SyncLinkStore.cs
@@ -0,0 +1,107 @@
+using System.Text.Json;
+using Titano.Core.Model;
+using Titano.Data.Repositories;
+
+namespace Titano.Data.Sync;
+
+/// The sync_links table and the sync columns of local sequences (origin, sync state).
+internal sealed class SyncLinkStore(TitanoDatabase db)
+{
+ private const string Columns =
+ "server, remote_id, local_id, title, frame_count, total_bytes, render_count, remote_status, remote_settings_version, " +
+ "remote_frames_version, remote_updated_at, base_local_settings, base_remote_settings, diff_local_frames, diff_remote_frames, " +
+ "diff_local_renders, diff_remote_renders, missing_remote, missing_local, exports_to_get, exports_to_get_bytes, exports_to_send, " +
+ "exports_to_send_bytes, conflict_local_settings, conflict_remote_settings, conflict_remote, proxies_cached, proxies_frames_version, error, synced_at";
+
+ private static readonly string UpsertSql = SqlDialect.Upsert("sync_links", Columns.Split(", "), 2);
+
+ private static readonly JobState[] Active = [JobState.Queued, JobState.Running, JobState.Paused];
+
+ private readonly DbAccess _db = new(db.Database);
+
+ public Task> ListAsync(string server, CancellationToken cancellationToken) =>
+ _db.ListAsync($"SELECT {Columns} FROM sync_links WHERE server = $1 ORDER BY remote_id", [server], Map, cancellationToken);
+
+ public Task GetAsync(string server, Guid remoteId, CancellationToken cancellationToken) =>
+ _db.SingleAsync($"SELECT {Columns} FROM sync_links WHERE server = $1 AND remote_id = $2", [server, remoteId], Map, cancellationToken);
+
+ public Task FindByLocalAsync(string server, Guid localId, CancellationToken cancellationToken) =>
+ _db.SingleAsync($"SELECT {Columns} FROM sync_links WHERE server = $1 AND local_id = $2", [server, localId], Map, cancellationToken);
+
+ public Task UpsertAsync(SyncLink l, CancellationToken cancellationToken) =>
+ _db.ExecuteAsync(UpsertSql,
+ [
+ l.Server, l.RemoteId, l.LocalId, l.Title, l.FrameCount, l.TotalBytes, l.RenderCount, (int)l.RemoteStatus, l.RemoteSettingsVersion,
+ l.RemoteFramesVersion, l.RemoteUpdatedAt, l.BaseLocalSettings, l.BaseRemoteSettings, l.DiffLocalFrames, l.DiffRemoteFrames,
+ l.DiffLocalRenders, l.DiffRemoteRenders, l.MissingRemote, l.MissingLocal, l.ExportsToGet, l.ExportsToGetBytes, l.ExportsToSend,
+ l.ExportsToSendBytes, l.ConflictLocalSettings, l.ConflictRemoteSettings,
+ l.ConflictRemote is { } remote ? JsonSerializer.Serialize(remote, SyncPayloadJson.Default.SyncPayload) : null,
+ l.ProxiesCached, l.ProxiesFramesVersion, l.Error, l.SyncedAt,
+ ], cancellationToken);
+
+ public Task DeleteAsync(string server, Guid remoteId, CancellationToken cancellationToken) =>
+ _db.ExecuteAsync("DELETE FROM sync_links WHERE server = $1 AND remote_id = $2", [server, remoteId], cancellationToken);
+
+ /// Records where a local sequence stands for the Library; touches neither its versions nor its update time.
+ public Task SetLocalStateAsync(Guid localId, SyncState state, CancellationToken cancellationToken) =>
+ _db.ExecuteAsync("UPDATE sequences SET sync_state = $2 WHERE id = $1 AND sync_state <> $2", [localId, (int)state], cancellationToken);
+
+ /// Marks a local sequence as downloaded from the server.
+ public Task SetOriginAsync(Guid localId, SequenceOrigin origin, CancellationToken cancellationToken) =>
+ _db.ExecuteAsync("UPDATE sequences SET origin = $2 WHERE id = $1", [localId, (int)origin], cancellationToken);
+
+ /// Upload and download jobs that are waiting, running or paused, by target id (local id for uploads, server id for downloads).
+ public async Task>> ActiveTransfersAsync(CancellationToken cancellationToken)
+ {
+ var jobs = new List();
+ foreach (var kind in new[] { JobKind.UploadCommit, JobKind.Download })
+ {
+ foreach (var state in Active)
+ {
+ string? cursor = null;
+ do
+ {
+ var page = await db.Jobs.ListAsync(state, kind, 500, cursor, cancellationToken).ConfigureAwait(false);
+ jobs.AddRange(page.Items.Where(j => j.TargetIds.Count > 0));
+ cursor = page.NextCursor;
+ }
+ while (cursor is not null);
+ }
+ }
+ return jobs.GroupBy(j => j.TargetIds[0]).ToDictionary(g => g.Key, g => (IReadOnlyList)[.. g]);
+ }
+
+ private static SyncLink Map(DbRow r) => new()
+ {
+ Server = r.GetString(0),
+ RemoteId = r.GetGuid(1),
+ LocalId = r.GetGuidOrNull(2),
+ Title = r.GetString(3),
+ FrameCount = r.GetInt32(4),
+ TotalBytes = r.GetInt64(5),
+ RenderCount = r.GetInt32(6),
+ RemoteStatus = (SequenceStatus)r.GetInt32(7),
+ RemoteSettingsVersion = r.GetInt32(8),
+ RemoteFramesVersion = r.GetInt32(9),
+ RemoteUpdatedAt = r.GetDateTimeOffset(10),
+ BaseLocalSettings = r.GetInt32OrNull(11),
+ BaseRemoteSettings = r.GetInt32OrNull(12),
+ DiffLocalFrames = r.GetInt32OrNull(13),
+ DiffRemoteFrames = r.GetInt32OrNull(14),
+ DiffLocalRenders = r.GetInt32OrNull(15),
+ DiffRemoteRenders = r.GetInt32OrNull(16),
+ MissingRemote = r.GetInt32(17),
+ MissingLocal = r.GetInt32(18),
+ ExportsToGet = r.GetInt32(19),
+ ExportsToGetBytes = r.GetInt64(20),
+ ExportsToSend = r.GetInt32(21),
+ ExportsToSendBytes = r.GetInt64(22),
+ ConflictLocalSettings = r.GetInt32OrNull(23),
+ ConflictRemoteSettings = r.GetInt32OrNull(24),
+ ConflictRemote = r.GetStringOrNull(25) is { } json ? JsonSerializer.Deserialize(json, SyncPayloadJson.Default.SyncPayload) : null,
+ ProxiesCached = r.GetInt32(26),
+ ProxiesFramesVersion = r.GetInt32OrNull(27),
+ Error = r.GetStringOrNull(28),
+ SyncedAt = r.GetDateTimeOffsetOrNull(29),
+ };
+}
diff --git a/src/Titano.Data/Sync/SyncModel.cs b/src/Titano.Data/Sync/SyncModel.cs
new file mode 100644
index 00000000..ca465d6c
--- /dev/null
+++ b/src/Titano.Data/Sync/SyncModel.cs
@@ -0,0 +1,170 @@
+using Titano.Core.Model;
+
+namespace Titano.Data.Sync;
+
+/// Where a sequence stands between this PC and the server (BRIEF §12.7, §14.5).
+public enum SyncStatus
+{
+ /// Same originals and settings on both sides.
+ InSync,
+
+ LocalOnly,
+ RemoteOnly,
+
+ /// Only on the server; this PC keeps its proxies for editing.
+ ProxiesOnly,
+
+ /// This PC holds originals or settings the server lacks.
+ LocalAhead,
+
+ /// The server holds originals or settings this PC lacks.
+ ServerAhead,
+
+ /// Both sides changed the settings, title, tags, rating or notes since they last agreed: the user picks.
+ Conflict,
+
+ /// An upload or download job is queued, running or paused.
+ Transferring,
+}
+
+/// How the user settles a conflict (BRIEF §12.7).
+public enum SyncResolution
+{
+ KeepMine,
+ TakeServer,
+
+ /// The server's version wins; this PC's settings are kept next to the project as a dated copy.
+ SaveBoth,
+}
+
+/// What a download job fetches.
+public enum SyncDownloadMode
+{
+ /// Originals, hash-verified, into the local archive.
+ Originals,
+
+ /// Proxies (thumbnails where the server has none) into the proxy cache.
+ Proxies,
+
+ /// The server's renders the local copy lacks, into its exports folder.
+ Exports,
+}
+
+/// What an upload job sends.
+public enum SyncUploadMode
+{
+ /// Originals and settings (creating the server sequence when needed).
+ Originals,
+
+ /// This PC's renders the server lacks (BRIEF §14.5: renders are uploaded on request).
+ Exports,
+}
+
+///
+/// One server sequence as this client last saw it, linked to its local copy when there is one. The base versions are
+/// the settings counters both sides had when they last agreed; the diff versions are the frame counters and render
+/// counts the missing counts were computed at, so originals and renders are compared again only when either side's change.
+///
+public sealed record SyncLink
+{
+ /// Normalised server address ().
+ public required string Server { get; init; }
+
+ public required Guid RemoteId { get; init; }
+ public Guid? LocalId { get; init; }
+
+ // ---- The server's side, from its sequence listing ----
+ public required string Title { get; init; }
+ public int FrameCount { get; init; }
+ public long TotalBytes { get; init; }
+ public int RenderCount { get; init; }
+ public SequenceStatus RemoteStatus { get; init; }
+ public int RemoteSettingsVersion { get; init; }
+ public int RemoteFramesVersion { get; init; }
+ public DateTimeOffset RemoteUpdatedAt { get; init; }
+
+ // ---- Agreement and comparison state ----
+ public int? BaseLocalSettings { get; init; }
+ public int? BaseRemoteSettings { get; init; }
+ public int? DiffLocalFrames { get; init; }
+ public int? DiffRemoteFrames { get; init; }
+ public int? DiffLocalRenders { get; init; }
+ public int? DiffRemoteRenders { get; init; }
+
+ /// Local originals the server does not have.
+ public int MissingRemote { get; init; }
+
+ /// Server originals this PC does not have.
+ public int MissingLocal { get; init; }
+
+ /// Server renders the local copy does not have, and their size.
+ public int ExportsToGet { get; init; }
+
+ public long ExportsToGetBytes { get; init; }
+
+ /// Renders of the local copy the server does not have (whose file is still on this PC), and their size.
+ public int ExportsToSend { get; init; }
+
+ public long ExportsToSendBytes { get; init; }
+
+ /// Settings versions at which the content was found to conflict; null when it does not.
+ public int? ConflictLocalSettings { get; init; }
+
+ public int? ConflictRemoteSettings { get; init; }
+
+ /// The server's side when the conflict was found: what the user is shown and what "Take server" applies.
+ public SyncPayload? ConflictRemote { get; init; }
+
+ /// Frames whose proxy (or thumbnail) is in this PC's proxy cache.
+ public int ProxiesCached { get; init; }
+
+ /// Server frames version the proxy cache was filled at.
+ public int? ProxiesFramesVersion { get; init; }
+
+ /// Why the last comparison of this sequence failed (it is compared again next time); null when it worked.
+ public string? Error { get; init; }
+
+ public DateTimeOffset? SyncedAt { get; init; }
+
+ public bool ServerHasProxies => (RemoteStatus & SequenceStatus.ProxiesBuilt) != 0;
+
+ ///
+ /// The proxy cache was never completed or predates the server's last frame change (frames the server has no
+ /// proxy or thumbnail for stay missing until their frames change, so they are not fetched again and again).
+ ///
+ public bool ProxiesStale => ProxiesFramesVersion != RemoteFramesVersion;
+}
+
+/// One row of the sync table: the local sequence, the server sequence, or both, and where they stand.
+/// The upload or download job working on it, if any (the user's before background ones).
+public sealed record SyncEntry(Sequence? Local, SyncLink? Link, SyncStatus Status, Job? Transfer = null)
+{
+ public string Title => Local?.DisplayTitle ?? Link?.Title ?? string.Empty;
+
+ /// The server's id, or the local one for a sequence the server does not have.
+ public Guid Id => Link?.RemoteId ?? Local!.Id;
+
+ /// This PC holds originals of the sequence.
+ public bool HasLocalOriginals => Local is { FrameCount: > 0 };
+}
+
+/// The sync table after a refresh.
+/// Time the refresh took (listing, manifest diffs, settings exchange).
+public sealed record SyncSnapshot(string Server, IReadOnlyList Entries, DateTimeOffset RefreshedAt, TimeSpan Duration)
+{
+ public long ServerBytes => Entries.Sum(e => e.Link?.TotalBytes ?? 0);
+
+ public int ServerSequences => Entries.Count(e => e.Link is not null);
+}
+
+/// Options a refresh applies.
+/// Send and take settings changed on one side only (Server.html "Sync projects automatically").
+/// Keep the proxy caches of server sequences this PC opened with proxies up to date.
+/// The account may change server sequences; without it this PC's edits are never sent.
+public sealed record SyncPolicy(bool AutoSyncSettings = true, bool KeepProxiesOffline = false, bool CanEdit = true);
+
+///
+/// A conflict could not be settled as the user chose because one side changed again after it was shown; the
+/// sequence was compared again, so the user can choose on the fresh content.
+///
+public sealed class SyncConflictChangedException(string message) : InvalidOperationException(message);
diff --git a/src/Titano.Data/Sync/SyncRemote.cs b/src/Titano.Data/Sync/SyncRemote.cs
new file mode 100644
index 00000000..3cf2dc88
--- /dev/null
+++ b/src/Titano.Data/Sync/SyncRemote.cs
@@ -0,0 +1,123 @@
+using Titano.Protocol;
+using Titano.Protocol.Client;
+
+namespace Titano.Data.Sync;
+
+///
+/// The server calls the sync engine makes (BRIEF §14.3). sends them with
+/// ; screenshots and tests substitute fakes. Failures are s
+/// (404 gone, 409 settings conflict) or network exceptions. Dispose a remote handed out by an .
+///
+public interface ISyncRemote : IDisposable
+{
+ /// Normalised server address the links are stored under ().
+ string Server { get; }
+
+ /// Every sequence on the server.
+ Task> ListSequencesAsync(CancellationToken cancellationToken);
+
+ Task GetSequenceAsync(Guid id, CancellationToken cancellationToken);
+
+ Task GetManifestAsync(Guid id, CancellationToken cancellationToken);
+
+ /// Every frame row of a sequence, in index order.
+ Task> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken);
+
+ /// A 409 means the settings version moved on the server.
+ Task UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken);
+
+ ///
+ /// Chunked, resumable upload of one original into , or into the sequence the server
+ /// files under (created by the first one); the server verifies
+ /// before committing it (BRIEF §14.4). An original the server already holds is not sent again: the response then
+ /// names ( without one). See .
+ ///
+ Task UploadFileAsync(string path, Guid? sequenceId, string? sessionKey, string sha256, DateTime? capturedAt,
+ CancellationToken cancellationToken);
+
+ /// Streams a frame's original, proxy or thumb, resuming with Range from the destination's length.
+ Task DownloadFrameAsync(Guid frameId, string kind, Stream destination, CancellationToken cancellationToken);
+
+ /// Streams a render's file, resuming with Range from the destination's length; returns the file name the server gives it.
+ Task DownloadRenderAsync(Guid renderId, Stream destination, CancellationToken cancellationToken);
+
+ ///
+ /// Chunked, resumable upload of a render of made on this PC; the server verifies the
+ /// SHA-256 and keeps the render's id. Null when the server already has it. See .
+ ///
+ Task UploadRenderAsync(Guid sequenceId, string path, RenderUploadRequest request, CancellationToken cancellationToken);
+
+ /// Server events until cancelled or the socket closes.
+ IAsyncEnumerable EventsAsync(CancellationToken cancellationToken);
+}
+
+/// Where sync jobs find their server connection.
+public interface ISyncConnector
+{
+ /// A signed-in remote of owned by the caller; null when this PC is not connected to that server.
+ ValueTask ConnectAsync(string server, CancellationToken cancellationToken);
+}
+
+/// over a signed-in , which it disposes when it owns it.
+public sealed class TitanoSyncRemote(TitanoClient client, bool ownsClient) : ISyncRemote
+{
+ private const int SequencePage = 500;
+ private const int FramePage = 1000;
+
+ public string Server { get; } = SyncService.ServerKey(client.BaseAddress);
+
+ public async Task> ListSequencesAsync(CancellationToken cancellationToken)
+ {
+ var all = new List();
+ string? cursor = null;
+ do
+ {
+ var page = await client.ListSequencesAsync(null, cursor, SequencePage, cancellationToken).ConfigureAwait(false);
+ all.AddRange(page.Items);
+ cursor = page.NextCursor;
+ }
+ while (cursor is not null);
+ return all;
+ }
+
+ public Task GetSequenceAsync(Guid id, CancellationToken cancellationToken) => client.GetSequenceAsync(id, cancellationToken);
+
+ public Task GetManifestAsync(Guid id, CancellationToken cancellationToken) => client.GetManifestAsync(id, cancellationToken);
+
+ public async Task> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken)
+ {
+ var all = new List();
+ string? cursor = null;
+ do
+ {
+ var page = await client.ListFramesAsync(sequenceId, cursor, FramePage, cancellationToken).ConfigureAwait(false);
+ all.AddRange(page.Items);
+ cursor = page.NextCursor;
+ }
+ while (cursor is not null);
+ return all;
+ }
+
+ public Task UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken) =>
+ client.UpdateSequenceAsync(id, request, cancellationToken);
+
+ public Task UploadFileAsync(string path, Guid? sequenceId, string? sessionKey, string sha256, DateTime? capturedAt,
+ CancellationToken cancellationToken) =>
+ client.UploadFileAsync(path, sequenceId, capturedAt, sessionKey, sha256, null, cancellationToken);
+
+ public Task DownloadFrameAsync(Guid frameId, string kind, Stream destination, CancellationToken cancellationToken) =>
+ client.DownloadFrameAsync(frameId, kind, destination, null, cancellationToken);
+
+ public Task DownloadRenderAsync(Guid renderId, Stream destination, CancellationToken cancellationToken) =>
+ client.DownloadRenderAsync(renderId, destination, cancellationToken);
+
+ public Task UploadRenderAsync(Guid sequenceId, string path, RenderUploadRequest request, CancellationToken cancellationToken) =>
+ client.UploadRenderAsync(sequenceId, path, request, null, cancellationToken);
+
+ public IAsyncEnumerable EventsAsync(CancellationToken cancellationToken) => client.EventsAsync(cancellationToken);
+
+ public void Dispose()
+ {
+ if (ownsClient) client.Dispose();
+ }
+}
diff --git a/src/Titano.Data/Sync/SyncRules.cs b/src/Titano.Data/Sync/SyncRules.cs
new file mode 100644
index 00000000..a8aa0e12
--- /dev/null
+++ b/src/Titano.Data/Sync/SyncRules.cs
@@ -0,0 +1,163 @@
+using System.Globalization;
+using System.Text.Json;
+using System.Text.Json.Nodes;
+using System.Text.Json.Serialization;
+using Titano.Core.Model;
+using Titano.Core.Project;
+using Titano.Protocol;
+
+namespace Titano.Data.Sync;
+
+/// The fields both sides version together (BRIEF §14.5: settings and tags carry version counters).
+public sealed record SyncPayload(string? Title, IReadOnlyList Tags, int Rating, string? Notes, string? SettingsJson)
+{
+ public static SyncPayload Of(Sequence s) => new(s.Title, s.Tags, s.Rating, s.Notes, s.SettingsJson);
+
+ public static SyncPayload Of(SequenceDto s, string? settingsJson) => new(s.Title, s.Tags, s.Rating, s.Notes, settingsJson);
+
+ /// Title, tags, rating and notes match (blank equals absent, tags ignore case and order).
+ public bool SameMetadata(SyncPayload other) =>
+ SyncRules.Blank(Title) == SyncRules.Blank(other.Title)
+ && SyncRules.Blank(Notes) == SyncRules.Blank(other.Notes)
+ && Rating == other.Rating
+ && Tags.ToHashSet(StringComparer.OrdinalIgnoreCase).SetEquals(other.Tags);
+
+ public bool SameAs(SyncPayload other) => SameMetadata(other) && SyncRules.SameSettings(SettingsJson, other.SettingsJson);
+
+ /// The PATCH that makes the server's copy equal to this one; settings are sent in their normalised form.
+ public UpdateSequenceRequest ToRequest(int? expectedSettingsVersion) =>
+ new(Title ?? string.Empty, Tags, Rating, Notes ?? string.Empty, SyncRules.NormalizeSettings(SettingsJson), expectedSettingsVersion);
+}
+
+[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
+[JsonSerializable(typeof(SyncPayload))]
+internal sealed partial class SyncPayloadJson : JsonSerializerContext;
+
+///
+/// One field that differs: its dotted path ("exposure.deflickerWindow.manual", or "sequence.tags" for the metadata)
+/// and the value on each side (JSON for settings, plain text for metadata; null when absent).
+///
+public sealed record SettingsDifference(string Path, string? Mine, string? Theirs);
+
+/// Decisions of the sync engine that need no I/O: the status of a row, settings equality and differences, merges.
+public static class SyncRules
+{
+ /// Path prefix of the title, tags, rating and notes in .
+ public const string MetadataPath = "sequence.";
+
+ ///
+ /// Where a linked pair stands. Settings changed on both sides since they last agreed are a conflict (the engine
+ /// settles equal content before a row is shown); missing originals count before settings changed on one side only.
+ ///
+ public static SyncStatus Status(Sequence? local, SyncLink? link)
+ {
+ if (link is null) return SyncStatus.LocalOnly;
+ if (local is null) return link.ProxiesCached > 0 ? SyncStatus.ProxiesOnly : SyncStatus.RemoteOnly;
+ var localChanged = link.BaseLocalSettings != local.SettingsVersion;
+ var remoteChanged = link.BaseRemoteSettings != link.RemoteSettingsVersion;
+ if (localChanged && remoteChanged) return SyncStatus.Conflict;
+ if (link.MissingRemote > 0 || localChanged) return SyncStatus.LocalAhead;
+ if (link.MissingLocal > 0 || remoteChanged) return SyncStatus.ServerAhead;
+ return SyncStatus.InSync;
+ }
+
+ /// The state stored on the local sequence for the Library; null for rows without a local copy or in transfer.
+ public static SyncState? ToSequenceState(SyncStatus status) => status switch
+ {
+ SyncStatus.InSync => SyncState.InSync,
+ SyncStatus.LocalOnly => SyncState.LocalOnly,
+ SyncStatus.LocalAhead => SyncState.LocalAhead,
+ SyncStatus.ServerAhead => SyncState.ServerAhead,
+ SyncStatus.Conflict => SyncState.Conflict,
+ _ => null,
+ };
+
+ ///
+ /// Settings JSON in the form both sides store: a project read and written again (missing members take their
+ /// defaults, so "no settings" equals the default project). Text that is not a project of this build is kept as is.
+ ///
+ public static string NormalizeSettings(string? json)
+ {
+ if (string.IsNullOrWhiteSpace(json)) return new ProjectSettings().ToJson();
+ try
+ {
+ return ProjectSettings.FromJson(json).ToJson();
+ }
+ catch (Exception ex) when (ex is JsonException or InvalidDataException)
+ {
+ return json.Trim();
+ }
+ }
+
+ public static bool SameSettings(string? a, string? b) => Differences(a, b, 1).Count == 0;
+
+ /// Up to settings that differ, in document order.
+ public static IReadOnlyList Differences(string? mine, string? theirs, int max = 3)
+ {
+ var differences = new List();
+ Collect(Parse(NormalizeSettings(mine)), Parse(NormalizeSettings(theirs)), string.Empty, differences, max);
+ return differences;
+ }
+
+ ///
+ /// Up to differences between two payloads: title, tags, rating and notes first (paths
+ /// sequence.title, sequence.tags, …, tags as one comma-separated value), then the settings.
+ ///
+ public static IReadOnlyList Differences(SyncPayload mine, SyncPayload theirs, int max = 3)
+ {
+ var differences = new List();
+ if (Blank(mine.Title) != Blank(theirs.Title)) differences.Add(new(MetadataPath + "title", Blank(mine.Title), Blank(theirs.Title)));
+ if (!mine.Tags.ToHashSet(StringComparer.OrdinalIgnoreCase).SetEquals(theirs.Tags))
+ differences.Add(new(MetadataPath + "tags", string.Join(", ", mine.Tags), string.Join(", ", theirs.Tags)));
+ if (mine.Rating != theirs.Rating)
+ differences.Add(new(MetadataPath + "rating", mine.Rating.ToString(CultureInfo.InvariantCulture), theirs.Rating.ToString(CultureInfo.InvariantCulture)));
+ if (Blank(mine.Notes) != Blank(theirs.Notes)) differences.Add(new(MetadataPath + "notes", Blank(mine.Notes), Blank(theirs.Notes)));
+ if (differences.Count < max) differences.AddRange(Differences(mine.SettingsJson, theirs.SettingsJson, max - differences.Count));
+ return differences.Count > max ? differences.GetRange(0, max) : differences;
+ }
+
+ ///
+ /// Originals missing on each side by content (BRIEF §14.5: originals never conflict). Local frames not hashed yet
+ /// (adopted, not verified) are assumed to match server frames that no hash matched.
+ ///
+ public static (int MissingRemote, int MissingLocal) CompareOriginals(IReadOnlyCollection localHashes, IReadOnlyCollection remoteHashes)
+ {
+ var remote = remoteHashes.Select(h => h.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
+ var hashed = localHashes.Where(h => !string.IsNullOrEmpty(h)).Select(h => h!.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
+ var unhashed = localHashes.Count(string.IsNullOrEmpty);
+ var matched = hashed.Count(remote.Contains);
+ var unmatchedRemote = remote.Count - matched;
+ return (hashed.Count - matched + Math.Max(0, unhashed - unmatchedRemote), Math.Max(0, unmatchedRemote - unhashed));
+ }
+
+ internal static string Blank(string? text) => text?.Trim() ?? string.Empty;
+
+ private static JsonNode? Parse(string json)
+ {
+ try
+ {
+ return JsonNode.Parse(json);
+ }
+ catch (JsonException)
+ {
+ return JsonValue.Create(json);
+ }
+ }
+
+ private static void Collect(JsonNode? a, JsonNode? b, string path, List differences, int max)
+ {
+ if (differences.Count >= max) return;
+ if (a is JsonObject left && b is JsonObject right)
+ {
+ foreach (var name in left.Select(p => p.Key).Concat(right.Select(p => p.Key)).Distinct(StringComparer.Ordinal))
+ {
+ left.TryGetPropertyValue(name, out var x);
+ right.TryGetPropertyValue(name, out var y);
+ Collect(x, y, path.Length == 0 ? name : path + "." + name, differences, max);
+ if (differences.Count >= max) return;
+ }
+ return;
+ }
+ if (!JsonNode.DeepEquals(a, b)) differences.Add(new SettingsDifference(path.Length == 0 ? "settings" : path, a?.ToJsonString(), b?.ToJsonString()));
+ }
+}
diff --git a/src/Titano.Data/Sync/SyncService.cs b/src/Titano.Data/Sync/SyncService.cs
new file mode 100644
index 00000000..a1a3232d
--- /dev/null
+++ b/src/Titano.Data/Sync/SyncService.cs
@@ -0,0 +1,800 @@
+using System.Collections.Concurrent;
+using System.Diagnostics;
+using System.Globalization;
+using System.Net;
+using System.Text.Json;
+using Titano.Core.Archiving;
+using Titano.Core.Diagnostics;
+using Titano.Core.IO;
+using Titano.Core.Localization;
+using Titano.Core.Model;
+using Titano.Data.Archiving;
+using Titano.Data.Jobs;
+using Titano.Data.Processing;
+using Titano.Data.Repositories;
+using Titano.Protocol;
+using Titano.Protocol.Client;
+using SequenceFrames = Titano.Data.Processing.SequenceFrames;
+using SequenceManifest = Titano.Protocol.SequenceManifest;
+
+namespace Titano.Data.Sync;
+
+/// Settings of a .
+public sealed record SyncOptions
+{
+ /// Decoders, lease owner and lease timing for sidecar and project writes (shared with the archive engine).
+ public ArchiveServiceOptions Archive { get; init; } = new();
+
+ /// Folder of the proxy cache of server sequences (inside the client's cache).
+ public required string ProxyCacheDirectory { get; init; }
+
+ /// Concurrent frame downloads of one job.
+ public int Downloads { get; init; } = 4;
+
+ /// Concurrent file uploads of one job (the server accepts 8 chunks in flight per user).
+ public int Uploads { get; init; } = 2;
+}
+
+///
+/// Client side of sync (BRIEF §4.4, §14.5). Compares every server sequence with its local copy from the server listing
+/// and, when frame counters or render counts moved, the manifest: originals are matched by SHA-256 and never conflict;
+/// renders by id. Settings, title, tags, rating and notes travel together under the settings version, so a change on
+/// one side is sent or taken (automatically or on request) and a change on both sides with different content is a
+/// conflict the user settles with , against the versions the user was shown. Uploads and
+/// downloads run as jobs (): uploads use the chunked, hash-verified, resumable protocol;
+/// downloaded originals are verified and committed through the archive ingest, so sidecars stay right; proxies go to a
+/// cache and open as a ; renders travel on request. Proxies and thumbnails never travel
+/// upward. A local copy and a server sequence holding the same originals are linked by content when no link joins
+/// them. The state of each local sequence is written to its sync_state for the Library. A failure while
+/// comparing one sequence is recorded on its link and does not stop the others.
+///
+public sealed class SyncService
+{
+ private const string LogCategory = "sync";
+ private const string SessionKeyPrefix = "titano-sync:";
+
+ /// Recomputes states without sending or taking settings on the user's behalf.
+ internal static readonly SyncPolicy CompareOnly = new(AutoSyncSettings: false);
+
+ private readonly TitanoDatabase _db;
+ private readonly SyncLinkStore _links;
+ private readonly ProjectStore _projects;
+ private readonly SemaphoreSlim _gate = new(1, 1);
+
+ /// Unlinked pairs whose manifests were compared at these frame versions without a match (not fetched again).
+ private readonly ConcurrentDictionary _unmatched = new(StringComparer.Ordinal);
+
+ public SyncService(TitanoDatabase db, ArchiveService archives, SyncOptions options)
+ {
+ _db = db;
+ Archives = archives;
+ Options = options;
+ _links = new SyncLinkStore(db);
+ _projects = new ProjectStore(db, new SequenceWriter(options.Archive));
+ Proxies = new ProxyCache(options.ProxyCacheDirectory);
+ }
+
+ public SyncOptions Options { get; }
+
+ /// The links or local states of a server (the argument) changed: refresh, resolution, transfer; raised on any thread.
+ public event Action? Changed;
+
+ internal ProxyCache Proxies { get; }
+
+ internal SyncLinkStore Links => _links;
+
+ internal TitanoDatabase Database => _db;
+
+ internal ArchiveService Archives { get; }
+
+ /// "https://nas.local:8443": the key links are stored under (scheme, lower-case host, port, path).
+ public static string ServerKey(Uri address) => address.GetLeftPart(UriPartial.Path).TrimEnd('/').ToLowerInvariant();
+
+ /// What an upload or download job moves; null for any other job.
+ public static SyncTransferKind? TransferKind(Job job) => SyncJobParameters.Read(job)?.Kind(job.Kind);
+
+ /// Session key the local archive groups the downloaded originals of one server sequence by.
+ internal static string SessionKey(Guid remoteId) => SessionKeyPrefix + remoteId.ToString("N");
+
+ // ---------------- Table ----------------
+
+ ///
+ /// Lists the server, compares every sequence with its local copy, sends or takes settings changed on one side when
+ /// is on, forgets sequences the server confirms deleted, links unlinked
+ /// copies holding the same originals, and stores the states.
+ ///
+ public async Task RefreshAsync(ISyncRemote remote, SyncPolicy policy, CancellationToken cancellationToken)
+ {
+ var clock = Stopwatch.StartNew();
+ var listing = await remote.ListSequencesAsync(cancellationToken).ConfigureAwait(false);
+ Dictionary locals;
+ await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
+ try
+ {
+ var links = (await _links.ListAsync(remote.Server, cancellationToken).ConfigureAwait(false)).ToDictionary(l => l.RemoteId);
+ locals = await LocalSequencesAsync(cancellationToken).ConfigureAwait(false);
+ foreach (var dto in listing)
+ {
+ links.Remove(dto.Id, out var link);
+ var local = await LocalOfAsync(link, locals, cancellationToken).ConfigureAwait(false);
+ await ReconcileSafelyAsync(remote, Observe(link, remote.Server, dto), dto, local, locals, policy, cancellationToken).ConfigureAwait(false);
+ }
+ // Not in the listing: deleted on the server, or created or moved while its pages were read. Only a 404 forgets a link.
+ foreach (var link in links.Values) await CompareOneAsync(remote, link.RemoteId, link, locals, policy, cancellationToken).ConfigureAwait(false);
+ await MatchByContentAsync(remote, listing, locals, policy, cancellationToken).ConfigureAwait(false);
+ }
+ finally
+ {
+ _gate.Release();
+ }
+ var entries = await StoreStatesAsync(remote.Server, locals, cancellationToken).ConfigureAwait(false);
+ Changed?.Invoke(remote.Server);
+ return new SyncSnapshot(remote.Server, entries, DateTimeOffset.UtcNow, clock.Elapsed);
+ }
+
+ /// Compares the given server sequences again (live events, finished transfers); a sequence gone from the server is forgotten.
+ public async Task RefreshSequencesAsync(ISyncRemote remote, IReadOnlyCollection remoteIds, SyncPolicy policy, CancellationToken cancellationToken)
+ {
+ await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
+ try
+ {
+ foreach (var id in remoteIds)
+ {
+ var link = await _links.GetAsync(remote.Server, id, cancellationToken).ConfigureAwait(false);
+ await CompareOneAsync(remote, id, link, null, policy, cancellationToken).ConfigureAwait(false);
+ }
+ }
+ finally
+ {
+ _gate.Release();
+ }
+ await StoreStatesAsync(remote.Server, null, cancellationToken).ConfigureAwait(false);
+ Changed?.Invoke(remote.Server);
+ }
+
+ ///
+ /// The sync table of as last compared: every server sequence and every local one, with
+ /// active transfers; conflicts first, then transfers, then by title.
+ ///
+ public Task> ListAsync(string server, CancellationToken cancellationToken) => EntriesAsync(server, null, cancellationToken);
+
+ ///
+ /// Links a local sequence to a server sequence holding the same originals. Nothing was agreed yet, so the next
+ /// comparison settles equal settings and reports different ones as a conflict.
+ ///
+ public async Task LinkAsync(string server, Guid remoteId, Guid localId, CancellationToken cancellationToken = default)
+ {
+ var local = await _db.Sequences.GetAsync(localId, cancellationToken).ConfigureAwait(false)
+ ?? throw new ArgumentException($"Unknown sequence {localId}.", nameof(localId));
+ await LinkAsync(server, remoteId, local, cancellationToken).ConfigureAwait(false);
+ }
+
+ // ---------------- Settings ----------------
+
+ ///
+ /// Settles a conflict as the user chose (BRIEF §12.7), against the versions the user was shown: when either side
+ /// changed again since, nothing is written, the sequence is compared again and
+ /// is thrown. Returns the file this PC's settings were saved to for , else null.
+ ///
+ public async Task ResolveAsync(ISyncRemote remote, Guid remoteId, SyncResolution resolution, CancellationToken cancellationToken)
+ {
+ string? saved = null;
+ var changed = false;
+ await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
+ try
+ {
+ var (link, local) = await LinkedAsync(remote.Server, remoteId, cancellationToken).ConfigureAwait(false);
+ if (link is not { ConflictRemote: { } theirs, ConflictLocalSettings: { } seenLocal, ConflictRemoteSettings: { } seenRemote }
+ || local.SettingsVersion != seenLocal)
+ {
+ changed = true;
+ }
+ else if (resolution == SyncResolution.KeepMine)
+ {
+ try
+ {
+ var updated = await remote.UpdateSequenceAsync(remoteId, SyncPayload.Of(local).ToRequest(seenRemote), cancellationToken).ConfigureAwait(false);
+ link = Agreed(Observe(link, remote.Server, updated), local.SettingsVersion, updated.SettingsVersion);
+ }
+ catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.Conflict)
+ {
+ changed = true;
+ }
+ }
+ else
+ {
+ var dto = await remote.GetSequenceAsync(remoteId, cancellationToken).ConfigureAwait(false);
+ if (dto.SettingsVersion != seenRemote)
+ {
+ changed = true;
+ }
+ else
+ {
+ if (resolution == SyncResolution.SaveBoth) saved = await SaveCopyAsync(local, cancellationToken).ConfigureAwait(false);
+ var applied = await ApplyLocallyAsync(local, theirs, cancellationToken).ConfigureAwait(false);
+ link = Agreed(Observe(link, remote.Server, dto), applied.SettingsVersion, seenRemote);
+ }
+ }
+ if (!changed)
+ {
+ await _links.UpsertAsync(link with { SyncedAt = DateTimeOffset.UtcNow }, cancellationToken).ConfigureAwait(false);
+ Log.Info(LogCategory, $"Conflict on {local.DisplayTitle} settled: {resolution}");
+ }
+ }
+ finally
+ {
+ _gate.Release();
+ }
+ if (changed)
+ {
+ await RefreshSequencesAsync(remote, [remoteId], CompareOnly, cancellationToken).ConfigureAwait(false);
+ throw new SyncConflictChangedException(Loc.L("Errors.Sync.ChangedAgain"));
+ }
+ await StoreStatesAsync(remote.Server, null, cancellationToken).ConfigureAwait(false);
+ Changed?.Invoke(remote.Server);
+ return saved;
+ }
+
+ /// Sends or takes settings changed on one side only (the row action while automatic sync is off).
+ public Task SyncSettingsAsync(ISyncRemote remote, Guid remoteId, SyncPolicy policy, CancellationToken cancellationToken) =>
+ RefreshSequencesAsync(remote, [remoteId], policy with { AutoSyncSettings = true }, cancellationToken);
+
+ // ---------------- Transfers ----------------
+
+ /// Queues the upload of a local sequence's originals and settings, unless one is already waiting or running.
+ public Task EnqueueUploadAsync(JobEngine engine, string server, Sequence local, CancellationToken cancellationToken = default) =>
+ EnqueueAsync(engine, JobKind.UploadCommit, local.Id, local.DisplayTitle, new SyncJobParameters(server), JobPriority.User, cancellationToken);
+
+ /// Queues sending the renders of a local copy the server lacks (BRIEF §14.5), unless that is already waiting or running.
+ public Task EnqueueSendExportsAsync(JobEngine engine, string server, Sequence local, CancellationToken cancellationToken = default) =>
+ EnqueueAsync(engine, JobKind.UploadCommit, local.Id, local.DisplayTitle, new SyncJobParameters(server, Upload: SyncUploadMode.Exports), JobPriority.User,
+ cancellationToken);
+
+ ///
+ /// Queues a download of a server sequence, unless the same one is already waiting or running: originals into
+ /// (ignored when the sequence already has a local copy), proxies into the cache, or the
+ /// server's renders into the local copy. A background proxy download gives way to the user's request for the same
+ /// proxies (queued again at the user's priority) or for the originals.
+ ///
+ public Task EnqueueDownloadAsync(JobEngine engine, string server, Guid remoteId, string title, SyncDownloadMode mode, Guid? archiveId,
+ JobPriority priority = JobPriority.User, CancellationToken cancellationToken = default) =>
+ EnqueueAsync(engine, JobKind.Download, remoteId, title, new SyncJobParameters(server, mode, archiveId), priority, cancellationToken);
+
+ /// Handlers for and ; register them on the client's engine.
+ public IReadOnlyList CreateJobHandlers(ISyncConnector connector)
+ {
+ var transfers = new SyncTransfers(this);
+ return [new SyncJobHandler(JobKind.UploadCommit, transfers, connector), new SyncJobHandler(JobKind.Download, transfers, connector)];
+ }
+
+ /// A server sequence from the proxy cache, for the editor; null when its proxies were never fetched or were cleared.
+ public RemoteSequence? OpenRemote(string server, Guid remoteId) => Proxies.Load(server, remoteId);
+
+ // ---------------- Engine ----------------
+
+ /// Server ids of the sequences an upload or download job is working on.
+ internal async Task> TransferringAsync(string server, CancellationToken cancellationToken)
+ {
+ var transfers = await _links.ActiveTransfersAsync(cancellationToken).ConfigureAwait(false);
+ var links = await _links.ListAsync(server, cancellationToken).ConfigureAwait(false);
+ return links.Where(l => transfers.ContainsKey(l.RemoteId) || (l.LocalId is { } id && transfers.ContainsKey(id))).Select(l => l.RemoteId).ToHashSet();
+ }
+
+ /// Creates or updates the link of a local sequence to a server sequence (an upload or download made it).
+ internal async Task LinkAsync(string server, Guid remoteId, Sequence local, CancellationToken cancellationToken)
+ {
+ await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
+ try
+ {
+ var link = await _links.GetAsync(server, remoteId, cancellationToken).ConfigureAwait(false)
+ ?? new SyncLink { Server = server, RemoteId = remoteId, Title = local.DisplayTitle, RemoteUpdatedAt = DateTimeOffset.UtcNow };
+ if (link.LocalId != local.Id) link = Unlinked(link) with { LocalId = local.Id };
+ await _links.UpsertAsync(link, cancellationToken).ConfigureAwait(false);
+ return link;
+ }
+ finally
+ {
+ _gate.Release();
+ }
+ }
+
+ /// Forgets a link whose server sequence an upload found deleted (its originals go into a new one).
+ internal async Task ForgetGoneAsync(string server, Guid remoteId, CancellationToken cancellationToken)
+ {
+ await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
+ try
+ {
+ if (await _links.GetAsync(server, remoteId, cancellationToken).ConfigureAwait(false) is { } link)
+ await ForgetAsync(link, cancellationToken).ConfigureAwait(false);
+ }
+ finally
+ {
+ _gate.Release();
+ }
+ }
+
+ ///
+ /// Makes the server's copy equal to this PC's (an upload sends the settings with the originals of the sequence it
+ /// created); the server's own processing may edit the new sequence meanwhile, so a refused edit is sent again.
+ ///
+ internal async Task PushAllAsync(ISyncRemote remote, Guid remoteId, CancellationToken cancellationToken)
+ {
+ await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
+ try
+ {
+ var (link, local) = await LinkedAsync(remote.Server, remoteId, cancellationToken).ConfigureAwait(false);
+ for (var attempt = 1; ; attempt++)
+ {
+ var dto = await remote.GetSequenceAsync(remoteId, cancellationToken).ConfigureAwait(false);
+ try
+ {
+ var updated = await remote.UpdateSequenceAsync(remoteId, SyncPayload.Of(local).ToRequest(dto.SettingsVersion), cancellationToken)
+ .ConfigureAwait(false);
+ await _links.UpsertAsync(Agreed(Observe(link, remote.Server, updated), local.SettingsVersion, updated.SettingsVersion), cancellationToken)
+ .ConfigureAwait(false);
+ return;
+ }
+ catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.Conflict && attempt < 3)
+ {
+ Log.Info(LogCategory, $"{local.DisplayTitle} changed on the server while its settings were sent; sending again");
+ }
+ }
+ }
+ finally
+ {
+ _gate.Release();
+ }
+ }
+
+ /// Makes this PC's copy equal to the server's (a sequence a download just created takes the server's settings).
+ internal async Task TakeAllAsync(ISyncRemote remote, Guid remoteId, CancellationToken cancellationToken)
+ {
+ await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
+ try
+ {
+ var (link, local) = await LinkedAsync(remote.Server, remoteId, cancellationToken).ConfigureAwait(false);
+ var dto = await remote.GetSequenceAsync(remoteId, cancellationToken).ConfigureAwait(false);
+ var manifest = await remote.GetManifestAsync(remoteId, cancellationToken).ConfigureAwait(false);
+ var applied = await ApplyLocallyAsync(local, SyncPayload.Of(dto, manifest.SettingsJson), cancellationToken).ConfigureAwait(false);
+ await _links.UpsertAsync(Agreed(Observe(link, remote.Server, dto), applied.SettingsVersion, manifest.SettingsVersion), cancellationToken)
+ .ConfigureAwait(false);
+ }
+ finally
+ {
+ _gate.Release();
+ }
+ }
+
+ ///
+ /// Compares a sequence again after a transfer, originals and renders included even when no counter moved (a
+ /// restored original or a hash given by verify changes no frame version), without sending or taking settings.
+ ///
+ internal async Task RecompareAsync(ISyncRemote remote, Guid remoteId, CancellationToken cancellationToken)
+ {
+ await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
+ try
+ {
+ if (await _links.GetAsync(remote.Server, remoteId, cancellationToken).ConfigureAwait(false) is { } link)
+ await _links.UpsertAsync(link with { DiffLocalFrames = null, DiffLocalRenders = null }, cancellationToken).ConfigureAwait(false);
+ }
+ finally
+ {
+ _gate.Release();
+ }
+ await RefreshSequencesAsync(remote, [remoteId], CompareOnly, cancellationToken).ConfigureAwait(false);
+ }
+
+ /// Records what the proxy cache holds for a server sequence.
+ internal async Task SetProxiesAsync(string server, SequenceDto dto, int cached, int framesVersion, CancellationToken cancellationToken)
+ {
+ await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
+ try
+ {
+ var link = Observe(await _links.GetAsync(server, dto.Id, cancellationToken).ConfigureAwait(false), server, dto);
+ await _links.UpsertAsync(link with { ProxiesCached = cached, ProxiesFramesVersion = framesVersion }, cancellationToken).ConfigureAwait(false);
+ }
+ finally
+ {
+ _gate.Release();
+ }
+ Changed?.Invoke(server);
+ }
+
+ /// The file of a local render: archive-relative for outputs inside the archive, absolute otherwise.
+ internal static string RenderFile(Archive archive, Render render) =>
+ Path.IsPathRooted(render.OutputPath) ? render.OutputPath : new ArchivePaths(archive.RootPath).FromRelative(render.OutputPath);
+
+ ///
+ /// Compares one server sequence (under the gate): fetches it, forgets its link on a 404, records a failure on its
+ /// link. (when given) receives the local copy as it stands after the comparison.
+ ///
+ private async Task CompareOneAsync(ISyncRemote remote, Guid remoteId, SyncLink? link, Dictionary? locals, SyncPolicy policy,
+ CancellationToken cancellationToken)
+ {
+ SequenceDto dto;
+ try
+ {
+ dto = await remote.GetSequenceAsync(remoteId, cancellationToken).ConfigureAwait(false);
+ }
+ catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound)
+ {
+ if (link is not null) await ForgetAsync(link, cancellationToken).ConfigureAwait(false);
+ return;
+ }
+ catch (Exception ex) when (IsIsolated(ex, cancellationToken))
+ {
+ Log.Warning(LogCategory, $"Sequence {remoteId} could not be compared", ex);
+ if (link is not null) await _links.UpsertAsync(link with { Error = ex.Message }, cancellationToken).ConfigureAwait(false);
+ return;
+ }
+ var local = await LocalOfAsync(link, locals, cancellationToken).ConfigureAwait(false);
+ await ReconcileSafelyAsync(remote, Observe(link, remote.Server, dto), dto, local, locals, policy, cancellationToken).ConfigureAwait(false);
+ }
+
+ private async Task ReconcileSafelyAsync(ISyncRemote remote, SyncLink link, SequenceDto dto, Sequence? local, Dictionary? locals,
+ SyncPolicy policy, CancellationToken cancellationToken)
+ {
+ try
+ {
+ (link, local) = await ReconcileAsync(remote, link, dto, local, policy, cancellationToken).ConfigureAwait(false);
+ link = link with { Error = null };
+ if (local is not null && locals is not null) locals[local.Id] = local;
+ }
+ catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound)
+ {
+ // Deleted between the listing and the manifest: the next comparison forgets it.
+ Log.Info(LogCategory, $"{dto.DisplayTitle} vanished from the server during the comparison");
+ }
+ catch (Exception ex) when (IsIsolated(ex, cancellationToken))
+ {
+ // The archive is offline or busy, the server refused this sequence, or its project is unreadable: it is
+ // compared again next time and the other sequences go on.
+ Log.Warning(LogCategory, $"{dto.DisplayTitle} could not be synced", ex);
+ link = link with { Error = ex.Message };
+ }
+ await _links.UpsertAsync(link, cancellationToken).ConfigureAwait(false);
+ }
+
+ /// A failure that concerns one sequence; a lost session (401) or the caller's cancellation stops the whole comparison.
+ private static bool IsIsolated(Exception ex, CancellationToken cancellationToken) => ex switch
+ {
+ TitanoApiException api => api.Status != HttpStatusCode.Unauthorized,
+ OperationCanceledException => !cancellationToken.IsCancellationRequested,
+ _ => ex is HttpRequestException or JsonException or IOException or UnauthorizedAccessException or InvalidDataException or LeaseUnavailableException,
+ };
+
+ /// Compares originals and renders when either side's moved, then settles the settings; returns the updated link and local copy.
+ private async Task<(SyncLink Link, Sequence? Local)> ReconcileAsync(ISyncRemote remote, SyncLink link, SequenceDto dto, Sequence? local, SyncPolicy policy,
+ CancellationToken cancellationToken)
+ {
+ if (local is null)
+ {
+ // A cleared cache leaves nothing to open; a deleted local copy makes the sequence remote again.
+ if (link.ProxiesCached > 0 && !Proxies.Exists(link.Server, link.RemoteId)) link = link with { ProxiesCached = 0, ProxiesFramesVersion = null };
+ return (link.LocalId is null ? link : Unlinked(link), null);
+ }
+ SequenceManifest? manifest = null;
+ if (link.DiffLocalFrames != local.FramesVersion || link.DiffRemoteFrames != link.RemoteFramesVersion
+ || link.DiffLocalRenders != local.RenderedCount || link.DiffRemoteRenders != link.RenderCount)
+ {
+ manifest = await remote.GetManifestAsync(link.RemoteId, cancellationToken).ConfigureAwait(false);
+ var frames = await SequenceFrames.ListAsync(_db, local.Id, cancellationToken).ConfigureAwait(false);
+ // A frame flagged missing here counts as absent: downloading the originals restores it from the server.
+ var (missingRemote, missingLocal) = SyncRules.CompareOriginals(
+ [.. frames.Where(f => (f.Flags & FrameFlags.Missing) == 0).Select(f => f.Sha256)], [.. manifest.Frames.Select(f => f.Sha256)]);
+ link = await CompareExportsAsync(link, local, manifest.Renders, cancellationToken).ConfigureAwait(false) with
+ {
+ DiffLocalFrames = local.FramesVersion,
+ DiffRemoteFrames = manifest.FramesVersion,
+ RemoteFramesVersion = manifest.FramesVersion,
+ DiffLocalRenders = local.RenderedCount,
+ DiffRemoteRenders = manifest.Renders.Count,
+ MissingRemote = missingRemote,
+ MissingLocal = missingLocal,
+ };
+ }
+ (link, local) = await SettleSettingsAsync(remote, link, dto, local, manifest, policy, cancellationToken).ConfigureAwait(false);
+ return (link with { SyncedAt = DateTimeOffset.UtcNow }, local);
+ }
+
+ /// Renders each side lacks, by id (a render keeps its id on both sides); local renders whose file is gone cannot be sent.
+ private async Task CompareExportsAsync(SyncLink link, Sequence local, IReadOnlyList remoteRenders, CancellationToken cancellationToken)
+ {
+ var renders = await _db.Renders.ListBySequenceAsync(local.Id, cancellationToken).ConfigureAwait(false);
+ var archive = await _db.Archives.GetAsync(local.ArchiveId, cancellationToken).ConfigureAwait(false);
+ var here = renders.Select(r => r.Id).ToHashSet();
+ var there = remoteRenders.Select(r => r.Id).ToHashSet();
+ var toGet = remoteRenders.Where(r => !here.Contains(r.Id)).ToList();
+ var toSend = archive is null ? [] : renders.Where(r => !there.Contains(r.Id) && File.Exists(RenderFile(archive, r))).ToList();
+ return link with
+ {
+ ExportsToGet = toGet.Count,
+ ExportsToGetBytes = toGet.Sum(r => r.Bytes),
+ ExportsToSend = toSend.Count,
+ ExportsToSendBytes = toSend.Sum(r => r.Bytes),
+ };
+ }
+
+ private async Task<(SyncLink Link, Sequence Local)> SettleSettingsAsync(ISyncRemote remote, SyncLink link, SequenceDto dto, Sequence local,
+ SequenceManifest? manifest, SyncPolicy policy, CancellationToken cancellationToken)
+ {
+ var localChanged = link.BaseLocalSettings != local.SettingsVersion;
+ var remoteChanged = link.BaseRemoteSettings != link.RemoteSettingsVersion;
+ if (!localChanged && !remoteChanged) return (link, local);
+ if (localChanged && remoteChanged)
+ {
+ if (link.ConflictLocalSettings == local.SettingsVersion && link.ConflictRemoteSettings == link.RemoteSettingsVersion) return (link, local);
+ manifest ??= await remote.GetManifestAsync(link.RemoteId, cancellationToken).ConfigureAwait(false);
+ // The listing and the manifest disagree: the server changed during the comparison; settle it next time.
+ if (manifest.SettingsVersion != dto.SettingsVersion) return (link, local);
+ var mine = SyncPayload.Of(local);
+ var theirs = SyncPayload.Of(dto, manifest.SettingsJson);
+ if (mine.SameAs(theirs)) return (Agreed(link, local.SettingsVersion, manifest.SettingsVersion), local);
+ // Last writer wins only when one side changed; both changed differently is the user's choice (BRIEF §14.5).
+ return (link with
+ {
+ ConflictLocalSettings = local.SettingsVersion,
+ ConflictRemoteSettings = manifest.SettingsVersion,
+ ConflictRemote = theirs with { SettingsJson = SyncRules.NormalizeSettings(theirs.SettingsJson) },
+ }, local);
+ }
+ if (!policy.AutoSyncSettings) return (link, local);
+ if (localChanged)
+ return (policy.CanEdit ? await PushAsync(remote, link, local, link.BaseRemoteSettings, cancellationToken).ConfigureAwait(false) : link, local);
+ manifest ??= await remote.GetManifestAsync(link.RemoteId, cancellationToken).ConfigureAwait(false);
+ if (manifest.SettingsVersion != dto.SettingsVersion) return (link, local);
+ var pulled = await ApplyLocallyAsync(local, SyncPayload.Of(dto, manifest.SettingsJson), cancellationToken).ConfigureAwait(false);
+ return (Agreed(link, pulled.SettingsVersion, manifest.SettingsVersion), pulled);
+ }
+
+ /// Sends this PC's payload unless the server moved past , which shows up as a conflict next.
+ private static async Task PushAsync(ISyncRemote remote, SyncLink link, Sequence local, int? expected, CancellationToken cancellationToken)
+ {
+ try
+ {
+ var updated = await remote.UpdateSequenceAsync(link.RemoteId, SyncPayload.Of(local).ToRequest(expected), cancellationToken).ConfigureAwait(false);
+ return Agreed(Observe(link, link.Server, updated), local.SettingsVersion, updated.SettingsVersion);
+ }
+ catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.Conflict)
+ {
+ return Observe(link, link.Server, await remote.GetSequenceAsync(link.RemoteId, cancellationToken).ConfigureAwait(false));
+ }
+ }
+
+ ///
+ /// Links local copies and server sequences that hold the same originals but no link joins (an Uploader upload of
+ /// the same card, a link lost with an old index): candidates start at the same second with the same camera, and
+ /// at least half of the smaller side's originals must match by SHA-256. A pair that does not match is not fetched
+ /// again until either side's frames change.
+ ///
+ private async Task MatchByContentAsync(ISyncRemote remote, IReadOnlyList listing, Dictionary locals, SyncPolicy policy,
+ CancellationToken cancellationToken)
+ {
+ var links = await _links.ListAsync(remote.Server, cancellationToken).ConfigureAwait(false);
+ var linkedLocals = links.Where(l => l.LocalId is not null).Select(l => l.LocalId!.Value).ToHashSet();
+ var linkedRemotes = links.Where(l => l.LocalId is not null).Select(l => l.RemoteId).ToHashSet();
+ var candidates = listing.Where(d => !linkedRemotes.Contains(d.Id) && d.FrameCount > 0 && d.FirstCapture is not null)
+ .ToLookup(d => Second(d.FirstCapture!.Value));
+ foreach (var local in locals.Values.Where(l => !linkedLocals.Contains(l.Id) && l.FrameCount > 0 && l.FirstCapture is not null).ToList())
+ {
+ foreach (var dto in candidates[Second(local.FirstCapture!.Value)])
+ {
+ if (linkedRemotes.Contains(dto.Id) || !string.Equals(dto.CameraModel, local.CameraModel, StringComparison.OrdinalIgnoreCase)) continue;
+ var key = string.Create(CultureInfo.InvariantCulture, $"{local.Id:N}:{local.FramesVersion}:{dto.Id:N}:{dto.FramesVersion}");
+ if (_unmatched.ContainsKey(key)) continue;
+ try
+ {
+ if (!await SameOriginalsAsync(remote, local, dto, cancellationToken).ConfigureAwait(false))
+ {
+ _unmatched[key] = 0;
+ continue;
+ }
+ }
+ catch (Exception ex) when (IsIsolated(ex, cancellationToken))
+ {
+ Log.Warning(LogCategory, $"{local.DisplayTitle} could not be matched with {dto.DisplayTitle}", ex);
+ continue;
+ }
+ Log.Info(LogCategory, $"{local.DisplayTitle} holds the originals of {dto.DisplayTitle} on {remote.Server}: linked");
+ var link = links.FirstOrDefault(l => l.RemoteId == dto.Id);
+ var linked = Unlinked(Observe(link, remote.Server, dto)) with { LocalId = local.Id };
+ await ReconcileSafelyAsync(remote, linked, dto, local, locals, policy, cancellationToken).ConfigureAwait(false);
+ linkedRemotes.Add(dto.Id);
+ break;
+ }
+ }
+ }
+
+ private async Task SameOriginalsAsync(ISyncRemote remote, Sequence local, SequenceDto dto, CancellationToken cancellationToken)
+ {
+ var hashes = (await SequenceFrames.ListAsync(_db, local.Id, cancellationToken).ConfigureAwait(false))
+ .Select(f => f.Sha256?.ToLowerInvariant()).OfType().ToHashSet(StringComparer.Ordinal);
+ if (hashes.Count == 0) return false;
+ var manifest = await remote.GetManifestAsync(dto.Id, cancellationToken).ConfigureAwait(false);
+ var shared = manifest.Frames.Select(f => f.Sha256.ToLowerInvariant()).Distinct(StringComparer.Ordinal).Count(hashes.Contains);
+ return shared > 0 && shared * 2 >= Math.Min(hashes.Count, manifest.Frames.Count);
+ }
+
+ private static DateTime Second(DateTime time) => new(time.Ticks - time.Ticks % TimeSpan.TicksPerSecond, DateTimeKind.Unspecified);
+
+ /// Writes a payload into the local sidecar, project and index (each write bumps the local settings version).
+ private async Task ApplyLocallyAsync(Sequence local, SyncPayload payload, CancellationToken cancellationToken)
+ {
+ var current = local;
+ if (!payload.SameMetadata(SyncPayload.Of(local)))
+ current = await Archives.SetSequenceInfoAsync(local.Id, payload.Title, payload.Tags, payload.Rating, payload.Notes, cancellationToken).ConfigureAwait(false);
+ if (!SyncRules.SameSettings(payload.SettingsJson, current.SettingsJson))
+ {
+ var archive = await _db.Archives.GetAsync(current.ArchiveId, cancellationToken).ConfigureAwait(false)
+ ?? throw new InvalidDataException($"Archive {current.ArchiveId} is not indexed.");
+ var project = ProjectStore.Parse(SyncRules.NormalizeSettings(payload.SettingsJson));
+ await _projects.UpdateAsync(new ArchivePaths(archive.RootPath), current, _ => project, cancellationToken).ConfigureAwait(false);
+ }
+ return await _db.Sequences.GetAsync(local.Id, cancellationToken).ConfigureAwait(false) ?? current;
+ }
+
+ ///
+ /// "Save both": this PC's project is kept next to project.json as project.this-pc-<local time>.json
+ /// before the server's replaces it; returns that file.
+ ///
+ private async Task SaveCopyAsync(Sequence local, CancellationToken cancellationToken)
+ {
+ var archive = await _db.Archives.GetAsync(local.ArchiveId, cancellationToken).ConfigureAwait(false)
+ ?? throw new InvalidDataException($"Archive {local.ArchiveId} is not indexed.");
+ var folder = new ArchivePaths(archive.RootPath).Sequence(local.Folder);
+ Directory.CreateDirectory(folder.MetaDirectory);
+ var path = Path.Combine(folder.MetaDirectory, SavedCopyName(DateTime.Now));
+ AtomicFile.WriteAllText(path, SyncRules.NormalizeSettings(local.SettingsJson));
+ Log.Info(LogCategory, $"Settings of {local.DisplayTitle} kept as {path}");
+ return path;
+ }
+
+ internal static string SavedCopyName(DateTime localTime) => string.Create(CultureInfo.InvariantCulture, $"project.this-pc-{localTime:yyyyMMdd-HHmmss}.json");
+
+ private async Task ForgetAsync(SyncLink link, CancellationToken cancellationToken)
+ {
+ await _links.DeleteAsync(link.Server, link.RemoteId, cancellationToken).ConfigureAwait(false);
+ Proxies.Delete(link.Server, link.RemoteId);
+ Log.Info(LogCategory, $"{link.Title} is no longer on {link.Server}");
+ }
+
+ /// Writes each local sequence's state for the Library and returns the table.
+ private async Task> StoreStatesAsync(string server, Dictionary? locals, CancellationToken cancellationToken)
+ {
+ var entries = await EntriesAsync(server, locals, cancellationToken).ConfigureAwait(false);
+ foreach (var entry in entries)
+ {
+ if (entry.Local is { } local && SyncRules.ToSequenceState(entry.Status) is { } state && state != local.SyncState)
+ await _links.SetLocalStateAsync(local.Id, state, cancellationToken).ConfigureAwait(false);
+ }
+ return entries;
+ }
+
+ /// The table from the stored links and local sequences (read from the index when null).
+ private async Task> EntriesAsync(string server, Dictionary? known, CancellationToken cancellationToken)
+ {
+ var links = await _links.ListAsync(server, cancellationToken).ConfigureAwait(false);
+ var locals = known is null ? await LocalSequencesAsync(cancellationToken).ConfigureAwait(false) : new Dictionary(known);
+ var transfers = await _links.ActiveTransfersAsync(cancellationToken).ConfigureAwait(false);
+ var entries = new List(links.Count + locals.Count);
+ foreach (var link in links)
+ {
+ var local = await LocalOfAsync(link, locals, cancellationToken).ConfigureAwait(false);
+ if (local is not null) locals.Remove(local.Id);
+ var transfer = Pick(local is null ? null : transfers.GetValueOrDefault(local.Id), transfers.GetValueOrDefault(link.RemoteId));
+ entries.Add(new SyncEntry(local, link, transfer is null ? SyncRules.Status(local, link) : SyncStatus.Transferring, transfer));
+ }
+ foreach (var local in locals.Values)
+ {
+ var transfer = Pick(transfers.GetValueOrDefault(local.Id), null);
+ entries.Add(new SyncEntry(local, null, transfer is null ? SyncStatus.LocalOnly : SyncStatus.Transferring, transfer));
+ }
+ return [.. entries.OrderBy(e => e.Status switch { SyncStatus.Conflict => 0, SyncStatus.Transferring => 1, _ => 2 })
+ .ThenBy(e => e.Title, StringComparer.CurrentCultureIgnoreCase)];
+ }
+
+ /// The transfer a row shows: the user's before background ones, originals before renders before proxies, running before waiting.
+ private static Job? Pick(IReadOnlyList? local, IReadOnlyList? remote) =>
+ (local ?? []).Concat(remote ?? [])
+ .OrderByDescending(j => j.Priority)
+ .ThenBy(j => TransferKind(j) switch
+ {
+ SyncTransferKind.DownloadProxies => 2,
+ SyncTransferKind.SendExports or SyncTransferKind.GetExports => 1,
+ _ => 0,
+ })
+ .ThenBy(j => j.State == JobState.Running ? 0 : 1)
+ .FirstOrDefault();
+
+ /// The local copy of a link: from , or the index when the paged listing missed it.
+ private async Task LocalOfAsync(SyncLink? link, Dictionary? locals, CancellationToken cancellationToken)
+ {
+ if (link?.LocalId is not { } id) return null;
+ if (locals is not null && locals.TryGetValue(id, out var known)) return known;
+ return await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false);
+ }
+
+ private async Task<(SyncLink Link, Sequence Local)> LinkedAsync(string server, Guid remoteId, CancellationToken cancellationToken)
+ {
+ var link = await _links.GetAsync(server, remoteId, cancellationToken).ConfigureAwait(false);
+ var local = link?.LocalId is { } id ? await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false) : null;
+ if (link is null || local is null) throw new InvalidOperationException($"Sequence {remoteId} has no local copy.");
+ return (link, local);
+ }
+
+ private async Task> LocalSequencesAsync(CancellationToken cancellationToken)
+ {
+ var all = new Dictionary();
+ string? cursor = null;
+ do
+ {
+ var page = await _db.Sequences.ListAsync(new SequenceQuery { Limit = 1000, Cursor = cursor, Sort = SequenceSort.Oldest }, cancellationToken)
+ .ConfigureAwait(false);
+ foreach (var s in page.Items) all[s.Id] = s;
+ cursor = page.NextCursor;
+ }
+ while (cursor is not null);
+ return all;
+ }
+
+ private async Task EnqueueAsync(JobEngine engine, JobKind kind, Guid target, string label, SyncJobParameters parameters, JobPriority priority,
+ CancellationToken cancellationToken)
+ {
+ var wanted = parameters.Kind(kind);
+ var active = (await _links.ActiveTransfersAsync(cancellationToken).ConfigureAwait(false)).GetValueOrDefault(target) ?? [];
+ foreach (var job in active)
+ {
+ var running = TransferKind(job);
+ var outranked = running == SyncTransferKind.DownloadProxies && job.Priority < priority;
+ if (running == wanted && !outranked) return job;
+ if (outranked && wanted is SyncTransferKind.DownloadProxies or SyncTransferKind.DownloadOriginals)
+ await engine.CancelAsync(job.Id, cancellationToken).ConfigureAwait(false);
+ }
+ return await engine.EnqueueAsync(kind, [target], label, JsonSerializer.Serialize(parameters, SyncJobJson.Default.SyncJobParameters), priority,
+ cancellationToken: cancellationToken).ConfigureAwait(false);
+ }
+
+ /// The link with the server's side as lists it (a new link when there was none).
+ internal static SyncLink Observe(SyncLink? link, string server, SequenceDto dto) =>
+ (link ?? new SyncLink { Server = server, RemoteId = dto.Id, Title = dto.DisplayTitle }) with
+ {
+ Title = dto.DisplayTitle,
+ FrameCount = dto.FrameCount,
+ TotalBytes = dto.TotalBytes,
+ RenderCount = dto.RenderedCount,
+ RemoteStatus = (SequenceStatus)dto.Status,
+ RemoteSettingsVersion = dto.SettingsVersion,
+ RemoteFramesVersion = dto.FramesVersion,
+ RemoteUpdatedAt = dto.UpdatedAt,
+ };
+
+ private static SyncLink Agreed(SyncLink link, int localVersion, int remoteVersion) => link with
+ {
+ BaseLocalSettings = localVersion,
+ BaseRemoteSettings = remoteVersion,
+ RemoteSettingsVersion = remoteVersion,
+ ConflictLocalSettings = null,
+ ConflictRemoteSettings = null,
+ ConflictRemote = null,
+ };
+
+ private static SyncLink Unlinked(SyncLink link) => link with
+ {
+ LocalId = null,
+ BaseLocalSettings = null,
+ BaseRemoteSettings = null,
+ DiffLocalFrames = null,
+ DiffRemoteFrames = null,
+ DiffLocalRenders = null,
+ DiffRemoteRenders = null,
+ MissingRemote = 0,
+ MissingLocal = 0,
+ ExportsToGet = 0,
+ ExportsToGetBytes = 0,
+ ExportsToSend = 0,
+ ExportsToSendBytes = 0,
+ ConflictLocalSettings = null,
+ ConflictRemoteSettings = null,
+ ConflictRemote = null,
+ };
+}
diff --git a/src/Titano.Data/Sync/SyncTransfers.cs b/src/Titano.Data/Sync/SyncTransfers.cs
new file mode 100644
index 00000000..3fb1fa6b
--- /dev/null
+++ b/src/Titano.Data/Sync/SyncTransfers.cs
@@ -0,0 +1,523 @@
+using System.Globalization;
+using System.Net;
+using Titano.Core.Archiving;
+using Titano.Core.Localization;
+using Titano.Core.Model;
+using Titano.Data.Archiving;
+using Titano.Data.Archiving.Jobs;
+using Titano.Data.Jobs;
+using Titano.Data.Processing;
+using Titano.Protocol;
+using Titano.Protocol.Client;
+using SequenceFrames = Titano.Data.Processing.SequenceFrames;
+
+namespace Titano.Data.Sync;
+
+///
+/// The work of upload and download jobs. Uploads send every local original the server lacks through the chunked,
+/// resumable protocol after hashing it again (an original that no longer matches its archived hash is never sent),
+/// creating the server sequence first and sending its settings when the upload made it. Downloads fetch originals the
+/// local copy lacks into the archive's staging folder (resuming with Range), require the manifest's SHA-256 and commit
+/// them through the archive ingest, which names them and writes the sidecar; the first original creates the local
+/// sequence, which then takes the server's settings. Frames of the local copy not hashed yet are hashed first (so the
+/// server's copies of them are recognised), and originals flagged missing here are restored to their recorded place.
+/// Proxy downloads fill the proxy cache. Renders travel on request: this PC's to the server (hash-verified chunked
+/// upload) and the server's into the local copy's exports. A resumed job skips what is already on the other side, so
+/// pausing or a crash loses at most the files in flight.
+///
+internal sealed class SyncTransfers(SyncService sync)
+{
+ private const long SpaceReserve = 512L << 20;
+
+ /// Space a cached proxy is assumed to take before it is downloaded (1920 px JPEG, BRIEF §8.5).
+ private const long ProxyEstimate = 3L << 19;
+
+ public async Task UploadAsync(JobContext context, ISyncRemote remote, Guid localId)
+ {
+ var ct = context.Cancellation;
+ var db = sync.Database;
+ var local = await db.Sequences.GetAsync(localId, ct).ConfigureAwait(false) ?? throw new InvalidOperationException(Loc.L("Errors.Sync.LocalMissing"));
+ var archive = await db.Archives.GetAsync(local.ArchiveId, ct).ConfigureAwait(false) ?? throw new InvalidOperationException(Loc.L("Errors.Sync.NoArchive"));
+ var paths = new ArchivePaths(archive.RootPath);
+ var (remoteId, created) = await TargetAsync(context, remote, local).ConfigureAwait(false);
+
+ var frames = (await SequenceFrames.ListAsync(db, local.Id, ct).ConfigureAwait(false)).Where(f => (f.Flags & FrameFlags.Missing) == 0).ToList();
+ var present = remoteId is { } known
+ ? (await remote.GetManifestAsync(known, ct).ConfigureAwait(false)).Frames.Select(f => f.Sha256.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal)
+ : [];
+ var pending = new Queue(frames.Where(f => f.Sha256 is null || !present.Contains(f.Sha256.ToLowerInvariant())));
+ var progress = new TransferProgress(context, frames.Count, frames.Count - pending.Count);
+ await progress.ReportAsync().ConfigureAwait(false);
+ var skipped = 0;
+
+ // Without a server sequence the originals go out one by one under this sequence's session key until the
+ // server has filed one, which creates the sequence (an original it already holds elsewhere creates nothing).
+ while (remoteId is null && pending.TryDequeue(out var first))
+ {
+ var sent = await UploadFrameAsync(context, remote, null, SyncService.SessionKey(local.Id), paths.FromRelative(first.RelativePath), first, ct)
+ .ConfigureAwait(false);
+ if (sent is null) skipped++;
+ else if (sent.SequenceId != Guid.Empty)
+ {
+ remoteId = sent.SequenceId;
+ await context.CheckpointAsync(sent.SequenceId.ToString(), progress.Done + 1, frames.Count).ConfigureAwait(false);
+ await sync.LinkAsync(remote.Server, sent.SequenceId, local, ct).ConfigureAwait(false);
+ }
+ await progress.StepAsync().ConfigureAwait(false);
+ }
+ if (remoteId is not { } target) throw new InvalidOperationException(Loc.L("Errors.Sync.NothingSent"));
+
+ await Parallel.ForEachAsync(pending, Workers(sync.Options.Uploads, ct), async (frame, token) =>
+ {
+ if (await UploadFrameAsync(context, remote, target, null, paths.FromRelative(frame.RelativePath), frame, token).ConfigureAwait(false) is null)
+ Interlocked.Increment(ref skipped);
+ await progress.StepAsync().ConfigureAwait(false);
+ }).ConfigureAwait(false);
+
+ if (created) await sync.PushAllAsync(remote, target, ct).ConfigureAwait(false);
+ await sync.RecompareAsync(remote, target, ct).ConfigureAwait(false);
+ if (skipped > 0) throw new InvalidDataException(Loc.Plural("Errors.Sync.Unreadable", skipped));
+ }
+
+ public async Task DownloadOriginalsAsync(JobContext context, ISyncRemote remote, Guid remoteId, Guid? targetArchive)
+ {
+ var ct = context.Cancellation;
+ var db = sync.Database;
+ var link = await sync.Links.GetAsync(remote.Server, remoteId, ct).ConfigureAwait(false);
+ var local = link?.LocalId is { } id ? await db.Sequences.GetAsync(id, ct).ConfigureAwait(false) : null;
+ var archive = (local?.ArchiveId ?? targetArchive) is { } archiveId ? await db.Archives.GetAsync(archiveId, ct).ConfigureAwait(false) : null;
+ if (archive is null) throw new InvalidOperationException(Loc.L("Errors.Sync.NoArchive"));
+ var paths = new ArchivePaths(archive.RootPath);
+ ArchiveVolume.EnsureWritable(paths);
+
+ var manifest = await remote.GetManifestAsync(remoteId, ct).ConfigureAwait(false);
+ var captured = (await remote.ListFramesAsync(remoteId, ct).ConfigureAwait(false)).ToDictionary(f => f.Id, f => f.CapturedAt);
+ var (have, restore) = local is null ? ([], []) : await LocalContentAsync(archive, local, ct).ConfigureAwait(false);
+ var wanted = manifest.Frames.Where(f => !have.Contains(f.Sha256.ToLowerInvariant())).DistinctBy(f => f.Sha256.ToLowerInvariant()).ToList();
+ EnsureSpace(paths.Root, wanted.Sum(f => f.Size));
+
+ var staging = Path.Combine(paths.StagingDirectory, "sync-" + remoteId.ToString("N"));
+ Directory.CreateDirectory(staging);
+ var progress = new TransferProgress(context, manifest.Frames.Count, manifest.Frames.Count - wanted.Count);
+ await progress.ReportAsync().ConfigureAwait(false);
+ var created = false;
+ var rest = wanted;
+ if (local is null && wanted.Count > 0)
+ {
+ // The first original creates the local sequence (grouped by the server id); the others join it.
+ var first = await CommitAsync(remote, remoteId, archive.Id, null, wanted[0], staging, captured, ct).ConfigureAwait(false);
+ local = await db.Sequences.GetAsync(first.SequenceId, ct).ConfigureAwait(false)
+ ?? throw new InvalidOperationException(Loc.L("Errors.Sync.LocalMissing"));
+ await sync.LinkAsync(remote.Server, remoteId, local, ct).ConfigureAwait(false);
+ await sync.Links.SetOriginAsync(local.Id, SequenceOrigin.Server, ct).ConfigureAwait(false);
+ created = true;
+ rest = wanted.GetRange(1, wanted.Count - 1);
+ await progress.StepAsync().ConfigureAwait(false);
+ }
+ var sequenceId = local?.Id;
+ var restored = 0;
+ await Parallel.ForEachAsync(rest, Workers(sync.Options.Downloads, ct), async (frame, token) =>
+ {
+ if (restore.TryGetValue(frame.Sha256.ToLowerInvariant(), out var place))
+ {
+ await RestoreAsync(remote, frame, staging, place, token).ConfigureAwait(false);
+ Interlocked.Increment(ref restored);
+ }
+ else
+ {
+ await CommitAsync(remote, remoteId, archive.Id, sequenceId, frame, staging, captured, token).ConfigureAwait(false);
+ }
+ await progress.StepAsync().ConfigureAwait(false);
+ }).ConfigureAwait(false);
+ TryDeleteDirectory(staging);
+ // Restored originals are checked against their records, which clears their missing flag.
+ if (restored > 0) await VerifyAsync(archive, local!.Id, ct).ConfigureAwait(false);
+
+ if (created) await sync.TakeAllAsync(remote, remoteId, ct).ConfigureAwait(false);
+ await sync.RecompareAsync(remote, remoteId, ct).ConfigureAwait(false);
+ if (sequenceId is { } downloaded && wanted.Count > restored)
+ {
+ var label = local!.DisplayTitle;
+ await EnqueueFollowUpAsync(ArchiveJobs.Thumbnails([downloaded], label), ct).ConfigureAwait(false);
+ await EnqueueFollowUpAsync(ProcessingJobs.LightAnalysis([downloaded], label), ct).ConfigureAwait(false);
+ }
+ }
+
+ ///
+ /// The originals a local copy holds (lower-case SHA-256) and where each original flagged missing belongs. Frames
+ /// not hashed yet (an adopted folder never verified) are hashed first through the archive's verify, so the
+ /// server's copies of them are recognised instead of committed again as duplicates.
+ ///
+ private async Task<(HashSet Have, Dictionary Restore)> LocalContentAsync(Archive archive, Sequence local, CancellationToken ct)
+ {
+ var frames = await SequenceFrames.ListAsync(sync.Database, local.Id, ct).ConfigureAwait(false);
+ if (frames.Any(f => f.Sha256 is null && (f.Flags & FrameFlags.Missing) == 0))
+ {
+ await VerifyAsync(archive, local.Id, ct).ConfigureAwait(false);
+ frames = await SequenceFrames.ListAsync(sync.Database, local.Id, ct).ConfigureAwait(false);
+ }
+ var have = frames.Where(f => (f.Flags & FrameFlags.Missing) == 0 && f.Sha256 is not null).Select(f => f.Sha256!.ToLowerInvariant())
+ .ToHashSet(StringComparer.Ordinal);
+ var paths = new ArchivePaths(archive.RootPath);
+ var restore = new Dictionary(StringComparer.Ordinal);
+ foreach (var frame in frames.Where(f => (f.Flags & FrameFlags.Missing) != 0 && f.Sha256 is not null))
+ {
+ var sha = frame.Sha256!.ToLowerInvariant();
+ if (!have.Contains(sha)) restore.TryAdd(sha, paths.FromRelative(frame.RelativePath));
+ }
+ return (have, restore);
+ }
+
+ private Task VerifyAsync(Archive archive, Guid sequenceId, CancellationToken ct) =>
+ sync.Archives.Verifier.VerifyAsync(archive, [sequenceId], default, (_, _, _) => ValueTask.CompletedTask, cancellationToken: ct);
+
+ /// Puts a verified copy of an original flagged missing back where its record says; a file that reappeared meanwhile is kept.
+ private static async Task RestoreAsync(ISyncRemote remote, ManifestFrame frame, string staging, string place, CancellationToken cancellationToken)
+ {
+ var staged = await FetchOriginalAsync(remote, frame, staging, cancellationToken).ConfigureAwait(false);
+ if (File.Exists(place))
+ {
+ File.Delete(staged);
+ return;
+ }
+ Directory.CreateDirectory(Path.GetDirectoryName(place)!);
+ File.Move(staged, place, overwrite: false);
+ }
+
+ public async Task SendExportsAsync(JobContext context, ISyncRemote remote, Guid localId)
+ {
+ var ct = context.Cancellation;
+ var db = sync.Database;
+ var local = await db.Sequences.GetAsync(localId, ct).ConfigureAwait(false) ?? throw new InvalidOperationException(Loc.L("Errors.Sync.LocalMissing"));
+ var archive = await db.Archives.GetAsync(local.ArchiveId, ct).ConfigureAwait(false) ?? throw new InvalidOperationException(Loc.L("Errors.Sync.NoArchive"));
+ var link = await sync.Links.FindByLocalAsync(remote.Server, local.Id, ct).ConfigureAwait(false)
+ ?? throw new InvalidOperationException(Loc.L("Errors.Sync.NotLinked"));
+ var there = (await remote.GetManifestAsync(link.RemoteId, ct).ConfigureAwait(false)).Renders.Select(r => r.Id).ToHashSet();
+ var renders = (await db.Renders.ListBySequenceAsync(local.Id, ct).ConfigureAwait(false)).Where(r => !there.Contains(r.Id)).ToList();
+ var progress = new TransferProgress(context, renders.Count, 0);
+ await progress.ReportAsync().ConfigureAwait(false);
+ var gone = 0;
+ foreach (var render in renders)
+ {
+ var file = SyncService.RenderFile(archive, render);
+ if (File.Exists(file))
+ {
+ var sha = await TitanoClient.HashFileAsync(file, ct).ConfigureAwait(false);
+ await remote.UploadRenderAsync(link.RemoteId, file, new RenderUploadRequest(render.Id, Path.GetFileName(file), new FileInfo(file).Length, sha,
+ render.PresetName, render.Codec, render.Width, render.Height, render.Fps, render.DurationSeconds, render.ProducedBy), ct).ConfigureAwait(false);
+ }
+ else
+ {
+ gone++;
+ }
+ await progress.StepAsync().ConfigureAwait(false);
+ }
+ await sync.RecompareAsync(remote, link.RemoteId, ct).ConfigureAwait(false);
+ if (gone > 0) throw new FileNotFoundException(Loc.Plural("Errors.Sync.ExportsGone", gone));
+ }
+
+ public async Task GetExportsAsync(JobContext context, ISyncRemote remote, Guid remoteId)
+ {
+ var ct = context.Cancellation;
+ var db = sync.Database;
+ var link = await sync.Links.GetAsync(remote.Server, remoteId, ct).ConfigureAwait(false);
+ var local = (link?.LocalId is { } id ? await db.Sequences.GetAsync(id, ct).ConfigureAwait(false) : null)
+ ?? throw new InvalidOperationException(Loc.L("Errors.Sync.LocalMissing"));
+ var archive = await db.Archives.GetAsync(local.ArchiveId, ct).ConfigureAwait(false) ?? throw new InvalidOperationException(Loc.L("Errors.Sync.NoArchive"));
+ var paths = new ArchivePaths(archive.RootPath);
+ ArchiveVolume.EnsureWritable(paths);
+ var here = (await db.Renders.ListBySequenceAsync(local.Id, ct).ConfigureAwait(false)).Select(r => r.Id).ToHashSet();
+ var wanted = (await remote.GetManifestAsync(remoteId, ct).ConfigureAwait(false)).Renders.Where(r => !here.Contains(r.Id)).ToList();
+ EnsureSpace(paths.Root, wanted.Sum(r => r.Bytes));
+
+ var staging = Path.Combine(paths.StagingDirectory, "exports-" + remoteId.ToString("N"));
+ var exports = paths.Sequence(local.Folder).Exports;
+ Directory.CreateDirectory(staging);
+ Directory.CreateDirectory(exports);
+ var progress = new TransferProgress(context, wanted.Count, 0);
+ await progress.ReportAsync().ConfigureAwait(false);
+ foreach (var render in wanted)
+ {
+ var (part, name) = await FetchRenderAsync(remote, render, staging, ct).ConfigureAwait(false);
+ var target = Unique(exports, name);
+ File.Move(part, target);
+ await db.Renders.InsertAsync(new Render
+ {
+ Id = render.Id,
+ SequenceId = local.Id,
+ PresetName = render.PresetName,
+ OutputPath = paths.ToRelative(target),
+ Codec = render.Codec,
+ Width = render.Width,
+ Height = render.Height,
+ Fps = render.Fps,
+ DurationSeconds = render.DurationSeconds,
+ Bytes = new FileInfo(target).Length,
+ Created = render.Created,
+ ProducedBy = render.ProducedBy,
+ }, ct).ConfigureAwait(false);
+ await progress.StepAsync().ConfigureAwait(false);
+ }
+ TryDeleteDirectory(staging);
+ await sync.RecompareAsync(remote, remoteId, ct).ConfigureAwait(false);
+ }
+
+ /// A render's file in staging (resumed with Range; started over once if the partial copy no longer fits) and the name the server gives it.
+ private static async Task<(string Part, string Name)> FetchRenderAsync(ISyncRemote remote, RenderDto render, string staging, CancellationToken cancellationToken)
+ {
+ var part = Path.Combine(staging, render.Id.ToString("N") + ".part");
+ for (var attempt = 1; ; attempt++)
+ {
+ try
+ {
+ string? name;
+ await using (var file = new FileStream(part, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
+ name = await remote.DownloadRenderAsync(render.Id, file, cancellationToken).ConfigureAwait(false);
+ return (part, SafeFileName(name) ?? render.Id.ToString("N"));
+ }
+ catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.RequestedRangeNotSatisfiable && attempt == 1)
+ {
+ File.Delete(part);
+ }
+ }
+ }
+
+ private static string? SafeFileName(string? name)
+ {
+ var file = Path.GetFileName(name?.Trim());
+ return string.IsNullOrEmpty(file) || file.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || file is "." or ".." ? null : file;
+ }
+
+ /// "name.mp4", else "name (2).mp4", … — an existing export is never replaced.
+ private static string Unique(string folder, string fileName)
+ {
+ var candidate = Path.Combine(folder, fileName);
+ var stem = Path.GetFileNameWithoutExtension(fileName);
+ var extension = Path.GetExtension(fileName);
+ for (var n = 2; File.Exists(candidate); n++) candidate = Path.Combine(folder, string.Create(CultureInfo.InvariantCulture, $"{stem} ({n}){extension}"));
+ return candidate;
+ }
+
+ public async Task DownloadProxiesAsync(JobContext context, ISyncRemote remote, Guid remoteId)
+ {
+ var ct = context.Cancellation;
+ var dto = await remote.GetSequenceAsync(remoteId, ct).ConfigureAwait(false);
+ var manifest = await remote.GetManifestAsync(remoteId, ct).ConfigureAwait(false);
+ var frames = await remote.ListFramesAsync(remoteId, ct).ConfigureAwait(false);
+ var assets = manifest.Frames.ToDictionary(f => f.Id);
+ var folder = sync.Proxies.Folder(remote.Server, remoteId);
+ Directory.CreateDirectory(folder);
+ ProxyCache.Prune(folder, frames.Select(f => ProxyCache.FileName(f.Id)).ToHashSet(StringComparer.Ordinal));
+ EnsureSpace(folder, frames.Count(f => !File.Exists(Path.Combine(folder, ProxyCache.FileName(f.Id)))) * ProxyEstimate);
+
+ var files = new string?[frames.Count];
+ var progress = new TransferProgress(context, frames.Count, 0);
+ await progress.ReportAsync().ConfigureAwait(false);
+ await Parallel.ForEachAsync(Enumerable.Range(0, frames.Count), Workers(sync.Options.Downloads, ct), async (i, token) =>
+ {
+ IReadOnlyList kinds = assets.TryGetValue(frames[i].Id, out var asset) ? Kinds(asset) : [];
+ files[i] = await FetchProxyAsync(remote, frames[i].Id, kinds, folder, token).ConfigureAwait(false);
+ await progress.StepAsync().ConfigureAwait(false);
+ }).ConfigureAwait(false);
+
+ sync.Proxies.Save(remote.Server, remoteId, new ProxyCacheIndex(dto, manifest.SettingsJson, manifest.FramesVersion, frames, files));
+ var cached = files.Count(f => f is not null);
+ await sync.SetProxiesAsync(remote.Server, dto, cached, manifest.FramesVersion, ct).ConfigureAwait(false);
+ if (cached < frames.Count) context.Log($"{frames.Count - cached} frame(s) have neither proxy nor thumbnail on the server");
+ }
+
+ ///
+ /// The server sequence an upload fills and whether this job creates it: the linked one, the one an interrupted
+ /// attempt created, or none yet (the first original creates it).
+ ///
+ private async Task<(Guid? RemoteId, bool Created)> TargetAsync(JobContext context, ISyncRemote remote, Sequence local)
+ {
+ var ct = context.Cancellation;
+ Guid? started = Guid.TryParse(context.Checkpoint, out var saved) ? saved : null;
+ var link = await sync.Links.FindByLocalAsync(remote.Server, local.Id, ct).ConfigureAwait(false);
+ foreach (var candidate in new[] { link?.RemoteId, started })
+ {
+ if (candidate is not { } id) continue;
+ if (await ExistsAsync(remote, id, ct).ConfigureAwait(false))
+ {
+ if (link?.RemoteId != id) await sync.LinkAsync(remote.Server, id, local, ct).ConfigureAwait(false);
+ return (id, id == started);
+ }
+ // Deleted on the server meanwhile: the originals go into a new sequence.
+ if (id == link?.RemoteId) await sync.ForgetGoneAsync(remote.Server, id, ct).ConfigureAwait(false);
+ }
+ return (null, true);
+ }
+
+ private static async Task ExistsAsync(ISyncRemote remote, Guid id, CancellationToken cancellationToken)
+ {
+ try
+ {
+ await remote.GetSequenceAsync(id, cancellationToken).ConfigureAwait(false);
+ return true;
+ }
+ catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound)
+ {
+ return false;
+ }
+ }
+
+ ///
+ /// Hashes the original again and sends it into (or the sequence of
+ /// ); null (logged) when it is gone or no longer the archived file.
+ ///
+ private static async Task UploadFrameAsync(JobContext context, ISyncRemote remote, Guid? sequenceId, string? sessionKey, string path,
+ Frame frame, CancellationToken cancellationToken)
+ {
+ if (!File.Exists(path))
+ {
+ context.Log($"{frame.FileName}: missing, not uploaded");
+ return null;
+ }
+ var sha = await TitanoClient.HashFileAsync(path, cancellationToken).ConfigureAwait(false);
+ if (frame.Sha256 is { } archived && !archived.Equals(sha, StringComparison.OrdinalIgnoreCase))
+ {
+ context.Log($"{frame.FileName}: changed since it was archived, not uploaded");
+ return null;
+ }
+ return await remote.UploadFileAsync(path, sequenceId, sessionKey, sha, frame.CapturedAt, cancellationToken).ConfigureAwait(false)
+ ?? new CompleteUploadResponse(Guid.Empty, sequenceId ?? Guid.Empty, -1);
+ }
+
+ /// Downloads one original into staging and commits it into the local sequence (created from the server id when null).
+ private async Task CommitAsync(ISyncRemote remote, Guid remoteId, Guid archiveId, Guid? sequenceId, ManifestFrame frame, string staging,
+ IReadOnlyDictionary captured, CancellationToken cancellationToken)
+ {
+ var staged = await FetchOriginalAsync(remote, frame, staging, cancellationToken).ConfigureAwait(false);
+ var request = new IngestRequest(archiveId, sequenceId, null, sequenceId is null ? SyncService.SessionKey(remoteId) : null, staged, frame.FileName,
+ frame.Size, frame.Sha256.ToLowerInvariant(), captured.GetValueOrDefault(frame.Id), null);
+ var result = await sync.Archives.Ingest.CommitAsync(request, cancellationToken).ConfigureAwait(false);
+ // A duplicate stays in staging (the sequence already holds that content).
+ if (result.Duplicate) File.Delete(staged);
+ return result;
+ }
+
+ /// A verified copy in staging: resumed from a partial download, accepted only with the manifest's SHA-256 (two attempts).
+ private static async Task FetchOriginalAsync(ISyncRemote remote, ManifestFrame frame, string staging, CancellationToken cancellationToken)
+ {
+ var sha = frame.Sha256.ToLowerInvariant();
+ if (sha.Length != 64 || !sha.All(char.IsAsciiHexDigitLower)) throw new InvalidDataException(Loc.L("Errors.Sync.Hash", frame.FileName));
+ var target = Path.Combine(staging, sha + Path.GetExtension(frame.FileName).ToLowerInvariant());
+ if (File.Exists(target)) return target;
+ var part = target + ".part";
+ for (var attempt = 1; ; attempt++)
+ {
+ await using (var file = new FileStream(part, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
+ await remote.DownloadFrameAsync(frame.Id, "original", file, cancellationToken).ConfigureAwait(false);
+ if (await TitanoClient.HashFileAsync(part, cancellationToken).ConfigureAwait(false) == sha)
+ {
+ File.Move(part, target, overwrite: true);
+ return target;
+ }
+ File.Delete(part);
+ if (attempt == 2) throw new InvalidDataException(Loc.L("Errors.Sync.Hash", frame.FileName));
+ }
+ }
+
+ /// The cached proxy's file name, downloading the first asset kind the server has; null when it has none.
+ private static async Task FetchProxyAsync(ISyncRemote remote, Guid frameId, IReadOnlyList kinds, string folder, CancellationToken cancellationToken)
+ {
+ var name = ProxyCache.FileName(frameId);
+ var path = Path.Combine(folder, name);
+ if (new FileInfo(path) is { Exists: true, Length: > 0 }) return name;
+ var part = path + ".part";
+ foreach (var kind in kinds)
+ {
+ try
+ {
+ await using (var file = new FileStream(part, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
+ await remote.DownloadFrameAsync(frameId, kind, file, cancellationToken).ConfigureAwait(false);
+ File.Move(part, path, overwrite: true);
+ return name;
+ }
+ catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound)
+ {
+ File.Delete(part);
+ }
+ }
+ return null;
+ }
+
+ private static string[] Kinds(ManifestFrame frame) => (frame.HasProxy, frame.HasThumb) switch
+ {
+ (true, true) => ["proxy", "thumb"],
+ (true, false) => ["proxy"],
+ (false, true) => ["thumb"],
+ _ => [],
+ };
+
+ /// Puts a follow-up job in the queue; the engine claims it on its next poll.
+ private Task EnqueueFollowUpAsync(ArchiveJobRequest request, CancellationToken cancellationToken) =>
+ sync.Database.Jobs.EnqueueAsync(new Job
+ {
+ Id = Guid.CreateVersion7(),
+ Kind = request.Kind,
+ TargetIds = request.Targets,
+ TargetLabel = request.Label,
+ ParametersJson = request.ParametersJson,
+ Priority = request.Priority,
+ State = JobState.Queued,
+ Created = DateTimeOffset.UtcNow,
+ }, cancellationToken);
+
+ private static void EnsureSpace(string root, long bytes)
+ {
+ long? free;
+ try
+ {
+ var full = Path.GetFullPath(root);
+ // Windows wants a drive root; Unix accepts any directory and reports the volume it is mounted on.
+ free = new DriveInfo(OperatingSystem.IsWindows() ? Path.GetPathRoot(full)! : full).AvailableFreeSpace;
+ }
+ catch (Exception ex) when (ex is ArgumentException or IOException or UnauthorizedAccessException)
+ {
+ free = null; // network shares: the copy itself reports a full disk
+ }
+ if (free is { } available && available < bytes + SpaceReserve)
+ throw new IOException(Loc.L("Errors.Sync.DiskFull", ((bytes + SpaceReserve - available) / 1e9).ToString("0.0", CultureInfo.CurrentCulture)));
+ }
+
+ private static void TryDeleteDirectory(string folder)
+ {
+ try
+ {
+ Directory.Delete(folder, recursive: true);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Core.Diagnostics.Log.Warning("sync", $"Staging folder {folder} could not be removed", ex);
+ }
+ }
+
+ private static ParallelOptions Workers(int degree, CancellationToken cancellationToken) =>
+ new() { MaxDegreeOfParallelism = Math.Max(1, degree), CancellationToken = cancellationToken };
+
+ /// Files done out of the total, reported in order from parallel workers.
+ private sealed class TransferProgress(JobContext context, long total, long done)
+ {
+ private readonly SemaphoreSlim _gate = new(1, 1);
+
+ public async Task StepAsync()
+ {
+ await _gate.WaitAsync(CancellationToken.None).ConfigureAwait(false);
+ try
+ {
+ done++;
+ await context.ReportAsync(done, total).ConfigureAwait(false);
+ }
+ finally
+ {
+ _gate.Release();
+ }
+ }
+
+ public long Done => done;
+
+ public ValueTask ReportAsync() => context.ReportAsync(done, total);
+ }
+}
diff --git a/src/Titano.Protocol/Client/TitanoClient.cs b/src/Titano.Protocol/Client/TitanoClient.cs
index d843ca82..96fe88a8 100644
--- a/src/Titano.Protocol/Client/TitanoClient.cs
+++ b/src/Titano.Protocol/Client/TitanoClient.cs
@@ -175,6 +175,46 @@ public sealed class TitanoClient : IDisposable
.ConfigureAwait(false);
}
+ ///
+ /// Sends a render of made on this PC in resumable chunks; the server verifies the
+ /// SHA-256 in and files it under the sequence's exports with the same id. Null when the
+ /// server already has that render.
+ ///
+ public async Task UploadRenderAsync(Guid sequenceId, string path, RenderUploadRequest request, IProgress? progress = null,
+ CancellationToken ct = default)
+ {
+ var length = new FileInfo(path).Length;
+ if (length != request.Size) throw new ArgumentException("The render size does not match the file.", nameof(request));
+ var start = await RetryAsync(() => SendAsync(HttpMethod.Post, $"api/v1/sequences/{sequenceId}/renders", request,
+ ProtocolJson.Default.RenderUploadRequest, ProtocolJson.Default.StartUploadResponse, ct), ct).ConfigureAwait(false);
+ if (start.AlreadyExists) return null;
+ var uploadId = start.UploadId ?? throw new InvalidOperationException("Server returned no upload id.");
+ await SendChunksAsync(path, length, uploadId, start.ChunkSize, start.Received, progress, ct).ConfigureAwait(false);
+ return await RetryAsync(() => SendAsync(HttpMethod.Post, $"api/v1/sequences/{sequenceId}/renders/{uploadId}/complete",
+ ProtocolJson.Default.RenderDto, ct), ct).ConfigureAwait(false);
+ }
+
+ ///
+ /// Streams a render's file to , resuming with Range from its current length; returns
+ /// the file name the server gives it.
+ ///
+ public async Task DownloadRenderAsync(Guid renderId, Stream destination, CancellationToken ct = default)
+ {
+ using var request = new HttpRequestMessage(HttpMethod.Get, $"api/v1/renders/{renderId}/file");
+ if (destination.CanSeek && destination.Length > 0)
+ {
+ destination.Seek(0, SeekOrigin.End);
+ request.Headers.Range = new RangeHeaderValue(destination.Length, null);
+ }
+ using var response = await _http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false);
+ await EnsureSuccessAsync(response, ct).ConfigureAwait(false);
+ if (response.StatusCode == HttpStatusCode.OK && destination.CanSeek) destination.SetLength(0);
+ await using var body = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false);
+ await body.CopyToAsync(destination, ct).ConfigureAwait(false);
+ var disposition = response.Content.Headers.ContentDisposition;
+ return (disposition?.FileNameStar ?? disposition?.FileName)?.Trim('"');
+ }
+
/// Sends every chunk the server does not have yet; each PUT is idempotent and retried on transient errors.
private async Task SendChunksAsync(string path, long length, Guid uploadId, int chunkSize, IReadOnlyList alreadyReceived,
IProgress? progress, CancellationToken ct)
diff --git a/src/Titano.Protocol/ProtocolJson.cs b/src/Titano.Protocol/ProtocolJson.cs
index 2db29cac..7af9a1b2 100644
--- a/src/Titano.Protocol/ProtocolJson.cs
+++ b/src/Titano.Protocol/ProtocolJson.cs
@@ -56,6 +56,7 @@ namespace Titano.Protocol;
[JsonSerializable(typeof(JobPriorityRequest))]
[JsonSerializable(typeof(RenderJobParameters))]
[JsonSerializable(typeof(RenderResultRequest))]
+[JsonSerializable(typeof(RenderUploadRequest))]
[JsonSerializable(typeof(NodeJobFailure))]
[JsonSerializable(typeof(ServerSettingsDto))]
[JsonSerializable(typeof(LogFileDto))]
diff --git a/src/Titano.Protocol/Uploads.cs b/src/Titano.Protocol/Uploads.cs
index b2ff863c..3be2f2e7 100644
--- a/src/Titano.Protocol/Uploads.cs
+++ b/src/Titano.Protocol/Uploads.cs
@@ -16,3 +16,23 @@ public sealed record CompleteUploadResponse(Guid FrameId, Guid SequenceId, int I
/// GET /api/v1/uploads/{id}: resume state.
public sealed record UploadState(Guid UploadId, string FileName, long Size, string Sha256, int ChunkSize, IReadOnlyList Received, string State);
+
+///
+/// POST /api/v1/sequences/{id}/renders: a client offers one of its renders of the sequence (BRIEF §14.5,
+/// renders are uploaded on request). The render keeps its id on the server, so both sides recognise it; when the
+/// server already has that id it answers 200 with . Chunks go to
+/// /uploads/{uploadId}/chunks/{n}; POST /sequences/{id}/renders/{uploadId}/complete verifies the SHA-256
+/// and files the render under the sequence's exports.
+///
+public sealed record RenderUploadRequest(
+ Guid RenderId,
+ string FileName,
+ long Size,
+ string Sha256,
+ string PresetName,
+ string? Codec,
+ int Width,
+ int Height,
+ double Fps,
+ double DurationSeconds,
+ string? ProducedBy);
diff --git a/src/Titano.Server/Api/SequenceEndpoints.cs b/src/Titano.Server/Api/SequenceEndpoints.cs
index dae6adf2..af64e3cc 100644
--- a/src/Titano.Server/Api/SequenceEndpoints.cs
+++ b/src/Titano.Server/Api/SequenceEndpoints.cs
@@ -37,6 +37,15 @@ public static class SequenceEndpoints
sequences.MapGet("/{id:guid}/analysis", AnalysisAsync).Requires(Permissions.Read);
sequences.MapGet("/{id:guid}/stats", StatsAsync).Requires(Permissions.Read);
sequences.MapGet("/{id:guid}/renders", RendersAsync).Requires(Permissions.Read);
+ // Renders made on a client, sent on request (BRIEF §14.5); chunks go through /uploads.
+ sequences.MapPost("/{id:guid}/renders", async (HttpContext c, Caller caller, Guid id, RenderUploadRequest request, RenderUploads uploads) =>
+ (await uploads.StartAsync(caller, id, request, c.RequestAborted)).ToResult(c, r => Results.Json(r, ProtocolJson.Default.StartUploadResponse,
+ statusCode: r.AlreadyExists ? StatusCodes.Status200OK : StatusCodes.Status201Created))).Requires(Permissions.Upload | Permissions.Edit);
+ sequences.MapPost("/{id:guid}/renders/{uploadId:guid}/complete", async (HttpContext c, Caller caller, Guid id, Guid uploadId, RenderUploads uploads,
+ IHostApplicationLifetime lifetime) =>
+ // The commit runs to the end even if the client disconnects meanwhile.
+ (await uploads.CompleteAsync(caller, id, uploadId, lifetime.ApplicationStopping)).ToResult(c, r => Results.Json(r, ProtocolJson.Default.RenderDto)))
+ .Requires(Permissions.Upload | Permissions.Edit);
}
private static async Task ListAsync(HttpContext context, TitanoDatabase db, ServerArchive archive, int? year, string? camera, string? status,
diff --git a/src/Titano.Server/Hosting/ServerHost.cs b/src/Titano.Server/Hosting/ServerHost.cs
index baedd368..4ed24d7d 100644
--- a/src/Titano.Server/Hosting/ServerHost.cs
+++ b/src/Titano.Server/Hosting/ServerHost.cs
@@ -121,6 +121,7 @@ public static class ServerHost
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
+ services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
diff --git a/src/Titano.Server/Storage/RenderStore.cs b/src/Titano.Server/Storage/RenderStore.cs
index 841e3f95..c23784d8 100644
--- a/src/Titano.Server/Storage/RenderStore.cs
+++ b/src/Titano.Server/Storage/RenderStore.cs
@@ -12,7 +12,12 @@ public sealed class RenderStore(TitanoDatabase db, ServerArchive archive, TimePr
/// Moves (on the archive volume) to <sequence folder>/exports/, never
/// replacing an existing export, and inserts the render row. Null when the sequence has no folder in the archive yet.
///
- public async Task CommitAsync(Sequence sequence, string stagedFile, RenderResultRequest output, string producedBy, CancellationToken cancellationToken)
+ public Task CommitAsync(Sequence sequence, string stagedFile, RenderResultRequest output, string producedBy, CancellationToken cancellationToken) =>
+ CommitAsync(sequence, stagedFile, output, producedBy, Guid.CreateVersion7(), cancellationToken);
+
+ /// As above, keeping : a render a client sends keeps the id it has on that client.
+ public async Task CommitAsync(Sequence sequence, string stagedFile, RenderResultRequest output, string producedBy, Guid id,
+ CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(sequence.Folder) || ArchivePathGuard.Resolve(archive.Root, sequence.Folder.TrimEnd('/') + "/exports") is not { } exports)
return null;
@@ -21,7 +26,7 @@ public sealed class RenderStore(TitanoDatabase db, ServerArchive archive, TimePr
File.Move(stagedFile, target);
var render = new Render
{
- Id = Guid.CreateVersion7(),
+ Id = id,
SequenceId = sequence.Id,
PresetName = output.PresetName,
OutputPath = LongPath.ToPortableRelative(archive.Root, target),
diff --git a/src/Titano.Server/Storage/RenderUploads.cs b/src/Titano.Server/Storage/RenderUploads.cs
new file mode 100644
index 00000000..f0345a41
--- /dev/null
+++ b/src/Titano.Server/Storage/RenderUploads.cs
@@ -0,0 +1,118 @@
+using System.Globalization;
+using System.Text.Json;
+using Titano.Data;
+using Titano.Data.Repositories;
+using Titano.Protocol;
+using Titano.Server.Api;
+using Titano.Server.Configuration;
+using Titano.Server.Events;
+using Titano.Server.Security;
+using UploadState = Titano.Data.Repositories.UploadState;
+
+namespace Titano.Server.Storage;
+
+///
+/// Renders a client sends on request (BRIEF §14.5): chunked like frame uploads (same store, chunk endpoint and
+/// retention), verified against their SHA-256 at completion and filed by under the
+/// sequence's exports with the client's render id, so both sides recognise the same render.
+///
+public sealed class RenderUploads(
+ TitanoDatabase db,
+ ServerOptions options,
+ UploadService uploads,
+ UploadStore store,
+ RenderStore renders,
+ EventHub events,
+ TimeProvider time)
+{
+ public async Task> StartAsync(Caller caller, Guid sequenceId, RenderUploadRequest request, CancellationToken cancellationToken)
+ {
+ if (await db.Sequences.GetAsync(sequenceId, cancellationToken) is null) return Outcome.Fail(404, "not_found", "sequence");
+ if (UploadRules.SafeFileName(request.FileName) is not { } fileName) return Outcome.Fail(400, "invalid_file_name");
+ if (!UploadRules.IsSha256(request.Sha256)) return Outcome.Fail(400, "invalid_hash");
+ if (request.Size <= 0) return Outcome.Fail(400, "bad_request", "size");
+ if (request.Size > options.MaxUploadBytes)
+ return Outcome.Fail(413, "too_large", options.MaxUploadBytes.ToString(CultureInfo.InvariantCulture));
+ if (string.IsNullOrWhiteSpace(request.PresetName) || request.PresetName.Length > 200) return Outcome.Fail(400, "bad_request", "presetName");
+ if (request.RenderId == Guid.Empty) return Outcome.Fail(400, "bad_request", "renderId");
+
+ if (await db.Renders.GetAsync(request.RenderId, cancellationToken) is { } known)
+ {
+ return known.SequenceId == sequenceId
+ ? new StartUploadResponse(null, options.ChunkSizeBytes, [], AlreadyExists: true, null)
+ : Outcome.Fail(409, "render_exists");
+ }
+ var sha = request.Sha256.ToLowerInvariant();
+ if (await db.Uploads.FindReceivingAsync(caller.Id, sha, cancellationToken) is { } open && open.SequenceId == sequenceId && open.Size == request.Size
+ && Read(open)?.RenderId == request.RenderId && store.Exists(open.Id))
+ return Started(open);
+ if (UploadRules.FreeBytes(options.UploadsPath) is { } free && free < request.Size) return Outcome.Fail(507, "insufficient_storage");
+
+ var now = time.GetUtcNow();
+ var upload = await db.Uploads.CreateAsync(new Upload
+ {
+ Id = Guid.CreateVersion7(),
+ UserId = caller.Id,
+ SequenceId = sequenceId,
+ FileName = fileName,
+ Size = request.Size,
+ Sha256 = sha,
+ ChunkSize = options.ChunkSizeBytes,
+ State = UploadState.Receiving,
+ Created = now,
+ UpdatedAt = now,
+ RenderJson = JsonSerializer.Serialize(request with { FileName = fileName, Sha256 = sha }, ProtocolJson.Default.RenderUploadRequest),
+ }, cancellationToken);
+ store.Create(upload.Id, upload.Size);
+ return Started(upload);
+ }
+
+ /// Verifies a fully received render and files it; completing a committed one answers it again (a lost response).
+ public async Task> CompleteAsync(Caller caller, Guid sequenceId, Guid uploadId, CancellationToken cancellationToken)
+ {
+ var upload = await db.Uploads.GetAsync(uploadId, cancellationToken);
+ if (upload is null || upload.UserId != caller.Id || upload.SequenceId != sequenceId || upload.JobId is not null || Read(upload) is not { } output)
+ return Outcome.Fail(404, "not_found", "upload");
+ if (upload.State == UploadState.Committed && await db.Renders.GetAsync(output.RenderId, cancellationToken) is { } done) return Dto.Render(done);
+ if (upload.State != UploadState.Receiving) return Outcome.Fail(409, "upload_state");
+ if (!upload.IsComplete)
+ return Outcome.Fail(409, "incomplete", (upload.ChunkCount - upload.ReceivedCount).ToString(CultureInfo.InvariantCulture));
+ if (!await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Receiving, UploadState.Committing, cancellationToken: cancellationToken))
+ return Outcome.Fail(409, "upload_state");
+
+ if (await uploads.StageVerifiedAsync(upload, cancellationToken) is not { } staged) return Outcome.Fail(422, "hash_mismatch");
+ var sequence = await db.Sequences.GetAsync(sequenceId, cancellationToken);
+ var result = new RenderResultRequest(output.FileName, output.Size, output.Sha256, output.PresetName, output.Codec, output.Width, output.Height, output.Fps,
+ output.DurationSeconds);
+ var render = sequence is null ? null : await renders.CommitAsync(sequence, staged, result, output.ProducedBy ?? caller.ClientName ?? caller.User.Username,
+ output.RenderId, cancellationToken);
+ if (render is null)
+ {
+ UploadStore.TryDelete(staged);
+ await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Committing, UploadState.Failed, cancellationToken: CancellationToken.None);
+ store.Delete(upload.Id);
+ return Outcome.Fail(409, "upload_state", "sequence");
+ }
+ await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Committing, UploadState.Committed, cancellationToken: CancellationToken.None);
+ store.Delete(upload.Id);
+ if (await db.Sequences.GetAsync(sequenceId, CancellationToken.None) is { } updated)
+ events.Publish(new SequenceChangedEvent(updated.Id, "renders", updated.FramesVersion, updated.SettingsVersion));
+ return Dto.Render(render);
+ }
+
+ private static RenderUploadRequest? Read(Upload upload)
+ {
+ if (upload.RenderJson is not { } json) return null;
+ try
+ {
+ return JsonSerializer.Deserialize(json, ProtocolJson.Default.RenderUploadRequest) is { RenderId: var id } request && id != Guid.Empty ? request : null;
+ }
+ catch (JsonException)
+ {
+ return null;
+ }
+ }
+
+ private static StartUploadResponse Started(Upload upload) =>
+ new(upload.Id, upload.ChunkSize, UploadRules.ReceivedChunks(upload), AlreadyExists: false, FrameId: null);
+}
diff --git a/src/Titano.Server/Storage/UploadService.cs b/src/Titano.Server/Storage/UploadService.cs
index cef9f2ff..327bd02d 100644
--- a/src/Titano.Server/Storage/UploadService.cs
+++ b/src/Titano.Server/Storage/UploadService.cs
@@ -144,7 +144,7 @@ public sealed class UploadService(
var stopping = lifetime.ApplicationStopping;
var upload = await db.Uploads.GetAsync(id, stopping);
if (upload is null || upload.UserId != caller.Id) return Fail(404, "not_found", "upload");
- if (upload.JobId is not null) return Fail(409, "wrong_upload_kind");
+ if (upload.JobId is not null || upload.RenderJson is not null) return Fail(409, "wrong_upload_kind");
if (upload is { State: UploadState.Committed, FrameId: { } committed } && await db.Frames.GetAsync(committed, stopping) is { } done)
return new CompleteUploadResponse(done.Id, done.SequenceId, done.Index);
if (upload.State != UploadState.Receiving) return Fail(409, "upload_state");
diff --git a/src/Titano.Ui/Themes/Controls.xaml b/src/Titano.Ui/Themes/Controls.xaml
index 2a689464..a22debfb 100644
--- a/src/Titano.Ui/Themes/Controls.xaml
+++ b/src/Titano.Ui/Themes/Controls.xaml
@@ -1248,10 +1248,11 @@
-
+
+
-
-
+
+
diff --git a/tests/Titano.App.Tests/Server/ServerScreenSmokeTests.cs b/tests/Titano.App.Tests/Server/ServerScreenSmokeTests.cs
new file mode 100644
index 00000000..8c1ee512
--- /dev/null
+++ b/tests/Titano.App.Tests/Server/ServerScreenSmokeTests.cs
@@ -0,0 +1,151 @@
+using System.Windows.Controls;
+using System.Windows.Input;
+using Titano.App.Infrastructure;
+using Titano.App.Sections;
+using Titano.App.Server;
+using Titano.App.Shell;
+using Titano.App.Tests.Windows;
+using Titano.Core.Localization;
+using Titano.Core.Model;
+using Titano.Data.Sync;
+using Titano.Testing;
+using Titano.Ui.Controls;
+
+namespace Titano.App.Tests.Server;
+
+/// The Server screen's sync table on the capture sample data: comparison, transfers, conflict and the Library's glyphs.
+[WindowsOnly]
+[Serial]
+[Timeout(300_000)]
+public sealed class ServerScreenSmokeTests
+{
+ [Test]
+ public Task TheSyncTableShowsEveryStateOfTheSample() => ScreenHost.RunAsync(async () =>
+ {
+ await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
+ var shell = app.Shell;
+ await app.Sample.FillAsync();
+ await shell.Library.RefreshAsync();
+ await shell.Services.Server.RestoreAsync();
+ Assert.NotNull(await shell.Services.Sync.RefreshAsync());
+ await app.Sample.CacheProxiesAsync();
+ var table = shell.Server.Sync;
+ await table.ReloadAsync();
+
+ // 36 sequences here (6 also on the server) and 2 only on the server; the conflict is listed first.
+ Assert.True(table.IsActive);
+ Assert.Equal(38, table.Rows.Count);
+ Assert.Equal("Holy grail · Monviso", table.Rows[0].Title);
+ Assert.True(table.Rows[0].IsConflict);
+ Assert.Equal(1, Chip(table, SyncFilter.Conflicts).Count);
+ Assert.Equal(2, Chip(table, SyncFilter.Remote).Count);
+ Assert.Equal(30, Chip(table, SyncFilter.LocalOnly).Count);
+ Assert.Equal(SyncStatus.InSync, Row(table, "Harbour sunset").Entry.Status);
+ Assert.Equal(SyncStatus.ServerAhead, Row(table, "Construction cam · week 38").Entry.Status);
+ Assert.SequenceEqual([SyncAction.DownloadOriginals], Actions(Row(table, "Construction cam · week 38")));
+ Assert.SequenceEqual([SyncAction.Upload], Actions(Row(table, "Milan skyline dusk")));
+ Assert.SequenceEqual([SyncAction.GetExports], Actions(Row(table, "Star trails, Colle del Nivolet")));
+ var sunrise = Row(table, "Sunrise over Superga");
+ Assert.Equal(SyncStatus.ProxiesOnly, sunrise.Entry.Status);
+ Assert.Equal(Loc.L("Server.Sync.Proxies"), sunrise.LocalText);
+ Assert.SequenceEqual([SyncAction.OpenWithProxies, SyncAction.DownloadOriginals], Actions(sunrise));
+ Assert.SequenceEqual([SyncAction.Upload], Actions(Row(table, "Clouds over the Langhe")));
+ var conflict = Row(table, "Holy grail · Monviso");
+ Assert.Equal(StatusKind.Warning, conflict.StateKind);
+ Assert.SequenceEqual([SyncAction.KeepMine, SyncAction.TakeServer, SyncAction.SaveBoth], Actions(conflict));
+ Assert.Equal(Loc.L("Server.Conflict.Difference", Loc.L("Server.Setting.DeflickerWindow"), "41", "33"), conflict.StateToolTip);
+ Assert.NotNull(table.LastSyncText);
+ Assert.NotNull(table.ArchiveText);
+ Assert.True(table.UploadAllCommand.CanExecute(null), "the table filled after the view bound");
+
+ // Resolving shows the plan first: what differs and which side is overwritten.
+ var keepMine = SyncTableViewModel.ConflictRequest(conflict.Entry, SyncAction.KeepMine);
+ Assert.True(keepMine.IsDestructive);
+ Assert.Contains(Loc.L("Server.Setting.DeflickerWindow"), keepMine.Detail);
+ Assert.False(SyncTableViewModel.ConflictRequest(conflict.Entry, SyncAction.SaveBoth).IsDestructive);
+
+ // The Library shows the real sync state of each local copy, in one word.
+ var holyGrail = shell.Library.Items.Single(i => i.Title == "Holy grail · Monviso");
+ Assert.Equal(SyncState.Conflict, holyGrail.Sequence.SyncState);
+ Assert.Equal(StatusKind.Warning, holyGrail.Statuses[^1].Kind);
+ Assert.Contains(shell.Library.Items.Single(i => i.Title == "Harbour sunset").Statuses, s => s.Kind == StatusKind.Synced);
+ var milan = shell.Library.Items.Single(i => i.Title == "Milan skyline dusk").Statuses[^1];
+ Assert.Equal((StatusKind.Synced, Loc.L("Library.Status.Synced")), (milan.Kind, milan.Text));
+
+ shell.Navigate(SectionKey.Server);
+ await app.ExpectAsync("server");
+
+ // Tab walks the row buttons of every row: the rows take no focus, the list passes Tab on to their content.
+ var list = app.FindAll().Single(l => l.Name == "SyncList");
+ Assert.Equal(KeyboardNavigationMode.Continue, KeyboardNavigation.GetTabNavigation(list));
+ var rowButtons = app.FindAll