Titano: editor, import/archive screens, analysis and render jobs, server sync — in progress #2

Merged
Alby96 merged 86 commits from claude/keen-knuth-uhxv8w into main 2026-10-05 23:55:39 +02:00
56 changed files with 6777 additions and 25 deletions
Showing only changes of commit 10a9db9c91 - Show all commits

No files matched your search

+12
View File
@@ -20,6 +20,18 @@
<data name="Errors.Render.Sequence" xml:space="preserve"><value>The sequence to render is no longer in the archive.</value></data>
<data name="Errors.Server.Address" xml:space="preserve"><value>Enter a server address such as nas.local:8443 or https://titano.example.com.</value></data>
<data name="Errors.Settings.Import" xml:space="preserve"><value>This file does not contain Titano settings.</value></data>
<data name="Errors.Sync.ChangedAgain" xml:space="preserve"><value>This PC or the server changed the sequence again; compare and choose again.</value></data>
<data name="Errors.Sync.DiskFull" xml:space="preserve"><value>The disk needs {0} GB more for this download.</value><comment>{0} gigabytes missing</comment></data>
<data name="Errors.Sync.ExportsGone.one" xml:space="preserve"><value>{0} render is no longer on this PC; the others were sent.</value><comment>{0} count</comment></data>
<data name="Errors.Sync.ExportsGone.other" xml:space="preserve"><value>{0} renders are no longer on this PC; the others were sent.</value><comment>{0} count</comment></data>
<data name="Errors.Sync.Hash" xml:space="preserve"><value>{0} did not arrive intact; download it again.</value><comment>{0} file name</comment></data>
<data name="Errors.Sync.LocalMissing" xml:space="preserve"><value>The sequence is no longer in this PC's archive index.</value></data>
<data name="Errors.Sync.NoArchive" xml:space="preserve"><value>Open or create an archive on this PC to receive the originals.</value></data>
<data name="Errors.Sync.NotConnected" xml:space="preserve"><value>Not connected to this server; connect and retry the job.</value></data>
<data name="Errors.Sync.NotLinked" xml:space="preserve"><value>This sequence is not on the server yet; upload it first.</value></data>
<data name="Errors.Sync.NothingSent" xml:space="preserve"><value>No original reached the server: they are missing here or already in another server sequence.</value></data>
<data name="Errors.Sync.Unreadable.one" xml:space="preserve"><value>{0} original is missing or changed since it was archived; verify the archive.</value><comment>{0} count</comment></data>
<data name="Errors.Sync.Unreadable.other" xml:space="preserve"><value>{0} originals are missing or changed since they were archived; verify the archive.</value><comment>{0} count</comment></data>
<data name="Errors.Template.Empty" xml:space="preserve"><value>The template is empty.</value></data>
<data name="Errors.Template.EmptyToken" xml:space="preserve"><value>Empty token at position {1}: write a name between the braces.</value></data>
<data name="Errors.Template.FileSeparator" xml:space="preserve"><value>File names cannot contain a slash; put folders in the folder template.</value></data>
+1
View File
@@ -33,6 +33,7 @@
<data name="Jobs.History.other" xml:space="preserve"><value>History keeps {0} days</value></data>
<data name="Jobs.Kind.Adopt" xml:space="preserve"><value>Adopt folder</value></data>
<data name="Jobs.Kind.DeepAnalyse" xml:space="preserve"><value>Deep analysis</value></data>
<data name="Jobs.Kind.Download" xml:space="preserve"><value>Download</value></data>
<data name="Jobs.Kind.Duplicates" xml:space="preserve"><value>Duplicates</value></data>
<data name="Jobs.Kind.Import" xml:space="preserve"><value>Import</value></data>
<data name="Jobs.Kind.LightAnalyse" xml:space="preserve"><value>Light analysis</value></data>
+1
View File
@@ -61,6 +61,7 @@
<data name="Library.Sort.Title" xml:space="preserve"><value>Title</value></data>
<data name="Library.Status.Analysed" xml:space="preserve"><value>Analysed</value></data>
<data name="Library.Status.Analysing" xml:space="preserve"><value>Analysing</value></data>
<data name="Library.Status.Conflict" xml:space="preserve"><value>Conflict</value></data>
<data name="Library.Status.Proxies" xml:space="preserve"><value>Proxies</value></data>
<data name="Library.Status.Remote" xml:space="preserve"><value>Remote</value></data>
<data name="Library.Status.Synced" xml:space="preserve"><value>Synced</value></data>
+104
View File
@@ -5,12 +5,23 @@
<resheader name="reader"><value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
<resheader name="writer"><value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
<data name="Server.AddressPlaceholder" xml:space="preserve"><value>nas.local:8443</value><comment>invariant</comment></data>
<data name="Server.AutoSync" xml:space="preserve"><value>Sync projects automatically</value></data>
<data name="Server.Certificate" xml:space="preserve"><value>Certificate</value></data>
<data name="Server.Certificate.Forget" xml:space="preserve"><value>Forget</value></data>
<data name="Server.Certificate.Keep" xml:space="preserve"><value>Keep</value></data>
<data name="Server.Certificate.Message" xml:space="preserve"><value>Titano trusts this certificate for this server. Forgetting it disconnects, and the next connection asks again.</value><comment>long</comment></data>
<data name="Server.Certificate.Title" xml:space="preserve"><value>Server certificate</value></data>
<data name="Server.Certificate.Trusted" xml:space="preserve"><value>TLS {0} trusted {1}</value></data>
<data name="Server.Conflict.Cancel" xml:space="preserve"><value>Cancel</value></data>
<data name="Server.Conflict.Changed" xml:space="preserve"><value>{0} differs</value><comment>{0} setting name</comment></data>
<data name="Server.Conflict.Difference" xml:space="preserve"><value>{0} {1} here, {2} on the server</value><comment>long; {0} setting name, {1} value on this PC, {2} value on the server</comment></data>
<data name="Server.Conflict.KeepMine.Message" xml:space="preserve"><value>The server copy of {0} will be replaced by this PC's settings.</value><comment>long; {0} sequence title</comment></data>
<data name="Server.Conflict.KeepMine.Title" xml:space="preserve"><value>Keep this PC's settings?</value></data>
<data name="Server.Conflict.More" xml:space="preserve"><value>{0} · +{1}</value><comment>invariant; {0} first difference, {1} count of the others</comment></data>
<data name="Server.Conflict.SaveBoth.Message" xml:space="preserve"><value>This PC takes the server's version of {0} and keeps its own settings as a dated copy next to the project.</value><comment>long; {0} sequence title</comment></data>
<data name="Server.Conflict.SaveBoth.Title" xml:space="preserve"><value>Save both versions?</value></data>
<data name="Server.Conflict.TakeServer.Message" xml:space="preserve"><value>This PC's settings of {0} will be replaced by the server copy.</value><comment>long; {0} sequence title</comment></data>
<data name="Server.Conflict.TakeServer.Title" xml:space="preserve"><value>Take the server's settings?</value></data>
<data name="Server.Connect" xml:space="preserve"><value>Connect</value></data>
<data name="Server.Disconnect" xml:space="preserve"><value>Disconnect</value></data>
<data name="Server.Empty" xml:space="preserve"><value>Not connected to a server</value></data>
@@ -71,6 +82,7 @@
<data name="Server.Error.WrongPassword" xml:space="preserve"><value>The current password is wrong.</value><comment>long</comment></data>
<data name="Server.Error.WrongUploadKind" xml:space="preserve"><value>This upload belongs to a render job.</value><comment>long</comment></data>
<data name="Server.Found" xml:space="preserve"><value>Servers found</value></data>
<data name="Server.KeepProxies" xml:space="preserve"><value>Keep proxies offline</value></data>
<data name="Server.Label.Account" xml:space="preserve"><value>Account</value></data>
<data name="Server.Label.Server" xml:space="preserve"><value>Server</value></data>
<data name="Server.Label.Status" xml:space="preserve"><value>Status</value></data>
@@ -80,6 +92,7 @@
<data name="Server.Login.SignIn" xml:space="preserve"><value>Sign in</value></data>
<data name="Server.Login.Title" xml:space="preserve"><value>Sign in</value></data>
<data name="Server.Login.User" xml:space="preserve"><value>User</value></data>
<data name="Server.PauseMetered" xml:space="preserve"><value>Pause metered uploads</value></data>
<data name="Server.Quota" xml:space="preserve"><value>{0} of {1}</value></data>
<data name="Server.QuotaUnlimited" xml:space="preserve"><value>{0} used</value></data>
<data name="Server.RenderNode" xml:space="preserve"><value>Offer this PC as render node</value></data>
@@ -88,11 +101,102 @@
<data name="Server.Role.Uploader" xml:space="preserve"><value>Uploader</value></data>
<data name="Server.Role.Viewer" xml:space="preserve"><value>Viewer</value></data>
<data name="Server.Service.Description" xml:space="preserve"><value>Titano time-lapse archive, uploads, jobs and rendering server.</value><comment>long</comment></data>
<data name="Server.Setting.Aspect" xml:space="preserve"><value>Aspect</value></data>
<data name="Server.Setting.Auto" xml:space="preserve"><value>auto</value></data>
<data name="Server.Setting.Batch" xml:space="preserve"><value>Batch list</value></data>
<data name="Server.Setting.CameraOffset" xml:space="preserve"><value>Camera offset</value></data>
<data name="Server.Setting.Crop" xml:space="preserve"><value>Crop</value></data>
<data name="Server.Setting.Deflicker" xml:space="preserve"><value>Deflicker</value></data>
<data name="Server.Setting.DeflickerStrength" xml:space="preserve"><value>Deflicker strength</value></data>
<data name="Server.Setting.DeflickerWindow" xml:space="preserve"><value>Deflicker window</value></data>
<data name="Server.Setting.ExcludedFrames" xml:space="preserve"><value>Excluded frames</value></data>
<data name="Server.Setting.ExportFolder" xml:space="preserve"><value>Export folder</value></data>
<data name="Server.Setting.ExportPreset" xml:space="preserve"><value>Export preset</value></data>
<data name="Server.Setting.ExportValues" xml:space="preserve"><value>Export values</value></data>
<data name="Server.Setting.ExposureOffset" xml:space="preserve"><value>Exposure offset</value></data>
<data name="Server.Setting.FitToDuration" xml:space="preserve"><value>Fit to duration</value></data>
<data name="Server.Setting.FlowQuality" xml:space="preserve"><value>Flow quality</value></data>
<data name="Server.Setting.FrameRate" xml:space="preserve"><value>Frame rate</value></data>
<data name="Server.Setting.HeroFrame" xml:space="preserve"><value>Hero frame</value></data>
<data name="Server.Setting.HighlightKnee" xml:space="preserve"><value>Highlight knee</value></data>
<data name="Server.Setting.HolyGrail" xml:space="preserve"><value>Holy grail</value></data>
<data name="Server.Setting.Keyframes" xml:space="preserve"><value>Camera keyframes</value></data>
<data name="Server.Setting.Manual" xml:space="preserve"><value>manual</value></data>
<data name="Server.Setting.MotionBlur" xml:space="preserve"><value>Motion blur</value></data>
<data name="Server.Setting.Notes" xml:space="preserve"><value>Notes</value></data>
<data name="Server.Setting.Off" xml:space="preserve"><value>off</value></data>
<data name="Server.Setting.On" xml:space="preserve"><value>on</value></data>
<data name="Server.Setting.Other" xml:space="preserve"><value>Other setting</value></data>
<data name="Server.Setting.OutputName" xml:space="preserve"><value>Output name</value></data>
<data name="Server.Setting.Rating" xml:space="preserve"><value>Rating</value></data>
<data name="Server.Setting.Regions" xml:space="preserve"><value>Regions</value></data>
<data name="Server.Setting.ShutterAngle" xml:space="preserve"><value>Shutter angle</value></data>
<data name="Server.Setting.Stabilize" xml:space="preserve"><value>Stabilisation</value></data>
<data name="Server.Setting.StabilizeSmoothing" xml:space="preserve"><value>Stabilisation smoothing</value></data>
<data name="Server.Setting.Stacking" xml:space="preserve"><value>Stacking</value></data>
<data name="Server.Setting.Tags" xml:space="preserve"><value>Tags</value></data>
<data name="Server.Setting.TimeRemap" xml:space="preserve"><value>Time remap</value></data>
<data name="Server.Setting.TimingMode" xml:space="preserve"><value>Timing mode</value></data>
<data name="Server.Setting.Title" xml:space="preserve"><value>Title</value></data>
<data name="Server.Setting.TrailLength" xml:space="preserve"><value>Trail length</value></data>
<data name="Server.Setting.Transitions" xml:space="preserve"><value>Transitions</value></data>
<data name="Server.Setting.WhiteBalance" xml:space="preserve"><value>WB smoothing</value></data>
<data name="Server.SignOut" xml:space="preserve"><value>Sign out</value></data>
<data name="Server.Status.Connected" xml:space="preserve"><value>Connected</value></data>
<data name="Server.Status.Connecting" xml:space="preserve"><value>Connecting…</value></data>
<data name="Server.Status.Disconnected" xml:space="preserve"><value>Disconnected</value></data>
<data name="Server.Status.NotConnected" xml:space="preserve"><value>Not connected</value></data>
<data name="Server.Sync.Action.DownloadOriginals" xml:space="preserve"><value>Download originals</value></data>
<data name="Server.Sync.Action.GetExports" xml:space="preserve"><value>Get exports</value></data>
<data name="Server.Sync.Action.KeepMine" xml:space="preserve"><value>Keep mine</value></data>
<data name="Server.Sync.Action.OpenWithProxies" xml:space="preserve"><value>Open with proxies</value></data>
<data name="Server.Sync.Action.Pause" xml:space="preserve"><value>Pause</value></data>
<data name="Server.Sync.Action.Resume" xml:space="preserve"><value>Resume</value></data>
<data name="Server.Sync.Action.SaveBoth" xml:space="preserve"><value>Save both</value></data>
<data name="Server.Sync.Action.SendExports" xml:space="preserve"><value>Send exports</value></data>
<data name="Server.Sync.Action.SyncSettings" xml:space="preserve"><value>Sync settings</value></data>
<data name="Server.Sync.Action.TakeServer" xml:space="preserve"><value>Take server</value></data>
<data name="Server.Sync.Action.Upload" xml:space="preserve"><value>Upload</value></data>
<data name="Server.Sync.Archive.one" xml:space="preserve"><value>Server archive {1} · {0} sequence</value><comment>long; {0} sequence count, {1} archive size</comment></data>
<data name="Server.Sync.Archive.other" xml:space="preserve"><value>Server archive {1} · {0} sequences</value><comment>long; {0} sequence count, {1} archive size</comment></data>
<data name="Server.Sync.Column.Local" xml:space="preserve"><value>This PC</value></data>
<data name="Server.Sync.Column.Sequence" xml:space="preserve"><value>Sequence</value></data>
<data name="Server.Sync.Column.Server" xml:space="preserve"><value>Server</value></data>
<data name="Server.Sync.Column.State" xml:space="preserve"><value>State</value></data>
<data name="Server.Sync.Empty" xml:space="preserve"><value>Nothing to compare yet</value></data>
<data name="Server.Sync.Exports.one" xml:space="preserve"><value>{0} export</value><comment>{0} count</comment></data>
<data name="Server.Sync.Exports.other" xml:space="preserve"><value>{0} exports</value><comment>{0} count</comment></data>
<data name="Server.Sync.Filter.All" xml:space="preserve"><value>All · {0}</value><comment>{0} count</comment></data>
<data name="Server.Sync.Filter.Conflicts" xml:space="preserve"><value>Conflicts · {0}</value><comment>{0} count</comment></data>
<data name="Server.Sync.Filter.LocalOnly" xml:space="preserve"><value>Local only · {0}</value><comment>{0} count</comment></data>
<data name="Server.Sync.Filter.Remote" xml:space="preserve"><value>Remote · {0}</value><comment>{0} count</comment></data>
<data name="Server.Sync.Last" xml:space="preserve"><value>Last sync {0} · manifest diff {1} s</value><comment>long; {0} time of day, {1} seconds</comment></data>
<data name="Server.Sync.NoMatch" xml:space="preserve"><value>No sequence matches</value></data>
<data name="Server.Sync.None" xml:space="preserve"><value>—</value><comment>invariant</comment></data>
<data name="Server.Sync.OpenAdmin" xml:space="preserve"><value>Open admin panel</value></data>
<data name="Server.Sync.Originals" xml:space="preserve"><value>originals</value></data>
<data name="Server.Sync.Proxies" xml:space="preserve"><value>proxies</value></data>
<data name="Server.Sync.Queued.one" xml:space="preserve"><value>{0} upload queued</value><comment>{0} count</comment></data>
<data name="Server.Sync.Queued.other" xml:space="preserve"><value>{0} uploads queued</value><comment>{0} count</comment></data>
<data name="Server.Sync.Received" xml:space="preserve"><value>{0} received</value><comment>{0} percent</comment></data>
<data name="Server.Sync.Retrying" xml:space="preserve"><value>Not compared · retrying</value></data>
<data name="Server.Sync.SavedBoth" xml:space="preserve"><value>This PC's settings saved</value><comment>long</comment></data>
<data name="Server.Sync.Search" xml:space="preserve"><value>Search</value></data>
<data name="Server.Sync.ShowCopy" xml:space="preserve"><value>Show file</value></data>
<data name="Server.Sync.State.Conflict" xml:space="preserve"><value>settings differ</value></data>
<data name="Server.Sync.State.Downloading" xml:space="preserve"><value>downloading</value></data>
<data name="Server.Sync.State.Failed" xml:space="preserve"><value>not compared</value></data>
<data name="Server.Sync.State.InSync" xml:space="preserve"><value>in sync</value></data>
<data name="Server.Sync.State.LocalAhead" xml:space="preserve"><value>newer here</value></data>
<data name="Server.Sync.State.LocalOnly" xml:space="preserve"><value>local only</value></data>
<data name="Server.Sync.State.Paused" xml:space="preserve"><value>paused</value></data>
<data name="Server.Sync.State.ProxiesOnly" xml:space="preserve"><value>proxies only</value></data>
<data name="Server.Sync.State.RemoteOnly" xml:space="preserve"><value>remote</value></data>
<data name="Server.Sync.State.ServerAhead" xml:space="preserve"><value>newer on server</value></data>
<data name="Server.Sync.State.Uploading" xml:space="preserve"><value>uploading</value></data>
<data name="Server.Sync.State.Waiting" xml:space="preserve"><value>waiting</value></data>
<data name="Server.Sync.Title" xml:space="preserve"><value>Sequences</value></data>
<data name="Server.Sync.UploadAll" xml:space="preserve"><value>Upload all local</value></data>
<data name="Server.Trust.Accept" xml:space="preserve"><value>Trust</value></data>
<data name="Server.Trust.Cancel" xml:space="preserve"><value>Cancel</value></data>
<data name="Server.Trust.Message" xml:space="preserve"><value>{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.</value><comment>long</comment></data>
+47
View File
@@ -79,13 +79,16 @@
<data name="Tooltips.Library.Status" xml:space="preserve"><value>Filter by analysis, proxies, verification or warnings</value></data>
<data name="Tooltips.Library.Status.Analysed" xml:space="preserve"><value>Analysed: exposure, flicker and motion are measured</value></data>
<data name="Tooltips.Library.Status.Analysing" xml:space="preserve"><value>An analysis job is running on this sequence</value></data>
<data name="Tooltips.Library.Status.Conflict" xml:space="preserve"><value>Settings changed here and on the server; choose on the Server screen</value></data>
<data name="Tooltips.Library.Status.Errors" xml:space="preserve"><value>Some frames are missing or unreadable; open the sequence for details</value></data>
<data name="Tooltips.Library.Status.LocalAhead" xml:space="preserve"><value>This PC has originals or settings the server does not have yet</value></data>
<data name="Tooltips.Library.Status.NoProxies" xml:space="preserve"><value>No proxies yet; editing reads the originals</value></data>
<data name="Tooltips.Library.Status.NotAnalysed" xml:space="preserve"><value>Not analysed yet</value></data>
<data name="Tooltips.Library.Status.Proxies" xml:space="preserve"><value>JPEG proxies built for fast editing</value></data>
<data name="Tooltips.Library.Status.Remote" xml:space="preserve"><value>Lives on the server; this PC has proxies at most</value></data>
<data name="Tooltips.Library.Status.Rendered.one" xml:space="preserve"><value>Rendered once</value></data>
<data name="Tooltips.Library.Status.Rendered.other" xml:space="preserve"><value>Rendered {0:N0} times</value></data>
<data name="Tooltips.Library.Status.ServerAhead" xml:space="preserve"><value>The server has originals or settings this PC does not have yet</value></data>
<data name="Tooltips.Library.Status.Synced" xml:space="preserve"><value>The same on this PC and on the server</value></data>
<data name="Tooltips.Library.Status.Warnings.one" xml:space="preserve"><value>{0:N0} warning; open the sequence for details</value></data>
<data name="Tooltips.Library.Status.Warnings.other" xml:space="preserve"><value>{0:N0} warnings; open the sequence for details</value></data>
@@ -102,18 +105,23 @@
<data name="Tooltips.Nav.Server" xml:space="preserve"><value>Connection, sync and render node · Ctrl+6</value></data>
<data name="Tooltips.Nav.Settings" xml:space="preserve"><value>Preferences of this PC · Ctrl+,</value></data>
<data name="Tooltips.Server.Address" xml:space="preserve"><value>Address of the Titano Server; https is assumed · Enter connects</value></data>
<data name="Tooltips.Server.AutoSync" xml:space="preserve"><value>Send and take project settings as they change; settings changed on both sides wait for your choice in the table below</value></data>
<data name="Tooltips.Server.Certificate" xml:space="preserve"><value>Show the full fingerprint, or forget the trust</value></data>
<data name="Tooltips.Server.CertificateTrusted" xml:space="preserve"><value>Fingerprint trusted on first use; a change blocks the connection and asks you again</value></data>
<data name="Tooltips.Server.Conflict.Cancel" xml:space="preserve"><value>Close without changing either copy</value></data>
<data name="Tooltips.Server.Conflict.Detail" xml:space="preserve"><value>The settings that differ: this PC's value, then the server's</value></data>
<data name="Tooltips.Server.Connect" xml:space="preserve"><value>Identify the server, confirm a new certificate, then sign in · Enter</value></data>
<data name="Tooltips.Server.Disconnect" xml:space="preserve"><value>Close the session and work with the local archive only; you stay signed in</value></data>
<data name="Tooltips.Server.DontTrust" xml:space="preserve"><value>Do not connect; nothing is sent to this server</value></data>
<data name="Tooltips.Server.Fingerprint" xml:space="preserve"><value>SHA-256 fingerprint of the server certificate</value></data>
<data name="Tooltips.Server.ForgetTrust" xml:space="preserve"><value>Forget this certificate; the next connection asks again</value></data>
<data name="Tooltips.Server.Found" xml:space="preserve"><value>Servers found on this network and used before</value></data>
<data name="Tooltips.Server.KeepProxies" xml:space="preserve"><value>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 folder</value><comment>long</comment></data>
<data name="Tooltips.Server.KeepTrust" xml:space="preserve"><value>Keep trusting this certificate</value></data>
<data name="Tooltips.Server.LoginCancel" xml:space="preserve"><value>Close without signing in · Esc</value></data>
<data name="Tooltips.Server.LoginPassword" xml:space="preserve"><value>Sent only to this server; Titano keeps a session token, never the password</value></data>
<data name="Tooltips.Server.LoginUser" xml:space="preserve"><value>Your user name on the server</value></data>
<data name="Tooltips.Server.PauseMetered" xml:space="preserve"><value>Pause uploads while Windows reports this connection as metered; they resume by themselves when it is not</value><comment>long</comment></data>
<data name="Tooltips.Server.Quota" xml:space="preserve"><value>Space you use on the server out of your quota</value></data>
<data name="Tooltips.Server.RenderNode" xml:space="preserve"><value>Let the server send render jobs to this PC when it is idle; uses your GPU encoders</value></data>
<data name="Tooltips.Server.Role.Admin" xml:space="preserve"><value>Admins manage users, the archive and the server</value></data>
@@ -123,6 +131,45 @@
<data name="Tooltips.Server.SignIn" xml:space="preserve"><value>Sign in; the token is stored encrypted for this Windows user · Enter</value></data>
<data name="Tooltips.Server.SignOut" xml:space="preserve"><value>Sign out; the token is removed from this PC</value></data>
<data name="Tooltips.Server.Status" xml:space="preserve"><value>Connection to the server</value></data>
<data name="Tooltips.Server.Sync.Archive" xml:space="preserve"><value>Size and sequences of the server archive</value></data>
<data name="Tooltips.Server.Sync.DownloadOriginals" xml:space="preserve"><value>Fetch the originals to this PC, verified by hash ({0})</value><comment>{0} size</comment></data>
<data name="Tooltips.Server.Sync.Filter.All" xml:space="preserve"><value>All sequences on this PC and on the server</value></data>
<data name="Tooltips.Server.Sync.Filter.Conflicts" xml:space="preserve"><value>Settings differ between this PC and the server</value></data>
<data name="Tooltips.Server.Sync.Filter.LocalOnly" xml:space="preserve"><value>Only on this PC</value></data>
<data name="Tooltips.Server.Sync.Filter.Remote" xml:space="preserve"><value>Only on the server</value></data>
<data name="Tooltips.Server.Sync.GetExports.one" xml:space="preserve"><value>Copy the server's render to this PC ({1})</value><comment>{0} count, {1} size</comment></data>
<data name="Tooltips.Server.Sync.GetExports.other" xml:space="preserve"><value>Copy the {0} server renders to this PC ({1})</value><comment>{0} count, {1} size</comment></data>
<data name="Tooltips.Server.Sync.KeepMine" xml:space="preserve"><value>Overwrite the server copy with this PC's settings</value></data>
<data name="Tooltips.Server.Sync.LastSync" xml:space="preserve"><value>When this PC last compared every sequence with the server, and how long it took</value></data>
<data name="Tooltips.Server.Sync.OpenAdmin" xml:space="preserve"><value>Open the web admin in your browser (admins only)</value></data>
<data name="Tooltips.Server.Sync.OpenWithProxies" xml:space="preserve"><value>Open the editor on the proxies; the render runs on the server</value></data>
<data name="Tooltips.Server.Sync.Pause" xml:space="preserve"><value>Pause this transfer; it resumes where it stopped</value></data>
<data name="Tooltips.Server.Sync.Resume" xml:space="preserve"><value>Resume this transfer where it stopped</value></data>
<data name="Tooltips.Server.Sync.Retrying" xml:space="preserve"><value>The last comparison failed: {0}. It is retried automatically.</value><comment>{0} reason</comment></data>
<data name="Tooltips.Server.Sync.SaveBoth" xml:space="preserve"><value>Take the server copy and keep this PC's settings as a dated copy of the project</value></data>
<data name="Tooltips.Server.Sync.Search" xml:space="preserve"><value>Filter the table by sequence title</value></data>
<data name="Tooltips.Server.Sync.SendExports.one" xml:space="preserve"><value>Send this PC's render to the server, verified by hash ({1})</value><comment>{0} count, {1} size</comment></data>
<data name="Tooltips.Server.Sync.SendExports.other" xml:space="preserve"><value>Send this PC's {0} renders to the server, verified by hash ({1})</value><comment>{0} count, {1} size</comment></data>
<data name="Tooltips.Server.Sync.ShowCopy" xml:space="preserve"><value>Show the saved copy of this PC's settings in File Explorer</value></data>
<data name="Tooltips.Server.Sync.State.Conflict" xml:space="preserve"><value>Settings changed both here and on the server; choose which to keep</value></data>
<data name="Tooltips.Server.Sync.State.Downloading" xml:space="preserve"><value>Originals or proxies are arriving from the server</value></data>
<data name="Tooltips.Server.Sync.State.Failed" xml:space="preserve"><value>This sequence could not be compared: {0}. It is compared again automatically.</value><comment>long; {0} reason</comment></data>
<data name="Tooltips.Server.Sync.State.InSync" xml:space="preserve"><value>Same originals and settings on this PC and on the server</value></data>
<data name="Tooltips.Server.Sync.State.LocalAhead" xml:space="preserve"><value>This PC has originals or settings the server does not have yet</value></data>
<data name="Tooltips.Server.Sync.State.LocalOnly" xml:space="preserve"><value>Only on this PC; upload it to keep it on the server too</value></data>
<data name="Tooltips.Server.Sync.State.Paused" xml:space="preserve"><value>The transfer is paused; resume it to continue</value></data>
<data name="Tooltips.Server.Sync.State.ProxiesOnly" xml:space="preserve"><value>On the server; this PC keeps its proxies for editing</value></data>
<data name="Tooltips.Server.Sync.State.RemoteOnly" xml:space="preserve"><value>Only on the server</value></data>
<data name="Tooltips.Server.Sync.State.ServerAhead" xml:space="preserve"><value>The server has originals or settings this PC does not have yet</value></data>
<data name="Tooltips.Server.Sync.State.Uploading" xml:space="preserve"><value>Originals are being sent to the server</value></data>
<data name="Tooltips.Server.Sync.State.Waiting" xml:space="preserve"><value>The transfer waits for its turn in the job queue</value></data>
<data name="Tooltips.Server.Sync.SyncSettings" xml:space="preserve"><value>Send or take the settings changed on one side</value></data>
<data name="Tooltips.Server.Sync.TakeServer" xml:space="preserve"><value>Replace this PC's settings with the server copy</value></data>
<data name="Tooltips.Server.Sync.Upload" xml:space="preserve"><value>Copy originals and settings to the server ({0})</value><comment>{0} size</comment></data>
<data name="Tooltips.Server.Sync.UploadAll" xml:space="preserve"><value>Send every local-only sequence to the server ({0} sequences, {1})</value><comment>{0} count, {1} size</comment></data>
<data name="Tooltips.Server.Sync.UploadAll.NoRight" xml:space="preserve"><value>Your account cannot upload to this server</value></data>
<data name="Tooltips.Server.Sync.UploadAll.NotConnected" xml:space="preserve"><value>Connect to a server to upload</value></data>
<data name="Tooltips.Server.Sync.UploadAll.Nothing" xml:space="preserve"><value>No sequence is only on this PC</value></data>
<data name="Tooltips.Server.Trust" xml:space="preserve"><value>Trust this certificate for this server and continue to sign in</value></data>
<data name="Tooltips.Server.UseFound" xml:space="preserve"><value>Use this address</value></data>
<data name="Tooltips.Settings.Adapter" xml:space="preserve"><value>Graphics adapter and Media Foundation encoders found</value></data>
+12
View File
@@ -20,6 +20,18 @@
<data name="Errors.Render.Sequence" xml:space="preserve"><value>La sequenza da renderizzare non è più nell'archivio.</value></data>
<data name="Errors.Server.Address" xml:space="preserve"><value>Inserisci l'indirizzo di un server, ad esempio nas.local:8443 o https://titano.example.com.</value></data>
<data name="Errors.Settings.Import" xml:space="preserve"><value>Questo file non contiene impostazioni di Titano.</value></data>
<data name="Errors.Sync.ChangedAgain" xml:space="preserve"><value>La sequenza è cambiata di nuovo su questo PC o sul server; confronta e scegli di nuovo.</value></data>
<data name="Errors.Sync.DiskFull" xml:space="preserve"><value>Al disco servono altri {0} GB per questo scaricamento.</value></data>
<data name="Errors.Sync.ExportsGone.one" xml:space="preserve"><value>{0} render non è più su questo PC; gli altri sono stati inviati.</value></data>
<data name="Errors.Sync.ExportsGone.other" xml:space="preserve"><value>{0} render non sono più su questo PC; gli altri sono stati inviati.</value></data>
<data name="Errors.Sync.Hash" xml:space="preserve"><value>{0} non è arrivato integro; scaricalo di nuovo.</value></data>
<data name="Errors.Sync.LocalMissing" xml:space="preserve"><value>La sequenza non è più nell'indice dell'archivio di questo PC.</value></data>
<data name="Errors.Sync.NoArchive" xml:space="preserve"><value>Apri o crea un archivio su questo PC per ricevere gli originali.</value></data>
<data name="Errors.Sync.NotConnected" xml:space="preserve"><value>Non connesso a questo server; collegati e riprova l'attività.</value></data>
<data name="Errors.Sync.NotLinked" xml:space="preserve"><value>Questa sequenza non è ancora sul server; caricala prima.</value></data>
<data name="Errors.Sync.NothingSent" xml:space="preserve"><value>Nessun originale è arrivato al server: mancano qui o sono già in un'altra sequenza del server.</value></data>
<data name="Errors.Sync.Unreadable.one" xml:space="preserve"><value>{0} originale manca o è cambiato dopo l'archiviazione; verifica l'archivio.</value></data>
<data name="Errors.Sync.Unreadable.other" xml:space="preserve"><value>{0} originali mancano o sono cambiati dopo l'archiviazione; verifica l'archivio.</value></data>
<data name="Errors.Template.Empty" xml:space="preserve"><value>Il modello è vuoto.</value></data>
<data name="Errors.Template.EmptyToken" xml:space="preserve"><value>Segnaposto vuoto alla posizione {1}: scrivi un nome tra le parentesi graffe.</value></data>
<data name="Errors.Template.FileSeparator" xml:space="preserve"><value>I nomi dei file non possono contenere la barra; metti le cartelle nel modello delle cartelle.</value></data>
+1
View File
@@ -33,6 +33,7 @@
<data name="Jobs.History.other" xml:space="preserve"><value>Cronologia di {0} giorni</value></data>
<data name="Jobs.Kind.Adopt" xml:space="preserve"><value>Adozione cartella</value></data>
<data name="Jobs.Kind.DeepAnalyse" xml:space="preserve"><value>Analisi approfondita</value></data>
<data name="Jobs.Kind.Download" xml:space="preserve"><value>Scaricamento</value></data>
<data name="Jobs.Kind.Duplicates" xml:space="preserve"><value>Duplicati</value></data>
<data name="Jobs.Kind.Import" xml:space="preserve"><value>Importazione</value></data>
<data name="Jobs.Kind.LightAnalyse" xml:space="preserve"><value>Analisi rapida</value></data>
+1
View File
@@ -61,6 +61,7 @@
<data name="Library.Sort.Title" xml:space="preserve"><value>Titolo</value></data>
<data name="Library.Status.Analysed" xml:space="preserve"><value>Analizzata</value></data>
<data name="Library.Status.Analysing" xml:space="preserve"><value>In analisi</value></data>
<data name="Library.Status.Conflict" xml:space="preserve"><value>Conflitto</value></data>
<data name="Library.Status.Proxies" xml:space="preserve"><value>Proxy</value></data>
<data name="Library.Status.Remote" xml:space="preserve"><value>Remota</value></data>
<data name="Library.Status.Synced" xml:space="preserve"><value>Sincronizzata</value></data>
+102
View File
@@ -4,12 +4,22 @@
<resheader name="version"><value>2.0</value></resheader>
<resheader name="reader"><value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
<resheader name="writer"><value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
<data name="Server.AutoSync" xml:space="preserve"><value>Sincronizza progetti automaticamente</value></data>
<data name="Server.Certificate" xml:space="preserve"><value>Certificato</value></data>
<data name="Server.Certificate.Forget" xml:space="preserve"><value>Dimentica</value></data>
<data name="Server.Certificate.Keep" xml:space="preserve"><value>Mantieni</value></data>
<data name="Server.Certificate.Message" xml:space="preserve"><value>Titano considera attendibile questo certificato per questo server. Se lo dimentichi la connessione si chiude e la prossima volta te lo chiederà di nuovo.</value></data>
<data name="Server.Certificate.Title" xml:space="preserve"><value>Certificato del server</value></data>
<data name="Server.Certificate.Trusted" xml:space="preserve"><value>TLS {0} attendibile dal {1}</value></data>
<data name="Server.Conflict.Cancel" xml:space="preserve"><value>Annulla</value></data>
<data name="Server.Conflict.Changed" xml:space="preserve"><value>{0}: valori diversi</value></data>
<data name="Server.Conflict.Difference" xml:space="preserve"><value>{0} {1} qui, {2} sul server</value></data>
<data name="Server.Conflict.KeepMine.Message" xml:space="preserve"><value>La copia sul server di {0} sarà sostituita dalle impostazioni di questo PC.</value></data>
<data name="Server.Conflict.KeepMine.Title" xml:space="preserve"><value>Tenere le impostazioni di questo PC?</value></data>
<data name="Server.Conflict.SaveBoth.Message" xml:space="preserve"><value>Questo PC prende la versione del server di {0} e conserva le proprie impostazioni come copia datata accanto al progetto.</value></data>
<data name="Server.Conflict.SaveBoth.Title" xml:space="preserve"><value>Salvare entrambe le versioni?</value></data>
<data name="Server.Conflict.TakeServer.Message" xml:space="preserve"><value>Le impostazioni di {0} su questo PC saranno sostituite dalla copia del server.</value></data>
<data name="Server.Conflict.TakeServer.Title" xml:space="preserve"><value>Usare le impostazioni del server?</value></data>
<data name="Server.Connect" xml:space="preserve"><value>Connetti</value></data>
<data name="Server.Disconnect" xml:space="preserve"><value>Disconnetti</value></data>
<data name="Server.Empty" xml:space="preserve"><value>Non connesso a un server</value></data>
@@ -70,6 +80,7 @@
<data name="Server.Error.WrongPassword" xml:space="preserve"><value>La password attuale è errata.</value></data>
<data name="Server.Error.WrongUploadKind" xml:space="preserve"><value>Questo caricamento appartiene a un job di rendering.</value></data>
<data name="Server.Found" xml:space="preserve"><value>Server trovati</value></data>
<data name="Server.KeepProxies" xml:space="preserve"><value>Proxy disponibili offline</value></data>
<data name="Server.Label.Account" xml:space="preserve"><value>Account</value></data>
<data name="Server.Label.Server" xml:space="preserve"><value>Server</value></data>
<data name="Server.Label.Status" xml:space="preserve"><value>Stato</value></data>
@@ -79,6 +90,7 @@
<data name="Server.Login.SignIn" xml:space="preserve"><value>Accedi</value></data>
<data name="Server.Login.Title" xml:space="preserve"><value>Accedi</value></data>
<data name="Server.Login.User" xml:space="preserve"><value>Utente</value></data>
<data name="Server.PauseMetered" xml:space="preserve"><value>Pausa su reti a consumo</value></data>
<data name="Server.Quota" xml:space="preserve"><value>{0} di {1}</value></data>
<data name="Server.QuotaUnlimited" xml:space="preserve"><value>{0} usati</value></data>
<data name="Server.RenderNode" xml:space="preserve"><value>Offri questo PC per il rendering</value></data>
@@ -87,11 +99,101 @@
<data name="Server.Role.Uploader" xml:space="preserve"><value>Caricatore</value></data>
<data name="Server.Role.Viewer" xml:space="preserve"><value>Visualizzatore</value></data>
<data name="Server.Service.Description" xml:space="preserve"><value>Server Titano per archivio time-lapse, caricamenti, job e rendering.</value></data>
<data name="Server.Setting.Aspect" xml:space="preserve"><value>Proporzioni</value></data>
<data name="Server.Setting.Auto" xml:space="preserve"><value>auto</value></data>
<data name="Server.Setting.Batch" xml:space="preserve"><value>Elenco batch</value></data>
<data name="Server.Setting.CameraOffset" xml:space="preserve"><value>Spostamento camera</value></data>
<data name="Server.Setting.Crop" xml:space="preserve"><value>Ritaglio</value></data>
<data name="Server.Setting.Deflicker" xml:space="preserve"><value>Deflicker</value></data>
<data name="Server.Setting.DeflickerStrength" xml:space="preserve"><value>Intensità deflicker</value></data>
<data name="Server.Setting.DeflickerWindow" xml:space="preserve"><value>Finestra deflicker</value></data>
<data name="Server.Setting.ExcludedFrames" xml:space="preserve"><value>Fotogrammi esclusi</value></data>
<data name="Server.Setting.ExportFolder" xml:space="preserve"><value>Cartella di esportazione</value></data>
<data name="Server.Setting.ExportPreset" xml:space="preserve"><value>Preset di esportazione</value></data>
<data name="Server.Setting.ExportValues" xml:space="preserve"><value>Valori di esportazione</value></data>
<data name="Server.Setting.ExposureOffset" xml:space="preserve"><value>Correzione esposizione</value></data>
<data name="Server.Setting.FitToDuration" xml:space="preserve"><value>Adatta alla durata</value></data>
<data name="Server.Setting.FlowQuality" xml:space="preserve"><value>Qualità del flusso</value></data>
<data name="Server.Setting.FrameRate" xml:space="preserve"><value>Frequenza fotogrammi</value></data>
<data name="Server.Setting.HeroFrame" xml:space="preserve"><value>Fotogramma copertina</value></data>
<data name="Server.Setting.HighlightKnee" xml:space="preserve"><value>Compressione alte luci</value></data>
<data name="Server.Setting.HolyGrail" xml:space="preserve"><value>Holy grail</value></data>
<data name="Server.Setting.Keyframes" xml:space="preserve"><value>Keyframe camera</value></data>
<data name="Server.Setting.Manual" xml:space="preserve"><value>manuale</value></data>
<data name="Server.Setting.MotionBlur" xml:space="preserve"><value>Sfocatura di movimento</value></data>
<data name="Server.Setting.Notes" xml:space="preserve"><value>Note</value></data>
<data name="Server.Setting.Off" xml:space="preserve"><value>disattivo</value></data>
<data name="Server.Setting.On" xml:space="preserve"><value>attivo</value></data>
<data name="Server.Setting.Other" xml:space="preserve"><value>Altra impostazione</value></data>
<data name="Server.Setting.OutputName" xml:space="preserve"><value>Nome del file</value></data>
<data name="Server.Setting.Rating" xml:space="preserve"><value>Valutazione</value></data>
<data name="Server.Setting.Regions" xml:space="preserve"><value>Regioni</value></data>
<data name="Server.Setting.ShutterAngle" xml:space="preserve"><value>Angolo otturatore</value></data>
<data name="Server.Setting.Stabilize" xml:space="preserve"><value>Stabilizzazione</value></data>
<data name="Server.Setting.StabilizeSmoothing" xml:space="preserve"><value>Morbidezza stabilizzazione</value></data>
<data name="Server.Setting.Stacking" xml:space="preserve"><value>Stacking</value></data>
<data name="Server.Setting.Tags" xml:space="preserve"><value>Tag</value></data>
<data name="Server.Setting.TimeRemap" xml:space="preserve"><value>Rimappatura del tempo</value></data>
<data name="Server.Setting.TimingMode" xml:space="preserve"><value>Modalità dei tempi</value></data>
<data name="Server.Setting.Title" xml:space="preserve"><value>Titolo</value></data>
<data name="Server.Setting.TrailLength" xml:space="preserve"><value>Lunghezza scie</value></data>
<data name="Server.Setting.Transitions" xml:space="preserve"><value>Transizioni</value></data>
<data name="Server.Setting.WhiteBalance" xml:space="preserve"><value>Livellamento WB</value></data>
<data name="Server.SignOut" xml:space="preserve"><value>Esci</value></data>
<data name="Server.Status.Connected" xml:space="preserve"><value>Connesso</value></data>
<data name="Server.Status.Connecting" xml:space="preserve"><value>Connessione…</value></data>
<data name="Server.Status.Disconnected" xml:space="preserve"><value>Disconnesso</value></data>
<data name="Server.Status.NotConnected" xml:space="preserve"><value>Non connesso</value></data>
<data name="Server.Sync.Action.DownloadOriginals" xml:space="preserve"><value>Scarica originali</value></data>
<data name="Server.Sync.Action.GetExports" xml:space="preserve"><value>Ricevi esportazioni</value></data>
<data name="Server.Sync.Action.KeepMine" xml:space="preserve"><value>Tieni le mie</value></data>
<data name="Server.Sync.Action.OpenWithProxies" xml:space="preserve"><value>Apri con i proxy</value></data>
<data name="Server.Sync.Action.Pause" xml:space="preserve"><value>Pausa</value></data>
<data name="Server.Sync.Action.Resume" xml:space="preserve"><value>Riprendi</value></data>
<data name="Server.Sync.Action.SaveBoth" xml:space="preserve"><value>Salva entrambe</value></data>
<data name="Server.Sync.Action.SendExports" xml:space="preserve"><value>Invia esportazioni</value></data>
<data name="Server.Sync.Action.SyncSettings" xml:space="preserve"><value>Sincronizza</value></data>
<data name="Server.Sync.Action.TakeServer" xml:space="preserve"><value>Usa il server</value></data>
<data name="Server.Sync.Action.Upload" xml:space="preserve"><value>Carica</value></data>
<data name="Server.Sync.Archive.one" xml:space="preserve"><value>Archivio del server {1} · {0} sequenza</value></data>
<data name="Server.Sync.Archive.other" xml:space="preserve"><value>Archivio del server {1} · {0} sequenze</value></data>
<data name="Server.Sync.Column.Local" xml:space="preserve"><value>Questo PC</value></data>
<data name="Server.Sync.Column.Sequence" xml:space="preserve"><value>Sequenza</value></data>
<data name="Server.Sync.Column.Server" xml:space="preserve"><value>Server</value></data>
<data name="Server.Sync.Column.State" xml:space="preserve"><value>Stato</value></data>
<data name="Server.Sync.Empty" xml:space="preserve"><value>Ancora nulla da confrontare</value></data>
<data name="Server.Sync.Exports.one" xml:space="preserve"><value>{0} esportazione</value></data>
<data name="Server.Sync.Exports.other" xml:space="preserve"><value>{0} esportazioni</value></data>
<data name="Server.Sync.Filter.All" xml:space="preserve"><value>Tutte · {0}</value></data>
<data name="Server.Sync.Filter.Conflicts" xml:space="preserve"><value>Conflitti · {0}</value></data>
<data name="Server.Sync.Filter.LocalOnly" xml:space="preserve"><value>Solo locali · {0}</value></data>
<data name="Server.Sync.Filter.Remote" xml:space="preserve"><value>Sul server · {0}</value></data>
<data name="Server.Sync.Last" xml:space="preserve"><value>Ultima sincronizzazione {0} · confronto {1} s</value></data>
<data name="Server.Sync.NoMatch" xml:space="preserve"><value>Nessuna sequenza corrisponde</value></data>
<data name="Server.Sync.OpenAdmin" xml:space="preserve"><value>Apri pannello admin</value></data>
<data name="Server.Sync.Originals" xml:space="preserve"><value>originali</value></data>
<data name="Server.Sync.Proxies" xml:space="preserve"><value>proxy</value></data>
<data name="Server.Sync.Queued.one" xml:space="preserve"><value>{0} caricamento in coda</value></data>
<data name="Server.Sync.Queued.other" xml:space="preserve"><value>{0} caricamenti in coda</value></data>
<data name="Server.Sync.Received" xml:space="preserve"><value>{0} ricevuto</value></data>
<data name="Server.Sync.Retrying" xml:space="preserve"><value>Confronto fallito · riprovo</value></data>
<data name="Server.Sync.SavedBoth" xml:space="preserve"><value>Impostazioni di questo PC salvate</value></data>
<data name="Server.Sync.Search" xml:space="preserve"><value>Cerca</value></data>
<data name="Server.Sync.ShowCopy" xml:space="preserve"><value>Mostra file</value></data>
<data name="Server.Sync.State.Conflict" xml:space="preserve"><value>impostazioni diverse</value></data>
<data name="Server.Sync.State.Downloading" xml:space="preserve"><value>in scaricamento</value></data>
<data name="Server.Sync.State.Failed" xml:space="preserve"><value>non confrontata</value></data>
<data name="Server.Sync.State.InSync" xml:space="preserve"><value>sincronizzata</value></data>
<data name="Server.Sync.State.LocalAhead" xml:space="preserve"><value>più recente qui</value></data>
<data name="Server.Sync.State.LocalOnly" xml:space="preserve"><value>solo locale</value></data>
<data name="Server.Sync.State.Paused" xml:space="preserve"><value>in pausa</value></data>
<data name="Server.Sync.State.ProxiesOnly" xml:space="preserve"><value>solo proxy</value></data>
<data name="Server.Sync.State.RemoteOnly" xml:space="preserve"><value>sul server</value></data>
<data name="Server.Sync.State.ServerAhead" xml:space="preserve"><value>server più recente</value></data>
<data name="Server.Sync.State.Uploading" xml:space="preserve"><value>in caricamento</value></data>
<data name="Server.Sync.State.Waiting" xml:space="preserve"><value>in attesa</value></data>
<data name="Server.Sync.Title" xml:space="preserve"><value>Sequenze</value></data>
<data name="Server.Sync.UploadAll" xml:space="preserve"><value>Carica le locali</value></data>
<data name="Server.Trust.Accept" xml:space="preserve"><value>Considera attendibile</value></data>
<data name="Server.Trust.Cancel" xml:space="preserve"><value>Annulla</value></data>
<data name="Server.Trust.Message" xml:space="preserve"><value>{0} usa un certificato che Titano non conosce ancora. Confronta l'impronta con quella del pannello di amministrazione del server prima di considerarlo attendibile.</value></data>
+47
View File
@@ -79,13 +79,16 @@
<data name="Tooltips.Library.Status" xml:space="preserve"><value>Filtra per analisi, proxy, verifica o avvisi</value></data>
<data name="Tooltips.Library.Status.Analysed" xml:space="preserve"><value>Analizzata: esposizione, flicker e movimento sono misurati</value></data>
<data name="Tooltips.Library.Status.Analysing" xml:space="preserve"><value>Un'attività di analisi è in corso su questa sequenza</value></data>
<data name="Tooltips.Library.Status.Conflict" xml:space="preserve"><value>Impostazioni cambiate qui e sul server; scegli nella schermata Server</value></data>
<data name="Tooltips.Library.Status.Errors" xml:space="preserve"><value>Alcuni fotogrammi mancano o sono illeggibili; apri la sequenza per i dettagli</value></data>
<data name="Tooltips.Library.Status.LocalAhead" xml:space="preserve"><value>Questo PC ha originali o impostazioni che il server non ha ancora</value></data>
<data name="Tooltips.Library.Status.NoProxies" xml:space="preserve"><value>Ancora nessun proxy; la modifica legge gli originali</value></data>
<data name="Tooltips.Library.Status.NotAnalysed" xml:space="preserve"><value>Non ancora analizzata</value></data>
<data name="Tooltips.Library.Status.Proxies" xml:space="preserve"><value>Proxy JPEG pronti per una modifica veloce</value></data>
<data name="Tooltips.Library.Status.Remote" xml:space="preserve"><value>Si trova sul server; questo PC ne ha al massimo i proxy</value></data>
<data name="Tooltips.Library.Status.Rendered.one" xml:space="preserve"><value>Esportata una volta</value></data>
<data name="Tooltips.Library.Status.Rendered.other" xml:space="preserve"><value>Esportata {0:N0} volte</value></data>
<data name="Tooltips.Library.Status.ServerAhead" xml:space="preserve"><value>Il server ha originali o impostazioni che questo PC non ha ancora</value></data>
<data name="Tooltips.Library.Status.Synced" xml:space="preserve"><value>Uguale su questo PC e sul server</value></data>
<data name="Tooltips.Library.Status.Warnings.one" xml:space="preserve"><value>{0:N0} avviso; apri la sequenza per i dettagli</value></data>
<data name="Tooltips.Library.Status.Warnings.other" xml:space="preserve"><value>{0:N0} avvisi; apri la sequenza per i dettagli</value></data>
@@ -102,18 +105,23 @@
<data name="Tooltips.Nav.Server" xml:space="preserve"><value>Connessione, sincronizzazione e nodo di rendering · Ctrl+6</value></data>
<data name="Tooltips.Nav.Settings" xml:space="preserve"><value>Preferenze di questo PC · Ctrl+,</value></data>
<data name="Tooltips.Server.Address" xml:space="preserve"><value>Indirizzo del Titano Server; si presume https · Invio per connettersi</value></data>
<data name="Tooltips.Server.AutoSync" xml:space="preserve"><value>Invia e ricevi le impostazioni dei progetti quando cambiano; quelle cambiate da entrambe le parti attendono la tua scelta nella tabella sotto</value></data>
<data name="Tooltips.Server.Certificate" xml:space="preserve"><value>Mostra l'impronta completa o revoca la fiducia</value></data>
<data name="Tooltips.Server.CertificateTrusted" xml:space="preserve"><value>Impronta accettata al primo utilizzo; se cambia, la connessione si blocca e te lo chiede di nuovo</value></data>
<data name="Tooltips.Server.Conflict.Cancel" xml:space="preserve"><value>Chiudi senza modificare nessuna delle due copie</value></data>
<data name="Tooltips.Server.Conflict.Detail" xml:space="preserve"><value>Le impostazioni diverse: il valore di questo PC, poi quello del server</value></data>
<data name="Tooltips.Server.Connect" xml:space="preserve"><value>Identifica il server, conferma un certificato nuovo e poi accedi · Invio</value></data>
<data name="Tooltips.Server.Disconnect" xml:space="preserve"><value>Chiude la sessione e lavora solo con l'archivio locale; l'accesso resta salvato</value></data>
<data name="Tooltips.Server.DontTrust" xml:space="preserve"><value>Non connetterti; a questo server non viene inviato nulla</value></data>
<data name="Tooltips.Server.Fingerprint" xml:space="preserve"><value>Impronta SHA-256 del certificato del server</value></data>
<data name="Tooltips.Server.ForgetTrust" xml:space="preserve"><value>Dimentica questo certificato; alla prossima connessione verrà chiesto di nuovo</value></data>
<data name="Tooltips.Server.Found" xml:space="preserve"><value>Server trovati in questa rete e usati in precedenza</value></data>
<data name="Tooltips.Server.KeepProxies" xml:space="preserve"><value>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</value></data>
<data name="Tooltips.Server.KeepTrust" xml:space="preserve"><value>Continua a considerare attendibile questo certificato</value></data>
<data name="Tooltips.Server.LoginCancel" xml:space="preserve"><value>Chiude senza accedere · Esc</value></data>
<data name="Tooltips.Server.LoginPassword" xml:space="preserve"><value>Inviata solo a questo server; Titano conserva un token di sessione, mai la password</value></data>
<data name="Tooltips.Server.LoginUser" xml:space="preserve"><value>Il tuo nome utente sul server</value></data>
<data name="Tooltips.Server.PauseMetered" xml:space="preserve"><value>Mette in pausa i caricamenti mentre Windows segnala questa connessione come a consumo; riprendono da soli quando non lo è</value></data>
<data name="Tooltips.Server.Quota" xml:space="preserve"><value>Spazio che usi sul server rispetto alla tua quota</value></data>
<data name="Tooltips.Server.RenderNode" xml:space="preserve"><value>Permette al server di inviare rendering a questo PC quando è inattivo; usa gli encoder della tua GPU</value></data>
<data name="Tooltips.Server.Role.Admin" xml:space="preserve"><value>Gli amministratori gestiscono utenti, archivio e server</value></data>
@@ -123,6 +131,45 @@
<data name="Tooltips.Server.SignIn" xml:space="preserve"><value>Accedi; il token viene salvato cifrato per questo utente di Windows · Invio</value></data>
<data name="Tooltips.Server.SignOut" xml:space="preserve"><value>Esci; il token viene rimosso da questo PC</value></data>
<data name="Tooltips.Server.Status" xml:space="preserve"><value>Connessione al server</value></data>
<data name="Tooltips.Server.Sync.Archive" xml:space="preserve"><value>Dimensione e sequenze dell'archivio del server</value></data>
<data name="Tooltips.Server.Sync.DownloadOriginals" xml:space="preserve"><value>Scarica gli originali su questo PC, verificati con l'hash ({0})</value></data>
<data name="Tooltips.Server.Sync.Filter.All" xml:space="preserve"><value>Tutte le sequenze di questo PC e del server</value></data>
<data name="Tooltips.Server.Sync.Filter.Conflicts" xml:space="preserve"><value>Le impostazioni differiscono tra questo PC e il server</value></data>
<data name="Tooltips.Server.Sync.Filter.LocalOnly" xml:space="preserve"><value>Solo su questo PC</value></data>
<data name="Tooltips.Server.Sync.Filter.Remote" xml:space="preserve"><value>Solo sul server</value></data>
<data name="Tooltips.Server.Sync.GetExports.one" xml:space="preserve"><value>Copia su questo PC il render del server ({1})</value></data>
<data name="Tooltips.Server.Sync.GetExports.other" xml:space="preserve"><value>Copia su questo PC i {0} render del server ({1})</value></data>
<data name="Tooltips.Server.Sync.KeepMine" xml:space="preserve"><value>Sovrascrivi la copia del server con le impostazioni di questo PC</value></data>
<data name="Tooltips.Server.Sync.LastSync" xml:space="preserve"><value>Quando questo PC ha confrontato per l'ultima volta tutte le sequenze con il server, e quanto ha impiegato</value></data>
<data name="Tooltips.Server.Sync.OpenAdmin" xml:space="preserve"><value>Apri l'amministrazione web nel browser (solo amministratori)</value></data>
<data name="Tooltips.Server.Sync.OpenWithProxies" xml:space="preserve"><value>Apri l'editor sui proxy; il rendering avviene sul server</value></data>
<data name="Tooltips.Server.Sync.Pause" xml:space="preserve"><value>Metti in pausa questo trasferimento; riprende da dove si è fermato</value></data>
<data name="Tooltips.Server.Sync.Resume" xml:space="preserve"><value>Riprendi questo trasferimento da dove si è fermato</value></data>
<data name="Tooltips.Server.Sync.Retrying" xml:space="preserve"><value>L'ultimo confronto non è riuscito: {0}. Viene ripetuto automaticamente.</value></data>
<data name="Tooltips.Server.Sync.SaveBoth" xml:space="preserve"><value>Usa la copia del server e conserva le impostazioni di questo PC come copia datata del progetto</value></data>
<data name="Tooltips.Server.Sync.Search" xml:space="preserve"><value>Filtra la tabella per titolo della sequenza</value></data>
<data name="Tooltips.Server.Sync.SendExports.one" xml:space="preserve"><value>Invia al server il render di questo PC, verificato con l'hash ({1})</value></data>
<data name="Tooltips.Server.Sync.SendExports.other" xml:space="preserve"><value>Invia al server i {0} render di questo PC, verificati con l'hash ({1})</value></data>
<data name="Tooltips.Server.Sync.ShowCopy" xml:space="preserve"><value>Mostra in Esplora file la copia salvata delle impostazioni di questo PC</value></data>
<data name="Tooltips.Server.Sync.State.Conflict" xml:space="preserve"><value>Le impostazioni sono cambiate sia qui sia sul server; scegli quali tenere</value></data>
<data name="Tooltips.Server.Sync.State.Downloading" xml:space="preserve"><value>Originali o proxy in arrivo dal server</value></data>
<data name="Tooltips.Server.Sync.State.Failed" xml:space="preserve"><value>Questa sequenza non è stata confrontata: {0}. Il confronto viene ripetuto automaticamente.</value></data>
<data name="Tooltips.Server.Sync.State.InSync" xml:space="preserve"><value>Stessi originali e impostazioni su questo PC e sul server</value></data>
<data name="Tooltips.Server.Sync.State.LocalAhead" xml:space="preserve"><value>Questo PC ha originali o impostazioni che il server non ha ancora</value></data>
<data name="Tooltips.Server.Sync.State.LocalOnly" xml:space="preserve"><value>Solo su questo PC; caricala per averla anche sul server</value></data>
<data name="Tooltips.Server.Sync.State.Paused" xml:space="preserve"><value>Il trasferimento è in pausa; riprendilo per continuare</value></data>
<data name="Tooltips.Server.Sync.State.ProxiesOnly" xml:space="preserve"><value>Sul server; questo PC ne conserva i proxy per modificarla</value></data>
<data name="Tooltips.Server.Sync.State.RemoteOnly" xml:space="preserve"><value>Solo sul server</value></data>
<data name="Tooltips.Server.Sync.State.ServerAhead" xml:space="preserve"><value>Il server ha originali o impostazioni che questo PC non ha ancora</value></data>
<data name="Tooltips.Server.Sync.State.Uploading" xml:space="preserve"><value>Originali in invio al server</value></data>
<data name="Tooltips.Server.Sync.State.Waiting" xml:space="preserve"><value>Il trasferimento attende il suo turno nella coda delle attività</value></data>
<data name="Tooltips.Server.Sync.SyncSettings" xml:space="preserve"><value>Invia o ricevi le impostazioni cambiate da una sola parte</value></data>
<data name="Tooltips.Server.Sync.TakeServer" xml:space="preserve"><value>Sostituisci le impostazioni di questo PC con la copia del server</value></data>
<data name="Tooltips.Server.Sync.Upload" xml:space="preserve"><value>Copia originali e impostazioni sul server ({0})</value></data>
<data name="Tooltips.Server.Sync.UploadAll" xml:space="preserve"><value>Invia al server ogni sequenza solo locale ({0} sequenze, {1})</value></data>
<data name="Tooltips.Server.Sync.UploadAll.NoRight" xml:space="preserve"><value>Il tuo account non può caricare su questo server</value></data>
<data name="Tooltips.Server.Sync.UploadAll.NotConnected" xml:space="preserve"><value>Collegati a un server per caricare</value></data>
<data name="Tooltips.Server.Sync.UploadAll.Nothing" xml:space="preserve"><value>Nessuna sequenza è solo su questo PC</value></data>
<data name="Tooltips.Server.Trust" xml:space="preserve"><value>Considera attendibile questo certificato per questo server e prosegui con l'accesso</value></data>
<data name="Tooltips.Server.UseFound" xml:space="preserve"><value>Usa questo indirizzo</value></data>
<data name="Tooltips.Settings.Adapter" xml:space="preserve"><value>Scheda grafica ed encoder Media Foundation trovati</value></data>
+216 -3
View File
@@ -9,6 +9,8 @@ using Titano.Core.Imaging;
using Titano.Core.Model;
using Titano.Core.Video;
using Titano.Data;
using Titano.Data.Jobs;
using Titano.Data.Sync;
using Titano.Protocol;
using Titano.Protocol.Client;
@@ -17,15 +19,21 @@ namespace Titano.App.DesignTime;
/// <summary>
/// Synthetic content for <c>--capture</c> screenshots and the screen smoke tests ONLY: a temporary SQLite index
/// with an archive of generated JPEGs (one sequence stores its thumbnail as an embedded preview inside a fake RAW
/// file), jobs in every state, a fake signed-in server and a fake encoder inventory. Everything lives in the
/// file), jobs in every state, a fake signed-in server with sequences to compare (one in conflict) and a fake
/// encoder inventory. Everything lives in the
/// capture environment's temporary folder; nothing touches the network or the user's data.
/// </summary>
public sealed class SampleData
{
public const string ServerFingerprint = "9A:3C:71:E0:5B:12:C4:88:0F:6D:2A:91:E7:44:B3:5C:19:D2:6F:80:A1:3E:57:C9:0B:64:F8:2D:93:A6:71:CE";
private const string ServerAddress = "https://nas.local:8443";
private readonly AppServices _services;
private readonly SampleSyncRemote _remote = new();
private TitanoDatabase? _db;
private Guid _sunrise;
private Guid _lakeComo;
private SampleData(AppServices services) => _services = services;
@@ -38,7 +46,9 @@ public sealed class SampleData
services.Server = new ServerSession(settings, services.SaveSettings, new SampleServerApiFactory(), new PlainTokenProtector());
services.Encoders = new SampleEncoders();
services.CheckForUpdateAsync = _ => Task.FromResult<ReleaseInfo?>(null);
return new SampleData(services);
var sample = new SampleData(services);
services.Sync.RemoteFactory = (_, _, _) => sample._remote;
return sample;
}
/// <summary>Opens the empty temporary index (first run: no archive, nothing indexed).</summary>
@@ -68,6 +78,7 @@ public sealed class SampleData
await db.Sequences.SetTagsAsync(sequences[9].Sequence.Id, ["holy grail"]);
foreach (var job in Jobs(sequences.Select(s => s.Sequence).ToList(), archive.Id)) await db.Jobs.EnqueueAsync(job);
await FillServerAsync(db, sequences.Select(s => s.Sequence).ToList());
settings.LastArchivePath = @"D:\TitanoArchive";
settings.ServerUrl = "https://nas.local:8443";
@@ -79,6 +90,111 @@ public sealed class SampleData
settings.FirstRunCompleted = true;
}
/// <summary>
/// Transfers for the sync table: an upload at 46 % (Comet over the ridge), an upload waiting (Fog lifting, Asti), a
/// download of originals running (Sunrise over Superga) and one paused (Lake Como storm).
/// </summary>
public async Task FillSyncAsync()
{
var db = _db ?? throw new InvalidOperationException("FillAsync first.");
async Task<Sequence> LocalAsync(string text) => (await db.Sequences.ListAsync(new Data.Repositories.SequenceQuery { Text = text, Limit = 1 })).Items[0];
var now = DateTimeOffset.UtcNow;
Job Transfer(JobKind kind, Guid target, string label, string parameters, JobState state, long done, long total) => new()
{
Id = Guid.CreateVersion7(),
Kind = kind,
TargetIds = [target],
TargetLabel = label,
ParametersJson = parameters,
State = state,
Priority = JobPriority.User,
ProgressDone = done,
ProgressTotal = total,
ItemsPerSecond = state == JobState.Running ? 1.6 : null,
Eta = state == JobState.Running ? TimeSpan.FromMinutes(4) : null,
NodeId = state == JobState.Queued ? null : _services.WorkerId,
Attempts = state == JobState.Queued ? 0 : 1,
Created = now.AddMinutes(-5),
Started = state == JobState.Queued ? null : now.AddMinutes(-5),
};
var upload = $$"""{"server":"{{ServerAddress}}"}""";
var originals = $$"""{"server":"{{ServerAddress}}","mode":"Originals"}""";
var comet = await LocalAsync("Comet");
var fog = await LocalAsync("Fog lifting");
await db.Jobs.EnqueueAsync(Transfer(JobKind.UploadCommit, comet.Id, comet.DisplayTitle, upload, JobState.Running, 462, 1_005));
await db.Jobs.EnqueueAsync(Transfer(JobKind.UploadCommit, fog.Id, fog.DisplayTitle, upload, JobState.Queued, 0, 0));
await db.Jobs.EnqueueAsync(Transfer(JobKind.Download, _sunrise, "Sunrise over Superga", originals, JobState.Running, 1_210, 2_880));
await db.Jobs.EnqueueAsync(Transfer(JobKind.Download, _lakeComo, "Lake Como storm", originals, JobState.Paused, 300, 1_450));
}
/// <summary>
/// Fetches the proxies of Sunrise over Superga into the proxy cache through a download job on a one-off engine (the
/// capture's engine does not run jobs), so the sync table shows a sequence kept with proxies only.
/// </summary>
public async Task CacheProxiesAsync()
{
var db = _db ?? throw new InvalidOperationException("FillAsync first.");
var service = _services.Sync.Service ?? throw new InvalidOperationException("The index is not open.");
await using var engine = new JobEngine(db, service.CreateJobHandlers(_services.Sync),
new JobEngineOptions { Workers = 1, WorkerId = "sample-proxies", Kinds = [JobKind.Download], PollInterval = TimeSpan.FromMilliseconds(50) });
await engine.StartAsync();
var job = await service.EnqueueDownloadAsync(engine, ServerAddress, _sunrise, "Sunrise over Superga", SyncDownloadMode.Proxies, null);
for (var i = 0; i < 200 && await db.Jobs.GetAsync(job.Id) is { State: JobState.Queued or JobState.Running }; i++) await Task.Delay(50);
}
/// <summary>
/// The server's side: six sequences this PC also holds (two the same, one with settings changed on both sides, one
/// with more originals on the server, one with more here, one with renders this PC lacks) and two only on the server;
/// the others are only here.
/// </summary>
private async Task FillServerAsync(TitanoDatabase db, IReadOnlyList<Sequence> local)
{
Guid Id(string title) => local.First(s => s.Title == title).Id;
await db.Sequences.EditAsync(Id("Holy grail · Monviso"), new Data.Repositories.SequenceEdit { SettingsJson = DeflickerWindow(41) }, null);
var linked = new (string Title, int Frames, string? Settings, int Renders)[]
{
("Harbour sunset", 3, null, 0),
("Aurora, Tromsø", 3, null, 0),
("Holy grail · Monviso", 3, DeflickerWindow(33), 0),
("Construction cam · week 38", 8, null, 0),
("Milan skyline dusk", 1, null, 0),
("Star trails, Colle del Nivolet", 3, null, 3),
};
foreach (var (title, frames, settings, renders) in linked)
{
// The server's copy carries the same title, tags and rating as this PC's.
var sequence = (await db.Sequences.GetAsync(Id(title)))!;
var remote = _remote.Add(SampleSyncRemote.Dto(sequence) with { RenderedCount = renders }, settings, frames);
await _services.Sync.Service!.LinkAsync(ServerAddress, remote, sequence.Id);
}
_sunrise = _remote.Add(SampleSyncRemote.Dto(new Sequence
{
Id = Guid.CreateVersion7(),
ArchiveId = Guid.Empty,
Title = "Sunrise over Superga",
Folder = "2026/2026-07-02 Sony ILCE-7M4",
FrameCount = 2_880,
TotalBytes = 2_880 * 21_000_000L,
Status = SequenceStatus.ProxiesBuilt | SequenceStatus.ThumbsBuilt,
RenderedCount = 1,
UpdatedAt = DateTimeOffset.UtcNow,
}), null, 3);
_lakeComo = _remote.Add(SampleSyncRemote.Dto(new Sequence
{
Id = Guid.CreateVersion7(),
ArchiveId = Guid.Empty,
Title = "Lake Como storm",
Folder = "2026/2026-08-21 Canon EOS R5",
FrameCount = 1_450,
TotalBytes = 1_450 * 45_000_000L,
Status = SequenceStatus.ThumbsBuilt,
UpdatedAt = DateTimeOffset.UtcNow,
}), null, 3);
static string DeflickerWindow(int frames) =>
"""{"exposure":{"deflickerWindow":{"isAuto":false,"manual":""" + frames.ToString(System.Globalization.CultureInfo.InvariantCulture) + "}}}";
}
private IEnumerable<(Sequence Sequence, string[] Colours, bool Raw)> Sequences(Guid archiveId)
{
var now = new DateTime(2026, 9, 28, 18, 2, 11);
@@ -278,7 +394,8 @@ public sealed class SampleData
private sealed class SampleServerApi(Uri baseAddress, IReadOnlyCollection<string> trusted) : IServerApi
{
private static readonly UserDto User = new(Guid.Empty, "alberto", "Alberto", "editor", 0, 5_000_000_000_000, 2_100_000_000_000, false, false,
private static readonly UserDto User = new(Guid.Empty, "alberto", "Alberto", "editor", (long)RolePermissions.Default(UserRole.Editor), 5_000_000_000_000,
2_100_000_000_000, false, false,
new DateTimeOffset(2025, 1, 1, 0, 0, 0, TimeSpan.Zero), DateTimeOffset.UtcNow);
public Uri BaseAddress { get; } = baseAddress;
@@ -308,6 +425,102 @@ public sealed class SampleData
}
}
/// <summary>
/// The sample server's sequences for the sync table: listings, manifests (frames hashed from their index, so
/// unhashed sample frames match them by count; renders as many as the listing says), settings edits and proxies
/// (generated JPEGs); uploads and originals are not part of the screenshots.
/// </summary>
private sealed class SampleSyncRemote : ISyncRemote
{
private readonly Dictionary<Guid, (SequenceDto Dto, string? Settings, Guid[] Frames)> _sequences = [];
public string Server => ServerAddress;
public static SequenceDto Dto(Sequence s) => new(Guid.CreateVersion7(), s.Title, s.DisplayTitle, s.Folder, s.CameraMake, s.CameraModel, s.Lens,
s.FirstCapture, s.LastCapture, s.FrameCount, s.MedianInterval, s.TotalBytes, (long)s.Status, s.RenderedCount, null, s.Tags, s.Rating, s.Notes, 2, 1,
0, null, s.UpdatedAt);
public Guid Add(SequenceDto dto, string? settings, int frames)
{
lock (_sequences) _sequences[dto.Id] = (dto, settings, [.. Enumerable.Range(0, frames).Select(_ => Guid.CreateVersion7())]);
return dto.Id;
}
public Task<IReadOnlyList<SequenceDto>> ListSequencesAsync(CancellationToken cancellationToken)
{
lock (_sequences) return Task.FromResult<IReadOnlyList<SequenceDto>>([.. _sequences.Values.Select(s => s.Dto)]);
}
public Task<SequenceDto> GetSequenceAsync(Guid id, CancellationToken cancellationToken)
{
lock (_sequences) return Task.FromResult(_sequences[id].Dto);
}
public Task<SequenceManifest> GetManifestAsync(Guid id, CancellationToken cancellationToken)
{
lock (_sequences)
{
var (dto, settings, frames) = _sequences[id];
var hasProxy = (dto.Status & (long)SequenceStatus.ProxiesBuilt) != 0;
var created = new DateTimeOffset(2026, 9, 20, 21, 0, 0, TimeSpan.Zero);
return Task.FromResult(new SequenceManifest(id, dto.FramesVersion, dto.SettingsVersion, settings, dto.Tags,
[.. frames.Select((frame, i) => new ManifestFrame(frame, i, $"IMG_{i + 1:0000}.JPG", 24_000_000,
Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(BitConverter.GetBytes(i))), hasProxy, true))],
[.. Enumerable.Range(0, dto.RenderedCount).Select(i => new RenderDto(Guid.CreateVersion7(), i == 0 ? "4K HEVC" : "1080p H.264", "hevc",
3840, 2160, 30, 21.3, 640_000_000, created.AddHours(i), "Studio NAS"))]));
}
}
public Task<IReadOnlyList<FrameDto>> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken)
{
lock (_sequences)
{
return Task.FromResult<IReadOnlyList<FrameDto>>([.. _sequences[sequenceId].Frames.Select((frame, i) => new FrameDto(frame, sequenceId, i,
$"IMG_{i + 1:0000}.JPG", 24_000_000, null, new DateTime(2026, 7, 2, 5, 40, 0).AddSeconds(30 * i), null, 1.0 / 250, 8, 100, 24, 1, 320, 180,
"jpeg", 0))]);
}
}
public Task<SequenceDto> UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken)
{
lock (_sequences)
{
var (dto, _, frames) = _sequences[id];
var updated = dto with { SettingsVersion = dto.SettingsVersion + 1, UpdatedAt = DateTimeOffset.UtcNow };
_sequences[id] = (updated, request.SettingsJson, frames);
return Task.FromResult(updated);
}
}
public Task<CompleteUploadResponse?> UploadFileAsync(string path, Guid? sequenceId, string? sessionKey, string sha256, DateTime? capturedAt,
CancellationToken cancellationToken) => throw new NotSupportedException("The sample server takes no uploads.");
/// <summary>Proxies and thumbnails: a dawn gradient whose sun rises with the frame.</summary>
public async Task DownloadFrameAsync(Guid frameId, string kind, Stream destination, CancellationToken cancellationToken)
{
if (kind == "original") throw new NotSupportedException("The sample server serves no originals.");
int index;
lock (_sequences) index = _sequences.Values.Select(s => Array.IndexOf(s.Frames, frameId)).Max();
await destination.WriteAsync(Gradient(["#1B2A4A", "#E8925A", "#F6D28B"], 320, 180, index / 3.0), cancellationToken);
}
public Task<string?> DownloadRenderAsync(Guid renderId, Stream destination, CancellationToken cancellationToken) =>
throw new NotSupportedException("The sample server serves no renders.");
public Task<RenderDto?> UploadRenderAsync(Guid sequenceId, string path, RenderUploadRequest request, CancellationToken cancellationToken) =>
throw new NotSupportedException("The sample server takes no renders.");
public async IAsyncEnumerable<ServerEvent> EventsAsync([System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken)
{
await Task.Delay(Timeout.Infinite, cancellationToken);
yield break;
}
public void Dispose()
{
}
}
/// <summary>No encryption: the capture environment is thrown away.</summary>
private sealed class PlainTokenProtector : ITokenProtector
{
+20 -4
View File
@@ -28,8 +28,9 @@ namespace Titano.App.Infrastructure;
/// Composition root of local mode (BRIEF §4.4): the SQLite index under the data folder (migrated on open), the
/// archive engine (WIC first, then managed decoders), the analysis and render engine (the same decoders; Media
/// Foundation, then managed encoders), the one <see cref="JobEngine"/> of this PC with the handlers of
/// <see cref="CreateJobHandlers"/>, thumbnails, the server session, the render node, the encoder inventory and the
/// update check. Started after the window shows, stopped when the app exits. The last archive is reopened at start and
/// <see cref="CreateJobHandlers"/>, thumbnails, the server session, the render node, the encoder inventory, the
/// update check and the sync with the signed-in server (<see cref="SyncHost"/>). Started after the window shows,
/// stopped when the app exits. The last archive is reopened at start and
/// rescanned every <see cref="ScanInterval"/> (BRIEF §7: polling, no file-system watchers). The render node runs while
/// the user offers this PC (<see cref="AppSettings.RenderNodeOptIn"/>) and a server session is open (never in capture
/// mode). Renders and the render node use hardware encoders as Settings › Rendering allows
@@ -60,6 +61,7 @@ public sealed class AppServices : IAsyncDisposable
Dialogs = dialogs;
_renderNode = new RenderNodeHost(StartRenderNode);
ArchiveSetup = new EngineArchiveSetup(this);
Sync = new SyncHost(this);
Server = new ServerSession(settings, saveSettings, new TitanoServerApiFactory(), new DpapiTokenProtector());
Encoders = new MediaFoundationInventory();
CheckForUpdateAsync = ct => UpdateCheck.FetchAsync(Http.Value, ProductLinks.LatestReleaseApi, VersionText, ct);
@@ -92,9 +94,13 @@ public sealed class AppServices : IAsyncDisposable
_server = value;
_server.PropertyChanged += OnServerChanged;
UpdateRenderNode();
Sync.Update();
}
}
/// <summary>Sync with the signed-in server: engine, job connection, background comparison.</summary>
public SyncHost Sync { get; }
public IEncoderInventory Encoders { get; set; }
/// <summary>Latest public release (GitHub Releases API of the releases repository, BRIEF §18).</summary>
@@ -125,7 +131,10 @@ public sealed class AppServices : IAsyncDisposable
/// <summary>The job handlers of this PC's engine — the single registration list; a kind without a handler stays
/// queued (it is never claimed here).</summary>
public static IReadOnlyList<IJobHandler> CreateJobHandlers(AppServices services) =>
[.. services.Archives?.CreateJobHandlers() ?? [], .. services.Processing?.CreateJobHandlers() ?? []];
[
.. services.Archives?.CreateJobHandlers() ?? [], .. services.Processing?.CreateJobHandlers() ?? [],
.. services.Sync.Service?.CreateJobHandlers(services.Sync) ?? [],
];
/// <summary>Queues a scan of <paramref name="archive"/> unless one is already waiting or running.</summary>
public async Task QueueScanAsync(Archive archive, bool full, CancellationToken ct = default)
@@ -199,6 +208,7 @@ public sealed class AppServices : IAsyncDisposable
_stopping.Dispose();
_server.PropertyChanged -= OnServerChanged;
await _renderNode.DisposeAsync().ConfigureAwait(false);
await Sync.DisposeAsync().ConfigureAwait(false);
(Jobs as IDisposable)?.Dispose();
if (Engine is not null) await Engine.DisposeAsync().ConfigureAwait(false);
Thumbnails?.Dispose();
@@ -235,6 +245,7 @@ public sealed class AppServices : IAsyncDisposable
var archive = new ArchiveServiceOptions { Decoder = DecoderFactory.CreateClient(new WicDecoderProvider()) };
Archives = new ArchiveService(database, archive);
Processing = new ProcessingService(database, ProcessingOptions(archive));
Sync.Open(database, Archives, archive);
var handlers = CreateJobHandlers(this);
var kinds = handlers.Select(h => h.Kind).Distinct().ToArray();
Engine = new JobEngine(database, handlers, new JobEngineOptions { WorkerId = WorkerId, Kinds = kinds });
@@ -244,6 +255,7 @@ public sealed class AppServices : IAsyncDisposable
Jobs = new EngineJobQueue(database, Engine, started);
Log.Info("jobs", started ? $"Job engine started with {Engine.Options.Workers} worker(s) for {string.Join(", ", kinds)}" : "No job handlers registered; jobs stay queued");
UpdateRenderNode();
Sync.Update();
}
/// <summary>Media Foundation (hardware first, software H.264; hardware as Settings › Rendering allows) then managed
@@ -263,7 +275,11 @@ public sealed class AppServices : IAsyncDisposable
},
};
private void OnServerChanged(object? sender, PropertyChangedEventArgs e) => UpdateRenderNode();
private void OnServerChanged(object? sender, PropertyChangedEventArgs e)
{
UpdateRenderNode();
Sync.Update();
}
/// <summary>
/// The render node of <paramref name="session"/>: this PC's encoders (Media Foundation, then managed), downloads and
@@ -111,6 +111,15 @@ public sealed class AppSettings
/// <summary>Let the server send render jobs to this PC (BRIEF §14.7).</summary>
public bool RenderNodeOptIn { get; set; }
/// <summary>Keep the proxy caches of the server sequences this PC opened with proxies up to date (BRIEF §12.7).</summary>
public bool KeepProxiesOffline { get; set; }
/// <summary>Send and take project settings changed on one side without asking (Server.html).</summary>
public bool SyncSettingsAutomatically { get; set; } = true;
/// <summary>Pause upload jobs while Windows reports the connection as metered (Server.html).</summary>
public bool PauseUploadsOnMetered { get; set; }
// ---- Jobs ----
/// <summary>"Clear done": finished jobs older than this are hidden from the Jobs list (they stay in the history).</summary>
public DateTimeOffset? JobsClearedAt { get; set; }
+15 -3
View File
@@ -147,7 +147,20 @@ public sealed class SequenceItem : ObservableObject
OnPropertyChanged(nameof(PrimaryStatus));
}
/// <summary>Card status row: analysed, proxies, renders, sync, warnings (Main.html).</summary>
/// <summary>
/// Where a local copy stands against the server (the sync engine writes the state), in one word as DESIGN §4 draws
/// it ("● Synced", "● Remote", "▲ Conflict") with the detail in the tooltip; null while it is only here.
/// </summary>
public static CardStatus? SyncStatus(SyncState state) => state switch
{
SyncState.InSync => new CardStatus(StatusKind.Synced, Loc.L("Library.Status.Synced"), Loc.L("Tooltips.Library.Status.Synced")),
SyncState.LocalAhead => new CardStatus(StatusKind.Synced, Loc.L("Library.Status.Synced"), Loc.L("Tooltips.Library.Status.LocalAhead")),
SyncState.ServerAhead => new CardStatus(StatusKind.Remote, Loc.L("Library.Status.Remote"), Loc.L("Tooltips.Library.Status.ServerAhead")),
SyncState.Conflict => new CardStatus(StatusKind.Warning, Loc.L("Library.Status.Conflict"), Loc.L("Tooltips.Library.Status.Conflict")),
_ => null,
};
/// <summary>Card status row: analysed, proxies, renders, errors or warnings, sync (Main.html); the sync glyph is last so a narrow card cuts it first.</summary>
public static IReadOnlyList<CardStatus> BuildStatuses(Sequence s, bool analysing)
{
var list = new List<CardStatus>(5);
@@ -168,12 +181,11 @@ public sealed class SequenceItem : ObservableObject
if (s.RenderedCount > 0)
list.Add(new CardStatus(StatusKind.Rendered, Formatting.Count(s.RenderedCount), Loc.Plural("Tooltips.Library.Status.Rendered", s.RenderedCount)));
if (s.SyncState == SyncState.InSync)
list.Add(new CardStatus(StatusKind.Synced, Loc.L("Library.Status.Synced"), Loc.L("Tooltips.Library.Status.Synced")));
if ((s.Status & SequenceStatus.HasErrors) != 0)
list.Add(new CardStatus(StatusKind.Error, Formatting.Count(Math.Max(1, s.WarningCount)), Loc.L("Tooltips.Library.Status.Errors")));
else if (s.WarningCount > 0 || (s.Status & SequenceStatus.HasWarnings) != 0)
list.Add(new CardStatus(StatusKind.Warning, Formatting.Count(Math.Max(1, s.WarningCount)), Loc.Plural("Tooltips.Library.Status.Warnings", Math.Max(1, s.WarningCount))));
if (SyncStatus(s.SyncState) is { } sync) list.Add(sync);
return list;
}
}
+4 -1
View File
@@ -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)
{
+135 -1
View File
@@ -15,9 +15,12 @@
<Setter Property="Margin" Value="8,0" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
<ItemsPanelTemplate x:Key="Panel.Row">
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</UserControl.Resources>
<!-- Server.html: the connection panel; the render-node panel (right) and the sync table (below) join later. -->
<!-- Server.html: the connection panel, then the sync table; the render-node panel joins the connection panel. -->
<Grid Margin="20,16,20,12">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
@@ -112,9 +115,140 @@
<Border Grid.Row="3" Grid.ColumnSpan="2" Margin="0,14,0,0" Padding="0,10,0,0" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,1,0,0">
<WrapPanel>
<CheckBox Content="{l:Loc Server.RenderNode}" IsChecked="{Binding RenderNodeOptIn}" ToolTip="{l:Loc Tooltips.Server.RenderNode}" Margin="0,0,22,0" />
<CheckBox Content="{l:Loc Server.KeepProxies}" IsChecked="{Binding KeepProxiesOffline}" ToolTip="{l:Loc Tooltips.Server.KeepProxies}" Margin="0,0,22,0" />
<CheckBox Content="{l:Loc Server.AutoSync}" IsChecked="{Binding SyncSettingsAutomatically}" ToolTip="{l:Loc Tooltips.Server.AutoSync}" Margin="0,0,22,0" />
<CheckBox Content="{l:Loc Server.PauseMetered}" IsChecked="{Binding PauseUploadsOnMetered}" ToolTip="{l:Loc Tooltips.Server.PauseMetered}" Margin="0,0,22,0" />
</WrapPanel>
</Border>
</Grid>
</Border>
<!-- Sequences of this PC and of the server: chips, search, Upload all local; table; footer. -->
<Border Grid.Row="1" Style="{StaticResource Border.Panel}" Margin="0,14,0,0" DataContext="{Binding Sync}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<!-- Toolbar in visual (and Tab) order: title, chips, search, Upload all local. -->
<Grid Margin="14,10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="{l:Loc Server.Sync.Title}" FontWeight="SemiBold" VerticalAlignment="Center" Margin="0,0,10,0" />
<ItemsControl Grid.Column="1" ItemsSource="{Binding Chips}" ItemsPanel="{StaticResource Panel.Row}" Focusable="False" VerticalAlignment="Center">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type srv:SyncFilterChip}">
<Button x:Name="Chip" Style="{StaticResource Button.Chip}" Content="{Binding Text}" Tag="{Binding IsSelected}" Command="{Binding SelectCommand}"
ToolTip="{Binding ToolTip}" Height="28" FontSize="12" Margin="0,0,10,0" Typography.NumeralAlignment="Tabular" />
<DataTemplate.Triggers>
<!-- Conflicts waiting are drawn in warning colours, unless the chip is the chosen one (then Accent, DESIGN §4). -->
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding NeedsAttention}" Value="True" />
<Condition Binding="{Binding IsSelected}" Value="False" />
</MultiDataTrigger.Conditions>
<Setter TargetName="Chip" Property="BorderBrush" Value="{DynamicResource Brush.Warning}" />
<Setter TargetName="Chip" Property="Foreground" Value="{DynamicResource Brush.Warning}" />
</MultiDataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<TextBox Grid.Column="3" Width="200" Height="30" Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}" ui:Field.Glyph="{StaticResource Icon.Search}"
ui:Field.Placeholder="{l:Loc Server.Sync.Search}" ToolTip="{l:Loc Tooltips.Server.Sync.Search}" AutomationProperties.Name="{l:Loc Server.Sync.Search}" />
<Button Grid.Column="4" Content="{l:Loc Server.Sync.UploadAll}" Command="{Binding UploadAllCommand}" ToolTip="{Binding UploadAllToolTip}"
ToolTipService.ShowOnDisabled="True" Height="30" Margin="10,0,0,0" />
</Grid>
<!-- Header; the rows repeat its columns (Server.html: 1.6fr 150px 150px 150px 1.4fr with 10 px gaps). The right padding
keeps the space of the rows' scroll bar, so the columns line up. -->
<Border Grid.Row="1" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,1,0,1" Padding="14,8,24,8">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1.6*" MinWidth="140" />
<ColumnDefinition Width="160" />
<ColumnDefinition Width="160" />
<ColumnDefinition Width="160" />
<ColumnDefinition Width="1.4*" MinWidth="280" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Header}" Text="{l:Loc Server.Sync.Column.Sequence}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Header}" Text="{l:Loc Server.Sync.Column.Local}" Margin="10,0,0,0" />
<TextBlock Grid.Column="2" Style="{StaticResource Text.Header}" Text="{l:Loc Server.Sync.Column.Server}" Margin="10,0,0,0" />
<TextBlock Grid.Column="3" Style="{StaticResource Text.Header}" Text="{l:Loc Server.Sync.Column.State}" Margin="10,0,0,0" />
</Grid>
</Border>
<!-- Rows (virtualised): this PC, the server, the state and the actions that apply; conflicts on the card colour.
Tab walks every row button (the rows themselves take no focus). Actions wrap when longer labels need it. -->
<ListBox x:Name="SyncList" Grid.Row="2" ItemsSource="{Binding Rows}" ItemContainerStyle="{StaticResource ListBoxItem.PlainRow}"
VirtualizingPanel.IsVirtualizing="True" VirtualizingPanel.VirtualizationMode="Recycling" VirtualizingPanel.ScrollUnit="Pixel"
ScrollViewer.HorizontalScrollBarVisibility="Disabled" KeyboardNavigation.TabNavigation="Continue"
AutomationProperties.Name="{l:Loc Server.Sync.Title}" Visibility="{Binding HasRows, Converter={StaticResource BoolToVisibility}}">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type srv:SyncRow}">
<Border x:Name="RowBorder" Background="Transparent" Padding="14,0">
<Grid MinHeight="40">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1.6*" MinWidth="140" />
<ColumnDefinition Width="160" />
<ColumnDefinition Width="160" />
<ColumnDefinition Width="160" />
<ColumnDefinition Width="1.4*" MinWidth="280" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Cell}" Text="{Binding Title}" ToolTip="{Binding Title}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding LocalText}" ToolTip="{Binding LocalText}" Margin="10,0,0,0" />
<TextBlock Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding ServerText}" ToolTip="{Binding ServerText}" Margin="10,0,0,0" />
<ui:StatusGlyph Grid.Column="3" Kind="{Binding StateKind}" Text="{Binding StateText}" ToolTip="{Binding StateToolTip}"
FontSize="13" VerticalAlignment="Center" Margin="10,0,0,0" />
<ItemsControl Grid.Column="4" ItemsSource="{Binding Actions}" Focusable="False" VerticalAlignment="Center" Margin="10,4,0,4">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type srv:SyncRowAction}">
<Button Style="{StaticResource Button.Row}" Content="{Binding Text}" Command="{Binding Command}" ToolTip="{Binding ToolTip}"
FontSize="12" Margin="0,2,6,2" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Border>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding IsConflict}" Value="True">
<Setter TargetName="RowBorder" Property="Background" Value="{DynamicResource Brush.Card}" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<ui:EmptyState Grid.Row="2" Message="{Binding EmptyText}" Visibility="{Binding EmptyText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}" />
<!-- Footer: last comparison · server archive · retry state · admin panel. -->
<Border Grid.Row="3" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,1,0,0" Padding="14,8">
<DockPanel LastChildFill="False" TextElement.FontSize="12">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Link}" Content="{l:Loc Server.Sync.OpenAdmin}" Command="{Binding OpenAdminCommand}"
ToolTip="{l:Loc Tooltips.Server.Sync.OpenAdmin}" Visibility="{Binding CanOpenAdmin, Converter={StaticResource BoolToVisibility}}" />
<TextBlock Text="{Binding LastSyncText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,0,16,0" VerticalAlignment="Center"
Typography.NumeralAlignment="Tabular" ToolTip="{l:Loc Tooltips.Server.Sync.LastSync}"
Visibility="{Binding LastSyncText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}" />
<TextBlock Text="{Binding ArchiveText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,0,16,0" VerticalAlignment="Center"
Typography.NumeralAlignment="Tabular" ToolTip="{l:Loc Tooltips.Server.Sync.Archive}"
Visibility="{Binding ArchiveText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}" />
<ui:StatusGlyph Kind="Warning" Text="{Binding ErrorText}" ToolTip="{Binding ErrorToolTip}" FontSize="12" VerticalAlignment="Center"
Visibility="{Binding ErrorText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}" />
</DockPanel>
</Border>
</Grid>
</Border>
</Grid>
</UserControl>
+46 -3
View File
@@ -10,9 +10,9 @@ using Titano.Ui.Mvvm;
namespace Titano.App.Sections;
/// <summary>
/// Server, connection part (BRIEF §12.7, Server.html): address with LAN-discovered servers, connect with
/// trust-on-first-use and login, status (name, version, latency, certificate), account and quota, sign out, and
/// the render-node opt-in. The sync table and render-node panel join this screen later.
/// Server (BRIEF §12.7, Server.html): address with LAN-discovered servers, connect with trust-on-first-use and login,
/// status (name, version, latency, certificate), account and quota, sign out, the options of this PC (render node,
/// proxies kept offline, automatic project sync, uploads paused on metered networks) and the sync table (<see cref="Sync"/>).
/// </summary>
public sealed class ServerViewModel : SectionViewModel
{
@@ -34,8 +34,12 @@ public sealed class ServerViewModel : SectionViewModel
else if (p is string text) Address = text;
});
CertificateCommand = new RelayCommand(ShowCertificate, () => Fingerprint is not null);
Sync = new SyncTableViewModel(shell);
}
/// <summary>Sequences of this PC and of the server, where they stand and what can be done.</summary>
public SyncTableViewModel Sync { get; }
public ShellViewModel Shell { get; }
private ServerSession Session => _session ?? Shell.Services.Server;
@@ -134,6 +138,34 @@ public sealed class ServerViewModel : SectionViewModel
}
}
/// <summary>Keep the proxy caches of server sequences opened with proxies up to date on this PC.</summary>
public bool KeepProxiesOffline
{
get => Shell.Services.Settings.KeepProxiesOffline;
set => SetSyncOption(value, Shell.Services.Settings.KeepProxiesOffline, v => Shell.Services.Settings.KeepProxiesOffline = v);
}
/// <summary>Send and take project settings changed on one side without asking.</summary>
public bool SyncSettingsAutomatically
{
get => Shell.Services.Settings.SyncSettingsAutomatically;
set => SetSyncOption(value, Shell.Services.Settings.SyncSettingsAutomatically, v => Shell.Services.Settings.SyncSettingsAutomatically = v);
}
/// <summary>Pause uploads while the connection is metered.</summary>
public bool PauseUploadsOnMetered
{
get => Shell.Services.Settings.PauseUploadsOnMetered;
set
{
if (Shell.Services.Settings.PauseUploadsOnMetered == value) return;
Shell.Services.Settings.PauseUploadsOnMetered = value;
Shell.Services.SaveSettings();
Shell.Services.Sync.Uploads.Request();
OnPropertyChanged();
}
}
/// <summary>Re-reads values another screen changed (Settings › Server).</summary>
public void Refresh() => OnPropertyChanged(nameof(RenderNodeOptIn));
@@ -149,6 +181,7 @@ public sealed class ServerViewModel : SectionViewModel
if (Address.Length == 0 && Session.Discovered.Count > 0) Address = Session.Discovered[0].Address;
};
if (!Shell.Services.Environment.IsCapture) _session.StartDiscovery();
Sync.Attach();
await _session.RestoreAsync();
if (_session.Flow.Error is not ConnectError.None and var error && !_session.IsConnected) ErrorText = ServerSession.ErrorText(error);
}
@@ -156,9 +189,19 @@ public sealed class ServerViewModel : SectionViewModel
public override void Dispose()
{
if (_session is not null) _session.PropertyChanged -= OnSessionChanged;
Sync.Dispose();
base.Dispose();
}
private void SetSyncOption(bool value, bool current, Action<bool> store, [System.Runtime.CompilerServices.CallerMemberName] string? name = null)
{
if (value == current) return;
store(value);
Shell.Services.SaveSettings();
Shell.Services.Sync.RequestRefresh();
OnPropertyChanged(name);
}
private async Task ConnectAsync()
{
ErrorText = null;
+152
View File
@@ -0,0 +1,152 @@
using System.IO;
using Titano.App.Infrastructure;
using Titano.Core.Diagnostics;
using Titano.Core.Model;
using Titano.Data;
using Titano.Data.Sync;
using Titano.Protocol.Client;
namespace Titano.App.Server;
/// <summary>Makes the sync connection of a signed-in session.</summary>
public delegate ISyncRemote SyncRemoteFactory(Uri address, string token, IReadOnlyCollection<string> trustedFingerprints);
/// <summary>
/// This PC's sync with the signed-in server (BRIEF §4.4, §14.5): the <see cref="SyncService"/> of the index, the
/// connection of upload and download jobs (<see cref="ISyncConnector"/>), a <see cref="SyncAgent"/> that keeps the
/// table current while a session is open, started and stopped in order as the session changes, and the
/// <see cref="UploadHold"/> for metered connections. Options come from <see cref="AppSettings.SyncSettingsAutomatically"/>,
/// <see cref="AppSettings.KeepProxiesOffline"/> and <see cref="AppSettings.PauseUploadsOnMetered"/>.
/// </summary>
public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDisposable
{
/// <summary>How long a job resumed at start waits for the saved session to be restored.</summary>
private static readonly TimeSpan RestoreWait = TimeSpan.FromSeconds(30);
private Task _switch = Task.CompletedTask;
private Credentials? _credentials;
private (SyncAgent Agent, ISyncRemote Remote, Credentials Credentials)? _running;
/// <summary>Connections over <see cref="TitanoClient"/>; screenshots substitute a fake server.</summary>
public SyncRemoteFactory RemoteFactory { get; set; } = (address, token, trusted) =>
new TitanoSyncRemote(new TitanoClient(address, new CertificatePinning(trusted), $"Titano ({Environment.MachineName})") { Token = token }, ownsClient: true);
/// <summary>The engine; null until the index is open.</summary>
public SyncService? Service { get; private set; }
/// <summary>The background comparison of the signed-in server; null while signed out.</summary>
public SyncAgent? Agent => _running?.Agent;
/// <summary>The agent's connection, for the table's own calls (conflict resolution); null while signed out.</summary>
public ISyncRemote? Remote => _running?.Remote;
/// <summary>Key of the signed-in server (<see cref="SyncService.ServerKey"/>); null while signed out.</summary>
public string? Server => Volatile.Read(ref _credentials) is { } c ? SyncService.ServerKey(c.Address) : null;
/// <summary>The options, and whether the account may change server sequences (without it this PC's edits are not sent).</summary>
public SyncPolicy Policy => new(services.Settings.SyncSettingsAutomatically, services.Settings.KeepProxiesOffline,
services.Server.User is { } user && (user.Permissions & (long)Permissions.Edit) != 0);
/// <summary>Pauses uploads while the connection is metered and the option is on.</summary>
public UploadHold Uploads { get; } = new(services);
/// <summary>The agent started, stopped or compared, or the table of the signed-in server changed (any thread).</summary>
public event Action? Changed;
/// <summary>Creates the engine over the open index; the proxy cache lives in the client's cache folder.</summary>
public SyncService Open(TitanoDatabase database, Titano.Data.Archiving.ArchiveService archives, Titano.Data.Archiving.ArchiveServiceOptions options)
{
var cache = CacheStore.Folder(services.Environment, services.Settings);
Service = new SyncService(database, archives, new SyncOptions { Archive = options, ProxyCacheDirectory = Path.Combine(cache, "proxies") });
Service.Changed += server =>
{
if (server == Server) Changed?.Invoke();
};
return Service;
}
/// <summary>Follows the server session (UI thread): starts the agent for a new sign-in, stops it on sign-out.</summary>
public void Update()
{
var session = services.Server;
Credentials? wanted = session.IsConnected && session.Flow is { Address: { } address, Token: { } token }
? new Credentials(address, token, session.Fingerprints)
: null;
Volatile.Write(ref _credentials, wanted);
_switch = SwitchAsync(_switch, wanted);
if (services.Engine is { } engine) Uploads.Attach(engine);
}
/// <summary>Compares now, once the session switch in progress settled; null while signed out.</summary>
public async Task<SyncSnapshot?> RefreshAsync(CancellationToken ct = default)
{
await _switch;
return Agent is { } agent ? await agent.RefreshAsync(ct) : null;
}
/// <summary>Compares again soon (an option changed, an edit on this PC).</summary>
public void RequestRefresh() => Agent?.RequestRefresh();
/// <summary>The archive downloaded originals go to when a sequence has no local copy: the one this PC works with.</summary>
public async Task<Archive?> CurrentArchiveAsync(CancellationToken ct = default)
{
if (services.Database is not { } db) return null;
var archives = await db.Archives.ListAsync(ct);
if (services.Settings.LastArchivePath is { Length: > 0 } root)
{
var full = Path.GetFullPath(root).TrimEnd(Path.DirectorySeparatorChar);
if (archives.FirstOrDefault(a => string.Equals(Path.GetFullPath(a.RootPath).TrimEnd(Path.DirectorySeparatorChar), full, StringComparison.OrdinalIgnoreCase))
is { } current) return current;
}
return archives.Count == 1 ? archives[0] : null;
}
public async ValueTask<ISyncRemote?> ConnectAsync(string server, CancellationToken cancellationToken)
{
// A job resumed at start runs before the saved session is restored: give the restore a moment.
var until = DateTime.UtcNow + RestoreWait;
while (Volatile.Read(ref _credentials) is null && services.Settings.ProtectedToken is not null && DateTime.UtcNow < until)
await Task.Delay(500, cancellationToken);
if (Volatile.Read(ref _credentials) is not { } c || SyncService.ServerKey(c.Address) != server) return null;
CacheStore.Prepare(CacheStore.Folder(services.Environment, services.Settings));
return RemoteFactory(c.Address, c.Token, c.Fingerprints);
}
public async ValueTask DisposeAsync()
{
Volatile.Write(ref _credentials, null);
Uploads.Dispose();
await _switch;
await StopAsync();
}
private async Task SwitchAsync(Task previous, Credentials? wanted)
{
await previous;
if (_running is { } running && wanted is { } same && running.Credentials.Address == same.Address && running.Credentials.Token == same.Token) return;
await StopAsync();
if (wanted is not { } start || Service is not { } service)
{
Changed?.Invoke();
return;
}
var remote = RemoteFactory(start.Address, start.Token, start.Fingerprints);
var agent = new SyncAgent(service, remote, () => Policy, services.Engine);
agent.Changed += () => Changed?.Invoke();
agent.Start();
_running = (agent, remote, start);
Log.Info("sync", $"Comparing with {remote.Server}");
Changed?.Invoke();
}
private async Task StopAsync()
{
if (_running is not { } running) return;
_running = null;
await running.Agent.DisposeAsync();
running.Remote.Dispose();
Changed?.Invoke();
}
private sealed record Credentials(Uri Address, string Token, IReadOnlyCollection<string> Fingerprints);
}
+109
View File
@@ -0,0 +1,109 @@
using System.Windows.Input;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data.Sync;
using Titano.Ui.Controls;
using Titano.Ui.Mvvm;
namespace Titano.App.Server;
/// <summary>A row button: "Upload", "Keep mine", …; kept while the row offers it, so focus, tooltips and clicks survive updates.</summary>
public sealed class SyncRowAction(SyncAction action, ICommand command) : ObservableObject
{
private string _toolTip = string.Empty;
public SyncAction Action { get; } = action;
public string Text => Loc.L("Server.Sync.Action." + Action);
public ICommand Command { get; } = command;
public string ToolTip
{
get => _toolTip;
set => Set(ref _toolTip, value);
}
/// <summary>The label in the current language.</summary>
public void Relabel() => OnPropertyChanged(nameof(Text));
}
/// <summary>One row of the sync table (Server.html): sequence, this PC, server, state and the actions that apply.</summary>
public sealed class SyncRow : ObservableObject
{
private readonly Func<SyncRow, SyncAction, Task> _act;
private SyncEntry _entry;
private IReadOnlyList<SyncRowAction> _actions = [];
public SyncRow(SyncEntry entry, SyncRights rights, Func<SyncRow, SyncAction, Task> act)
{
_entry = entry;
_act = act;
UpdateActions(rights);
}
public SyncEntry Entry => _entry;
public Guid Id => _entry.Id;
public string Title => _entry.Title;
public string LocalText => SyncText.Local(_entry);
public string ServerText => SyncText.Server(_entry);
public StatusKind StateKind => SyncText.State(_entry).Kind;
public string StateText => SyncText.State(_entry).Text;
public string StateToolTip => SyncText.State(_entry).ToolTip;
/// <summary>Settings differ on both sides: the row is drawn on the card colour, as in Server.html.</summary>
public bool IsConflict => _entry.Status == SyncStatus.Conflict && _entry.Transfer is null;
public IReadOnlyList<SyncRowAction> Actions
{
get => _actions;
private set => Set(ref _actions, value);
}
/// <summary>Takes a fresher comparison of the same sequence; buttons the row still offers are kept.</summary>
public void Update(SyncEntry entry, SyncRights rights)
{
_entry = entry;
UpdateActions(rights);
RaiseTexts();
}
/// <summary>Takes the progress of the row's transfer ("46 % received") without touching its buttons.</summary>
public void UpdateProgress(long done, long total)
{
if (_entry.Transfer is not { } job) return;
_entry = _entry with { Transfer = job with { ProgressDone = done, ProgressTotal = total } };
OnPropertyChanged(nameof(ServerText));
}
/// <summary>Texts in the current language.</summary>
public void Relabel()
{
foreach (var action in _actions)
{
action.Relabel();
action.ToolTip = SyncText.ToolTip(_entry, action.Action);
}
RaiseTexts();
}
private void UpdateActions(SyncRights rights)
{
var wanted = SyncText.Actions(_entry, rights);
if (!wanted.SequenceEqual(_actions.Select(a => a.Action)))
{
var kept = _actions.ToDictionary(a => a.Action);
Actions = [.. wanted.Select(action => kept.GetValueOrDefault(action) ?? new SyncRowAction(action, new AsyncRelayCommand(() => _act(this, action))))];
}
foreach (var action in _actions) action.ToolTip = SyncText.ToolTip(_entry, action.Action);
}
private void RaiseTexts()
{
OnPropertyChanged(nameof(Title));
OnPropertyChanged(nameof(LocalText));
OnPropertyChanged(nameof(ServerText));
OnPropertyChanged(nameof(StateKind));
OnPropertyChanged(nameof(StateText));
OnPropertyChanged(nameof(StateToolTip));
OnPropertyChanged(nameof(IsConflict));
}
}
+428
View File
@@ -0,0 +1,428 @@
using System.Collections.Concurrent;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows.Input;
using System.Windows.Threading;
using Titano.App.Infrastructure;
using Titano.App.Shell;
using Titano.Core.Diagnostics;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data.Jobs;
using Titano.Data.Sync;
using Titano.Ui.Mvvm;
namespace Titano.App.Server;
/// <summary>A filter chip of the sync table: "Conflicts · 1".</summary>
public sealed class SyncFilterChip(SyncFilter filter, Action<SyncFilter> select) : ObservableObject
{
private int _count;
private bool _isSelected;
public SyncFilter Filter { get; } = filter;
public string Text => Loc.L("Server.Sync.Filter." + Filter, Formatting.Count(_count));
public string ToolTip => Loc.L("Tooltips.Server.Sync.Filter." + Filter);
public ICommand SelectCommand { get; } = new RelayCommand(() => select(filter));
/// <summary>Conflicts waiting for a choice: the chip is drawn in the warning colour unless it is the selected one.</summary>
public bool NeedsAttention => Filter == SyncFilter.Conflicts && _count > 0;
public bool IsSelected
{
get => _isSelected;
set => Set(ref _isSelected, value);
}
public int Count
{
get => _count;
set
{
if (!Set(ref _count, value)) return;
OnPropertyChanged(nameof(Text));
OnPropertyChanged(nameof(NeedsAttention));
}
}
/// <summary>Texts in the current language.</summary>
public void Relabel()
{
OnPropertyChanged(nameof(Text));
OnPropertyChanged(nameof(ToolTip));
}
}
/// <summary>
/// The sync table of the Server screen (BRIEF §12.7, Server.html): every sequence of this PC and of the signed-in
/// server with what each side holds, where it stands and what can be done (upload, download originals, open with
/// proxies, get or send exports, settle a conflict, pause or resume a transfer), filter chips, search, "Upload all
/// local" and the footer (last comparison, server archive, admin panel). Reloads when the sync engine reports a change;
/// transfer progress is applied at most a few times a second. Runs on the UI thread.
/// </summary>
public sealed class SyncTableViewModel : ObservableObject, IDisposable
{
private readonly ShellViewModel _shell;
private readonly IReadOnlyList<SyncFilterChip> _chips;
/// <summary>"Open with proxies" waiting for its proxy download: server id → the job that fills the cache.</summary>
private readonly Dictionary<Guid, Guid> _openWhenCached = [];
private readonly ConcurrentDictionary<Guid, JobProgressInfo> _progress = new();
private readonly SemaphoreSlim _reloading = new(1, 1);
private readonly AsyncRelayCommand _uploadAll;
private IReadOnlyList<SyncEntry> _entries = [];
private SyncFilter _filter = SyncFilter.All;
private string _search = string.Empty;
private int _progressQueued;
private int _reloadQueued;
private bool _attached;
public SyncTableViewModel(ShellViewModel shell)
{
_shell = shell;
_chips = [.. Enum.GetValues<SyncFilter>().Select(f => new SyncFilterChip(f, Select) { IsSelected = f == SyncFilter.All })];
_uploadAll = new AsyncRelayCommand(UploadAllAsync, () => IsActive && Rights.CanUpload && LocalOnly.Any());
OpenAdminCommand = new RelayCommand(() =>
{
if (Host.Server is { } server) ShellActions.OpenUrl(server + "/admin");
});
}
public ObservableCollection<SyncRow> Rows { get; } = [];
public IReadOnlyList<SyncFilterChip> Chips => _chips;
public ICommand UploadAllCommand => _uploadAll;
public ICommand OpenAdminCommand { get; }
public string SearchText
{
get => _search;
set
{
if (Set(ref _search, value ?? string.Empty)) ApplyFilter(rebuild: true);
}
}
/// <summary>Signed in: the table compares this PC with that server.</summary>
public bool IsActive => Host.Server is not null;
public bool HasRows => Rows.Count > 0;
/// <summary>"Not connected to a server", "Nothing to compare yet" or "No sequence matches"; null when rows show.</summary>
public string? EmptyText => HasRows ? null
: !IsActive ? Loc.L("Server.Empty")
: _entries.Count == 0 ? Loc.L("Server.Sync.Empty")
: Loc.L("Server.Sync.NoMatch");
/// <summary>What "Upload all local" sends, or why it is disabled.</summary>
public string UploadAllToolTip =>
!IsActive ? Loc.L("Tooltips.Server.Sync.UploadAll.NotConnected")
: !Rights.CanUpload ? Loc.L("Tooltips.Server.Sync.UploadAll.NoRight")
: !LocalOnly.Any() ? Loc.L("Tooltips.Server.Sync.UploadAll.Nothing")
: Loc.L("Tooltips.Server.Sync.UploadAll", Formatting.Count(LocalOnly.Count()), Formatting.Bytes(LocalOnly.Sum(e => e.Local!.TotalBytes)));
/// <summary>"Last sync 10:15 · manifest diff 0.4 s"; null before the first comparison.</summary>
public string? LastSyncText => Host.Agent?.Snapshot is { } s
? Loc.L("Server.Sync.Last", Formatting.TimeOfDay(s.RefreshedAt), s.Duration.TotalSeconds.ToString("0.0", Loc.Culture))
: null;
/// <summary>"Server archive 9.4 TB · 412 sequences".</summary>
public string? ArchiveText => Host.Agent?.Snapshot is { } s ? Loc.Plural("Server.Sync.Archive", s.ServerSequences, Formatting.Bytes(s.ServerBytes)) : null;
/// <summary>The last comparison failed (it is retried with growing pauses); null when it worked.</summary>
public string? ErrorText => Host.Agent?.LastError is not null ? Loc.L("Server.Sync.Retrying") : null;
public string? ErrorToolTip => Host.Agent?.LastError is { } error ? Loc.L("Tooltips.Server.Sync.Retrying", error.Message) : null;
/// <summary>The server's web admin (it admits administrators only).</summary>
public bool CanOpenAdmin => IsActive;
private SyncHost Host => _shell.Services.Sync;
private SyncRights Rights => _shell.Services.Server.User is { } user ? SyncRights.Of(user.Permissions) : default;
private IEnumerable<SyncEntry> LocalOnly => _entries.Where(e => e.Status == SyncStatus.LocalOnly);
/// <summary>Starts following the sync engine, the transfer jobs and the language.</summary>
public void Attach()
{
if (_attached) return;
_attached = true;
Host.Changed += OnChanged;
Loc.CultureChanged += OnCultureChanged;
if (_shell.Services.Jobs is { } jobs)
{
jobs.JobChanged += OnJobChanged;
jobs.Progress += OnProgress;
}
_ = ReloadAsync();
}
/// <summary>Reads the table again; requests made while a pass runs share the next one, which they wait for.</summary>
public async Task ReloadAsync()
{
Interlocked.Exchange(ref _reloadQueued, 1);
await _reloading.WaitAsync();
try
{
while (Interlocked.Exchange(ref _reloadQueued, 0) == 1)
{
_entries = Host is { Service: { } service, Server: { } server } ? await service.ListAsync(server, CancellationToken.None) : [];
Refresh();
}
}
catch (Exception ex) when (ex is Data.DatabaseException or InvalidOperationException)
{
Log.Warning("sync", "The sync table could not be read", ex);
}
finally
{
_reloading.Release();
}
}
public void Dispose()
{
if (!_attached) return;
_attached = false;
Host.Changed -= OnChanged;
Loc.CultureChanged -= OnCultureChanged;
if (_shell.Services.Jobs is { } jobs)
{
jobs.JobChanged -= OnJobChanged;
jobs.Progress -= OnProgress;
}
}
private void Select(SyncFilter filter)
{
_filter = filter;
foreach (var chip in _chips) chip.IsSelected = chip.Filter == filter;
ApplyFilter(rebuild: true);
}
/// <summary>Counts, rows, footer and the Library's sync glyphs after a reload.</summary>
private void Refresh()
{
foreach (var chip in _chips) chip.Count = _entries.Count(e => SyncText.Matches(e, chip.Filter, string.Empty));
ApplyFilter(rebuild: false);
UpdateLibrary();
OnPropertyChanged(nameof(IsActive));
OnPropertyChanged(nameof(UploadAllToolTip));
OnPropertyChanged(nameof(LastSyncText));
OnPropertyChanged(nameof(ArchiveText));
OnPropertyChanged(nameof(ErrorText));
OnPropertyChanged(nameof(ErrorToolTip));
OnPropertyChanged(nameof(CanOpenAdmin));
_uploadAll.RaiseCanExecuteChanged();
}
/// <summary>
/// Shows the entries the filter and search keep. A reload updates the rows in place (scroll position, focus and
/// recycled containers survive); a new filter or search lays the rows out again.
/// </summary>
private void ApplyFilter(bool rebuild)
{
var rights = Rights;
var wanted = _entries.Where(e => SyncText.Matches(e, _filter, _search.Trim())).ToList();
var byId = Rows.ToDictionary(r => r.Id);
if (rebuild)
{
Rows.Clear();
foreach (var entry in wanted) Rows.Add(Row(entry, rights, byId));
}
else
{
for (var i = 0; i < wanted.Count; i++)
{
var entry = wanted[i];
if (i < Rows.Count && Rows[i].Id == entry.Id)
{
Rows[i].Update(entry, rights);
continue;
}
var row = Row(entry, rights, byId);
var at = byId.ContainsKey(entry.Id) ? Rows.IndexOf(row) : -1;
if (at >= 0) Rows.Move(at, i);
else Rows.Insert(i, row);
}
while (Rows.Count > wanted.Count) Rows.RemoveAt(Rows.Count - 1);
}
OnPropertyChanged(nameof(HasRows));
OnPropertyChanged(nameof(EmptyText));
}
/// <summary>The existing row of an entry, updated, or a new one.</summary>
private SyncRow Row(SyncEntry entry, SyncRights rights, Dictionary<Guid, SyncRow> existing)
{
if (!existing.TryGetValue(entry.Id, out var row)) return new SyncRow(entry, rights, ActAsync);
row.Update(entry, rights);
return row;
}
/// <summary>The Library shows each local copy's sync state: rows it has loaded take the fresh state.</summary>
private void UpdateLibrary()
{
var locals = _entries.Where(e => e.Local is not null).ToDictionary(e => e.Local!.Id, e => e.Local!);
foreach (var item in _shell.Library.Items)
{
if (locals.TryGetValue(item.Id, out var fresh) && fresh.SyncState != item.Sequence.SyncState) item.Update(fresh);
}
}
private async Task ActAsync(SyncRow row, SyncAction action)
{
if (Host is not { Service: { } service, Server: { } server } || _shell.Services.Engine is not { } engine) return;
var entry = row.Entry;
switch (action)
{
case SyncAction.Upload:
await service.EnqueueUploadAsync(engine, server, entry.Local!);
break;
case SyncAction.SendExports:
await service.EnqueueSendExportsAsync(engine, server, entry.Local!);
break;
case SyncAction.DownloadOriginals:
if ((entry.Local?.ArchiveId ?? (await Host.CurrentArchiveAsync())?.Id) is not { } archive)
{
_shell.Notify(Loc.L("Errors.Sync.NoArchive"));
return;
}
await service.EnqueueDownloadAsync(engine, server, entry.Id, entry.Title, SyncDownloadMode.Originals, archive);
break;
case SyncAction.GetExports:
await service.EnqueueDownloadAsync(engine, server, entry.Id, entry.Title, SyncDownloadMode.Exports, null);
break;
case SyncAction.OpenWithProxies when entry.Status == SyncStatus.ProxiesOnly && service.OpenRemote(server, entry.Id) is not null:
_shell.OpenSequence(entry.Id);
return;
case SyncAction.OpenWithProxies:
var job = await service.EnqueueDownloadAsync(engine, server, entry.Id, entry.Title, SyncDownloadMode.Proxies, null);
_openWhenCached[entry.Id] = job.Id;
// A download that finished before it was recorded here opens at once.
if (await _shell.Services.Database!.Jobs.GetAsync(job.Id) is { State: JobState.Done or JobState.Failed or JobState.Cancelled } ended)
OpenWhenCached(ended);
break;
case SyncAction.Pause:
await _shell.Services.Jobs!.PauseAsync(entry.Transfer!.Id);
break;
case SyncAction.Resume:
await _shell.Services.Jobs!.ResumeAsync(entry.Transfer!.Id);
break;
case SyncAction.SyncSettings when Host.Remote is { } remote:
await service.SyncSettingsAsync(remote, entry.Id, Host.Policy, CancellationToken.None);
break;
case SyncAction.KeepMine or SyncAction.TakeServer or SyncAction.SaveBoth when Host.Remote is { } remote:
await ResolveAsync(service, remote, entry, action);
break;
}
await ReloadAsync();
}
/// <summary>Settles a conflict once the user confirmed the plan: the settings that differ and what each choice overwrites.</summary>
private async Task ResolveAsync(SyncService service, ISyncRemote remote, SyncEntry entry, SyncAction action)
{
if (!_shell.Services.Dialogs.Confirm(ConflictRequest(entry, action))) return;
var resolution = action switch
{
SyncAction.KeepMine => SyncResolution.KeepMine,
SyncAction.TakeServer => SyncResolution.TakeServer,
_ => SyncResolution.SaveBoth,
};
try
{
if (await service.ResolveAsync(remote, entry.Id, resolution, CancellationToken.None) is { } saved)
{
_shell.Notify(Loc.L("Server.Sync.SavedBoth"), Path.GetFileName(saved), Loc.L("Server.Sync.ShowCopy"), Loc.L("Tooltips.Server.Sync.ShowCopy"),
() => ShellActions.Reveal(saved));
}
}
catch (SyncConflictChangedException ex)
{
// One side changed after the choice was shown: the row now shows the fresh content.
_shell.Notify(ex.Message);
}
}
/// <summary>The dry run of a resolution: what is replaced, by which side's values, and where "Save both" keeps this PC's.</summary>
internal static ConfirmRequest ConflictRequest(SyncEntry entry, SyncAction action) => new()
{
Heading = Loc.L("Server.Conflict." + action + ".Title"),
Message = Loc.L("Server.Conflict." + action + ".Message", entry.Title),
Detail = string.Join(Environment.NewLine, SyncText.Conflict(entry, 10)),
DetailToolTip = Loc.L("Tooltips.Server.Conflict.Detail"),
SafeText = Loc.L("Server.Conflict.Cancel"),
SafeToolTip = Loc.L("Tooltips.Server.Conflict.Cancel"),
ActionText = Loc.L("Server.Sync.Action." + action),
ActionToolTip = Loc.L("Tooltips.Server.Sync." + action),
IsDestructive = action != SyncAction.SaveBoth,
};
private async Task UploadAllAsync()
{
if (Host is not { Service: { } service, Server: { } server } || _shell.Services.Engine is not { } engine) return;
var queued = 0;
foreach (var entry in LocalOnly.ToList())
{
await service.EnqueueUploadAsync(engine, server, entry.Local!);
queued++;
}
_shell.Notify(Loc.Plural("Server.Sync.Queued", queued));
await ReloadAsync();
}
private void OnChanged() => Dispatch(() => _ = ReloadAsync());
private void OnCultureChanged(object? sender, EventArgs e) => Dispatch(() =>
{
foreach (var chip in _chips) chip.Relabel();
foreach (var row in Rows) row.Relabel();
OnAllPropertiesChanged();
});
private void OnJobChanged(Job job)
{
if (job.Kind is not (JobKind.UploadCommit or JobKind.Download)) return;
_progress.TryRemove(job.Id, out _);
Dispatch(() =>
{
OpenWhenCached(job);
_ = ReloadAsync();
});
}
/// <summary>
/// "Open with proxies" opens the editor when the download it queued is done, if the Server screen is still the one
/// in front; a failed or cancelled download drops the request.
/// </summary>
private void OpenWhenCached(Job job)
{
if (job.State is not (JobState.Done or JobState.Failed or JobState.Cancelled)) return;
var remoteId = _openWhenCached.FirstOrDefault(p => p.Value == job.Id).Key;
if (!_openWhenCached.Remove(remoteId)) return;
if (job.State == JobState.Done && ReferenceEquals(_shell.Current, _shell.Server)) _shell.OpenSequence(remoteId);
}
/// <summary>Transfer progress ("46 % received") without reading the table again, at most a few times a second.</summary>
private void OnProgress(JobProgressInfo info)
{
if (info.Kind is not (JobKind.UploadCommit or JobKind.Download)) return;
_progress[info.JobId] = info;
if (Interlocked.Exchange(ref _progressQueued, 1) == 1) return;
System.Windows.Application.Current?.Dispatcher.BeginInvoke(DispatcherPriority.Background, async () =>
{
await Task.Delay(250);
Interlocked.Exchange(ref _progressQueued, 0);
foreach (var row in Rows)
{
if (row.Entry.Transfer is { } job && _progress.TryGetValue(job.Id, out var p)) row.UpdateProgress(p.Done, p.Total);
}
});
}
private static void Dispatch(Action action)
{
if (System.Windows.Application.Current?.Dispatcher is not { } dispatcher || dispatcher.CheckAccess()) action();
else dispatcher.BeginInvoke(action);
}
}
+291
View File
@@ -0,0 +1,291 @@
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Nodes;
using Titano.App.Infrastructure;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data.Sync;
using Titano.Ui.Controls;
namespace Titano.App.Server;
/// <summary>Filter chips of the sync table (Server.html).</summary>
public enum SyncFilter
{
All,
LocalOnly,
Remote,
Conflicts,
}
/// <summary>What a row of the sync table offers.</summary>
public enum SyncAction
{
Upload,
OpenWithProxies,
DownloadOriginals,
SyncSettings,
KeepMine,
TakeServer,
SaveBoth,
GetExports,
SendExports,
Pause,
Resume,
}
/// <summary>What the signed-in account may do (server permission bits).</summary>
/// <param name="CanUpload">Send originals, settings and renders (upload and edit rights).</param>
/// <param name="CanFetchOriginals">Download originals (editors and render nodes).</param>
/// <param name="CanEdit">Change the server's copy of a sequence's settings, title, tags, rating and notes.</param>
public readonly record struct SyncRights(bool CanUpload, bool CanFetchOriginals, bool CanEdit)
{
public static SyncRights Of(long permissions) => new(
(permissions & (long)Permissions.Upload) != 0 && (permissions & (long)Permissions.Edit) != 0,
(permissions & (long)(Permissions.Edit | Permissions.RenderNode)) != 0,
(permissions & (long)Permissions.Edit) != 0);
}
/// <summary>The words, glyphs and actions of the sync table (BRIEF §12.7): plain functions of a <see cref="SyncEntry"/>.</summary>
public static class SyncText
{
/// <summary>Resource keys of the settings and sequence fields a conflict can show, by JSON path (sections, then members).</summary>
private static readonly Dictionary<string, string> SettingKeys = new(StringComparer.OrdinalIgnoreCase)
{
["sequence.title"] = "Server.Setting.Title",
["sequence.tags"] = "Server.Setting.Tags",
["sequence.rating"] = "Server.Setting.Rating",
["sequence.notes"] = "Server.Setting.Notes",
["timing.mode"] = "Server.Setting.TimingMode",
["timing.frameRate"] = "Server.Setting.FrameRate",
["timing.fitToSeconds"] = "Server.Setting.FitToDuration",
["timing.remapCurve"] = "Server.Setting.TimeRemap",
["exposure.deflicker"] = "Server.Setting.Deflicker",
["exposure.deflickerWindow"] = "Server.Setting.DeflickerWindow",
["exposure.deflickerStrength"] = "Server.Setting.DeflickerStrength",
["exposure.regions"] = "Server.Setting.Regions",
["exposure.holyGrail"] = "Server.Setting.HolyGrail",
["exposure.transitionLength"] = "Server.Setting.Transitions",
["exposure.whiteBalanceSmoothing"] = "Server.Setting.WhiteBalance",
["exposure.exposureOffsetEv"] = "Server.Setting.ExposureOffset",
["exposure.highlightKnee"] = "Server.Setting.HighlightKnee",
["motion.motionBlur"] = "Server.Setting.MotionBlur",
["motion.targetShutterAngle"] = "Server.Setting.ShutterAngle",
["motion.flowQuality"] = "Server.Setting.FlowQuality",
["motion.stabilize"] = "Server.Setting.Stabilize",
["motion.stabilizeSmoothing"] = "Server.Setting.StabilizeSmoothing",
["camera.crop"] = "Server.Setting.Crop",
["camera.aspect"] = "Server.Setting.Aspect",
["camera.offsetX"] = "Server.Setting.CameraOffset",
["camera.offsetY"] = "Server.Setting.CameraOffset",
["camera.keyframes"] = "Server.Setting.Keyframes",
["stack.mode"] = "Server.Setting.Stacking",
["stack.length"] = "Server.Setting.TrailLength",
["export.preset"] = "Server.Setting.ExportPreset",
["export.overrides"] = "Server.Setting.ExportValues",
["export.nameTemplate"] = "Server.Setting.OutputName",
["export.folder"] = "Server.Setting.ExportFolder",
["export.batch"] = "Server.Setting.Batch",
["excludedFrames"] = "Server.Setting.ExcludedFrames",
["heroFrame"] = "Server.Setting.HeroFrame",
};
/// <summary>"originals · proxies", "proxies" (cached server proxies) or "—".</summary>
public static string Local(SyncEntry entry)
{
if (entry.HasLocalOriginals)
{
return (entry.Local!.Status & SequenceStatus.ProxiesBuilt) != 0
? Join(Loc.L("Server.Sync.Originals"), Loc.L("Server.Sync.Proxies"))
: Loc.L("Server.Sync.Originals");
}
return entry.Link is { ProxiesCached: > 0 } ? Loc.L("Server.Sync.Proxies") : Loc.L("Server.Sync.None");
}
/// <summary>"originals · proxies · 3 exports", "46 % received" while uploading, or "—".</summary>
public static string Server(SyncEntry entry)
{
if (entry.Transfer is { Kind: JobKind.UploadCommit, State: JobState.Running, ProgressTotal: > 0 } upload)
return Loc.L("Server.Sync.Received", Formatting.Percent((double)upload.ProgressDone / upload.ProgressTotal));
if (entry.Link is not { } link) return Loc.L("Server.Sync.None");
var parts = new List<string>(3) { Loc.L("Server.Sync.Originals") };
if (link.ServerHasProxies) parts.Add(Loc.L("Server.Sync.Proxies"));
if (link.RenderCount > 0) parts.Add(Loc.Plural("Server.Sync.Exports", link.RenderCount));
return Join([.. parts]);
}
/// <summary>The State column: glyph kind, word and tooltip (never colour alone).</summary>
public static (StatusKind Kind, string Text, string ToolTip) State(SyncEntry entry)
{
if (entry.Transfer is { } job)
{
var upload = job.Kind == JobKind.UploadCommit;
return job.State switch
{
JobState.Paused => (StatusKind.Paused, Loc.L("Server.Sync.State.Paused"), Loc.L("Tooltips.Server.Sync.State.Paused")),
JobState.Queued => (StatusKind.Queued, Loc.L("Server.Sync.State.Waiting"), Loc.L("Tooltips.Server.Sync.State.Waiting")),
_ => (StatusKind.Running, Loc.L(upload ? "Server.Sync.State.Uploading" : "Server.Sync.State.Downloading"),
Loc.L(upload ? "Tooltips.Server.Sync.State.Uploading" : "Tooltips.Server.Sync.State.Downloading")),
};
}
if (entry.Link?.Error is { } error) return (StatusKind.Warning, Loc.L("Server.Sync.State.Failed"), Loc.L("Tooltips.Server.Sync.State.Failed", error));
return entry.Status switch
{
SyncStatus.InSync => (StatusKind.Done, Loc.L("Server.Sync.State.InSync"), Loc.L("Tooltips.Server.Sync.State.InSync")),
SyncStatus.LocalOnly => (StatusKind.Offline, Loc.L("Server.Sync.State.LocalOnly"), Loc.L("Tooltips.Server.Sync.State.LocalOnly")),
SyncStatus.RemoteOnly => (StatusKind.Remote, Loc.L("Server.Sync.State.RemoteOnly"), Loc.L("Tooltips.Server.Sync.State.RemoteOnly")),
SyncStatus.ProxiesOnly => (StatusKind.Remote, Loc.L("Server.Sync.State.ProxiesOnly"), Loc.L("Tooltips.Server.Sync.State.ProxiesOnly")),
SyncStatus.LocalAhead => (StatusKind.Synced, Loc.L("Server.Sync.State.LocalAhead"), Loc.L("Tooltips.Server.Sync.State.LocalAhead")),
SyncStatus.ServerAhead => (StatusKind.Remote, Loc.L("Server.Sync.State.ServerAhead"), Loc.L("Tooltips.Server.Sync.State.ServerAhead")),
_ => (StatusKind.Warning, Loc.L("Server.Sync.State.Conflict"), ConflictSummary(entry)),
};
}
/// <summary>One line for the State tooltip: "Deflicker window 41 here, 33 on the server · +2".</summary>
public static string ConflictSummary(SyncEntry entry)
{
var lines = Conflict(entry, int.MaxValue);
return lines.Count switch
{
0 => Loc.L("Tooltips.Server.Sync.State.Conflict"),
1 => lines[0],
_ => Loc.L("Server.Conflict.More", lines[0], Formatting.Count(lines.Count - 1)),
};
}
/// <summary>
/// What differs, one line per setting or sequence field in project order ("Deflicker window 41 here, 33 on the
/// server", "Tags differ"), at most <paramref name="max"/>.
/// </summary>
public static IReadOnlyList<string> Conflict(SyncEntry entry, int max)
{
if (entry is not { Local: { } local, Link.ConflictRemote: { } theirs }) return [];
var lines = new List<string>();
var shown = new HashSet<string>(StringComparer.Ordinal);
foreach (var difference in SyncRules.Differences(SyncPayload.Of(local), theirs, 64))
{
var (key, field) = Setting(difference.Path);
if (!shown.Add(key)) continue;
var label = Loc.L(key);
var metadata = difference.Path.StartsWith(SyncRules.MetadataPath, StringComparison.Ordinal);
lines.Add((metadata ? Text(difference.Mine) : Value(difference.Mine, field)) is { } mine
&& (metadata ? Text(difference.Theirs) : Value(difference.Theirs, field)) is { } server
? Loc.L("Server.Conflict.Difference", label, mine, server)
: Loc.L("Server.Conflict.Changed", label));
if (lines.Count == max) break;
}
return lines;
}
/// <summary>The row's buttons, in the order the mockup shows them.</summary>
public static IReadOnlyList<SyncAction> Actions(SyncEntry entry, SyncRights rights)
{
if (entry.Transfer is { } job) return job.State == JobState.Paused ? [SyncAction.Resume] : [SyncAction.Pause];
var actions = new List<SyncAction>(3);
switch (entry.Status)
{
case SyncStatus.LocalOnly when rights.CanUpload:
actions.Add(SyncAction.Upload);
break;
case SyncStatus.RemoteOnly or SyncStatus.ProxiesOnly:
actions.Add(SyncAction.OpenWithProxies);
if (rights.CanFetchOriginals) actions.Add(SyncAction.DownloadOriginals);
break;
case SyncStatus.LocalAhead when entry.Link is { MissingRemote: > 0 }:
if (rights.CanUpload) actions.Add(SyncAction.Upload);
break;
case SyncStatus.ServerAhead when entry.Link is { MissingLocal: > 0 }:
if (rights.CanFetchOriginals) actions.Add(SyncAction.DownloadOriginals);
break;
case SyncStatus.LocalAhead when rights.CanEdit:
case SyncStatus.ServerAhead:
actions.Add(SyncAction.SyncSettings);
break;
case SyncStatus.Conflict:
if (rights.CanEdit) actions.Add(SyncAction.KeepMine);
actions.AddRange([SyncAction.TakeServer, SyncAction.SaveBoth]);
return actions;
}
// Renders travel on request once no original is waiting to go either way.
if (entry is { Local: not null, Link: { MissingRemote: 0, MissingLocal: 0 } link })
{
if (link.ExportsToGet > 0) actions.Add(SyncAction.GetExports);
if (link.ExportsToSend > 0 && rights.CanUpload) actions.Add(SyncAction.SendExports);
}
return actions;
}
/// <summary>The bytes an action moves (for the tooltips).</summary>
public static long Size(SyncEntry entry, SyncAction action) => action switch
{
SyncAction.Upload => entry.Local?.TotalBytes ?? 0,
SyncAction.DownloadOriginals => entry.Link?.TotalBytes ?? 0,
SyncAction.GetExports => entry.Link?.ExportsToGetBytes ?? 0,
SyncAction.SendExports => entry.Link?.ExportsToSendBytes ?? 0,
_ => 0,
};
/// <summary>The tooltip of a row button: what it does and, for transfers, what it moves.</summary>
public static string ToolTip(SyncEntry entry, SyncAction action) => action switch
{
SyncAction.Upload or SyncAction.DownloadOriginals => Loc.L("Tooltips.Server.Sync." + action, Formatting.Bytes(Size(entry, action))),
SyncAction.GetExports => Loc.Plural("Tooltips.Server.Sync.GetExports", entry.Link!.ExportsToGet, Formatting.Bytes(Size(entry, action))),
SyncAction.SendExports => Loc.Plural("Tooltips.Server.Sync.SendExports", entry.Link!.ExportsToSend, Formatting.Bytes(Size(entry, action))),
_ => Loc.L("Tooltips.Server.Sync." + action),
};
public static bool Matches(SyncEntry entry, SyncFilter filter, string search) =>
(filter switch
{
SyncFilter.LocalOnly => entry.Status == SyncStatus.LocalOnly,
SyncFilter.Remote => entry.Status is SyncStatus.RemoteOnly or SyncStatus.ProxiesOnly,
SyncFilter.Conflicts => entry.Status == SyncStatus.Conflict,
_ => true,
}) && (search.Length == 0 || entry.Title.Contains(search, StringComparison.CurrentCultureIgnoreCase));
/// <summary>
/// The label key of a difference path and the member below the setting it reaches ("isAuto", "manual", … of an
/// Auto parameter; null for the setting itself): "exposure.deflickerWindow.manual" is the deflicker window's manual value.
/// </summary>
private static (string Key, string? Field) Setting(string path)
{
var segments = path.Split('.');
for (var length = segments.Length; length > 0; length--)
{
if (SettingKeys.TryGetValue(string.Join('.', segments[..length]), out var key)) return (key, length < segments.Length ? segments[length] : null);
}
return ("Server.Setting.Other", segments[^1]);
}
/// <summary>A title, tags, rating or notes value as shown ("—" when empty).</summary>
private static string Text(string? value) => string.IsNullOrWhiteSpace(value) ? Loc.L("Server.Sync.None") : Shorten(value);
/// <summary>A side's value as shown ("41", "on", "auto"); null when it is not a single value worth printing.</summary>
private static string? Value(string? json, string? field)
{
if (json is null) return field is null or "manual" ? Loc.L("Server.Sync.None") : null;
if (field is not (null or "manual" or "autoValue" or "isAuto")) return null;
JsonNode? node;
try
{
node = JsonNode.Parse(json);
}
catch (JsonException)
{
return null;
}
if (field == "isAuto") return node is JsonValue v && v.TryGetValue<bool>(out var auto) ? Loc.L(auto ? "Server.Setting.Auto" : "Server.Setting.Manual") : null;
return node switch
{
null => Loc.L("Server.Sync.None"),
JsonValue value when value.TryGetValue<bool>(out var flag) => Loc.L(flag ? "Server.Setting.On" : "Server.Setting.Off"),
JsonValue value when value.TryGetValue<double>(out var number) => number.ToString("0.###", Loc.Culture),
JsonValue value when value.TryGetValue<string>(out var text) => Shorten(text),
_ => null,
};
}
private static string Shorten(string text) => text.Length <= 40 ? text : string.Concat(text.AsSpan(0, 39), "…");
private static string Join(params string[] parts) => string.Join(" · ", parts);
}
+147
View File
@@ -0,0 +1,147 @@
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using Titano.App.Infrastructure;
using Titano.Core.Diagnostics;
using Titano.Core.Model;
using Titano.Data.Jobs;
namespace Titano.App.Server;
/// <summary>
/// "Pause uploads on metered networks" (Server.html): while <see cref="AppSettings.PauseUploadsOnMetered"/> is on and
/// Windows reports the connection as metered, upload jobs are paused (a running one stops after its current chunk and
/// keeps its checkpoint); they are resumed when the connection is no longer metered or the option goes off. Only the
/// uploads it paused are resumed. Checked when the network or an upload job changes, and every minute.
/// </summary>
public sealed class UploadHold : IDisposable
{
private static readonly TimeSpan Interval = TimeSpan.FromMinutes(1);
private readonly AppServices _services;
private readonly HashSet<Guid> _held = [];
private readonly SemaphoreSlim _gate = new(1, 1);
private readonly Timer _timer;
private JobEngine? _engine;
public UploadHold(AppServices services)
{
_services = services;
_timer = new Timer(_ => Request(), null, Interval, Interval);
NetworkChange.NetworkAddressChanged += OnNetworkChanged;
NetworkChange.NetworkAvailabilityChanged += OnNetworkChanged;
}
/// <summary>Follows the jobs of <paramref name="engine"/> (once the index is open).</summary>
public void Attach(JobEngine engine)
{
if (ReferenceEquals(_engine, engine)) return;
if (_engine is not null) _engine.JobChanged -= OnJobChanged;
_engine = engine;
engine.JobChanged += OnJobChanged;
Request();
}
/// <summary>Applies the option and the connection's cost now (the option changed).</summary>
public void Request() => _ = ApplyAsync();
public void Dispose()
{
_timer.Dispose();
NetworkChange.NetworkAddressChanged -= OnNetworkChanged;
NetworkChange.NetworkAvailabilityChanged -= OnNetworkChanged;
if (_engine is not null) _engine.JobChanged -= OnJobChanged;
}
private bool Holding => _services.Settings.PauseUploadsOnMetered && MeteredNetwork.IsMetered();
private void OnNetworkChanged(object? sender, EventArgs e) => Request();
private void OnJobChanged(Job job)
{
if (job is { Kind: JobKind.UploadCommit, State: JobState.Queued or JobState.Running }) Request();
}
private async Task ApplyAsync()
{
if (_engine is not { } engine || _services.Database is not { } db) return;
await _gate.WaitAsync();
try
{
if (Holding)
{
foreach (var state in new[] { JobState.Queued, JobState.Running })
{
foreach (var job in (await db.Jobs.ListAsync(state, JobKind.UploadCommit, 500)).Items)
{
await engine.PauseAsync(job.Id);
_held.Add(job.Id);
}
}
return;
}
foreach (var id in _held)
{
if (await db.Jobs.GetAsync(id) is { State: JobState.Paused }) await engine.ResumeAsync(id);
}
_held.Clear();
}
catch (Data.DatabaseException ex)
{
Log.Warning("sync", "Uploads could not be paused or resumed for the metered connection", ex);
}
finally
{
_gate.Release();
}
}
}
/// <summary>The connection cost Windows reports (Settings › Network › Metered connection) through <c>INetworkCostManager</c>.</summary>
internal static class MeteredNetwork
{
private const uint Fixed = 0x2;
private const uint Variable = 0x4;
private const uint OverDataLimit = 0x10000;
private const uint Roaming = 0x40000;
/// <summary>True when the machine's connection is metered (fixed or variable cost, over its data limit, or roaming); false when unknown.</summary>
public static bool IsMetered()
{
try
{
var manager = (INetworkCostManager)new NetworkListManagerClass();
try
{
return manager.GetCost(out var cost, IntPtr.Zero) == 0 && (cost & (Fixed | Variable | OverDataLimit | Roaming)) != 0;
}
finally
{
Marshal.ReleaseComObject(manager);
}
}
catch (COMException ex)
{
Log.Warning("sync", "The connection cost could not be read", ex);
return false;
}
}
[ComImport]
[Guid("DCB00C01-570F-4A9B-8D69-199FDBA5723B")]
private class NetworkListManagerClass;
[ComImport]
[Guid("DCB00008-570F-4A9B-8D69-199FDBA5723B")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface INetworkCostManager
{
[PreserveSig]
int GetCost(out uint cost, IntPtr destination);
[PreserveSig]
int GetDataPlanStatus(IntPtr status, IntPtr destination);
[PreserveSig]
int SetDestinationAddresses(uint length, IntPtr addresses, short append);
}
}
+44 -1
View File
@@ -4,6 +4,7 @@ using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Titano.App.DesignTime;
using Titano.App.Server;
using Titano.App.Settings;
using Titano.Core.Diagnostics;
using Titano.Ui.Theming;
@@ -13,7 +14,7 @@ namespace Titano.App.Shell;
/// <summary>
/// <c>Titano.exe --capture &lt;dir&gt;</c>: renders every client screen at 1440×900 in the dark and light themes to
/// <c>&lt;screen&gt;-&lt;theme&gt;.png</c> from <see cref="SampleData"/> (first run on an empty index, then a populated
/// one), for visual review and phase reports (BRIEF §20.2), then exits.
/// one, then the sync table with transfers, a conflict and its confirmation), for visual review and phase reports (BRIEF §20.2), then exits.
/// </summary>
public static class ScreenCapture
{
@@ -55,6 +56,8 @@ public static class ScreenCapture
await shell.Library.RefreshAsync();
await shell.Jobs.ReloadAsync();
await shell.Services.Server.RestoreAsync();
await shell.Services.Sync.RefreshAsync();
await shell.Server.Sync.ReloadAsync();
shell.About.SetResult(null);
await shell.Settings.DetectEncodersAsync();
await shell.Settings.SelfTestAsync();
@@ -97,6 +100,24 @@ public static class ScreenCapture
written += await SaveAsync(window, directory, key.ToString().ToLowerInvariant(), theme);
}
}
// The sync table with proxies kept here and transfers in every state, then filtered to the conflict, then the
// conflict's confirmation (after the other screens, so the Jobs capture keeps its own sample).
await sample.CacheProxiesAsync();
await sample.FillSyncAsync();
await shell.Server.Sync.ReloadAsync();
foreach (var theme in Themes)
{
ThemeManager.Apply(theme);
shell.Navigate(SectionKey.Server);
SelectSyncFilter(shell, SyncFilter.All);
written += await SaveAsync(window, directory, "server-sync", theme);
SelectSyncFilter(shell, SyncFilter.Conflicts);
written += await SaveAsync(window, directory, "server-conflict", theme);
if (shell.Server.Sync.Rows.FirstOrDefault() is { } conflict)
written += await SaveDialogAsync(new ConfirmDialog(SyncTableViewModel.ConflictRequest(conflict.Entry, SyncAction.KeepMine)), directory,
"server-conflict-confirm", theme);
SelectSyncFilter(shell, SyncFilter.All);
}
Log.Info("capture", $"{written} screenshot(s) written to {Path.GetFullPath(directory)}");
if (written == 0) Environment.ExitCode = 1;
}
@@ -111,6 +132,28 @@ public static class ScreenCapture
}
}
private static void SelectSyncFilter(ShellViewModel shell, SyncFilter filter) =>
shell.Server.Sync.Chips.First(c => c.Filter == filter).SelectCommand.Execute(null);
/// <summary>A dialog shown off screen, saved, then closed.</summary>
private static async Task<int> SaveDialogAsync(Window dialog, string directory, string screen, AppTheme theme)
{
dialog.WindowStartupLocation = WindowStartupLocation.Manual;
dialog.Left = -20000;
dialog.Top = -20000;
dialog.ShowActivated = false;
dialog.ShowInTaskbar = false;
dialog.Show();
try
{
return await SaveAsync(dialog, directory, screen, theme);
}
finally
{
dialog.Close();
}
}
private static async Task<int> SaveAsync(Window window, string directory, string screen, AppTheme theme, ShellViewModel? waitForThumbnails = null)
{
await Settle(window);
+3
View File
@@ -72,6 +72,9 @@ public enum JobKind
Orphans,
Adopt,
Move,
/// <summary>Client: originals or proxies of a server sequence fetched into this PC (BRIEF §14.5).</summary>
Download,
}
public enum JobState
@@ -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);
@@ -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);
@@ -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,
+157
View File
@@ -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;
/// <summary>
/// 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 <see cref="FrameFlags.Missing"/>, so analysis and renders
/// skip them. Not part of the local index.
/// </summary>
public sealed class RemoteSequence
{
internal RemoteSequence(string server, Sequence sequence, IReadOnlyList<Frame> frames, IReadOnlyList<string?> files)
{
Server = server;
Sequence = sequence;
Frames = frames;
Files = files;
}
/// <summary>The server it belongs to (<see cref="SyncService.ServerKey"/>).</summary>
public string Server { get; }
/// <summary>The server's sequence: its id, <see cref="SequenceOrigin.Server"/>, its settings JSON and versions; no archive.</summary>
public Sequence Sequence { get; }
public IReadOnlyList<Frame> Frames { get; }
/// <summary>Absolute path of each frame's cached proxy, in frame order; null when it is not cached.</summary>
public IReadOnlyList<string?> Files { get; }
public int CachedCount => Files.Count(f => f is not null);
/// <summary>
/// The editor's frame source over the cached proxies, decoded by <paramref name="decoder"/> through the same
/// read-ahead window as archive renders. The result also implements <see cref="Core.Analysis.Deep.IFrameSource"/>
/// and <see cref="IAsyncDisposable"/>; dispose it when done. Frames are proxy-sized while the source reports the
/// originals' size, which <see cref="IRenderFrameSource"/> allows.
/// </summary>
public IRenderFrameSource OpenFrames(ImageDecoder decoder, FrameWindowOptions? window = null)
{
var frames = new SequenceFrames(Sequence, Frames, Files);
return new SequenceFrameSource(frames, frames.LightFrames(), decoder, window);
}
}
/// <summary>What the proxy cache keeps next to the files of one server sequence.</summary>
internal sealed record ProxyCacheIndex(SequenceDto Sequence, string? SettingsJson, int FramesVersion, IReadOnlyList<FrameDto> Frames, IReadOnlyList<string?> Files);
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
[JsonSerializable(typeof(ProxyCacheIndex))]
internal sealed partial class ProxyCacheJson : JsonSerializerContext;
/// <summary>
/// Proxies of server sequences on this PC: <c>&lt;root&gt;/&lt;server hash&gt;/&lt;sequence id&gt;/</c> with one JPEG per
/// frame (named by frame id, so renumbering never mixes them up) and <c>remote.json</c>. Everything here can be
/// downloaded again, so the folder lives in the client's cache.
/// </summary>
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));
/// <summary>The cached sequence, or null when it was never cached or the cache was cleared.</summary>
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);
}
/// <summary>Removes the files of a sequence the server no longer has.</summary>
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);
}
}
/// <summary>Deletes proxies of frames <paramref name="keep"/> does not name (frames removed on the server).</summary>
public static void Prune(string folder, IReadOnlySet<string> 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);
}
}
}
}
+271
View File
@@ -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;
/// <summary>Timing of a <see cref="SyncAgent"/>.</summary>
public sealed record SyncAgentOptions
{
/// <summary>Full comparison while nothing asks for one sooner (catches edits on this PC and missed events).</summary>
public TimeSpan RefreshInterval { get; init; } = TimeSpan.FromMinutes(2);
/// <summary>Server events are collected this long, then their sequences are compared in one pass.</summary>
public TimeSpan EventDelay { get; init; } = TimeSpan.FromSeconds(1);
/// <summary>First wait after a failed refresh or a lost event socket; doubles up to <see cref="MaxBackoff"/>.</summary>
public TimeSpan MinBackoff { get; init; } = TimeSpan.FromSeconds(5);
public TimeSpan MaxBackoff { get; init; } = TimeSpan.FromMinutes(5);
}
/// <summary>
/// Keeps the sync table of one signed-in server current in the background: a full comparison at start, on request
/// and every <see cref="SyncAgentOptions.RefreshInterval"/>; the sequences named by the server's <c>sequenceChanged</c>
/// 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
/// <see cref="SyncPolicy.KeepProxiesOffline"/>, 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.
/// </summary>
public sealed class SyncAgent : IAsyncDisposable
{
private const string LogCategory = "sync";
private readonly SyncService _sync;
private readonly ISyncRemote _remote;
private readonly Func<SyncPolicy> _policy;
private readonly JobEngine? _engine;
private readonly SyncAgentOptions _options;
private readonly CancellationTokenSource _stopping = new();
private readonly Channel<bool> _refreshWake = Channel.CreateBounded<bool>(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite });
private readonly Channel<bool> _eventWake = Channel.CreateBounded<bool>(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite });
private readonly ConcurrentDictionary<Guid, byte> _changed = new();
/// <summary>Proxy downloads this agent queued, by server id, and the failures of each sequence's last ones.</summary>
private readonly Dictionary<Guid, Guid> _proxyJobs = [];
private readonly Dictionary<Guid, (int Failures, DateTime NotBefore)> _proxyFailures = [];
private readonly SemaphoreSlim _refreshing = new(1, 1);
private Task _running = Task.CompletedTask;
private SyncSnapshot? _snapshot;
private Exception? _lastError;
/// <param name="policy">Read before every comparison, so option changes apply at once.</param>
/// <param name="engine">Queue for proxy downloads; null keeps no proxies offline.</param>
public SyncAgent(SyncService sync, ISyncRemote remote, Func<SyncPolicy> policy, JobEngine? engine, SyncAgentOptions? options = null)
{
_sync = sync;
_remote = remote;
_policy = policy;
_engine = engine;
_options = options ?? new SyncAgentOptions();
}
public string Server => _remote.Server;
/// <summary>The last full comparison; null until the first one finished.</summary>
public SyncSnapshot? Snapshot => Volatile.Read(ref _snapshot);
/// <summary>Why the last full comparison failed; null after a successful one.</summary>
public Exception? LastError => Volatile.Read(ref _lastError);
/// <summary><see cref="Snapshot"/> or <see cref="LastError"/> changed (any thread).</summary>
public event Action? Changed;
/// <summary>Starts the comparison and event loops.</summary>
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));
}
/// <summary>Asks for a full comparison soon (after an edit on this PC, an option change, a reconnect).</summary>
public void RequestRefresh() => _refreshWake.Writer.TryWrite(true);
/// <summary>Compares everything now; concurrent calls run one after the other.</summary>
public async Task<SyncSnapshot> 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;
}
}
/// <summary>Listens to the server's events; a lost socket reconnects with backoff and asks for a full comparison (events were missed).</summary>
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();
}
}
/// <summary>Compares the sequences named by events, a short while after the first one arrived.</summary>
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)
{
}
}
/// <summary>
/// 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.
/// </summary>
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;
}
}
/// <summary>Waits for a wake-up or the delay; false when stopping.</summary>
private static async Task<bool> WaitAsync(ChannelReader<bool> 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;
}
}
+93
View File
@@ -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;
/// <summary>What an upload or download job moves.</summary>
public enum SyncTransferKind
{
/// <summary>Originals and settings of a local sequence to the server.</summary>
Upload,
/// <summary>Renders of a local copy to the server.</summary>
SendExports,
/// <summary>Originals of a server sequence into the local archive.</summary>
DownloadOriginals,
/// <summary>Proxies of a server sequence into the proxy cache.</summary>
DownloadProxies,
/// <summary>Renders of a server sequence into the local copy's exports.</summary>
GetExports,
}
/// <summary>
/// Parameters of upload and download jobs. The job's target is the local sequence for an upload and the server
/// sequence for a download.
/// </summary>
/// <param name="ArchiveId">Archive that receives downloaded originals when the sequence has no local copy yet.</param>
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;
/// <summary>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.</summary>
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;
}
}
}
+107
View File
@@ -0,0 +1,107 @@
using System.Text.Json;
using Titano.Core.Model;
using Titano.Data.Repositories;
namespace Titano.Data.Sync;
/// <summary>The <c>sync_links</c> table and the sync columns of local sequences (origin, sync state).</summary>
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<IReadOnlyList<SyncLink>> ListAsync(string server, CancellationToken cancellationToken) =>
_db.ListAsync($"SELECT {Columns} FROM sync_links WHERE server = $1 ORDER BY remote_id", [server], Map, cancellationToken);
public Task<SyncLink?> 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<SyncLink?> 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);
/// <summary>Records where a local sequence stands for the Library; touches neither its versions nor its update time.</summary>
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);
/// <summary>Marks a local sequence as downloaded from the server.</summary>
public Task SetOriginAsync(Guid localId, SequenceOrigin origin, CancellationToken cancellationToken) =>
_db.ExecuteAsync("UPDATE sequences SET origin = $2 WHERE id = $1", [localId, (int)origin], cancellationToken);
/// <summary>Upload and download jobs that are waiting, running or paused, by target id (local id for uploads, server id for downloads).</summary>
public async Task<IReadOnlyDictionary<Guid, IReadOnlyList<Job>>> ActiveTransfersAsync(CancellationToken cancellationToken)
{
var jobs = new List<Job>();
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<Job>)[.. 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),
};
}
+170
View File
@@ -0,0 +1,170 @@
using Titano.Core.Model;
namespace Titano.Data.Sync;
/// <summary>Where a sequence stands between this PC and the server (BRIEF §12.7, §14.5).</summary>
public enum SyncStatus
{
/// <summary>Same originals and settings on both sides.</summary>
InSync,
LocalOnly,
RemoteOnly,
/// <summary>Only on the server; this PC keeps its proxies for editing.</summary>
ProxiesOnly,
/// <summary>This PC holds originals or settings the server lacks.</summary>
LocalAhead,
/// <summary>The server holds originals or settings this PC lacks.</summary>
ServerAhead,
/// <summary>Both sides changed the settings, title, tags, rating or notes since they last agreed: the user picks.</summary>
Conflict,
/// <summary>An upload or download job is queued, running or paused.</summary>
Transferring,
}
/// <summary>How the user settles a conflict (BRIEF §12.7).</summary>
public enum SyncResolution
{
KeepMine,
TakeServer,
/// <summary>The server's version wins; this PC's settings are kept next to the project as a dated copy.</summary>
SaveBoth,
}
/// <summary>What a download job fetches.</summary>
public enum SyncDownloadMode
{
/// <summary>Originals, hash-verified, into the local archive.</summary>
Originals,
/// <summary>Proxies (thumbnails where the server has none) into the proxy cache.</summary>
Proxies,
/// <summary>The server's renders the local copy lacks, into its exports folder.</summary>
Exports,
}
/// <summary>What an upload job sends.</summary>
public enum SyncUploadMode
{
/// <summary>Originals and settings (creating the server sequence when needed).</summary>
Originals,
/// <summary>This PC's renders the server lacks (BRIEF §14.5: renders are uploaded on request).</summary>
Exports,
}
/// <summary>
/// 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.
/// </summary>
public sealed record SyncLink
{
/// <summary>Normalised server address (<see cref="SyncService.ServerKey"/>).</summary>
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; }
/// <summary>Local originals the server does not have.</summary>
public int MissingRemote { get; init; }
/// <summary>Server originals this PC does not have.</summary>
public int MissingLocal { get; init; }
/// <summary>Server renders the local copy does not have, and their size.</summary>
public int ExportsToGet { get; init; }
public long ExportsToGetBytes { get; init; }
/// <summary>Renders of the local copy the server does not have (whose file is still on this PC), and their size.</summary>
public int ExportsToSend { get; init; }
public long ExportsToSendBytes { get; init; }
/// <summary>Settings versions at which the content was found to conflict; null when it does not.</summary>
public int? ConflictLocalSettings { get; init; }
public int? ConflictRemoteSettings { get; init; }
/// <summary>The server's side when the conflict was found: what the user is shown and what "Take server" applies.</summary>
public SyncPayload? ConflictRemote { get; init; }
/// <summary>Frames whose proxy (or thumbnail) is in this PC's proxy cache.</summary>
public int ProxiesCached { get; init; }
/// <summary>Server frames version the proxy cache was filled at.</summary>
public int? ProxiesFramesVersion { get; init; }
/// <summary>Why the last comparison of this sequence failed (it is compared again next time); null when it worked.</summary>
public string? Error { get; init; }
public DateTimeOffset? SyncedAt { get; init; }
public bool ServerHasProxies => (RemoteStatus & SequenceStatus.ProxiesBuilt) != 0;
/// <summary>
/// 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).
/// </summary>
public bool ProxiesStale => ProxiesFramesVersion != RemoteFramesVersion;
}
/// <summary>One row of the sync table: the local sequence, the server sequence, or both, and where they stand.</summary>
/// <param name="Transfer">The upload or download job working on it, if any (the user's before background ones).</param>
public sealed record SyncEntry(Sequence? Local, SyncLink? Link, SyncStatus Status, Job? Transfer = null)
{
public string Title => Local?.DisplayTitle ?? Link?.Title ?? string.Empty;
/// <summary>The server's id, or the local one for a sequence the server does not have.</summary>
public Guid Id => Link?.RemoteId ?? Local!.Id;
/// <summary>This PC holds originals of the sequence.</summary>
public bool HasLocalOriginals => Local is { FrameCount: > 0 };
}
/// <summary>The sync table after a refresh.</summary>
/// <param name="Duration">Time the refresh took (listing, manifest diffs, settings exchange).</param>
public sealed record SyncSnapshot(string Server, IReadOnlyList<SyncEntry> 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);
}
/// <summary>Options a refresh applies.</summary>
/// <param name="AutoSyncSettings">Send and take settings changed on one side only (Server.html "Sync projects automatically").</param>
/// <param name="KeepProxiesOffline">Keep the proxy caches of server sequences this PC opened with proxies up to date.</param>
/// <param name="CanEdit">The account may change server sequences; without it this PC's edits are never sent.</param>
public sealed record SyncPolicy(bool AutoSyncSettings = true, bool KeepProxiesOffline = false, bool CanEdit = true);
/// <summary>
/// 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.
/// </summary>
public sealed class SyncConflictChangedException(string message) : InvalidOperationException(message);
+123
View File
@@ -0,0 +1,123 @@
using Titano.Protocol;
using Titano.Protocol.Client;
namespace Titano.Data.Sync;
/// <summary>
/// The server calls the sync engine makes (BRIEF §14.3). <see cref="TitanoSyncRemote"/> sends them with
/// <see cref="TitanoClient"/>; screenshots and tests substitute fakes. Failures are <see cref="TitanoApiException"/>s
/// (404 gone, 409 settings conflict) or network exceptions. Dispose a remote handed out by an <see cref="ISyncConnector"/>.
/// </summary>
public interface ISyncRemote : IDisposable
{
/// <summary>Normalised server address the links are stored under (<see cref="SyncService.ServerKey"/>).</summary>
string Server { get; }
/// <summary>Every sequence on the server.</summary>
Task<IReadOnlyList<SequenceDto>> ListSequencesAsync(CancellationToken cancellationToken);
Task<SequenceDto> GetSequenceAsync(Guid id, CancellationToken cancellationToken);
Task<SequenceManifest> GetManifestAsync(Guid id, CancellationToken cancellationToken);
/// <summary>Every frame row of a sequence, in index order.</summary>
Task<IReadOnlyList<FrameDto>> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken);
/// <summary>A 409 <see cref="TitanoApiException"/> means the settings version moved on the server.</summary>
Task<SequenceDto> UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken);
/// <summary>
/// Chunked, resumable upload of one original into <paramref name="sequenceId"/>, or into the sequence the server
/// files <paramref name="sessionKey"/> under (created by the first one); the server verifies <paramref name="sha256"/>
/// before committing it (BRIEF §14.4). An original the server already holds is not sent again: the response then
/// names <paramref name="sequenceId"/> (<see cref="Guid.Empty"/> without one). See <see cref="TitanoClient.UploadFileAsync"/>.
/// </summary>
Task<CompleteUploadResponse?> UploadFileAsync(string path, Guid? sequenceId, string? sessionKey, string sha256, DateTime? capturedAt,
CancellationToken cancellationToken);
/// <summary>Streams a frame's original, proxy or thumb, resuming with Range from the destination's length.</summary>
Task DownloadFrameAsync(Guid frameId, string kind, Stream destination, CancellationToken cancellationToken);
/// <summary>Streams a render's file, resuming with Range from the destination's length; returns the file name the server gives it.</summary>
Task<string?> DownloadRenderAsync(Guid renderId, Stream destination, CancellationToken cancellationToken);
/// <summary>
/// Chunked, resumable upload of a render of <paramref name="sequenceId"/> made on this PC; the server verifies the
/// SHA-256 and keeps the render's id. Null when the server already has it. See <see cref="TitanoClient.UploadRenderAsync"/>.
/// </summary>
Task<RenderDto?> UploadRenderAsync(Guid sequenceId, string path, RenderUploadRequest request, CancellationToken cancellationToken);
/// <summary>Server events until cancelled or the socket closes.</summary>
IAsyncEnumerable<ServerEvent> EventsAsync(CancellationToken cancellationToken);
}
/// <summary>Where sync jobs find their server connection.</summary>
public interface ISyncConnector
{
/// <summary>A signed-in remote of <paramref name="server"/> owned by the caller; null when this PC is not connected to that server.</summary>
ValueTask<ISyncRemote?> ConnectAsync(string server, CancellationToken cancellationToken);
}
/// <summary><see cref="ISyncRemote"/> over a signed-in <see cref="TitanoClient"/>, which it disposes when it owns it.</summary>
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<IReadOnlyList<SequenceDto>> ListSequencesAsync(CancellationToken cancellationToken)
{
var all = new List<SequenceDto>();
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<SequenceDto> GetSequenceAsync(Guid id, CancellationToken cancellationToken) => client.GetSequenceAsync(id, cancellationToken);
public Task<SequenceManifest> GetManifestAsync(Guid id, CancellationToken cancellationToken) => client.GetManifestAsync(id, cancellationToken);
public async Task<IReadOnlyList<FrameDto>> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken)
{
var all = new List<FrameDto>();
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<SequenceDto> UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken) =>
client.UpdateSequenceAsync(id, request, cancellationToken);
public Task<CompleteUploadResponse?> 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<string?> DownloadRenderAsync(Guid renderId, Stream destination, CancellationToken cancellationToken) =>
client.DownloadRenderAsync(renderId, destination, cancellationToken);
public Task<RenderDto?> UploadRenderAsync(Guid sequenceId, string path, RenderUploadRequest request, CancellationToken cancellationToken) =>
client.UploadRenderAsync(sequenceId, path, request, null, cancellationToken);
public IAsyncEnumerable<ServerEvent> EventsAsync(CancellationToken cancellationToken) => client.EventsAsync(cancellationToken);
public void Dispose()
{
if (ownsClient) client.Dispose();
}
}
+163
View File
@@ -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;
/// <summary>The fields both sides version together (BRIEF §14.5: settings and tags carry version counters).</summary>
public sealed record SyncPayload(string? Title, IReadOnlyList<string> 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);
/// <summary>Title, tags, rating and notes match (blank equals absent, tags ignore case and order).</summary>
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);
/// <summary>The PATCH that makes the server's copy equal to this one; settings are sent in their normalised form.</summary>
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;
/// <summary>
/// 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).
/// </summary>
public sealed record SettingsDifference(string Path, string? Mine, string? Theirs);
/// <summary>Decisions of the sync engine that need no I/O: the status of a row, settings equality and differences, merges.</summary>
public static class SyncRules
{
/// <summary>Path prefix of the title, tags, rating and notes in <see cref="Differences(SyncPayload, SyncPayload, int)"/>.</summary>
public const string MetadataPath = "sequence.";
/// <summary>
/// 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.
/// </summary>
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;
}
/// <summary>The state stored on the local sequence for the Library; null for rows without a local copy or in transfer.</summary>
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,
};
/// <summary>
/// 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.
/// </summary>
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;
/// <summary>Up to <paramref name="max"/> settings that differ, in document order.</summary>
public static IReadOnlyList<SettingsDifference> Differences(string? mine, string? theirs, int max = 3)
{
var differences = new List<SettingsDifference>();
Collect(Parse(NormalizeSettings(mine)), Parse(NormalizeSettings(theirs)), string.Empty, differences, max);
return differences;
}
/// <summary>
/// Up to <paramref name="max"/> differences between two payloads: title, tags, rating and notes first (paths
/// <c>sequence.title</c>, <c>sequence.tags</c>, …, tags as one comma-separated value), then the settings.
/// </summary>
public static IReadOnlyList<SettingsDifference> Differences(SyncPayload mine, SyncPayload theirs, int max = 3)
{
var differences = new List<SettingsDifference>();
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;
}
/// <summary>
/// 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.
/// </summary>
public static (int MissingRemote, int MissingLocal) CompareOriginals(IReadOnlyCollection<string?> localHashes, IReadOnlyCollection<string> 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<SettingsDifference> 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()));
}
}
+800
View File
@@ -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;
/// <summary>Settings of a <see cref="SyncService"/>.</summary>
public sealed record SyncOptions
{
/// <summary>Decoders, lease owner and lease timing for sidecar and project writes (shared with the archive engine).</summary>
public ArchiveServiceOptions Archive { get; init; } = new();
/// <summary>Folder of the proxy cache of server sequences (inside the client's cache).</summary>
public required string ProxyCacheDirectory { get; init; }
/// <summary>Concurrent frame downloads of one job.</summary>
public int Downloads { get; init; } = 4;
/// <summary>Concurrent file uploads of one job (the server accepts 8 chunks in flight per user).</summary>
public int Uploads { get; init; } = 2;
}
/// <summary>
/// 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 <see cref="ResolveAsync"/>, against the versions the user was shown. Uploads and
/// downloads run as jobs (<see cref="CreateJobHandlers"/>): 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 <see cref="RemoteSequence"/>; 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 <c>sync_state</c> for the Library. A failure while
/// comparing one sequence is recorded on its link and does not stop the others.
/// </summary>
public sealed class SyncService
{
private const string LogCategory = "sync";
private const string SessionKeyPrefix = "titano-sync:";
/// <summary>Recomputes states without sending or taking settings on the user's behalf.</summary>
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);
/// <summary>Unlinked pairs whose manifests were compared at these frame versions without a match (not fetched again).</summary>
private readonly ConcurrentDictionary<string, byte> _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; }
/// <summary>The links or local states of a server (the argument) changed: refresh, resolution, transfer; raised on any thread.</summary>
public event Action<string>? Changed;
internal ProxyCache Proxies { get; }
internal SyncLinkStore Links => _links;
internal TitanoDatabase Database => _db;
internal ArchiveService Archives { get; }
/// <summary>"https://nas.local:8443": the key links are stored under (scheme, lower-case host, port, path).</summary>
public static string ServerKey(Uri address) => address.GetLeftPart(UriPartial.Path).TrimEnd('/').ToLowerInvariant();
/// <summary>What an upload or download job moves; null for any other job.</summary>
public static SyncTransferKind? TransferKind(Job job) => SyncJobParameters.Read(job)?.Kind(job.Kind);
/// <summary>Session key the local archive groups the downloaded originals of one server sequence by.</summary>
internal static string SessionKey(Guid remoteId) => SessionKeyPrefix + remoteId.ToString("N");
// ---------------- Table ----------------
/// <summary>
/// Lists the server, compares every sequence with its local copy, sends or takes settings changed on one side when
/// <see cref="SyncPolicy.AutoSyncSettings"/> is on, forgets sequences the server confirms deleted, links unlinked
/// copies holding the same originals, and stores the states.
/// </summary>
public async Task<SyncSnapshot> RefreshAsync(ISyncRemote remote, SyncPolicy policy, CancellationToken cancellationToken)
{
var clock = Stopwatch.StartNew();
var listing = await remote.ListSequencesAsync(cancellationToken).ConfigureAwait(false);
Dictionary<Guid, Sequence> 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);
}
/// <summary>Compares the given server sequences again (live events, finished transfers); a sequence gone from the server is forgotten.</summary>
public async Task RefreshSequencesAsync(ISyncRemote remote, IReadOnlyCollection<Guid> 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);
}
/// <summary>
/// The sync table of <paramref name="server"/> as last compared: every server sequence and every local one, with
/// active transfers; conflicts first, then transfers, then by title.
/// </summary>
public Task<IReadOnlyList<SyncEntry>> ListAsync(string server, CancellationToken cancellationToken) => EntriesAsync(server, null, cancellationToken);
/// <summary>
/// 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.
/// </summary>
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 ----------------
/// <summary>
/// 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 <see cref="SyncConflictChangedException"/>
/// is thrown. Returns the file this PC's settings were saved to for <see cref="SyncResolution.SaveBoth"/>, else null.
/// </summary>
public async Task<string?> 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;
}
/// <summary>Sends or takes settings changed on one side only (the row action while automatic sync is off).</summary>
public Task SyncSettingsAsync(ISyncRemote remote, Guid remoteId, SyncPolicy policy, CancellationToken cancellationToken) =>
RefreshSequencesAsync(remote, [remoteId], policy with { AutoSyncSettings = true }, cancellationToken);
// ---------------- Transfers ----------------
/// <summary>Queues the upload of a local sequence's originals and settings, unless one is already waiting or running.</summary>
public Task<Job> EnqueueUploadAsync(JobEngine engine, string server, Sequence local, CancellationToken cancellationToken = default) =>
EnqueueAsync(engine, JobKind.UploadCommit, local.Id, local.DisplayTitle, new SyncJobParameters(server), JobPriority.User, cancellationToken);
/// <summary>Queues sending the renders of a local copy the server lacks (BRIEF §14.5), unless that is already waiting or running.</summary>
public Task<Job> 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);
/// <summary>
/// Queues a download of a server sequence, unless the same one is already waiting or running: originals into
/// <paramref name="archiveId"/> (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.
/// </summary>
public Task<Job> 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);
/// <summary>Handlers for <see cref="JobKind.UploadCommit"/> and <see cref="JobKind.Download"/>; register them on the client's engine.</summary>
public IReadOnlyList<IJobHandler> CreateJobHandlers(ISyncConnector connector)
{
var transfers = new SyncTransfers(this);
return [new SyncJobHandler(JobKind.UploadCommit, transfers, connector), new SyncJobHandler(JobKind.Download, transfers, connector)];
}
/// <summary>A server sequence from the proxy cache, for the editor; null when its proxies were never fetched or were cleared.</summary>
public RemoteSequence? OpenRemote(string server, Guid remoteId) => Proxies.Load(server, remoteId);
// ---------------- Engine ----------------
/// <summary>Server ids of the sequences an upload or download job is working on.</summary>
internal async Task<IReadOnlySet<Guid>> 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();
}
/// <summary>Creates or updates the link of a local sequence to a server sequence (an upload or download made it).</summary>
internal async Task<SyncLink> 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();
}
}
/// <summary>Forgets a link whose server sequence an upload found deleted (its originals go into a new one).</summary>
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();
}
}
/// <summary>
/// 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.
/// </summary>
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();
}
}
/// <summary>Makes this PC's copy equal to the server's (a sequence a download just created takes the server's settings).</summary>
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();
}
}
/// <summary>
/// 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.
/// </summary>
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);
}
/// <summary>Records what the proxy cache holds for a server sequence.</summary>
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);
}
/// <summary>The file of a local render: archive-relative for outputs inside the archive, absolute otherwise.</summary>
internal static string RenderFile(Archive archive, Render render) =>
Path.IsPathRooted(render.OutputPath) ? render.OutputPath : new ArchivePaths(archive.RootPath).FromRelative(render.OutputPath);
/// <summary>
/// Compares one server sequence (under the gate): fetches it, forgets its link on a 404, records a failure on its
/// link. <paramref name="locals"/> (when given) receives the local copy as it stands after the comparison.
/// </summary>
private async Task CompareOneAsync(ISyncRemote remote, Guid remoteId, SyncLink? link, Dictionary<Guid, Sequence>? 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<Guid, Sequence>? 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);
}
/// <summary>A failure that concerns one sequence; a lost session (401) or the caller's cancellation stops the whole comparison.</summary>
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,
};
/// <summary>Compares originals and renders when either side's moved, then settles the settings; returns the updated link and local copy.</summary>
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);
}
/// <summary>Renders each side lacks, by id (a render keeps its id on both sides); local renders whose file is gone cannot be sent.</summary>
private async Task<SyncLink> CompareExportsAsync(SyncLink link, Sequence local, IReadOnlyList<RenderDto> 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);
}
/// <summary>Sends this PC's payload unless the server moved past <paramref name="expected"/>, which shows up as a conflict next.</summary>
private static async Task<SyncLink> 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));
}
}
/// <summary>
/// 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.
/// </summary>
private async Task MatchByContentAsync(ISyncRemote remote, IReadOnlyList<SequenceDto> listing, Dictionary<Guid, Sequence> 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<bool> 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<string>().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);
/// <summary>Writes a payload into the local sidecar, project and index (each write bumps the local settings version).</summary>
private async Task<Sequence> 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;
}
/// <summary>
/// "Save both": this PC's project is kept next to <c>project.json</c> as <c>project.this-pc-&lt;local time&gt;.json</c>
/// before the server's replaces it; returns that file.
/// </summary>
private async Task<string> 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}");
}
/// <summary>Writes each local sequence's state for the Library and returns the table.</summary>
private async Task<IReadOnlyList<SyncEntry>> StoreStatesAsync(string server, Dictionary<Guid, Sequence>? 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;
}
/// <summary>The table from the stored links and <paramref name="known"/> local sequences (read from the index when null).</summary>
private async Task<IReadOnlyList<SyncEntry>> EntriesAsync(string server, Dictionary<Guid, Sequence>? known, CancellationToken cancellationToken)
{
var links = await _links.ListAsync(server, cancellationToken).ConfigureAwait(false);
var locals = known is null ? await LocalSequencesAsync(cancellationToken).ConfigureAwait(false) : new Dictionary<Guid, Sequence>(known);
var transfers = await _links.ActiveTransfersAsync(cancellationToken).ConfigureAwait(false);
var entries = new List<SyncEntry>(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)];
}
/// <summary>The transfer a row shows: the user's before background ones, originals before renders before proxies, running before waiting.</summary>
private static Job? Pick(IReadOnlyList<Job>? local, IReadOnlyList<Job>? 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();
/// <summary>The local copy of a link: from <paramref name="locals"/>, or the index when the paged listing missed it.</summary>
private async Task<Sequence?> LocalOfAsync(SyncLink? link, Dictionary<Guid, Sequence>? 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<Dictionary<Guid, Sequence>> LocalSequencesAsync(CancellationToken cancellationToken)
{
var all = new Dictionary<Guid, Sequence>();
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<Job> 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);
}
/// <summary>The link with the server's side as <paramref name="dto"/> lists it (a new link when there was none).</summary>
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,
};
}
+523
View File
@@ -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;
/// <summary>
/// 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.
/// </summary>
internal sealed class SyncTransfers(SyncService sync)
{
private const long SpaceReserve = 512L << 20;
/// <summary>Space a cached proxy is assumed to take before it is downloaded (1920 px JPEG, BRIEF §8.5).</summary>
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<Frame>(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);
}
}
/// <summary>
/// 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.
/// </summary>
private async Task<(HashSet<string> Have, Dictionary<string, string> 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<string, string>(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);
/// <summary>Puts a verified copy of an original flagged missing back where its record says; a file that reappeared meanwhile is kept.</summary>
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);
}
/// <summary>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.</summary>
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;
}
/// <summary>"name.mp4", else "name (2).mp4", … — an existing export is never replaced.</summary>
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<string> 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");
}
/// <summary>
/// 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).
/// </summary>
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<bool> 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;
}
}
/// <summary>
/// Hashes the original again and sends it into <paramref name="sequenceId"/> (or the sequence of
/// <paramref name="sessionKey"/>); null (logged) when it is gone or no longer the archived file.
/// </summary>
private static async Task<CompleteUploadResponse?> 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);
}
/// <summary>Downloads one original into staging and commits it into the local sequence (created from the server id when null).</summary>
private async Task<IngestResult> CommitAsync(ISyncRemote remote, Guid remoteId, Guid archiveId, Guid? sequenceId, ManifestFrame frame, string staging,
IReadOnlyDictionary<Guid, DateTime?> 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;
}
/// <summary>A verified copy in staging: resumed from a partial download, accepted only with the manifest's SHA-256 (two attempts).</summary>
private static async Task<string> 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));
}
}
/// <summary>The cached proxy's file name, downloading the first asset kind the server has; null when it has none.</summary>
private static async Task<string?> FetchProxyAsync(ISyncRemote remote, Guid frameId, IReadOnlyList<string> 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"],
_ => [],
};
/// <summary>Puts a follow-up job in the queue; the engine claims it on its next poll.</summary>
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 };
/// <summary>Files done out of the total, reported in order from parallel workers.</summary>
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);
}
}
@@ -175,6 +175,46 @@ public sealed class TitanoClient : IDisposable
.ConfigureAwait(false);
}
/// <summary>
/// Sends a render of <paramref name="sequenceId"/> made on this PC in resumable chunks; the server verifies the
/// SHA-256 in <paramref name="request"/> and files it under the sequence's exports with the same id. Null when the
/// server already has that render.
/// </summary>
public async Task<RenderDto?> UploadRenderAsync(Guid sequenceId, string path, RenderUploadRequest request, IProgress<UploadProgress>? 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<RenderDto>(HttpMethod.Post, $"api/v1/sequences/{sequenceId}/renders/{uploadId}/complete",
ProtocolJson.Default.RenderDto, ct), ct).ConfigureAwait(false);
}
/// <summary>
/// Streams a render's file to <paramref name="destination"/>, resuming with Range from its current length; returns
/// the file name the server gives it.
/// </summary>
public async Task<string?> 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('"');
}
/// <summary>Sends every chunk the server does not have yet; each PUT is idempotent and retried on transient errors.</summary>
private async Task SendChunksAsync(string path, long length, Guid uploadId, int chunkSize, IReadOnlyList<int> alreadyReceived,
IProgress<UploadProgress>? progress, CancellationToken ct)
+1
View File
@@ -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))]
+20
View File
@@ -16,3 +16,23 @@ public sealed record CompleteUploadResponse(Guid FrameId, Guid SequenceId, int I
/// <summary><c>GET /api/v1/uploads/{id}</c>: resume state.</summary>
public sealed record UploadState(Guid UploadId, string FileName, long Size, string Sha256, int ChunkSize, IReadOnlyList<int> Received, string State);
/// <summary>
/// <c>POST /api/v1/sequences/{id}/renders</c>: 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 <see cref="StartUploadResponse.AlreadyExists"/>. Chunks go to
/// <c>/uploads/{uploadId}/chunks/{n}</c>; <c>POST /sequences/{id}/renders/{uploadId}/complete</c> verifies the SHA-256
/// and files the render under the sequence's exports.
/// </summary>
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);
@@ -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<IResult> ListAsync(HttpContext context, TitanoDatabase db, ServerArchive archive, int? year, string? camera, string? status,
+1
View File
@@ -121,6 +121,7 @@ public static class ServerHost
services.AddSingleton<UploadStore>();
services.AddSingleton<UploadService>();
services.AddSingleton<RenderStore>();
services.AddSingleton<RenderUploads>();
services.AddSingleton<SequenceJobs>();
services.AddSingleton<RenderNodeService>();
services.AddSingleton<JobEngineHost>();
+7 -2
View File
@@ -12,7 +12,12 @@ public sealed class RenderStore(TitanoDatabase db, ServerArchive archive, TimePr
/// Moves <paramref name="stagedFile"/> (on the archive volume) to <c>&lt;sequence folder&gt;/exports/</c>, never
/// replacing an existing export, and inserts the render row. Null when the sequence has no folder in the archive yet.
/// </summary>
public async Task<Render?> CommitAsync(Sequence sequence, string stagedFile, RenderResultRequest output, string producedBy, CancellationToken cancellationToken)
public Task<Render?> CommitAsync(Sequence sequence, string stagedFile, RenderResultRequest output, string producedBy, CancellationToken cancellationToken) =>
CommitAsync(sequence, stagedFile, output, producedBy, Guid.CreateVersion7(), cancellationToken);
/// <summary>As above, keeping <paramref name="id"/>: a render a client sends keeps the id it has on that client.</summary>
public async Task<Render?> 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),
+118
View File
@@ -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;
/// <summary>
/// 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 <see cref="RenderStore"/> under the
/// sequence's exports with the client's render id, so both sides recognise the same render.
/// </summary>
public sealed class RenderUploads(
TitanoDatabase db,
ServerOptions options,
UploadService uploads,
UploadStore store,
RenderStore renders,
EventHub events,
TimeProvider time)
{
public async Task<Outcome<StartUploadResponse>> StartAsync(Caller caller, Guid sequenceId, RenderUploadRequest request, CancellationToken cancellationToken)
{
if (await db.Sequences.GetAsync(sequenceId, cancellationToken) is null) return Outcome<StartUploadResponse>.Fail(404, "not_found", "sequence");
if (UploadRules.SafeFileName(request.FileName) is not { } fileName) return Outcome<StartUploadResponse>.Fail(400, "invalid_file_name");
if (!UploadRules.IsSha256(request.Sha256)) return Outcome<StartUploadResponse>.Fail(400, "invalid_hash");
if (request.Size <= 0) return Outcome<StartUploadResponse>.Fail(400, "bad_request", "size");
if (request.Size > options.MaxUploadBytes)
return Outcome<StartUploadResponse>.Fail(413, "too_large", options.MaxUploadBytes.ToString(CultureInfo.InvariantCulture));
if (string.IsNullOrWhiteSpace(request.PresetName) || request.PresetName.Length > 200) return Outcome<StartUploadResponse>.Fail(400, "bad_request", "presetName");
if (request.RenderId == Guid.Empty) return Outcome<StartUploadResponse>.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<StartUploadResponse>.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<StartUploadResponse>.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);
}
/// <summary>Verifies a fully received render and files it; completing a committed one answers it again (a lost response).</summary>
public async Task<Outcome<RenderDto>> 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<RenderDto>.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<RenderDto>.Fail(409, "upload_state");
if (!upload.IsComplete)
return Outcome<RenderDto>.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<RenderDto>.Fail(409, "upload_state");
if (await uploads.StageVerifiedAsync(upload, cancellationToken) is not { } staged) return Outcome<RenderDto>.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<RenderDto>.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);
}
+1 -1
View File
@@ -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<CompleteUploadResponse>(404, "not_found", "upload");
if (upload.JobId is not null) return Fail<CompleteUploadResponse>(409, "wrong_upload_kind");
if (upload.JobId is not null || upload.RenderJson is not null) return Fail<CompleteUploadResponse>(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<CompleteUploadResponse>(409, "upload_state");
+4 -3
View File
@@ -1248,10 +1248,11 @@
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ui:StatusGlyph">
<StackPanel Orientation="Horizontal" Background="Transparent">
<!-- A dock panel, so a glyph in a fixed-width cell ends in an ellipsis instead of being cut. -->
<DockPanel Background="Transparent">
<ui:Icon x:Name="Glyph" Glyph="{StaticResource Icon.Dot}" Size="11" Margin="0,0,4,0" VerticalAlignment="Center" />
<TextBlock Text="{TemplateBinding Text}" VerticalAlignment="Center" />
</StackPanel>
<TextBlock Text="{TemplateBinding Text}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" />
</DockPanel>
<ControlTemplate.Triggers>
<Trigger Property="Kind" Value="Analysed"><Setter Property="Foreground" Value="{DynamicResource Brush.Success}" /></Trigger>
<Trigger Property="Kind" Value="Done"><Setter Property="Foreground" Value="{DynamicResource Brush.Success}" /></Trigger>
@@ -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;
/// <summary>The Server screen's sync table on the capture sample data: comparison, transfers, conflict and the Library's glyphs.</summary>
[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<ServerView>("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<ListBox>().Single(l => l.Name == "SyncList");
Assert.Equal(KeyboardNavigationMode.Continue, KeyboardNavigation.GetTabNavigation(list));
var rowButtons = app.FindAll<Button>().Where(b => b.DataContext is SyncRowAction && b.IsVisible).ToList();
Assert.True(rowButtons.Select(b => b.DataContext).OfType<SyncRowAction>().Count() > 3, "buttons of several rows are on screen");
Assert.True(rowButtons.All(b => b.Focusable && b.IsTabStop), "every row button is a tab stop");
// Transfers in every state: the rows show what moves and offer Pause or Resume.
await app.Sample.FillSyncAsync();
await table.ReloadAsync();
var comet = Row(table, "Comet over the ridge");
Assert.Equal(SyncStatus.Transferring, comet.Entry.Status);
Assert.SequenceEqual([SyncAction.Pause], Actions(comet));
Assert.Contains("46", comet.ServerText);
Assert.Equal(StatusKind.Queued, Row(table, "Fog lifting, Asti").StateKind);
Assert.Equal((StatusKind.Running, Loc.L("Server.Sync.State.Downloading")), (Row(table, "Sunrise over Superga").StateKind, Row(table, "Sunrise over Superga").StateText));
Assert.SequenceEqual([SyncAction.Resume], Actions(Row(table, "Lake Como storm")));
await app.ExpectAsync<ServerView>("server-sync");
// A reload keeps the row's buttons (focus, tooltips and clicks survive progress and comparisons).
var pause = comet.Actions[0];
await table.ReloadAsync();
Assert.Same(pause, Row(table, "Comet over the ridge").Actions[0]);
// The conflict filter leaves the one row waiting for a choice.
Chip(table, SyncFilter.Conflicts).SelectCommand.Execute(null);
Assert.Equal("Holy grail · Monviso", Assert.Contains(table.Rows, _ => true).Title);
Assert.Count(1, table.Rows);
await app.ExpectAsync<ServerView>("server-conflict");
table.SearchText = "nothing like this";
Assert.False(table.HasRows);
Assert.NotNull(table.EmptyText);
// Another language relabels chips and rows at once.
UiLanguage.Apply("it");
try
{
Assert.Equal("Tutte · 38", Chip(table, SyncFilter.All).Text);
}
finally
{
UiLanguage.Apply("en");
}
});
[Test]
public Task SigningOutEmptiesTheTable() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var shell = app.Shell;
await app.Sample.FillAsync();
await shell.Services.Server.RestoreAsync();
await shell.Services.Sync.RefreshAsync();
await shell.Server.Sync.ReloadAsync();
Assert.True(shell.Server.Sync.HasRows);
await shell.Services.Server.SignOutAsync();
Assert.Null(await shell.Services.Sync.RefreshAsync());
await shell.Server.Sync.ReloadAsync();
Assert.False(shell.Server.Sync.IsActive);
Assert.False(shell.Server.Sync.HasRows);
Assert.False(shell.Server.Sync.UploadAllCommand.CanExecute(null));
Assert.Equal(Loc.L("Tooltips.Server.Sync.UploadAll.NotConnected"), shell.Server.Sync.UploadAllToolTip);
shell.Navigate(SectionKey.Server);
await app.ExpectAsync<ServerView>("server-signedout-table");
});
private static SyncFilterChip Chip(SyncTableViewModel table, SyncFilter filter) => table.Chips.Single(c => c.Filter == filter);
private static SyncRow Row(SyncTableViewModel table, string title) => table.Rows.Single(r => r.Title == title);
private static IEnumerable<SyncAction> Actions(SyncRow row) => row.Actions.Select(a => a.Action);
}
@@ -0,0 +1,167 @@
using Titano.App.Server;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data.Sync;
using Titano.Testing;
using Titano.Ui.Controls;
namespace Titano.App.Tests.Server;
/// <summary>Words, glyphs and actions of the sync table rows (Server.html).</summary>
public sealed class SyncTextTests
{
private static readonly SyncRights Editor = SyncRights.Of((long)RolePermissions.Default(UserRole.Editor));
private static readonly SyncRights Viewer = SyncRights.Of((long)RolePermissions.Default(UserRole.Viewer));
private static readonly Sequence Local = new()
{
Id = Guid.CreateVersion7(),
ArchiveId = Guid.CreateVersion7(),
Title = "Harbour sunset",
Folder = "2026/harbour",
FrameCount = 3_600,
TotalBytes = 86_000_000_000,
Status = SequenceStatus.ProxiesBuilt,
SettingsJson = """{"exposure":{"deflickerWindow":{"isAuto":false,"manual":41}}}""",
};
private static readonly SyncLink Link = new()
{
Server = "https://nas.local:8443",
RemoteId = Guid.CreateVersion7(),
Title = "Harbour sunset",
TotalBytes = 61_000_000_000,
RemoteStatus = SequenceStatus.ProxiesBuilt | SequenceStatus.ThumbsBuilt,
RenderCount = 2,
};
[Test]
public void RightsFollowTheServerPermissions()
{
Assert.Equal(new SyncRights(true, true, true), Editor);
Assert.Equal(new SyncRights(false, false, false), Viewer);
Assert.Equal(new SyncRights(false, true, false), SyncRights.Of((long)Permissions.RenderNode));
}
[Test]
public void EachStateOffersItsActions()
{
Assert.SequenceEqual([SyncAction.Upload], SyncText.Actions(Entry(SyncStatus.LocalOnly, link: null), Editor));
Assert.Empty(SyncText.Actions(Entry(SyncStatus.LocalOnly, link: null), Viewer));
Assert.SequenceEqual([SyncAction.OpenWithProxies, SyncAction.DownloadOriginals], SyncText.Actions(Entry(SyncStatus.RemoteOnly, local: null), Editor));
Assert.SequenceEqual([SyncAction.OpenWithProxies], SyncText.Actions(Entry(SyncStatus.ProxiesOnly, local: null), Viewer));
Assert.SequenceEqual([SyncAction.Upload], SyncText.Actions(Entry(SyncStatus.LocalAhead, Link with { MissingRemote = 4 }), Editor));
Assert.SequenceEqual([SyncAction.DownloadOriginals], SyncText.Actions(Entry(SyncStatus.ServerAhead, Link with { MissingLocal = 2 }), Editor));
Assert.SequenceEqual([SyncAction.SyncSettings], SyncText.Actions(Entry(SyncStatus.ServerAhead), Editor));
Assert.SequenceEqual([SyncAction.KeepMine, SyncAction.TakeServer, SyncAction.SaveBoth], SyncText.Actions(Entry(SyncStatus.Conflict), Editor));
Assert.Empty(SyncText.Actions(Entry(SyncStatus.InSync), Editor));
// Without the edit right nothing of this PC is sent: no "Keep mine", no settings push.
Assert.SequenceEqual([SyncAction.TakeServer, SyncAction.SaveBoth], SyncText.Actions(Entry(SyncStatus.Conflict), Viewer));
Assert.Empty(SyncText.Actions(Entry(SyncStatus.LocalAhead), Viewer));
Assert.SequenceEqual([SyncAction.SyncSettings], SyncText.Actions(Entry(SyncStatus.ServerAhead), Viewer));
// Renders travel on request once the originals agree.
var exports = Link with { ExportsToGet = 3, ExportsToGetBytes = 1_900_000_000, ExportsToSend = 1, ExportsToSendBytes = 600_000_000 };
Assert.SequenceEqual([SyncAction.GetExports, SyncAction.SendExports], SyncText.Actions(Entry(SyncStatus.InSync, exports), Editor));
Assert.SequenceEqual([SyncAction.GetExports], SyncText.Actions(Entry(SyncStatus.InSync, exports), Viewer));
Assert.SequenceEqual([SyncAction.KeepMine, SyncAction.TakeServer, SyncAction.SaveBoth], SyncText.Actions(Entry(SyncStatus.Conflict, exports), Editor));
Assert.Equal(Loc.Plural("Tooltips.Server.Sync.GetExports", 3, Titano.App.Infrastructure.Formatting.Bytes(1_900_000_000)),
SyncText.ToolTip(Entry(SyncStatus.InSync, exports), SyncAction.GetExports));
Assert.SequenceEqual([SyncAction.Pause], SyncText.Actions(Entry(SyncStatus.Transferring, transfer: Upload(JobState.Running)), Editor));
Assert.SequenceEqual([SyncAction.Pause], SyncText.Actions(Entry(SyncStatus.Transferring, transfer: Upload(JobState.Queued)), Editor));
Assert.SequenceEqual([SyncAction.Resume], SyncText.Actions(Entry(SyncStatus.Transferring, transfer: Upload(JobState.Paused)), Editor));
}
[Test]
public void ColumnsSayWhatEachSideHolds()
{
var originals = Loc.L("Server.Sync.Originals");
var proxies = Loc.L("Server.Sync.Proxies");
Assert.Equal($"{originals} · {proxies}", SyncText.Local(Entry(SyncStatus.InSync)));
Assert.Equal(originals, SyncText.Local(Entry(SyncStatus.InSync, local: Local with { Status = SequenceStatus.None })));
Assert.Equal(proxies, SyncText.Local(Entry(SyncStatus.ProxiesOnly, Link with { ProxiesCached = 10 }, local: null)));
Assert.Equal(Loc.L("Server.Sync.None"), SyncText.Local(Entry(SyncStatus.RemoteOnly, local: null)));
Assert.Equal($"{originals} · {proxies} · {Loc.Plural("Server.Sync.Exports", 2)}", SyncText.Server(Entry(SyncStatus.InSync)));
Assert.Equal(Loc.L("Server.Sync.None"), SyncText.Server(Entry(SyncStatus.LocalOnly, link: null)));
var uploading = Entry(SyncStatus.Transferring, link: null, transfer: Upload(JobState.Running) with { ProgressDone = 462, ProgressTotal = 1_005 });
Assert.Equal(Loc.L("Server.Sync.Received", Loc.L("Common.Percent", "46")), SyncText.Server(uploading));
Assert.Equal(86_000_000_000, SyncText.Size(Entry(SyncStatus.LocalOnly, link: null), SyncAction.Upload));
Assert.Equal(61_000_000_000, SyncText.Size(Entry(SyncStatus.RemoteOnly, local: null), SyncAction.DownloadOriginals));
}
[Test]
public void StatesPairAGlyphWithAWord()
{
Assert.Equal((StatusKind.Done, Loc.L("Server.Sync.State.InSync")), Kind(Entry(SyncStatus.InSync)));
Assert.Equal((StatusKind.Offline, Loc.L("Server.Sync.State.LocalOnly")), Kind(Entry(SyncStatus.LocalOnly, link: null)));
Assert.Equal((StatusKind.Remote, Loc.L("Server.Sync.State.RemoteOnly")), Kind(Entry(SyncStatus.RemoteOnly, local: null)));
Assert.Equal((StatusKind.Warning, Loc.L("Server.Sync.State.Conflict")), Kind(Entry(SyncStatus.Conflict)));
Assert.Equal((StatusKind.Running, Loc.L("Server.Sync.State.Uploading")), Kind(Entry(SyncStatus.Transferring, transfer: Upload(JobState.Running))));
Assert.Equal((StatusKind.Paused, Loc.L("Server.Sync.State.Paused")), Kind(Entry(SyncStatus.Transferring, transfer: Upload(JobState.Paused))));
Assert.Equal((StatusKind.Running, Loc.L("Server.Sync.State.Downloading")),
Kind(Entry(SyncStatus.Transferring, transfer: Upload(JobState.Running) with { Kind = JobKind.Download })));
}
[Test]
public void AConflictNamesTheSettingsThatDifferInWords()
{
var theirs = new SyncPayload(Local.Title, ["boats"], 0, null, """{"exposure":{"deflickerWindow":{"isAuto":false,"manual":33},"deflicker":{"isAuto":false,"manual":true}}}""");
var conflict = Entry(SyncStatus.Conflict, Link with { ConflictRemote = theirs });
var lines = SyncText.Conflict(conflict, 10);
Assert.SequenceEqual(
[
Loc.L("Server.Conflict.Difference", Loc.L("Server.Setting.Tags"), Loc.L("Server.Sync.None"), "boats"),
Loc.L("Server.Conflict.Difference", Loc.L("Server.Setting.Deflicker"), Loc.L("Server.Setting.Auto"), Loc.L("Server.Setting.Manual")),
Loc.L("Server.Conflict.Difference", Loc.L("Server.Setting.DeflickerWindow"), "41", "33"),
], lines);
// The State tooltip is one line: the first difference and how many more.
Assert.Equal(Loc.L("Server.Conflict.More", lines[0], "2"), SyncText.State(conflict).ToolTip);
Assert.False(SyncText.State(conflict).ToolTip.Contains('\n', StringComparison.Ordinal), "one line");
Assert.Equal(Loc.L("Tooltips.Server.Sync.State.Conflict"), SyncText.ConflictSummary(Entry(SyncStatus.Conflict)));
}
[Test]
public void ASequenceThatCouldNotBeComparedSaysWhy()
{
var (kind, text, tip) = SyncText.State(Entry(SyncStatus.InSync, Link with { Error = "403 forbidden" }));
Assert.Equal((StatusKind.Warning, Loc.L("Server.Sync.State.Failed")), (kind, text));
Assert.Contains("403 forbidden", tip);
}
[Test]
public void FiltersAndSearchSelectRows()
{
var rows = new[]
{
Entry(SyncStatus.LocalOnly, link: null),
Entry(SyncStatus.RemoteOnly, local: null),
Entry(SyncStatus.ProxiesOnly, local: null),
Entry(SyncStatus.Conflict),
Entry(SyncStatus.InSync, local: Local with { Title = "Comet over the ridge" }),
};
Assert.Equal(5, rows.Count(r => SyncText.Matches(r, SyncFilter.All, string.Empty)));
Assert.Equal(1, rows.Count(r => SyncText.Matches(r, SyncFilter.LocalOnly, string.Empty)));
Assert.Equal(2, rows.Count(r => SyncText.Matches(r, SyncFilter.Remote, string.Empty)));
Assert.Equal(1, rows.Count(r => SyncText.Matches(r, SyncFilter.Conflicts, string.Empty)));
Assert.Equal(1, rows.Count(r => SyncText.Matches(r, SyncFilter.All, "COMET")));
Assert.Equal(0, rows.Count(r => SyncText.Matches(r, SyncFilter.Conflicts, "comet")));
}
private static (StatusKind, string) Kind(SyncEntry entry)
{
var (kind, text, _) = SyncText.State(entry);
return (kind, text);
}
private static SyncEntry Entry(SyncStatus status, SyncLink? link = null, Sequence? local = null, Job? transfer = null) =>
new(local ?? (status is SyncStatus.RemoteOnly or SyncStatus.ProxiesOnly ? null : Local), link ?? (status == SyncStatus.LocalOnly ? null : Link), status,
transfer);
private static Job Upload(JobState state) => new() { Id = Guid.CreateVersion7(), Kind = JobKind.UploadCommit, State = state };
}
@@ -122,7 +122,7 @@ public sealed class ScreenSmokeTests
});
/// <summary>A <see cref="MainWindow"/> on capture services and sample data, shown off screen like <c>--capture</c>.</summary>
private sealed class SampleApp : IAsyncDisposable
internal sealed class SampleApp : IAsyncDisposable
{
private const double Width = 1440;
private const double Height = 900;
@@ -0,0 +1,265 @@
using System.Net;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Threading.Channels;
using Titano.Core.Model;
using Titano.Data.Sync;
using Titano.Protocol;
using Titano.Protocol.Client;
namespace Titano.Data.Tests.Sync;
/// <summary>An in-memory Titano Server for the sync engine: sequences with versions, originals, proxies, thumbnails and events.</summary>
internal sealed class FakeSyncRemote : ISyncRemote
{
private readonly Lock _gate = new();
private readonly Channel<ServerEvent> _events = Channel.CreateUnbounded<ServerEvent>();
private readonly Dictionary<string, FakeSequence> _sessions = [];
public string Server => "https://nas.test:8443";
public Dictionary<Guid, FakeSequence> Sequences { get; } = [];
/// <summary>Manifest requests so far (comparisons skip them while frame counters stand still).</summary>
public int ManifestCalls { get; private set; }
/// <summary>Listings still to fail with a network error.</summary>
public int FailingListings { get; set; }
/// <summary>The next original download of this frame returns damaged bytes.</summary>
public Guid? CorruptOnce { get; set; }
/// <summary>Sequences the listing skips (a page boundary moved while it was read); they are still there.</summary>
public HashSet<Guid> Unlisted { get; } = [];
/// <summary>Sequences whose manifest the server refuses (403), as for an account that lost a right.</summary>
public HashSet<Guid> Refused { get; } = [];
/// <summary>Proxy and thumbnail downloads fail with a server error.</summary>
public bool FailAssets { get; set; }
public FakeSequence Add(string? title, IEnumerable<byte[]> originals, string? settingsJson = null,
SequenceStatus status = SequenceStatus.ProxiesBuilt | SequenceStatus.ThumbsBuilt)
{
var sequence = new FakeSequence { Id = Guid.CreateVersion7(), Title = title, SettingsJson = settingsJson, Status = status };
foreach (var bytes in originals) sequence.AddFrame(bytes);
lock (_gate) Sequences[sequence.Id] = sequence;
return sequence;
}
/// <summary>Someone else edits the settings on the server.</summary>
public void EditSettings(Guid id, string settingsJson)
{
lock (_gate)
{
var s = Sequences[id];
s.SettingsJson = settingsJson;
s.SettingsVersion++;
s.UpdatedAt = DateTimeOffset.UtcNow;
}
}
public void Publish(ServerEvent e) => _events.Writer.TryWrite(e);
public Task<IReadOnlyList<SequenceDto>> ListSequencesAsync(CancellationToken cancellationToken)
{
lock (_gate)
{
if (FailingListings > 0)
{
FailingListings--;
throw new HttpRequestException("connection refused");
}
return Task.FromResult<IReadOnlyList<SequenceDto>>([.. Sequences.Values.Where(s => !Unlisted.Contains(s.Id)).Select(s => s.Dto())]);
}
}
/// <summary>The next request for this sequence times out (HttpClient reports a timeout as a cancellation).</summary>
public Guid? TimeoutOnce { get; set; }
public Task<SequenceDto> GetSequenceAsync(Guid id, CancellationToken cancellationToken)
{
lock (_gate)
{
if (TimeoutOnce == id)
{
TimeoutOnce = null;
throw new TaskCanceledException("The request timed out.");
}
return Task.FromResult(Find(id).Dto());
}
}
public Task<SequenceManifest> GetManifestAsync(Guid id, CancellationToken cancellationToken)
{
lock (_gate)
{
ManifestCalls++;
if (Refused.Contains(id)) throw new TitanoApiException(HttpStatusCode.Forbidden, new ApiError("forbidden", "refused"));
return Task.FromResult(Find(id).Manifest());
}
}
public Task<IReadOnlyList<FrameDto>> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken)
{
lock (_gate) return Task.FromResult<IReadOnlyList<FrameDto>>([.. Find(sequenceId).Frames.Select((f, i) => f.Dto(sequenceId, i))]);
}
public Task<SequenceDto> UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken)
{
lock (_gate)
{
var s = Find(id);
if (request.ExpectedSettingsVersion is { } expected && expected != s.SettingsVersion)
throw new TitanoApiException(HttpStatusCode.Conflict, new ApiError("settings_conflict", "changed"));
if (request.Title is not null) s.Title = request.Title.Length == 0 ? null : request.Title;
if (request.Tags is not null) s.Tags = [.. request.Tags];
if (request.Rating is { } rating) s.Rating = rating;
if (request.Notes is not null) s.Notes = request.Notes.Length == 0 ? null : request.Notes;
if (request.SettingsJson is not null) s.SettingsJson = request.SettingsJson;
s.SettingsVersion++;
s.UpdatedAt = DateTimeOffset.UtcNow;
return Task.FromResult(s.Dto());
}
}
/// <summary>Like the server: content it already holds anywhere is not stored again; a session key files the first original into a new sequence.</summary>
public async Task<CompleteUploadResponse?> UploadFileAsync(string path, Guid? sequenceId, string? sessionKey, string sha256, DateTime? capturedAt,
CancellationToken cancellationToken)
{
var bytes = await File.ReadAllBytesAsync(path, cancellationToken);
if (Convert.ToHexStringLower(SHA256.HashData(bytes)) != sha256)
throw new TitanoApiException(HttpStatusCode.BadRequest, new ApiError("hash_mismatch", "hash"));
lock (_gate)
{
if (Sequences.Values.SelectMany(s => s.Frames).FirstOrDefault(f => f.Sha256 == sha256) is { } existing)
return new CompleteUploadResponse(existing.Id, sequenceId ?? Guid.Empty, -1);
FakeSequence target;
if (sequenceId is { } id) target = Find(id);
else if (!_sessions.TryGetValue(sessionKey!, out target!))
{
target = new FakeSequence { Id = Guid.CreateVersion7() };
Sequences[target.Id] = target;
_sessions[sessionKey!] = target;
}
var frame = target.AddFrame(bytes, Path.GetFileName(path), capturedAt);
return new CompleteUploadResponse(frame.Id, target.Id, target.Frames.Count - 1);
}
}
public async Task DownloadFrameAsync(Guid frameId, string kind, Stream destination, CancellationToken cancellationToken)
{
byte[] bytes;
lock (_gate)
{
var (sequence, frame) = Sequences.Values.SelectMany(s => s.Frames.Select(f => (s, f))).FirstOrDefault(p => p.f.Id == frameId);
if (frame is null) throw NotFound();
bytes = kind switch
{
"original" when CorruptOnce == frameId => [.. frame.Bytes.Select(b => (byte)~b)],
"original" => frame.Bytes,
"proxy" or "thumb" when FailAssets => throw new TitanoApiException(HttpStatusCode.InternalServerError, new ApiError("internal", "failed")),
"proxy" when (sequence.Status & SequenceStatus.ProxiesBuilt) != 0 => frame.Proxy,
"thumb" when (sequence.Status & SequenceStatus.ThumbsBuilt) != 0 => frame.Proxy[..Math.Min(frame.Proxy.Length, 64)],
_ => throw NotFound(),
};
if (kind == "original" && CorruptOnce == frameId) CorruptOnce = null;
}
// Range: continue after what the destination already holds, like the real endpoint.
var offset = destination.CanSeek ? (int)Math.Min(destination.Length, bytes.Length) : 0;
if (destination.CanSeek) destination.Seek(0, SeekOrigin.End);
await destination.WriteAsync(bytes.AsMemory(offset), cancellationToken);
}
public async Task<string?> DownloadRenderAsync(Guid renderId, Stream destination, CancellationToken cancellationToken)
{
FakeRender render;
lock (_gate) render = Sequences.Values.SelectMany(s => s.Renders).FirstOrDefault(r => r.Id == renderId) ?? throw NotFound();
var offset = destination.CanSeek ? (int)Math.Min(destination.Length, render.Bytes.Length) : 0;
if (destination.CanSeek) destination.Seek(0, SeekOrigin.End);
await destination.WriteAsync(render.Bytes.AsMemory(offset), cancellationToken);
return render.FileName;
}
/// <summary>Like the server: the SHA-256 is checked and a render keeps its id; one it already has is not sent again.</summary>
public async Task<RenderDto?> UploadRenderAsync(Guid sequenceId, string path, RenderUploadRequest request, CancellationToken cancellationToken)
{
var bytes = await File.ReadAllBytesAsync(path, cancellationToken);
if (Convert.ToHexStringLower(SHA256.HashData(bytes)) != request.Sha256 || bytes.Length != request.Size)
throw new TitanoApiException(HttpStatusCode.UnprocessableEntity, new ApiError("hash_mismatch", "hash"));
lock (_gate)
{
var sequence = Find(sequenceId);
if (sequence.Renders.Any(r => r.Id == request.RenderId)) return null;
var render = new FakeRender(request.RenderId, request.FileName, request.PresetName, bytes);
sequence.Renders.Add(render);
return render.Dto();
}
}
public async IAsyncEnumerable<ServerEvent> EventsAsync([EnumeratorCancellation] CancellationToken cancellationToken)
{
while (await _events.Reader.WaitToReadAsync(cancellationToken))
{
while (_events.Reader.TryRead(out var e)) yield return e;
}
}
public void Dispose()
{
}
private FakeSequence Find(Guid id) => Sequences.TryGetValue(id, out var s) ? s : throw NotFound();
private static TitanoApiException NotFound() => new(HttpStatusCode.NotFound, new ApiError("not_found", "sequence"));
}
internal sealed class FakeSequence
{
public required Guid Id { get; init; }
public string? Title { get; set; }
public List<string> Tags { get; set; } = [];
public int Rating { get; set; }
public string? Notes { get; set; }
public string? SettingsJson { get; set; }
public int SettingsVersion { get; set; } = 1;
public int FramesVersion { get; set; }
public SequenceStatus Status { get; set; }
public DateTimeOffset UpdatedAt { get; set; } = DateTimeOffset.UtcNow;
public DateTime? FirstCapture { get; set; }
public string? CameraModel { get; set; } = "Canon EOS R5";
public List<FakeFrame> Frames { get; } = [];
public List<FakeRender> Renders { get; } = [];
public FakeFrame AddFrame(byte[] bytes, string? name = null, DateTime? capturedAt = null)
{
var frame = new FakeFrame(Guid.CreateVersion7(), name ?? $"IMG_{Frames.Count + 1:0000}.JPG", bytes, capturedAt);
Frames.Add(frame);
FramesVersion++;
UpdatedAt = DateTimeOffset.UtcNow;
return frame;
}
public SequenceDto Dto() => new(Id, Title, Title ?? "Untitled", "2026/" + Id.ToString("N"), "Canon", CameraModel, null, FirstCapture, null, Frames.Count, 10,
Frames.Sum(f => (long)f.Bytes.Length), (long)Status, Renders.Count, null, Tags, Rating, Notes, SettingsVersion, FramesVersion, 0, null, UpdatedAt);
public SequenceManifest Manifest() => new(Id, FramesVersion, SettingsVersion, SettingsJson, Tags,
[.. Frames.Select((f, i) => new ManifestFrame(f.Id, i, f.FileName, f.Bytes.Length, f.Sha256, (Status & SequenceStatus.ProxiesBuilt) != 0,
(Status & SequenceStatus.ThumbsBuilt) != 0))], [.. Renders.Select(r => r.Dto())]);
}
internal sealed record FakeRender(Guid Id, string FileName, string PresetName, byte[] Bytes)
{
public RenderDto Dto() => new(Id, PresetName, "hevc", 3840, 2160, 30, 12, Bytes.Length, new DateTimeOffset(2026, 9, 20, 21, 0, 0, TimeSpan.Zero), "Studio NAS");
}
internal sealed record FakeFrame(Guid Id, string FileName, byte[] Bytes, DateTime? CapturedAt)
{
public string Sha256 { get; } = Convert.ToHexStringLower(SHA256.HashData(Bytes));
/// <summary>The original stands in for its proxy: a real JPEG the decoders read.</summary>
public byte[] Proxy => Bytes;
public FrameDto Dto(Guid sequenceId, int index) =>
new(Id, sequenceId, index, FileName, Bytes.Length, Sha256, CapturedAt, null, 1.0 / 250, 8, 100, 24, 1, 48, 32, "jpeg", 0);
}
@@ -0,0 +1,152 @@
using Titano.Core.Model;
using Titano.Data.Sync;
using Titano.Protocol;
using Titano.Testing;
namespace Titano.Data.Tests.Sync;
/// <summary>The background agent: event-driven comparisons, retries with backoff, proxies kept offline.</summary>
[Category("sync")]
public sealed class SyncAgentTests(TestContext context)
{
/// <summary>Full comparisons only at start, so anything later comes from events or explicit requests.</summary>
private static readonly SyncAgentOptions EventsOnly = new()
{
RefreshInterval = TimeSpan.FromHours(1),
EventDelay = TimeSpan.FromMilliseconds(20),
MinBackoff = TimeSpan.FromMilliseconds(20),
MaxBackoff = TimeSpan.FromMilliseconds(200),
};
[Test]
public async Task ServerEventsBringChangesWithoutAFullComparison()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Harbour", photos);
var remote = f.Remote.Add("Harbour", photos);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await using var agent = new SyncAgent(f.Sync, f.Remote, () => new SyncPolicy(), null, EventsOnly);
agent.Start();
await WaitAsync(() => agent.Snapshot is not null, "first comparison");
var first = agent.Snapshot!;
f.Remote.EditSettings(remote.Id, SyncFixture.Window33);
f.Remote.Publish(new SequenceChangedEvent(remote.Id, "settings", remote.FramesVersion, remote.SettingsVersion));
await WaitAsync(async () => SyncRules.SameSettings(SyncFixture.Window33, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson),
"the server's edit reached this PC");
var created = f.Remote.Add("New on the server", f.NewPhotos(1));
f.Remote.Publish(new SequenceChangedEvent(created.Id, "created", 1, 1));
await WaitAsync(async () => (await f.Sync.ListAsync(f.Server, f.Ct)).Any(e => e.Title == "New on the server"), "a sequence created on the server");
Assert.Same(first, agent.Snapshot);
}
[Test]
public async Task FailedComparisonsAreRetriedWithBackoff()
{
await using var f = await SyncFixture.CreateAsync(context);
f.Remote.Add("Harbour", f.NewPhotos(1));
f.Remote.FailingListings = 3;
var changes = 0;
await using var agent = new SyncAgent(f.Sync, f.Remote, () => new SyncPolicy(), null, EventsOnly);
agent.Changed += () => Interlocked.Increment(ref changes);
agent.Start();
await WaitAsync(() => agent.Snapshot is not null, "a comparison after the failures");
Assert.Null(agent.LastError);
Assert.Equal(0, f.Remote.FailingListings);
Assert.GreaterOrEqual(changes, 4);
Assert.Equal(1, agent.Snapshot!.ServerSequences);
}
[Test]
public async Task ATimedOutComparisonIsRecordedAndLiveUpdatesGoOn()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(1);
var local = await f.LocalAsync("Harbour", photos);
var remote = f.Remote.Add("Harbour", photos);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await using var agent = new SyncAgent(f.Sync, f.Remote, () => new SyncPolicy(), null, EventsOnly);
agent.Start();
await WaitAsync(() => agent.Snapshot is not null, "first comparison");
f.Remote.TimeoutOnce = remote.Id;
f.Remote.Publish(new SequenceChangedEvent(remote.Id, "settings", remote.FramesVersion, remote.SettingsVersion));
await WaitAsync(async () => (await f.EntryAsync("Harbour")).Link!.Error is not null, "the timeout recorded on the sequence");
f.Remote.EditSettings(remote.Id, SyncFixture.Window33);
f.Remote.Publish(new SequenceChangedEvent(remote.Id, "settings", remote.FramesVersion, remote.SettingsVersion));
await WaitAsync(async () => SyncRules.SameSettings(SyncFixture.Window33, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson),
"a later event still reaches this PC");
Assert.Null((await f.EntryAsync("Harbour")).Link!.Error);
}
[Test]
public async Task KeepingProxiesOfflineRefreshesTheCachesThisPcOpened()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Harbour", photos);
await f.Sync.LinkAsync(f.Server, f.Remote.Add("Harbour", photos).Id, local.Id, f.Ct);
var opened = f.Remote.Add("Construction cam", f.NewPhotos(2));
var never = f.Remote.Add("Never opened", f.NewPhotos(1));
var engine = await f.StartEngineAsync();
await f.RefreshAsync();
var first = await f.Sync.EnqueueDownloadAsync(engine, f.Server, opened.Id, "Construction cam", SyncDownloadMode.Proxies, null);
await f.Archive.WaitForAsync(first.Id, JobState.Done);
opened.AddFrame(f.NewPhotos(1)[0]);
var keep = false;
await using var agent = new SyncAgent(f.Sync, f.Remote, () => new SyncPolicy(KeepProxiesOffline: keep), engine, EventsOnly);
agent.Start();
await WaitAsync(() => agent.Snapshot is not null, "first comparison");
Assert.True((await f.EntryAsync("Construction cam")).Link!.ProxiesStale);
keep = true;
await agent.RefreshAsync(f.Ct);
await WaitAsync(() => f.Sync.OpenRemote(f.Server, opened.Id) is { CachedCount: 3 }, "the stale cache brought up to date");
Assert.Null(f.Sync.OpenRemote(f.Server, never.Id));
var entries = await f.Sync.ListAsync(f.Server, f.Ct);
Assert.Equal(SyncStatus.ProxiesOnly, entries.Single(e => e.Title == "Construction cam").Status);
Assert.Equal(SyncStatus.RemoteOnly, entries.Single(e => e.Title == "Never opened").Status);
Assert.Equal(SyncStatus.InSync, entries.Single(e => e.Title == "Harbour").Status);
}
[Test]
public async Task AFailedProxyRefreshWaitsForItsBackoff()
{
await using var f = await SyncFixture.CreateAsync(context);
var opened = f.Remote.Add("Construction cam", f.NewPhotos(2));
var engine = await f.StartEngineAsync();
await f.RefreshAsync();
await f.Archive.WaitForAsync((await f.Sync.EnqueueDownloadAsync(engine, f.Server, opened.Id, "Construction cam", SyncDownloadMode.Proxies, null)).Id,
JobState.Done);
opened.AddFrame(f.NewPhotos(1)[0]);
f.Remote.FailAssets = true;
await using var agent = new SyncAgent(f.Sync, f.Remote, () => new SyncPolicy(KeepProxiesOffline: true), engine,
EventsOnly with { MinBackoff = TimeSpan.FromHours(1), MaxBackoff = TimeSpan.FromHours(2) });
agent.Start();
await WaitAsync(async () => (await DownloadsAsync(f)).Any(j => j.State == JobState.Failed), "the background refresh failing");
await agent.RefreshAsync(f.Ct);
await agent.RefreshAsync(f.Ct);
Assert.Equal(2, (await DownloadsAsync(f)).Count);
}
private static async Task<IReadOnlyList<Job>> DownloadsAsync(SyncFixture f) =>
(await f.Db.Jobs.ListAsync(null, JobKind.Download, 100, null, f.Ct)).Items;
private async Task WaitAsync(Func<bool> condition, string what) => await WaitAsync(() => Task.FromResult(condition()), what);
private async Task WaitAsync(Func<Task<bool>> condition, string what)
{
var until = DateTime.UtcNow.AddSeconds(30);
while (!await condition())
{
if (DateTime.UtcNow > until) Assert.Fail("Timed out waiting for " + what);
await Task.Delay(20, context.Cancellation);
}
}
}
+108
View File
@@ -0,0 +1,108 @@
using Titano.Core.Model;
using Titano.Data.Archiving;
using Titano.Data.Jobs;
using Titano.Data.Sync;
using Titano.Data.Tests.Archiving;
using Titano.Testing;
namespace Titano.Data.Tests.Sync;
/// <summary>A local archive and index, the sync engine over them and an in-memory server.</summary>
internal sealed class SyncFixture : IAsyncDisposable
{
public const string Window41 = """{"exposure":{"deflickerWindow":{"isAuto":false,"manual":41}}}""";
public const string Window33 = """{"exposure":{"deflickerWindow":{"isAuto":false,"manual":33}}}""";
private readonly List<IAsyncDisposable> _owned = [];
private int _seed;
private SyncFixture(ArchiveFixture archive, SyncService sync)
{
Archive = archive;
Sync = sync;
_owned.Add(archive);
}
public ArchiveFixture Archive { get; }
public SyncService Sync { get; }
public FakeSyncRemote Remote { get; } = new();
public TitanoDatabase Db => Archive.Db;
public string Server => Remote.Server;
public CancellationToken Ct => Archive.Ct;
public static async Task<SyncFixture> CreateAsync(TestContext context)
{
var archive = await ArchiveFixture.CreateAsync(context);
var sync = new SyncService(archive.Db, archive.Service, new SyncOptions
{
Archive = new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) },
ProxyCacheDirectory = context.CreateTempDirectory("proxies"),
});
return new SyncFixture(archive, sync);
}
public Task<SyncSnapshot> RefreshAsync(SyncPolicy? policy = null) => Sync.RefreshAsync(Remote, policy ?? new SyncPolicy(), Ct);
public async Task<SyncEntry> EntryAsync(string title) =>
(await Sync.ListAsync(Server, Ct)).Single(e => e.Title == title);
/// <summary>Distinct photos (the same bytes on both sides make the same original).</summary>
public List<byte[]> NewPhotos(int count)
{
var photos = new List<byte[]>(count);
for (var i = 0; i < count; i++, _seed++) photos.Add(Photos.Jpeg(ArchiveFixture.Start.AddSeconds(10 * _seed), 1000 + _seed));
return photos;
}
/// <summary>A local sequence made through the archive ingest (hashed frames, a real sidecar).</summary>
public async Task<Sequence> LocalAsync(string title, IReadOnlyList<byte[]> originals, string? settingsJson = null)
{
Guid? id = null;
var staging = Path.Combine(Archive.Paths.StagingDirectory, "test");
Directory.CreateDirectory(staging);
for (var i = 0; i < originals.Count; i++)
{
var path = Path.Combine(staging, $"{Guid.NewGuid():N}.part");
await File.WriteAllBytesAsync(path, originals[i], Ct);
var sha = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(originals[i]));
var result = await Archive.Service.Ingest.CommitAsync(new IngestRequest(Archive.Archive.Id, id, id is null ? title : null, null, path,
$"IMG_{i + 1:0000}.JPG", originals[i].Length, sha, ArchiveFixture.Start.AddSeconds(10 * i), null), Ct);
id = result.SequenceId;
}
var sequence = (await Db.Sequences.GetAsync(id!.Value, Ct))!;
if (settingsJson is not null) sequence = await EditLocalSettingsAsync(sequence.Id, settingsJson);
return sequence;
}
/// <summary>An edit on this PC, as the editor makes it (project file and index, settings version + 1).</summary>
public async Task<Sequence> EditLocalSettingsAsync(Guid id, string settingsJson)
{
var sequence = (await Db.Sequences.GetAsync(id, Ct))!;
var folder = Archive.Paths.Sequence(sequence.Folder);
await File.WriteAllTextAsync(folder.ProjectPath, settingsJson, Ct);
var result = await Db.Sequences.EditAsync(id, new Titano.Data.Repositories.SequenceEdit { SettingsJson = settingsJson }, sequence.SettingsVersion, Ct);
return result.Sequence!;
}
/// <summary>A started engine with the archive and sync handlers; jobs reach the server through <paramref name="connector"/> (the fake by default).</summary>
public async Task<JobEngine> StartEngineAsync(ISyncConnector? connector = null)
{
var engine = new JobEngine(Db, [.. Archive.Service.CreateJobHandlers(), .. Sync.CreateJobHandlers(connector ?? new Connector(Remote))],
new JobEngineOptions { Workers = 2, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
_owned.Insert(0, engine);
await engine.StartAsync(Ct);
return engine;
}
public async ValueTask DisposeAsync()
{
foreach (var owned in _owned) await owned.DisposeAsync();
}
/// <summary>Hands out <paramref name="remote"/> for its own server; null for any other, or always when <paramref name="remote"/> is null.</summary>
public sealed class Connector(ISyncRemote? remote) : ISyncConnector
{
public ValueTask<ISyncRemote?> ConnectAsync(string server, CancellationToken cancellationToken) =>
ValueTask.FromResult(remote is not null && remote.Server == server ? remote : null);
}
}
@@ -0,0 +1,95 @@
using Titano.Core.Model;
using Titano.Data.Sync;
using Titano.Testing;
namespace Titano.Data.Tests.Sync;
public sealed class SyncRulesTests
{
private static readonly Sequence Local = new() { Id = Guid.CreateVersion7(), ArchiveId = Guid.CreateVersion7(), Folder = "2026/a", SettingsVersion = 4 };
private static readonly SyncLink Agreed = new()
{
Server = "https://nas",
RemoteId = Guid.CreateVersion7(),
Title = "Harbour",
RemoteSettingsVersion = 7,
BaseLocalSettings = 4,
BaseRemoteSettings = 7,
};
[Test]
public void StateFollowsLinksOriginalsAndSettingsVersions()
{
Assert.Equal(SyncStatus.LocalOnly, SyncRules.Status(Local, null));
Assert.Equal(SyncStatus.RemoteOnly, SyncRules.Status(null, Agreed));
Assert.Equal(SyncStatus.ProxiesOnly, SyncRules.Status(null, Agreed with { ProxiesCached = 3 }));
Assert.Equal(SyncStatus.InSync, SyncRules.Status(Local, Agreed));
Assert.Equal(SyncStatus.LocalAhead, SyncRules.Status(Local, Agreed with { MissingRemote = 2 }));
Assert.Equal(SyncStatus.LocalAhead, SyncRules.Status(Local with { SettingsVersion = 5 }, Agreed));
Assert.Equal(SyncStatus.ServerAhead, SyncRules.Status(Local, Agreed with { MissingLocal = 1 }));
Assert.Equal(SyncStatus.ServerAhead, SyncRules.Status(Local, Agreed with { RemoteSettingsVersion = 8 }));
// Originals never conflict: what this PC lacks is downloaded after what the server lacks is uploaded.
Assert.Equal(SyncStatus.LocalAhead, SyncRules.Status(Local, Agreed with { MissingRemote = 1, MissingLocal = 1 }));
Assert.Equal(SyncStatus.Conflict, SyncRules.Status(Local with { SettingsVersion = 5 }, Agreed with { RemoteSettingsVersion = 8 }));
// A link nothing was agreed on yet: both sides count as changed until the content is compared.
Assert.Equal(SyncStatus.Conflict, SyncRules.Status(Local, Agreed with { BaseLocalSettings = null, BaseRemoteSettings = null }));
}
[Test]
public void TheLibraryStoresOnlyStatesOfLocalCopies()
{
Assert.Equal(SyncState.InSync, SyncRules.ToSequenceState(SyncStatus.InSync));
Assert.Equal(SyncState.Conflict, SyncRules.ToSequenceState(SyncStatus.Conflict));
Assert.Equal(SyncState.LocalAhead, SyncRules.ToSequenceState(SyncStatus.LocalAhead));
Assert.Equal(SyncState.ServerAhead, SyncRules.ToSequenceState(SyncStatus.ServerAhead));
Assert.Equal(SyncState.LocalOnly, SyncRules.ToSequenceState(SyncStatus.LocalOnly));
Assert.Null(SyncRules.ToSequenceState(SyncStatus.Transferring));
Assert.Null(SyncRules.ToSequenceState(SyncStatus.RemoteOnly));
}
[Test]
public void OriginalsAreComparedByContent()
{
Assert.Equal((0, 0), SyncRules.CompareOriginals(["AA", "bb"], ["aa", "BB"]));
Assert.Equal((1, 0), SyncRules.CompareOriginals(["aa", "bb", "cc"], ["aa", "bb"]));
Assert.Equal((0, 2), SyncRules.CompareOriginals(["aa"], ["aa", "bb", "cc"]));
Assert.Equal((1, 1), SyncRules.CompareOriginals(["aa", "dd"], ["aa", "ee"]));
// Frames not hashed yet (adopted, not verified) stand for server frames no hash matched.
Assert.Equal((0, 0), SyncRules.CompareOriginals(["aa", null, null], ["aa", "bb", "cc"]));
Assert.Equal((0, 1), SyncRules.CompareOriginals([null], ["bb", "cc"]));
Assert.Equal((1, 0), SyncRules.CompareOriginals([null, null], ["bb"]));
}
[Test]
public void SettingsAreComparedAsProjectsNotAsText()
{
Assert.True(SyncRules.SameSettings(null, "{}"), "no settings is the default project");
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, "{ \"exposure\": { \"deflickerWindow\": { \"manual\": 41, \"isAuto\": false } } }"));
Assert.False(SyncRules.SameSettings(SyncFixture.Window41, SyncFixture.Window33));
var difference = Assert.Contains(SyncRules.Differences(SyncFixture.Window41, SyncFixture.Window33), d => d.Path.StartsWith("exposure.deflickerWindow", StringComparison.Ordinal));
Assert.Equal("exposure.deflickerWindow.manual", difference.Path);
Assert.Equal("41", difference.Mine);
Assert.Equal("33", difference.Theirs);
Assert.Count(1, SyncRules.Differences("""{"exposure":{"exposureOffsetEv":1},"stack":{"length":3}}""", "{}", max: 1));
Assert.Empty(SyncRules.Differences(SyncFixture.Window33, SyncFixture.Window33));
}
[Test]
public void PayloadDifferencesListTheSequenceFieldsBeforeTheSettings()
{
var mine = new SyncPayload("Harbour", ["sunset", "Harbour"], 3, "mine", SyncFixture.Window41);
var theirs = new SyncPayload("Harbour at dusk", ["harbour", "SUNSET"], 3, " mine ", SyncFixture.Window33);
var differences = SyncRules.Differences(mine, theirs, 10);
Assert.SequenceEqual(["sequence.title", "exposure.deflickerWindow.manual"], differences.Select(d => d.Path));
Assert.Equal(("Harbour", "Harbour at dusk"), (differences[0].Mine, differences[0].Theirs));
Assert.Count(1, SyncRules.Differences(mine, theirs, 1));
Assert.True(mine.SameMetadata(mine with { Tags = ["HARBOUR", "sunset"], Notes = "mine " }), "tags ignore case and order, blanks are trimmed");
Assert.Empty(SyncRules.Differences(mine, mine with { Tags = ["harbour", "SUNSET"] }));
}
}
@@ -0,0 +1,477 @@
using Titano.Core.Model;
using Titano.Data.Sync;
using Titano.Protocol;
using Titano.Protocol.Client;
using Titano.Testing;
namespace Titano.Data.Tests.Sync;
/// <summary>Comparison, settings exchange and conflict resolution against an in-memory server.</summary>
[Category("sync")]
public sealed class SyncServiceTests(TestContext context)
{
[Test]
public async Task TheTableListsLocalAndServerSequences()
{
await using var f = await SyncFixture.CreateAsync(context);
await f.LocalAsync("Comet", f.NewPhotos(2));
f.Remote.Add("Construction cam", f.NewPhotos(3));
var snapshot = await f.RefreshAsync();
Assert.Equal(2, snapshot.Entries.Count);
Assert.Equal(1, snapshot.ServerSequences);
Assert.Equal(SyncStatus.LocalOnly, (await f.EntryAsync("Comet")).Status);
var remote = await f.EntryAsync("Construction cam");
Assert.Equal(SyncStatus.RemoteOnly, remote.Status);
Assert.Null(remote.Local);
Assert.Equal(3, remote.Link!.FrameCount);
}
[Test]
public async Task LinkedCopiesWithTheSameOriginalsAreInSyncAndTheLibraryKnows()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Harbour", photos);
var remote = f.Remote.Add("Harbour", photos);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status);
Assert.Equal(SyncState.InSync, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SyncState);
// Nothing moved: the manifest is not fetched again.
var manifests = f.Remote.ManifestCalls;
await f.RefreshAsync();
Assert.Equal(manifests, f.Remote.ManifestCalls);
}
[Test]
public async Task OriginalsMissingOnEitherSideAreCountedFromTheManifest()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(4);
var local = await f.LocalAsync("Harbour", photos[..3]);
var remote = f.Remote.Add("Harbour", photos[..2]);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
var ahead = await f.EntryAsync("Harbour");
Assert.Equal(SyncStatus.LocalAhead, ahead.Status);
Assert.Equal(1, ahead.Link!.MissingRemote);
Assert.Equal(SyncState.LocalAhead, ahead.Local!.SyncState);
remote.AddFrame(photos[2]);
remote.AddFrame(photos[3]);
await f.RefreshAsync();
var behind = await f.EntryAsync("Harbour");
Assert.Equal(SyncStatus.ServerAhead, behind.Status);
Assert.Equal((0, 1), (behind.Link!.MissingRemote, behind.Link.MissingLocal));
}
[Test]
public async Task SettingsChangedOnOneSideAreSentOrTaken()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Harbour", photos);
var remote = f.Remote.Add("Harbour", photos);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
await f.EditLocalSettingsAsync(local.Id, SyncFixture.Window41);
await f.RefreshAsync();
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, remote.SettingsJson), "this PC's edit reached the server");
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status);
f.Remote.EditSettings(remote.Id, SyncFixture.Window33);
await f.RefreshAsync();
var taken = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!;
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, taken.SettingsJson), "the server's edit reached this PC");
var project = await File.ReadAllTextAsync(f.Archive.Paths.Sequence(taken.Folder).ProjectPath, f.Ct);
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, project), "project.json follows the index");
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status);
}
[Test]
public async Task WithoutAutomaticSyncAnEditWaitsForTheUser()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(1);
var local = await f.LocalAsync("Harbour", photos);
var remote = f.Remote.Add("Harbour", photos);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
await f.EditLocalSettingsAsync(local.Id, SyncFixture.Window41);
await f.RefreshAsync(new SyncPolicy(AutoSyncSettings: false));
Assert.Equal(SyncStatus.LocalAhead, (await f.EntryAsync("Harbour")).Status);
Assert.Null(remote.SettingsJson);
await f.Sync.SyncSettingsAsync(f.Remote, remote.Id, new SyncPolicy(AutoSyncSettings: false), f.Ct);
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, remote.SettingsJson));
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status);
}
[Test]
public async Task TagsChangedDifferentlyOnBothSidesAreAConflictToo()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(1);
var local = await f.LocalAsync("Harbour", photos);
var remote = f.Remote.Add("Harbour", photos);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
await f.Remote.UpdateSequenceAsync(remote.Id, new UpdateSequenceRequest(null, ["boats"], null, null, null, null), f.Ct);
await f.Archive.Service.SetSequenceInfoAsync(local.Id, "Harbour", ["sunset"], 0, null, f.Ct);
await f.RefreshAsync();
// No side wins silently: a tag removed on one side must not come back, and an edit must not be lost.
var entry = await f.EntryAsync("Harbour");
Assert.Equal(SyncStatus.Conflict, entry.Status);
Assert.SequenceEqual(["boats"], entry.Link!.ConflictRemote!.Tags);
Assert.Equal("sequence.tags", SyncRules.Differences(SyncPayload.Of(entry.Local!), entry.Link.ConflictRemote)[0].Path);
Assert.SequenceEqual(["boats"], remote.Tags);
Assert.SequenceEqual(["sunset"], (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.Tags);
}
[Test]
public async Task TheSameEditOnBothSidesIsAgreedWithoutAConflict()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(1);
var local = await f.LocalAsync("Harbour", photos);
var remote = f.Remote.Add("Harbour", photos);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
await f.Remote.UpdateSequenceAsync(remote.Id, new UpdateSequenceRequest(null, ["sunset"], null, null, SyncFixture.Window41, null), f.Ct);
await f.Archive.Service.SetSequenceInfoAsync(local.Id, "Harbour", ["SUNSET"], 0, null, f.Ct);
await f.EditLocalSettingsAsync(local.Id, SyncFixture.Window41);
await f.RefreshAsync();
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status);
}
[Test]
public async Task SettingsChangedOnBothSidesAreAConflictUntilTheUserPicks()
{
await using var f = await SyncFixture.CreateAsync(context);
var (local, remote) = await ConflictAsync(f);
var entry = await f.EntryAsync("Holy grail");
Assert.Equal(SyncStatus.Conflict, entry.Status);
Assert.Equal(SyncState.Conflict, entry.Local!.SyncState);
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, entry.Link!.ConflictRemote!.SettingsJson), "the server's side is kept for display");
Assert.Equal("exposure.deflickerWindow.manual", SyncRules.Differences(entry.Local.SettingsJson, entry.Link.ConflictRemote.SettingsJson)[0].Path);
// Neither side is overwritten while the conflict stands, and the comparison does not fetch it again.
var manifests = f.Remote.ManifestCalls;
await f.RefreshAsync();
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, remote.SettingsJson));
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson));
Assert.Equal(manifests, f.Remote.ManifestCalls);
}
[Test]
public async Task KeepMineSendsThisPcsSettings()
{
await using var f = await SyncFixture.CreateAsync(context);
var (local, remote) = await ConflictAsync(f);
await f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.KeepMine, f.Ct);
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, remote.SettingsJson));
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson));
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Holy grail")).Status);
await f.RefreshAsync();
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Holy grail")).Status);
}
[Test]
public async Task TakeServerReplacesThisPcsSettings()
{
await using var f = await SyncFixture.CreateAsync(context);
var (local, remote) = await ConflictAsync(f);
await f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.TakeServer, f.Ct);
var taken = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!;
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, taken.SettingsJson));
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, await File.ReadAllTextAsync(f.Archive.Paths.Sequence(taken.Folder).ProjectPath, f.Ct)));
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, remote.SettingsJson));
Assert.Empty(Directory.GetFiles(f.Archive.Paths.Sequence(taken.Folder).MetaDirectory, "project.this-pc-*.json"));
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Holy grail")).Status);
}
[Test]
public async Task SaveBothKeepsThisPcsSettingsNextToTheServers()
{
await using var f = await SyncFixture.CreateAsync(context);
var (local, remote) = await ConflictAsync(f);
var copy = await f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.SaveBoth, f.Ct);
var taken = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!;
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, taken.SettingsJson));
Assert.Equal(copy, Assert.Contains(Directory.GetFiles(f.Archive.Paths.Sequence(taken.Folder).MetaDirectory, "project.this-pc-*.json"), _ => true));
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, await File.ReadAllTextAsync(copy!, f.Ct)), "this PC's version is kept");
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Holy grail")).Status);
}
[Test]
public async Task KeepMineRefusesWhenTheServerChangedAfterTheConflictWasShown()
{
await using var f = await SyncFixture.CreateAsync(context);
var (_, remote) = await ConflictAsync(f);
var later = SyncFixture.Window33.Replace("33", "35", StringComparison.Ordinal);
f.Remote.EditSettings(remote.Id, later);
await Assert.ThrowsAsync<SyncConflictChangedException>(() => f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.KeepMine, f.Ct));
Assert.True(SyncRules.SameSettings(later, remote.SettingsJson), "the edit the user never saw is not overwritten");
var entry = await f.EntryAsync("Holy grail");
Assert.Equal(SyncStatus.Conflict, entry.Status);
Assert.True(SyncRules.SameSettings(later, entry.Link!.ConflictRemote!.SettingsJson), "the conflict now shows the server's latest edit");
await f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.KeepMine, f.Ct);
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, remote.SettingsJson));
}
[Test]
public async Task KeepMineRefusesWhenTheServerChangesWhileItIsSent()
{
await using var f = await SyncFixture.CreateAsync(context);
var (_, remote) = await ConflictAsync(f);
var later = SyncFixture.Window33.Replace("33", "35", StringComparison.Ordinal);
var racing = new RacingRemote(f.Remote, () => f.Remote.EditSettings(remote.Id, later), beforeUpdate: true);
await Assert.ThrowsAsync<SyncConflictChangedException>(() => f.Sync.ResolveAsync(racing, remote.Id, SyncResolution.KeepMine, f.Ct));
Assert.True(SyncRules.SameSettings(later, remote.SettingsJson), "nothing overwritten");
}
[Test]
public async Task TakeServerRefusesWhenThisPcChangedAfterTheConflictWasShown()
{
await using var f = await SyncFixture.CreateAsync(context);
var (local, remote) = await ConflictAsync(f);
var later = SyncFixture.Window41.Replace("41", "45", StringComparison.Ordinal);
await f.EditLocalSettingsAsync(local.Id, later);
await Assert.ThrowsAsync<SyncConflictChangedException>(() => f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.TakeServer, f.Ct));
Assert.True(SyncRules.SameSettings(later, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson), "this PC's later edit is kept");
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, remote.SettingsJson));
var entry = await f.EntryAsync("Holy grail");
Assert.Equal(SyncStatus.Conflict, entry.Status);
Assert.Equal(entry.Local!.SettingsVersion, entry.Link!.ConflictLocalSettings);
}
[Test]
public async Task TakeServerRefusesWhenTheServerChangedAfterTheConflictWasShown()
{
await using var f = await SyncFixture.CreateAsync(context);
var (local, remote) = await ConflictAsync(f);
f.Remote.EditSettings(remote.Id, SyncFixture.Window33.Replace("33", "35", StringComparison.Ordinal));
await Assert.ThrowsAsync<SyncConflictChangedException>(() => f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.SaveBoth, f.Ct));
var kept = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!;
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, kept.SettingsJson), "nothing taken that the user did not see");
Assert.Empty(Directory.GetFiles(f.Archive.Paths.Sequence(kept.Folder).MetaDirectory, "project.this-pc-*.json"));
}
[Test]
public async Task SequencesDeletedOnTheServerAreForgotten()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(1);
var local = await f.LocalAsync("Harbour", photos);
var remote = f.Remote.Add("Harbour", photos);
f.Remote.Add("Gone", f.NewPhotos(1));
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
f.Remote.Sequences.Clear();
var snapshot = await f.RefreshAsync();
Assert.Equal(0, snapshot.ServerSequences);
Assert.Equal(SyncStatus.LocalOnly, (await f.EntryAsync("Harbour")).Status);
Assert.Equal(SyncState.LocalOnly, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SyncState);
}
[Test]
public async Task ALinkIsForgottenOnlyWhenTheServerSaysTheSequenceIsGone()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Harbour", photos);
var remote = f.Remote.Add("Harbour", photos);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
// A listing whose pages moved while they were read misses the sequence: it is asked for by id instead.
f.Remote.Unlisted.Add(remote.Id);
await f.RefreshAsync();
var kept = await f.EntryAsync("Harbour");
Assert.Equal(SyncStatus.InSync, kept.Status);
Assert.Equal(remote.Id, kept.Link!.RemoteId);
f.Remote.Sequences.Remove(remote.Id);
await f.RefreshAsync();
Assert.Equal(SyncStatus.LocalOnly, (await f.EntryAsync("Harbour")).Status);
}
[Test]
public async Task AServerRefusalOnOneSequenceIsRecordedAndTheOthersAreStillCompared()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(4);
var harbour = await f.LocalAsync("Harbour", photos[..2]);
var aurora = await f.LocalAsync("Aurora", photos[2..]);
var refused = f.Remote.Add("Harbour", photos[..2]);
var fine = f.Remote.Add("Aurora", photos[2..]);
await f.Sync.LinkAsync(f.Server, refused.Id, harbour.Id, f.Ct);
await f.Sync.LinkAsync(f.Server, fine.Id, aurora.Id, f.Ct);
f.Remote.Refused.Add(refused.Id);
await f.RefreshAsync();
Assert.NotNull((await f.EntryAsync("Harbour")).Link!.Error);
var compared = await f.EntryAsync("Aurora");
Assert.Equal(SyncStatus.InSync, compared.Status);
Assert.Null(compared.Link!.Error);
f.Remote.Refused.Clear();
await f.RefreshAsync();
var recovered = await f.EntryAsync("Harbour");
Assert.Null(recovered.Link!.Error);
Assert.Equal(SyncStatus.InSync, recovered.Status);
}
[Test]
public async Task WithoutTheEditRightThisPcsEditsWaitInsteadOfFailing()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(1);
var local = await f.LocalAsync("Harbour", photos);
var remote = f.Remote.Add("Harbour", photos);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
await f.EditLocalSettingsAsync(local.Id, SyncFixture.Window41);
await f.RefreshAsync(new SyncPolicy(CanEdit: false));
Assert.Null(remote.SettingsJson);
var entry = await f.EntryAsync("Harbour");
Assert.Equal(SyncStatus.LocalAhead, entry.Status);
Assert.Null(entry.Link!.Error);
}
[Test]
public async Task CopiesHoldingTheSameOriginalsAreLinkedByContent()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Comet", photos);
// The Uploader sent the same card to the server; nothing links the two yet.
var remote = f.Remote.Add("2026-09-28 Canon", photos);
remote.FirstCapture = local.FirstCapture;
remote.CameraModel = local.CameraModel;
var other = f.Remote.Add("Other card", f.NewPhotos(2));
other.FirstCapture = local.FirstCapture;
other.CameraModel = local.CameraModel;
await f.RefreshAsync();
var entry = await f.EntryAsync("Comet");
Assert.Equal(remote.Id, entry.Link?.RemoteId);
Assert.Equal((0, 0), (entry.Link!.MissingRemote, entry.Link.MissingLocal));
Assert.Null((await f.EntryAsync("Other card")).Local);
var manifests = f.Remote.ManifestCalls;
await f.RefreshAsync();
Assert.Equal(manifests, f.Remote.ManifestCalls);
}
[Test]
public async Task ABackgroundProxyDownloadGivesWayToTheUsersRequest()
{
await using var f = await SyncFixture.CreateAsync(context);
var remote = f.Remote.Add("Construction cam", f.NewPhotos(1));
await f.RefreshAsync();
await using var engine = new Titano.Data.Jobs.JobEngine(f.Db, f.Sync.CreateJobHandlers(new SyncFixture.Connector(f.Remote)));
var background = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Construction cam", SyncDownloadMode.Proxies, null, JobPriority.Background);
Assert.Equal(background.Id, (await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Construction cam", SyncDownloadMode.Proxies, null,
JobPriority.Background)).Id);
var opened = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Construction cam", SyncDownloadMode.Proxies, null);
Assert.NotEqual(background.Id, opened.Id);
Assert.Equal(JobPriority.User, opened.Priority);
Assert.Equal(JobState.Cancelled, (await f.Db.Jobs.GetAsync(background.Id, f.Ct))!.State);
var originals = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Construction cam", SyncDownloadMode.Originals, f.Archive.Archive.Id);
Assert.NotEqual(opened.Id, originals.Id);
Assert.Equal(SyncTransferKind.DownloadOriginals, SyncService.TransferKind(originals));
Assert.Equal(originals.Id, (await f.EntryAsync("Construction cam")).Transfer!.Id);
}
/// <summary>A linked sequence whose settings changed differently on both sides since they last agreed (41 here, 33 on the server).</summary>
private static async Task<(Sequence Local, FakeSequence Remote)> ConflictAsync(SyncFixture f)
{
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Holy grail", photos);
var remote = f.Remote.Add("Holy grail", photos);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Holy grail")).Status);
local = await f.EditLocalSettingsAsync(local.Id, SyncFixture.Window41);
f.Remote.EditSettings(remote.Id, SyncFixture.Window33);
await f.RefreshAsync();
return (local, remote);
}
/// <summary>A remote where someone else edits the settings right after the first read of a sequence, or right before the first edit.</summary>
private sealed class RacingRemote(FakeSyncRemote inner, Action race, bool beforeUpdate = false) : ISyncRemote
{
private Action? _race = race;
public string Server => inner.Server;
public async Task<SequenceDto> GetSequenceAsync(Guid id, CancellationToken cancellationToken)
{
var dto = await inner.GetSequenceAsync(id, cancellationToken);
if (!beforeUpdate) Interlocked.Exchange(ref _race, null)?.Invoke();
return dto;
}
public Task<IReadOnlyList<SequenceDto>> ListSequencesAsync(CancellationToken cancellationToken) => inner.ListSequencesAsync(cancellationToken);
public Task<SequenceManifest> GetManifestAsync(Guid id, CancellationToken cancellationToken) => inner.GetManifestAsync(id, cancellationToken);
public Task<IReadOnlyList<FrameDto>> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken) => inner.ListFramesAsync(sequenceId, cancellationToken);
public Task<SequenceDto> UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken)
{
if (beforeUpdate) Interlocked.Exchange(ref _race, null)?.Invoke();
return inner.UpdateSequenceAsync(id, request, cancellationToken);
}
public Task<CompleteUploadResponse?> UploadFileAsync(string path, Guid? sequenceId, string? sessionKey, string sha256, DateTime? capturedAt,
CancellationToken cancellationToken) =>
inner.UploadFileAsync(path, sequenceId, sessionKey, sha256, capturedAt, cancellationToken);
public Task DownloadFrameAsync(Guid frameId, string kind, Stream destination, CancellationToken cancellationToken) =>
inner.DownloadFrameAsync(frameId, kind, destination, cancellationToken);
public Task<string?> DownloadRenderAsync(Guid renderId, Stream destination, CancellationToken cancellationToken) =>
inner.DownloadRenderAsync(renderId, destination, cancellationToken);
public Task<RenderDto?> UploadRenderAsync(Guid sequenceId, string path, RenderUploadRequest request, CancellationToken cancellationToken) =>
inner.UploadRenderAsync(sequenceId, path, request, cancellationToken);
public IAsyncEnumerable<ServerEvent> EventsAsync(CancellationToken cancellationToken) => inner.EventsAsync(cancellationToken);
public void Dispose()
{
}
}
}
@@ -0,0 +1,327 @@
using Titano.Core.Imaging;
using Titano.Core.Imaging.Decoders;
using Titano.Core.Model;
using Titano.Core.Render;
using Titano.Data.Sync;
using Titano.Testing;
namespace Titano.Data.Tests.Sync;
/// <summary>Upload, download and proxy jobs on the job engine against an in-memory server.</summary>
[Category("sync")]
public sealed class SyncTransferTests(TestContext context)
{
[Test]
public async Task UploadSendsTheOriginalsAndSettingsOfALocalSequence()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Comet", photos, SyncFixture.Window41);
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
Assert.Equal(job.Id, (await f.Sync.EnqueueUploadAsync(engine, f.Server, local)).Id);
var done = await f.Archive.WaitForAsync(job.Id, JobState.Done);
Assert.Equal((3L, 3L), (done.ProgressDone, done.ProgressTotal));
var remote = Assert.Contains(f.Remote.Sequences.Values, s => s.Title == "Comet");
Assert.True(remote.Frames.Select(r => r.Sha256).ToHashSet().SetEquals(photos.Select(Sha)), "every original arrived");
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, remote.SettingsJson), "the settings travel with the originals");
var entry = await f.EntryAsync("Comet");
Assert.Equal(SyncStatus.InSync, entry.Status);
Assert.Equal(remote.Id, entry.Link!.RemoteId);
}
[Test]
public async Task AResumedUploadSendsOnlyWhatTheServerLacks()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(4);
var local = await f.LocalAsync("Comet", photos);
// A crashed attempt had created the server sequence and sent two originals.
var remote = f.Remote.Add("Comet", photos[..2]);
var engine = await f.StartEngineAsync();
var job = await f.Archive.EnqueueWithCheckpointAsync(engine,
new(JobKind.UploadCommit, [local.Id], "Comet", """{"server":"https://nas.test:8443"}""", JobPriority.User), remote.Id.ToString());
await f.Archive.WaitForAsync(job.Id, JobState.Done);
Assert.Count(1, f.Remote.Sequences.Values);
Assert.Equal(4, remote.Frames.Count);
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Comet")).Status);
}
[Test]
public async Task OriginalsChangedSinceTheyWereArchivedAreNeverUploaded()
{
await using var f = await SyncFixture.CreateAsync(context);
var local = await f.LocalAsync("Comet", f.NewPhotos(3));
var damaged = (await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct))[1];
var path = f.Archive.Paths.FromRelative(damaged.RelativePath);
var bytes = await File.ReadAllBytesAsync(path, f.Ct);
bytes[^3] ^= 0xFF;
await File.WriteAllBytesAsync(path, bytes, f.Ct);
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
var failed = await f.Archive.WaitForAsync(job.Id, JobState.Failed);
Assert.Contains("1", failed.Error);
var remote = Assert.Contains(f.Remote.Sequences.Values, s => s.Title == "Comet");
Assert.Equal(2, remote.Frames.Count);
Assert.DoesNotContain(damaged.Sha256!, remote.Frames.Select(r => r.Sha256));
Assert.Equal(SyncStatus.LocalAhead, (await f.EntryAsync("Comet")).Status);
}
[Test]
public async Task DownloadedOriginalsAreVerifiedAndCommittedThroughTheArchive()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(3);
var remote = f.Remote.Add("Construction cam", photos, SyncFixture.Window33);
remote.Tags = ["site"];
f.Remote.CorruptOnce = remote.Frames[1].Id;
await f.RefreshAsync();
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Construction cam", SyncDownloadMode.Originals, f.Archive.Archive.Id);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
var entry = await f.EntryAsync("Construction cam");
Assert.Equal(SyncStatus.InSync, entry.Status);
var local = Assert.NotNull(entry.Local);
Assert.Equal(SequenceOrigin.Server, local.Origin);
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, local.SettingsJson), "the server's settings came along");
Assert.SequenceEqual(["site"], local.Tags);
var frames = await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct);
Assert.Equal(3, frames.Count);
foreach (var frame in frames)
{
var bytes = await File.ReadAllBytesAsync(f.Archive.Paths.FromRelative(frame.RelativePath), f.Ct);
Assert.Equal(frame.Sha256, Sha(bytes));
}
Assert.True(frames.Select(r => r.Sha256).ToHashSet().SetEquals(photos.Select(Sha)), "the damaged transfer was fetched again");
Assert.FileExists(f.Archive.Paths.Sequence(local.Folder).ManifestPath);
Assert.False(Directory.Exists(Path.Combine(f.Archive.Paths.StagingDirectory, "sync-" + remote.Id.ToString("N"))), "staging cleaned up");
}
[Test]
public async Task DownloadFillsInWhatALocalCopyLacks()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Harbour", photos[..1], SyncFixture.Window41);
var remote = f.Remote.Add("Harbour", photos);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
await f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.KeepMine, f.Ct);
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Harbour", SyncDownloadMode.Originals, null);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
Assert.Equal(3, (await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct)).Count);
var entry = await f.EntryAsync("Harbour");
Assert.Equal(SyncStatus.InSync, entry.Status);
Assert.Equal(SequenceOrigin.Local, entry.Local!.Origin);
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, entry.Local.SettingsJson), "an existing copy keeps its settings");
}
[Test]
public async Task DownloadingIntoAnUnverifiedCopyHashesItFirstAndFetchesOnlyWhatItLacks()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(5);
// An adopted folder: indexed by a scan, never verified, so its frames have no hash yet.
var folder = Path.Combine(f.Archive.Paths.Root, "Adopted");
Directory.CreateDirectory(folder);
for (var i = 0; i < 3; i++) await File.WriteAllBytesAsync(Path.Combine(folder, $"IMG_{i + 1:0000}.JPG"), photos[i], f.Ct);
await f.Archive.ScanAsync();
var local = Assert.Contains((await f.Db.Sequences.ListAsync(new Titano.Data.Repositories.SequenceQuery(), f.Ct)).Items, s => s.Folder == "Adopted");
Assert.True((await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct)).All(fr => fr.Sha256 is null), "adopted frames are unhashed");
var remote = f.Remote.Add("Adopted", photos);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
Assert.Equal(2, (await f.EntryAsync(local.DisplayTitle)).Link!.MissingLocal);
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Adopted", SyncDownloadMode.Originals, null);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
var frames = await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct);
Assert.Equal(5, frames.Count);
Assert.True(frames.Select(fr => fr.Sha256).ToHashSet().SetEquals(photos.Select(Sha)), "no original arrived twice");
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync(local.DisplayTitle)).Status);
}
[Test]
public async Task DownloadingOriginalsRestoresTheOnesMissingHere()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Harbour", photos);
var lost = (await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct))[1];
var place = f.Archive.Paths.FromRelative(lost.RelativePath);
File.Delete(place);
await f.Archive.Service.Verifier.VerifyAsync(f.Archive.Archive, [local.Id], default, (_, _, _) => ValueTask.CompletedTask, cancellationToken: f.Ct);
var remote = f.Remote.Add("Harbour", photos);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
var behind = await f.EntryAsync("Harbour");
Assert.Equal((SyncStatus.ServerAhead, 1), (behind.Status, behind.Link!.MissingLocal));
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Harbour", SyncDownloadMode.Originals, null);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
Assert.Equal(lost.Sha256, Sha(await File.ReadAllBytesAsync(place, f.Ct)));
var frames = await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct);
Assert.Equal(3, frames.Count);
Assert.True(frames.All(fr => (fr.Flags & FrameFlags.Missing) == 0), "the restored original is no longer missing");
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status);
}
[Test]
public async Task TheServersRendersAreFetchedIntoTheLocalExports()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Star trails", photos);
var remote = f.Remote.Add("Star trails", photos);
var render = new FakeRender(Guid.CreateVersion7(), "Star trails 4K.mp4", "4K HEVC", [.. Enumerable.Range(0, 5000).Select(i => (byte)i)]);
remote.Renders.Add(render);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
var entry = await f.EntryAsync("Star trails");
Assert.Equal((SyncStatus.InSync, 1, 5000L), (entry.Status, entry.Link!.ExportsToGet, entry.Link.ExportsToGetBytes));
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Star trails", SyncDownloadMode.Exports, null);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
var fetched = Assert.Contains(await f.Db.Renders.ListBySequenceAsync(local.Id, f.Ct), r => r.Id == render.Id);
Assert.Equal("4K HEVC", fetched.PresetName);
var file = f.Archive.Paths.FromRelative(fetched.OutputPath);
Assert.Equal(Path.Combine(f.Archive.Paths.Sequence(local.Folder).Exports, "Star trails 4K.mp4"), file);
Assert.SequenceEqual(render.Bytes, await File.ReadAllBytesAsync(file, f.Ct));
Assert.Equal(0, (await f.EntryAsync("Star trails")).Link!.ExportsToGet);
}
[Test]
public async Task RendersMadeHereAreSentOnRequestAndAGoneFileIsReported()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Harbour", photos);
var remote = f.Remote.Add("Harbour", photos);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
var exports = f.Archive.Paths.Sequence(local.Folder).Exports;
Directory.CreateDirectory(exports);
var bytes = Enumerable.Range(0, 3000).Select(i => (byte)(i * 7)).ToArray();
await File.WriteAllBytesAsync(Path.Combine(exports, "Harbour 1080p.mp4"), bytes, f.Ct);
var made = await AddRenderAsync(f, local, "Harbour 1080p.mp4", bytes.Length);
var gone = await AddRenderAsync(f, local, "Harbour draft.mp4", 10);
await f.RefreshAsync();
Assert.Equal((1, 3000L), ((await f.EntryAsync("Harbour")).Link!.ExportsToSend, (await f.EntryAsync("Harbour")).Link!.ExportsToSendBytes));
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueSendExportsAsync(engine, f.Server, local);
Assert.Equal(SyncTransferKind.SendExports, SyncService.TransferKind(job));
var failed = await f.Archive.WaitForAsync(job.Id, JobState.Failed);
Assert.Contains("1", failed.Error);
var sent = Assert.Contains(remote.Renders, r => r.Id == made.Id);
Assert.SequenceEqual(bytes, sent.Bytes);
Assert.DoesNotContain(gone.Id, remote.Renders.Select(r => r.Id));
Assert.Equal(0, (await f.EntryAsync("Harbour")).Link!.ExportsToSend);
}
[Test]
public async Task ProxiesOpenARemoteSequenceForTheEditor()
{
await using var f = await SyncFixture.CreateAsync(context);
var remote = f.Remote.Add("Milan skyline", f.NewPhotos(3), SyncFixture.Window33);
await f.RefreshAsync();
Assert.Null(f.Sync.OpenRemote(f.Server, remote.Id));
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Milan skyline", SyncDownloadMode.Proxies, null);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
var entry = await f.EntryAsync("Milan skyline");
Assert.Equal(SyncStatus.ProxiesOnly, entry.Status);
Assert.Equal(3, entry.Link!.ProxiesCached);
Assert.False(entry.Link.ProxiesStale);
var opened = Assert.NotNull(f.Sync.OpenRemote(f.Server, remote.Id));
Assert.Equal(remote.Id, opened.Sequence.Id);
Assert.Equal(SequenceOrigin.Server, opened.Sequence.Origin);
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, opened.Sequence.SettingsJson));
Assert.Equal(3, opened.CachedCount);
var source = opened.OpenFrames(DecoderFactory.CreateServer());
await using (source as IAsyncDisposable)
{
Assert.Equal(3, source.FrameCount);
using var frame = await source.GetFrameAsync(2, 0, DecodePurpose.Render, f.Ct);
Assert.Equal((48, 32), (frame.Width, frame.Height));
}
// Nothing local was created, and a frame added on the server makes the cache stale.
Assert.Null(entry.Local);
remote.AddFrame(f.NewPhotos(1)[0]);
await f.RefreshAsync();
Assert.True((await f.EntryAsync("Milan skyline")).Link!.ProxiesStale);
}
[Test]
public async Task ThumbnailsStandInWhenTheServerHasNoProxies()
{
await using var f = await SyncFixture.CreateAsync(context);
var remote = f.Remote.Add("Fog", f.NewPhotos(2), status: SequenceStatus.ThumbsBuilt);
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Fog", SyncDownloadMode.Proxies, null);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
var opened = Assert.NotNull(f.Sync.OpenRemote(f.Server, remote.Id));
Assert.Equal(2, opened.CachedCount);
Assert.True(opened.Files.All(file => new FileInfo(file!).Length == 64), "thumbnails");
}
[Test]
public async Task TransfersFailWithAReasonWhenThisPcIsNotConnected()
{
await using var f = await SyncFixture.CreateAsync(context);
var local = await f.LocalAsync("Comet", f.NewPhotos(1));
var engine = await f.StartEngineAsync(new SyncFixture.Connector(null));
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
var failed = await f.Archive.WaitForAsync(job.Id, JobState.Failed);
Assert.Equal(Titano.Core.Localization.Loc.L("Errors.Sync.NotConnected"), failed.Error);
Assert.Empty(f.Remote.Sequences);
}
private static async Task<Render> AddRenderAsync(SyncFixture f, Sequence local, string name, long bytes)
{
var render = new Render
{
Id = Guid.CreateVersion7(),
SequenceId = local.Id,
PresetName = "1080p H.264",
OutputPath = local.Folder + "/exports/" + name,
Codec = "h264",
Width = 1920,
Height = 1080,
Fps = 30,
DurationSeconds = 10,
Bytes = bytes,
Created = DateTimeOffset.UtcNow,
ProducedBy = "studio",
};
await f.Db.Renders.InsertAsync(render, f.Ct);
return render;
}
private static string Sha(byte[] bytes) => Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(bytes));
}
@@ -0,0 +1,147 @@
using System.Security.Cryptography;
using Titano.Core.Codecs.Jpeg;
using Titano.Core.Model;
using Titano.Data;
using Titano.Data.Archiving;
using Titano.Data.Jobs;
using Titano.Data.Sync;
using Titano.Protocol.Client;
using Titano.Testing;
namespace Titano.Server.Tests.Sync;
/// <summary>A desktop client's sync side: its own index and archive, the sync engine and a job engine, signed in to a test server.</summary>
internal sealed class SyncClient : IAsyncDisposable
{
private readonly TestContext _context;
private readonly TitanoClient _client;
private SyncClient(TestContext context, TitanoDatabase db, ArchiveService archives, Archive archive, SyncService sync, TitanoClient client, JobEngine engine)
{
_context = context;
Db = db;
Archives = archives;
Archive = archive;
Sync = sync;
_client = client;
Engine = engine;
Remote = new TitanoSyncRemote(client, ownsClient: false);
}
public TitanoDatabase Db { get; }
public ArchiveService Archives { get; }
public Archive Archive { get; }
public SyncService Sync { get; }
public JobEngine Engine { get; }
/// <summary>The connection the table and the agent use (jobs get their own from the connector).</summary>
public TitanoSyncRemote Remote { get; }
public string Server => Remote.Server;
private CancellationToken Ct => _context.Cancellation;
public static async Task<SyncClient> StartAsync(TestContext context, TestServer server, string token, string name)
{
var db = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory(name + "-db"), "titano.db")), context.Cancellation);
var options = new ArchiveServiceOptions { Owner = name, LeaseWait = TimeSpan.FromSeconds(20) };
var archives = new ArchiveService(db, options);
var archive = await archives.CreateAsync(context.CreateTempDirectory(name + "-archive"), "Main", cancellationToken: context.Cancellation);
var sync = new SyncService(db, archives, new SyncOptions { Archive = options, ProxyCacheDirectory = context.CreateTempDirectory(name + "-proxies") });
var client = new TitanoClient(server.HttpBase, new CertificatePinning([]), name) { Token = token };
var engine = new JobEngine(db, [.. archives.CreateJobHandlers(), .. sync.CreateJobHandlers(new Connector(client))],
new JobEngineOptions { Workers = 2, WorkerId = name, PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
await engine.StartAsync(context.Cancellation);
return new SyncClient(context, db, archives, archive, sync, client, engine);
}
/// <summary>Distinct JPEGs larger than one 64 KiB chunk.</summary>
public static byte[] Photo(int seed)
{
const int width = 512, height = 384;
var pixels = new byte[width * height * 3];
new Random(seed).NextBytes(pixels);
return JpegEncoder.Encode(pixels, width, height, 3, new JpegEncodeOptions { Quality = 95 });
}
public static string Sha(byte[] bytes) => Convert.ToHexStringLower(SHA256.HashData(bytes));
/// <summary>A local sequence committed through the archive ingest, optionally with project settings edited on this PC.</summary>
public async Task<Sequence> LocalAsync(string title, IReadOnlyList<byte[]> photos, string? settingsJson = null)
{
var staging = Path.Combine(Archive.RootPath, ".titano", "staging", "test");
Directory.CreateDirectory(staging);
Guid? id = null;
for (var i = 0; i < photos.Count; i++)
{
var path = Path.Combine(staging, $"{Guid.NewGuid():N}.part");
await File.WriteAllBytesAsync(path, photos[i], Ct);
var result = await Archives.Ingest.CommitAsync(new IngestRequest(Archive.Id, id, id is null ? title : null, null, path, $"IMG_{i + 1:0000}.JPG",
photos[i].Length, Sha(photos[i]), new DateTime(2026, 9, 28, 18, 0, 0).AddSeconds(10 * i), null), Ct);
id = result.SequenceId;
}
var sequence = (await Db.Sequences.GetAsync(id!.Value, Ct))!;
if (settingsJson is null) return sequence;
var edited = await Db.Sequences.EditAsync(sequence.Id, new Titano.Data.Repositories.SequenceEdit { SettingsJson = settingsJson }, null, Ct);
return edited.Sequence!;
}
/// <summary>A render of <paramref name="sequence"/> made on this PC: its file in the sequence's exports and its row.</summary>
public async Task<Render> RenderAsync(Sequence sequence, string fileName, byte[] bytes)
{
var exports = Path.Combine(Archive.RootPath, sequence.Folder, "exports");
Directory.CreateDirectory(exports);
await File.WriteAllBytesAsync(Path.Combine(exports, fileName), bytes, Ct);
var render = new Render
{
Id = Guid.CreateVersion7(),
SequenceId = sequence.Id,
PresetName = "4K HEVC",
OutputPath = sequence.Folder + "/exports/" + fileName,
Codec = "hevc",
Width = 3840,
Height = 2160,
Fps = 30,
DurationSeconds = 10,
Bytes = bytes.Length,
Created = DateTimeOffset.UtcNow,
ProducedBy = "studio",
};
await Db.Renders.InsertAsync(render, Ct);
return render;
}
public string RenderFile(Render render) => Path.Combine(Archive.RootPath, render.OutputPath);
public async Task<Job> WaitAsync(Guid jobId, JobState state = JobState.Done)
{
var until = DateTime.UtcNow.AddSeconds(60);
while (true)
{
var job = await Db.Jobs.GetAsync(jobId, Ct);
if (job?.State == state) return job;
if (job?.State is JobState.Failed && state != JobState.Failed) Assert.Fail($"Job failed: {job.Error}\n{job.LogTail}");
if (DateTime.UtcNow > until) Assert.Fail($"Job {jobId} did not reach {state} (now {job?.State})");
await Task.Delay(25, Ct);
}
}
public async Task<SyncEntry> EntryAsync(string title) => (await Sync.ListAsync(Server, Ct)).Single(e => e.Title == title);
public async ValueTask DisposeAsync()
{
await Engine.DisposeAsync();
Remote.Dispose();
_client.Dispose();
await Db.DisposeAsync();
}
/// <summary>Every job gets its own remote over the shared signed-in client.</summary>
private sealed class Connector(TitanoClient client) : ISyncConnector
{
public ValueTask<ISyncRemote?> ConnectAsync(string server, CancellationToken cancellationToken)
{
ISyncRemote remote = new TitanoSyncRemote(client, ownsClient: false);
return ValueTask.FromResult<ISyncRemote?>(remote.Server == server ? remote : null);
}
}
}
@@ -0,0 +1,254 @@
using System.Net;
using System.Net.Http.Json;
using Microsoft.Extensions.DependencyInjection;
using Titano.Core.Imaging;
using Titano.Core.Imaging.Decoders;
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Data.Repositories;
using Titano.Data.Sync;
using Titano.Protocol;
using Titano.Server.Events;
using Titano.Server.Storage;
using Titano.Testing;
namespace Titano.Server.Tests.Sync;
/// <summary>The client's sync engine against the real server: uploads, downloads, proxies and live events through the API.</summary>
[Category("server")]
[Timeout(180_000)]
public sealed class SyncServerTests(TestContext context)
{
private const string Window41 = """{"exposure":{"deflickerWindow":{"isAuto":false,"manual":41}}}""";
private const string Window33 = """{"exposure":{"deflickerWindow":{"isAuto":false,"manual":33}}}""";
[Test]
public async Task ASequenceUploadedFromOnePcDownloadsIdenticallyOnAnother()
{
await using var server = await StartServerAsync();
var (_, _, token) = await server.UserAsync("alberto", "editor");
await using var studio = await SyncClient.StartAsync(context, server, token, "studio");
await using var laptop = await SyncClient.StartAsync(context, server, token, "laptop");
var photos = Enumerable.Range(1, 3).Select(SyncClient.Photo).ToList();
var local = await studio.LocalAsync("Comet over the ridge", photos, Window41);
var upload = await studio.Sync.EnqueueUploadAsync(studio.Engine, studio.Server, local);
await studio.WaitAsync(upload.Id);
var uploaded = await studio.EntryAsync("Comet over the ridge");
Assert.Equal((0, 0), (uploaded.Link!.MissingRemote, uploaded.Link.MissingLocal));
var remoteId = uploaded.Link!.RemoteId;
var onServer = Assert.NotNull(await server.Database.Sequences.GetAsync(remoteId));
Assert.Equal(41, ProjectSettings.FromJson(onServer.SettingsJson!).Exposure.DeflickerWindow.Manual, "settings travel with the originals");
var serverFrames = await server.Database.Frames.ListBySequenceAsync(remoteId);
Assert.True(serverFrames.Select(f => f.Sha256).ToHashSet().SetEquals(photos.Select(SyncClient.Sha)), "every original was committed");
await ServerIdleAsync(server);
await laptop.Sync.RefreshAsync(laptop.Remote, new SyncPolicy(), context.Cancellation);
Assert.Equal(SyncStatus.RemoteOnly, (await laptop.EntryAsync("Comet over the ridge")).Status);
var download = await laptop.Sync.EnqueueDownloadAsync(laptop.Engine, laptop.Server, remoteId, "Comet over the ridge", SyncDownloadMode.Originals,
laptop.Archive.Id);
await laptop.WaitAsync(download.Id);
var copy = await laptop.EntryAsync("Comet over the ridge");
Assert.Equal(SyncStatus.InSync, copy.Status);
Assert.Equal(SequenceOrigin.Server, copy.Local!.Origin);
// The server's analysis may have added its advice meanwhile; the copy has what the server has, the user's edit included.
Assert.True(SyncRules.SameSettings((await server.Database.Sequences.GetAsync(remoteId))!.SettingsJson, copy.Local.SettingsJson));
Assert.Equal(41, ProjectSettings.FromJson(copy.Local.SettingsJson!).Exposure.DeflickerWindow.Manual);
var files = (await laptop.Db.Frames.ListBySequenceAsync(copy.Local.Id))
.Select(f => File.ReadAllBytes(Path.Combine(laptop.Archive.RootPath, f.RelativePath))).ToList();
Assert.True(files.Select(SyncClient.Sha).ToHashSet().SetEquals(photos.Select(SyncClient.Sha)), "byte-identical originals");
await studio.Sync.RefreshAsync(studio.Remote, new SyncPolicy(), context.Cancellation);
Assert.Equal(SyncStatus.InSync, (await studio.EntryAsync("Comet over the ridge")).Status);
}
[Test]
public async Task AnUploadInterruptedMidFileResumesTheServersPartialUpload()
{
await using var server = await StartServerAsync();
var (http, _, token) = await server.UserAsync("alberto", "editor");
await using var studio = await SyncClient.StartAsync(context, server, token, "studio");
var photos = Enumerable.Range(10, 2).Select(SyncClient.Photo).ToList();
var local = await studio.LocalAsync("Clouds", photos);
// The crashed attempt had sent the first original (which created the server sequence) and one chunk of the second.
var first = await Uploads.UploadAsync(http, photos[0], "IMG_0001.JPG", sessionKey: "crashed-attempt");
var partial = await Uploads.StartAsync(http, photos[1], "IMG_0002.JPG", first.SequenceId);
Assert.True(photos[1].Length > partial.ChunkSize, "the photo spans several chunks");
using (var chunk = await Uploads.PutChunkAsync(http, partial.UploadId!.Value, 0, Uploads.Chunk(photos[1], partial.ChunkSize, 0)))
await chunk.ExpectAsync(HttpStatusCode.OK);
var job = new Job
{
Id = Guid.CreateVersion7(),
Kind = JobKind.UploadCommit,
TargetIds = [local.Id],
TargetLabel = "Clouds",
ParametersJson = $$"""{"server":"{{studio.Server}}"}""",
Checkpoint = first.SequenceId.ToString(),
State = JobState.Queued,
Created = DateTimeOffset.UtcNow,
};
await studio.Db.Jobs.EnqueueAsync(job, context.Cancellation);
studio.Engine.Wake();
await studio.WaitAsync(job.Id);
var resumed = Assert.NotNull(await server.Database.Uploads.GetAsync(partial.UploadId!.Value));
Assert.Equal(Titano.Data.Repositories.UploadState.Committed, resumed.State);
Assert.Equal(2, (await server.Database.Frames.ListBySequenceAsync(first.SequenceId)).Count);
// Every original is on both sides (the server's analysis may still be editing the settings).
var link = (await studio.EntryAsync("Clouds")).Link!;
Assert.Equal((first.SequenceId, 0, 0), (link.RemoteId, link.MissingRemote, link.MissingLocal));
}
[Test]
public async Task ADownloadResumesPartialFilesAndRefusesDamagedOnes()
{
await using var server = await StartServerAsync();
var (_, _, token) = await server.UserAsync("alberto", "editor");
await using var studio = await SyncClient.StartAsync(context, server, token, "studio");
await using var laptop = await SyncClient.StartAsync(context, server, token, "laptop");
var photos = Enumerable.Range(20, 3).Select(SyncClient.Photo).ToList();
var local = await studio.LocalAsync("Aurora", photos);
await studio.WaitAsync((await studio.Sync.EnqueueUploadAsync(studio.Engine, studio.Server, local)).Id);
var remoteId = (await studio.EntryAsync("Aurora")).Link!.RemoteId;
// An earlier attempt left half of one original, and a damaged half of another.
var staging = Path.Combine(laptop.Archive.RootPath, ".titano", "staging", "sync-" + remoteId.ToString("N"));
Directory.CreateDirectory(staging);
await File.WriteAllBytesAsync(Path.Combine(staging, SyncClient.Sha(photos[0]) + ".jpg.part"), photos[0][..(photos[0].Length / 2)]);
await File.WriteAllBytesAsync(Path.Combine(staging, SyncClient.Sha(photos[1]) + ".jpg.part"), new byte[photos[1].Length / 2]);
await laptop.Sync.RefreshAsync(laptop.Remote, new SyncPolicy(), context.Cancellation);
var download = await laptop.Sync.EnqueueDownloadAsync(laptop.Engine, laptop.Server, remoteId, "Aurora", SyncDownloadMode.Originals, laptop.Archive.Id);
await laptop.WaitAsync(download.Id);
var copy = Assert.NotNull((await laptop.EntryAsync("Aurora")).Local);
var hashes = (await laptop.Db.Frames.ListBySequenceAsync(copy.Id))
.Select(f => SyncClient.Sha(File.ReadAllBytes(Path.Combine(laptop.Archive.RootPath, f.RelativePath)))).ToHashSet();
Assert.True(hashes.SetEquals(photos.Select(SyncClient.Sha)), "every original arrived intact");
Assert.False(Directory.Exists(staging), "staging cleaned up");
}
[Test]
public async Task ServerEventsUpdateThisPcWithoutWaitingForTheNextComparison()
{
await using var server = await StartServerAsync();
var (http, _, token) = await server.UserAsync("alberto", "editor");
await using var studio = await SyncClient.StartAsync(context, server, token, "studio");
var local = await studio.LocalAsync("Harbour sunset", [SyncClient.Photo(30)]);
await studio.WaitAsync((await studio.Sync.EnqueueUploadAsync(studio.Engine, studio.Server, local)).Id);
var remoteId = (await studio.EntryAsync("Harbour sunset")).Link!.RemoteId;
await ServerIdleAsync(server);
await using var agent = new SyncAgent(studio.Sync, studio.Remote, () => new SyncPolicy(), studio.Engine,
new SyncAgentOptions { RefreshInterval = TimeSpan.FromHours(1), EventDelay = TimeSpan.FromMilliseconds(50) });
agent.Start();
var hub = server.Services.GetRequiredService<EventHub>();
await UntilAsync(() => Task.FromResult(agent.Snapshot is not null && hub.SubscriberCount > 0), "the agent's first comparison and event socket");
// Someone edits the project on the server (web or another PC).
using (var patch = await http.PatchAsJsonAsync($"/api/v1/sequences/{remoteId}",
new UpdateSequenceRequest(null, null, null, null, Window33, null), ProtocolJson.Default.UpdateSequenceRequest))
await patch.ExpectAsync(HttpStatusCode.OK);
await UntilAsync(async () => ProjectSettings.FromJson((await studio.Db.Sequences.GetAsync(local.Id))!.SettingsJson ?? "{}").Exposure.DeflickerWindow.Manual == 33,
"the edit reached this PC");
Assert.Equal(SyncStatus.InSync, (await studio.EntryAsync("Harbour sunset")).Status);
}
[Test]
public async Task ARemoteSequenceOpensWithProxiesOnly()
{
await using var server = await StartServerAsync();
var (_, _, token) = await server.UserAsync("alberto", "editor");
await using var studio = await SyncClient.StartAsync(context, server, token, "studio");
await using var laptop = await SyncClient.StartAsync(context, server, token, "laptop");
var photos = Enumerable.Range(40, 2).Select(SyncClient.Photo).ToList();
var local = await studio.LocalAsync("Milan skyline dusk", photos, Window41);
await studio.WaitAsync((await studio.Sync.EnqueueUploadAsync(studio.Engine, studio.Server, local)).Id);
var remoteId = (await studio.EntryAsync("Milan skyline dusk")).Link!.RemoteId;
await ServerIdleAsync(server);
Assert.True(((await server.Database.Sequences.GetAsync(remoteId))!.Status & SequenceStatus.ThumbsBuilt) != 0, "thumbnails on the server");
await laptop.Sync.RefreshAsync(laptop.Remote, new SyncPolicy(), context.Cancellation);
var job = await laptop.Sync.EnqueueDownloadAsync(laptop.Engine, laptop.Server, remoteId, "Milan skyline dusk", SyncDownloadMode.Proxies, null);
await laptop.WaitAsync(job.Id);
Assert.Equal(SyncStatus.ProxiesOnly, (await laptop.EntryAsync("Milan skyline dusk")).Status);
Assert.Empty((await laptop.Db.Sequences.ListAsync(new SequenceQuery())).Items);
var opened = Assert.NotNull(laptop.Sync.OpenRemote(laptop.Server, remoteId));
Assert.Equal(2, opened.CachedCount);
Assert.Equal(41, ProjectSettings.FromJson(opened.Sequence.SettingsJson!).Exposure.DeflickerWindow.Manual);
var source = opened.OpenFrames(DecoderFactory.CreateServer());
await using (source as IAsyncDisposable)
{
using var frame = await source.GetFrameAsync(0, 0, DecodePurpose.Render, context.Cancellation);
Assert.True(frame.Width > 0 && frame.Height > 0, "a proxy decodes");
}
}
[Test]
public async Task RendersTravelOnRequestWithTheirIdAndAreVerified()
{
await using var server = await StartServerAsync();
var (_, _, token) = await server.UserAsync("alberto", "editor");
await using var studio = await SyncClient.StartAsync(context, server, token, "studio");
await using var laptop = await SyncClient.StartAsync(context, server, token, "laptop");
var photos = Enumerable.Range(50, 2).Select(SyncClient.Photo).ToList();
var local = await studio.LocalAsync("Star trails", photos);
await studio.WaitAsync((await studio.Sync.EnqueueUploadAsync(studio.Engine, studio.Server, local)).Id);
var remoteId = (await studio.EntryAsync("Star trails")).Link!.RemoteId;
await ServerIdleAsync(server);
// A render made on the studio PC, larger than one chunk, is sent on request and keeps its id.
var output = Enumerable.Range(0, 200_000).Select(i => (byte)(i * 31)).ToArray();
var render = await studio.RenderAsync(local, "Star trails 4K.mp4", output);
await studio.Sync.RefreshAsync(studio.Remote, new SyncPolicy(), context.Cancellation);
Assert.Equal(1, (await studio.EntryAsync("Star trails")).Link!.ExportsToSend);
await studio.WaitAsync((await studio.Sync.EnqueueSendExportsAsync(studio.Engine, studio.Server, local)).Id);
var filed = Assert.NotNull(await server.Database.Renders.GetAsync(render.Id));
Assert.Equal(remoteId, filed.SequenceId);
Assert.SequenceEqual(output, await File.ReadAllBytesAsync(Path.Combine(server.Options.ArchivePath, filed.OutputPath)));
Assert.Equal(0, (await studio.EntryAsync("Star trails")).Link!.ExportsToSend);
Assert.Null(await studio.Remote.UploadRenderAsync(remoteId, studio.RenderFile(render), new RenderUploadRequest(render.Id, "Star trails 4K.mp4",
output.Length, SyncClient.Sha(output), "4K HEVC", "hevc", 3840, 2160, 30, 10, "studio"), context.Cancellation));
// A damaged transfer is refused at completion.
var bad = new RenderUploadRequest(Guid.CreateVersion7(), "Damaged.mp4", output.Length, SyncClient.Sha(output), "4K HEVC", "hevc", 3840, 2160, 30, 10, null);
var damaged = Path.Combine(context.CreateTempDirectory("damaged"), "Damaged.mp4");
await File.WriteAllBytesAsync(damaged, [.. output.Select(b => (byte)~b)]);
var refused = await Assert.ThrowsAsync<Titano.Protocol.Client.TitanoApiException>(() =>
studio.Remote.UploadRenderAsync(remoteId, damaged, bad, context.Cancellation));
Assert.Equal(HttpStatusCode.UnprocessableEntity, refused.Status);
Assert.Null(await server.Database.Renders.GetAsync(bad.RenderId));
// Another PC with the originals gets the render into its own exports, byte-identical.
await laptop.Sync.RefreshAsync(laptop.Remote, new SyncPolicy(), context.Cancellation);
await laptop.WaitAsync((await laptop.Sync.EnqueueDownloadAsync(laptop.Engine, laptop.Server, remoteId, "Star trails", SyncDownloadMode.Originals,
laptop.Archive.Id)).Id);
Assert.Equal(1, (await laptop.EntryAsync("Star trails")).Link!.ExportsToGet);
await laptop.WaitAsync((await laptop.Sync.EnqueueDownloadAsync(laptop.Engine, laptop.Server, remoteId, "Star trails", SyncDownloadMode.Exports, null)).Id);
var copy = (await laptop.EntryAsync("Star trails")).Local!;
var fetched = Assert.Contains(await laptop.Db.Renders.ListBySequenceAsync(copy.Id), r => r.Id == render.Id);
Assert.SequenceEqual(output, await File.ReadAllBytesAsync(Path.Combine(laptop.Archive.RootPath, fetched.OutputPath)));
Assert.Equal(0, (await laptop.EntryAsync("Star trails")).Link!.ExportsToGet);
}
private Task<TestServer> StartServerAsync() => TestServer.StartAsync(context, o => o.ChunkSizeBytes = 64 * 1024, ArchiveModule.Register);
/// <summary>Waits until the server's engines finished what the commits queued (thumbnails, proxies, analysis, which may edit settings).</summary>
private Task ServerIdleAsync(TestServer server) =>
UntilAsync(async () => await server.Database.Jobs.CountAsync(DateTimeOffset.UtcNow) is { Queued: 0, Running: 0 }, "the server's jobs");
private async Task UntilAsync(Func<Task<bool>> condition, string what)
{
var until = DateTime.UtcNow.AddSeconds(60);
while (!await condition())
{
if (DateTime.UtcNow > until) Assert.Fail("Timed out waiting for " + what);
await Task.Delay(50, context.Cancellation);
}
}
}