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} count The 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} days Adopt folder Deep analysis + Download Duplicates Import Light 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 @@ Title Analysed Analysing + Conflict Proxies Remote Synced 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=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 nas.local:8443invariant + Sync projects automatically Certificate Forget Keep Titano trusts this certificate for this server. Forgetting it disconnects, and the next connection asks again.long Server certificate TLS {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? Connect Disconnect Not connected to a server @@ -71,6 +82,7 @@ The current password is wrong.long This upload belongs to a render job.long Servers found + Keep proxies offline Account Server Status @@ -80,6 +92,7 @@ Sign in Sign in User + Pause metered uploads {0} of {1} {0} used Offer this PC as render node @@ -88,11 +101,102 @@ Uploader Viewer Titano 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 smoothing Sign out Connected Connecting… Disconnected Not 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 local Trust Cancel {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 warnings Analysed: exposure, flicker and motion are measured An analysis job is running on this sequence + Settings changed here and on the server; choose on the Server screen Some frames are missing or unreadable; open the sequence for details + This PC has originals or settings the server does not have yet No proxies yet; editing reads the originals Not analysed yet JPEG proxies built for fast editing Lives on the server; this PC has proxies at most Rendered once Rendered {0:N0} times + The server has originals or settings this PC does not have yet The 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+6 Preferences 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 below Show the full fingerprint, or forget the trust Fingerprint 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's Identify the server, confirm a new certificate, then sign in · Enter Close the session and work with the local archive only; you stay signed in Do not connect; nothing is sent to this server SHA-256 fingerprint of the server certificate Forget this certificate; the next connection asks again Servers 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 folderlong Keep trusting this certificate Close without signing in · Esc Sent only to this server; Titano keeps a session token, never the password Your user name on the server + Pause uploads while Windows reports this connection as metered; they resume by themselves when it is notlong Space you use on the server out of your quota Let the server send render jobs to this PC when it is idle; uses your GPU encoders Admins manage users, the archive and the server @@ -123,6 +131,45 @@ Sign in; the token is stored encrypted for this Windows user · Enter Sign out; the token is removed from this PC Connection 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 PC Trust this certificate for this server and continue to sign in Use this address Graphics 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} giorni Adozione cartella Analisi approfondita + Scaricamento Duplicati Importazione Analisi 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 @@ Titolo Analizzata In analisi + Conflitto Proxy Remota Sincronizzata 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.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Sincronizza progetti automaticamente Certificato Dimentica Mantieni Titano 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 server TLS {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? Connetti Disconnetti Non connesso a un server @@ -70,6 +80,7 @@ La password attuale è errata. Questo caricamento appartiene a un job di rendering. Server trovati + Proxy disponibili offline Account Server Stato @@ -79,6 +90,7 @@ Accedi Accedi Utente + Pausa su reti a consumo {0} di {1} {0} usati Offri questo PC per il rendering @@ -87,11 +99,101 @@ Caricatore Visualizzatore Server 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 WB Esci Connesso Connessione… Disconnesso Non 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 locali Considera attendibile Annulla {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 avvisi Analizzata: esposizione, flicker e movimento sono misurati Un'attività di analisi è in corso su questa sequenza + Impostazioni cambiate qui e sul server; scegli nella schermata Server Alcuni fotogrammi mancano o sono illeggibili; apri la sequenza per i dettagli + Questo PC ha originali o impostazioni che il server non ha ancora Ancora nessun proxy; la modifica legge gli originali Non ancora analizzata Proxy JPEG pronti per una modifica veloce Si trova sul server; questo PC ne ha al massimo i proxy Esportata una volta Esportata {0:N0} volte + Il server ha originali o impostazioni che questo PC non ha ancora Uguale 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+6 Preferenze 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 sotto Mostra l'impronta completa o revoca la fiducia Impronta 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 server Identifica il server, conferma un certificato nuovo e poi accedi · Invio Chiude la sessione e lavora solo con l'archivio locale; l'accesso resta salvato Non connetterti; a questo server non viene inviato nulla Impronta SHA-256 del certificato del server Dimentica questo certificato; alla prossima connessione verrà chiesto di nuovo Server 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 cache Continua a considerare attendibile questo certificato Chiude senza accedere · Esc Inviata solo a questo server; Titano conserva un token di sessione, mai la password Il 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 quota Permette al server di inviare rendering a questo PC quando è inattivo; usa gli encoder della tua GPU Gli amministratori gestiscono utenti, archivio e server @@ -123,6 +131,45 @@ Accedi; il token viene salvato cifrato per questo utente di Windows · Invio Esci; il token viene rimosso da questo PC Connessione 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 PC Considera attendibile questo certificato per questo server e prosegui con l'accesso Usa questo indirizzo Scheda 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 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + - 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