merge: or5 parcel p4

# Conflicts:
#	src/Chronos.App/Sections/ServerView.xaml
#	src/Chronos.App/Sections/ServerViewModel.cs
#	src/Chronos.Server/Jobs/JobEngineHost.cs
This commit is contained in:
Alby96 committed 2026-11-15 15:01:31 +01:00
commit e367f03c80
127 files changed
+6822 -1117

No files matched your search

+1
View File
@@ -5,6 +5,7 @@
<Project Path="src/Chronos.Data/Chronos.Data.csproj" /> <Project Path="src/Chronos.Data/Chronos.Data.csproj" />
<Project Path="src/Chronos.Protocol/Chronos.Protocol.csproj" /> <Project Path="src/Chronos.Protocol/Chronos.Protocol.csproj" />
<Project Path="src/Chronos.Server/Chronos.Server.csproj" /> <Project Path="src/Chronos.Server/Chronos.Server.csproj" />
<Project Path="src/Chronos.Server.Host/Chronos.Server.Host.csproj" />
<Project Path="src/Chronos.Ui/Chronos.Ui.csproj" /> <Project Path="src/Chronos.Ui/Chronos.Ui.csproj" />
<Project Path="src/Chronos.App/Chronos.App.csproj" /> <Project Path="src/Chronos.App/Chronos.App.csproj" />
<Project Path="src/Chronos.Uploader/Chronos.Uploader.csproj" /> <Project Path="src/Chronos.Uploader/Chronos.Uploader.csproj" />
+3 -2
View File
@@ -10,7 +10,8 @@ COPY src/Chronos.Core/ src/Chronos.Core/
COPY src/Chronos.Data/ src/Chronos.Data/ COPY src/Chronos.Data/ src/Chronos.Data/
COPY src/Chronos.Protocol/ src/Chronos.Protocol/ COPY src/Chronos.Protocol/ src/Chronos.Protocol/
COPY src/Chronos.Server/ src/Chronos.Server/ COPY src/Chronos.Server/ src/Chronos.Server/
RUN dotnet publish src/Chronos.Server/Chronos.Server.csproj \ COPY src/Chronos.Server.Host/ src/Chronos.Server.Host/
RUN dotnet publish src/Chronos.Server.Host/Chronos.Server.Host.csproj \
-c Release -a "$TARGETARCH" --no-self-contained \ -c Release -a "$TARGETARCH" --no-self-contained \
-p:ChronosVersion="$CHRONOS_VERSION" -o /out \ -p:ChronosVersion="$CHRONOS_VERSION" -o /out \
&& rm -f /out/*.pdb && rm -f /out/*.pdb
@@ -43,5 +44,5 @@ RUN chmod 0755 /usr/local/bin/chronos-entrypoint && mkdir -p /archive /data /vid
VOLUME ["/archive", "/data"] VOLUME ["/archive", "/data"]
EXPOSE 8080 8443 EXPOSE 8080 8443
HEALTHCHECK --interval=30s --timeout=8s --start-period=40s --retries=3 \ HEALTHCHECK --interval=30s --timeout=8s --start-period=40s --retries=3 \
CMD ["dotnet", "/app/Chronos.Server.dll", "--healthcheck"] CMD ["dotnet", "/app/Chronos.Server.Host.dll", "--healthcheck"]
ENTRYPOINT ["/usr/local/bin/chronos-entrypoint"] ENTRYPOINT ["/usr/local/bin/chronos-entrypoint"]
+3 -3
View File
@@ -14,7 +14,7 @@ umask 002
# Help and the health probe touch neither folder. # Help and the health probe touch neither folder.
case "${1:-}" in case "${1:-}" in
--help | -h | -\? | /\? | --healthcheck) exec dotnet /app/Chronos.Server.dll "$@" ;; --help | -h | -\? | /\? | --healthcheck) exec dotnet /app/Chronos.Server.Host.dll "$@" ;;
esac esac
as_user() { as_user() {
@@ -62,7 +62,7 @@ if [ "$(id -u)" = "0" ]; then
fi fi
fi fi
fi fi
exec setpriv --reuid="$PUID" --regid="$PGID" --clear-groups -- dotnet /app/Chronos.Server.dll "$@" exec setpriv --reuid="$PUID" --regid="$PGID" --clear-groups -- dotnet /app/Chronos.Server.Host.dll "$@"
fi fi
exec dotnet /app/Chronos.Server.dll "$@" exec dotnet /app/Chronos.Server.Host.dll "$@"
+1
View File
@@ -869,6 +869,7 @@
<data name="Admin.Settings.Level.Warning" xml:space="preserve"><value>Warning</value></data> <data name="Admin.Settings.Level.Warning" xml:space="preserve"><value>Warning</value></data>
<data name="Admin.Settings.Limits" xml:space="preserve"><value>Limits and retention</value></data> <data name="Admin.Settings.Limits" xml:space="preserve"><value>Limits and retention</value></data>
<data name="Admin.Settings.Locked.Tip" xml:space="preserve"><value>Set by the environment variable {0}; remove the variable to change it here</value></data> <data name="Admin.Settings.Locked.Tip" xml:space="preserve"><value>Set by the environment variable {0}; remove the variable to change it here</value></data>
<data name="Admin.Settings.LockedByDesktop.Tip" xml:space="preserve"><value>Set in Chronos Desktop; change it in Settings on the PC that shares this library</value></data>
<data name="Admin.Settings.LogLevel" xml:space="preserve"><value>File level</value></data> <data name="Admin.Settings.LogLevel" xml:space="preserve"><value>File level</value></data>
<data name="Admin.Settings.LogLevel.Tip" xml:space="preserve"><value>Least severe level written to the log files; Debug and Trace help find problems but fill the files fast</value></data> <data name="Admin.Settings.LogLevel.Tip" xml:space="preserve"><value>Least severe level written to the log files; Debug and Trace help find problems but fill the files fast</value></data>
<data name="Admin.Settings.LogMaxFileMb" xml:space="preserve"><value>File size (MB)</value></data> <data name="Admin.Settings.LogMaxFileMb" xml:space="preserve"><value>File size (MB)</value></data>
+1
View File
@@ -291,6 +291,7 @@
<data name="Archive.Maintenance.Restore" xml:space="preserve"><value>Restore database…</value></data> <data name="Archive.Maintenance.Restore" xml:space="preserve"><value>Restore database…</value></data>
<data name="Archive.Maintenance.Run" xml:space="preserve"><value>Run maintenance</value></data> <data name="Archive.Maintenance.Run" xml:space="preserve"><value>Run maintenance</value></data>
<data name="Archive.Maintenance.Trash" xml:space="preserve"><value>Trash…</value></data> <data name="Archive.Maintenance.Trash" xml:space="preserve"><value>Trash…</value></data>
<data name="Archive.Name.ServerOriginals" xml:space="preserve"><value>{0} (server)</value><comment>the name of the archive of a server's downloaded originals; {0} the server's name</comment></data>
<data name="Archive.Orphans.Count.one" xml:space="preserve"><value>{0:N0} issue</value></data> <data name="Archive.Orphans.Count.one" xml:space="preserve"><value>{0:N0} issue</value></data>
<data name="Archive.Orphans.Count.other" xml:space="preserve"><value>{0:N0} issues</value></data> <data name="Archive.Orphans.Count.other" xml:space="preserve"><value>{0:N0} issues</value></data>
<data name="Archive.Orphans.Failed" xml:space="preserve"><value>The orphan search stopped</value><comment>long</comment></data> <data name="Archive.Orphans.Failed" xml:space="preserve"><value>The orphan search stopped</value><comment>long</comment></data>
+7
View File
@@ -9,6 +9,8 @@
<data name="Errors.Archive.Open" xml:space="preserve"><value>The archive could not be opened.</value><comment>long</comment></data> <data name="Errors.Archive.Open" xml:space="preserve"><value>The archive could not be opened.</value><comment>long</comment></data>
<data name="Errors.Backup.Deferred" xml:space="preserve"><value>The current index could not be backed up or replaced; the restore runs again at the next start.</value><comment>long</comment></data> <data name="Errors.Backup.Deferred" xml:space="preserve"><value>The current index could not be backed up or replaced; the restore runs again at the next start.</value><comment>long</comment></data>
<data name="Errors.Backup.Unreadable" xml:space="preserve"><value>This backup cannot be restored; choose another one.</value><comment>long</comment></data> <data name="Errors.Backup.Unreadable" xml:space="preserve"><value>This backup cannot be restored; choose another one.</value><comment>long</comment></data>
<data name="Errors.Homes.Clash" xml:space="preserve"><value>{0} presents the ID of {1} with another certificate; check that it is not a copy of that server.</value><comment>{0} the server's name now, {1} the name it had</comment></data>
<data name="Errors.Homes.Failed" xml:space="preserve"><value>The folders could not be sorted: {0}. Nothing was deleted; Chronos tries again at the next start.</value><comment>{0} the reason</comment></data>
<data name="Errors.Number.DecimalRange" xml:space="preserve"><value>Enter a number from {0} to {1}.</value></data> <data name="Errors.Number.DecimalRange" xml:space="preserve"><value>Enter a number from {0} to {1}.</value></data>
<data name="Errors.Number.Range" xml:space="preserve"><value>Enter a whole number from {0} to {1}.</value></data> <data name="Errors.Number.Range" xml:space="preserve"><value>Enter a whole number from {0} to {1}.</value></data>
<data name="Errors.Path.Empty" xml:space="preserve"><value>Enter a folder.</value></data> <data name="Errors.Path.Empty" xml:space="preserve"><value>Enter a folder.</value></data>
@@ -27,6 +29,10 @@
<data name="Errors.Render.Sequence" xml:space="preserve"><value>The sequence to render is no longer in the archive.</value></data> <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://chronos.example.com.</value></data> <data name="Errors.Server.Address" xml:space="preserve"><value>Enter a server address such as nas.local:8443 or https://chronos.example.com.</value></data>
<data name="Errors.Settings.Import" xml:space="preserve"><value>This file does not contain Chronos settings.</value></data> <data name="Errors.Settings.Import" xml:space="preserve"><value>This file does not contain Chronos settings.</value></data>
<data name="Errors.Share.Failed" xml:space="preserve"><value>Sharing could not start: {0}</value></data>
<data name="Errors.Share.NoArchive" xml:space="preserve"><value>Open or create an archive before sharing it.</value></data>
<data name="Errors.Share.NotReady" xml:space="preserve"><value>The library is not open yet; sharing starts once it is.</value></data>
<data name="Errors.Share.PortInUse" xml:space="preserve"><value>Port {0} is used by another program. Choose another one in Settings › Server.</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.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.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.one" xml:space="preserve"><value>{0} render is no longer on this PC; the others were sent.</value><comment>{0} count</comment></data>
@@ -34,6 +40,7 @@
<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.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.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.NoArchive" xml:space="preserve"><value>Open or create an archive on this PC to receive the originals.</value></data>
<data name="Errors.Sync.NoOriginalsFolder" xml:space="preserve"><value>No folder could be made for the originals of {0}; check that the drive of this PC's archive can be written.</value><comment>{0} the server's name</comment></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.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.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.NothingSent" xml:space="preserve"><value>No original reached the server: they are missing here or already in another server sequence.</value></data>
+24
View File
@@ -85,6 +85,7 @@
<data name="Server.Error.NotFound" xml:space="preserve"><value>Not found.</value><comment>long</comment></data> <data name="Server.Error.NotFound" xml:space="preserve"><value>Not found.</value><comment>long</comment></data>
<data name="Server.Error.NotChronos" xml:space="preserve"><value>That address is not a Chronos Server.</value><comment>long</comment></data> <data name="Server.Error.NotChronos" xml:space="preserve"><value>That address is not a Chronos Server.</value><comment>long</comment></data>
<data name="Server.Error.NothingToConvert" xml:space="preserve"><value>The plan converts nothing: every photo is skipped or every sequence is blocked.</value><comment>long</comment></data> <data name="Server.Error.NothingToConvert" xml:space="preserve"><value>The plan converts nothing: every photo is skipped or every sequence is blocked.</value><comment>long</comment></data>
<data name="Server.Error.OwnLibrary" xml:space="preserve"><value>This address is this PC's own shared library, already open here.</value><comment>long</comment></data>
<data name="Server.Error.PasswordChangeRequired" xml:space="preserve"><value>Change your password first.</value><comment>long</comment></data> <data name="Server.Error.PasswordChangeRequired" xml:space="preserve"><value>Change your password first.</value><comment>long</comment></data>
<data name="Server.Error.PhotoRemoved" xml:space="preserve"><value>The photo was deleted from the sequence while it was being uploaded, so it was not added.</value><comment>long</comment></data> <data name="Server.Error.PhotoRemoved" xml:space="preserve"><value>The photo was deleted from the sequence while it was being uploaded, so it was not added.</value><comment>long</comment></data>
<data name="Server.Error.PhotoUnreadable" xml:space="preserve"><value>{0} cannot be read, and without its hash other copies would not learn it was deleted; close the program using it or check its permissions, then try again.</value><comment>long</comment></data> <data name="Server.Error.PhotoUnreadable" xml:space="preserve"><value>{0} cannot be read, and without its hash other copies would not learn it was deleted; close the program using it or check its permissions, then try again.</value><comment>long</comment></data>
@@ -136,6 +137,7 @@
<data name="Server.Label.Server" xml:space="preserve"><value>Server</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> <data name="Server.Label.Status" xml:space="preserve"><value>Status</value></data>
<data name="Server.Latency" xml:space="preserve"><value>{0} ms</value></data> <data name="Server.Latency" xml:space="preserve"><value>{0} ms</value></data>
<data name="Server.Log.SharingOff" xml:space="preserve"><value>Sharing off: nothing swept.</value><comment>long</comment></data>
<data name="Server.Log.UploadsSwept" xml:space="preserve"><value>Uploads expired: {0}, files removed: {1}, records removed: {2}, tokens removed: {3}</value><comment>long: job log line</comment></data> <data name="Server.Log.UploadsSwept" xml:space="preserve"><value>Uploads expired: {0}, files removed: {1}, records removed: {2}, tokens removed: {3}</value><comment>long: job log line</comment></data>
<data name="Server.Login.Cancel" xml:space="preserve"><value>Cancel</value></data> <data name="Server.Login.Cancel" xml:space="preserve"><value>Cancel</value></data>
<data name="Server.Login.Password" xml:space="preserve"><value>Password</value></data> <data name="Server.Login.Password" xml:space="preserve"><value>Password</value></data>
@@ -199,6 +201,28 @@
<data name="Server.Setting.TrailLength" xml:space="preserve"><value>Trail length</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.Transitions" xml:space="preserve"><value>Transitions</value></data>
<data name="Server.Setting.WhiteBalance" xml:space="preserve"><value>WB smoothing</value></data> <data name="Server.Setting.WhiteBalance" xml:space="preserve"><value>WB smoothing</value></data>
<data name="Server.Share.Addresses" xml:space="preserve"><value>Addresses</value></data>
<data name="Server.Share.AdminPanel" xml:space="preserve"><value>Admin panel</value></data>
<data name="Server.Share.AdminPassword" xml:space="preserve"><value>Admin password</value></data>
<data name="Server.Share.ClientCount.one" xml:space="preserve"><value>{0} client</value></data>
<data name="Server.Share.ClientCount.other" xml:space="preserve"><value>{0} clients</value></data>
<data name="Server.Share.ClientRow" xml:space="preserve"><value>{0} · {1} · {2}</value></data>
<data name="Server.Share.Clients" xml:space="preserve"><value>Clients</value></data>
<data name="Server.Share.Copy" xml:space="preserve"><value>Copy</value></data>
<data name="Server.Share.Fingerprint" xml:space="preserve"><value>Fingerprint</value></data>
<data name="Server.Share.Hide" xml:space="preserve"><value>Hide</value></data>
<data name="Server.Share.NoClients" xml:space="preserve"><value>None</value></data>
<data name="Server.Share.Ports" xml:space="preserve"><value>Ports</value></data>
<data name="Server.Share.PortsValue" xml:space="preserve"><value>HTTPS {0} · HTTP {1}</value></data>
<data name="Server.Share.RenderNode" xml:space="preserve"><value>Render node</value></data>
<data name="Server.Share.Restart" xml:space="preserve"><value>Restart</value></data>
<data name="Server.Share.Settings" xml:space="preserve"><value>Sharing settings</value></data>
<data name="Server.Share.Show" xml:space="preserve"><value>Show</value></data>
<data name="Server.Share.State.Failed" xml:space="preserve"><value>Not started</value></data>
<data name="Server.Share.State.Off" xml:space="preserve"><value>Not shared</value></data>
<data name="Server.Share.State.On" xml:space="preserve"><value>Sharing</value></data>
<data name="Server.Share.State.Starting" xml:space="preserve"><value>Starting…</value></data>
<data name="Server.Share.Title" xml:space="preserve"><value>This library</value></data>
<data name="Server.SignOut" xml:space="preserve"><value>Sign out</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.Connected" xml:space="preserve"><value>Connected</value></data>
<data name="Server.Status.Connecting" xml:space="preserve"><value>Connecting…</value></data> <data name="Server.Status.Connecting" xml:space="preserve"><value>Connecting…</value></data>
+18
View File
@@ -178,12 +178,28 @@
<data name="Settings.Rendering.Testing" xml:space="preserve"><value>testing…</value></data> <data name="Settings.Rendering.Testing" xml:space="preserve"><value>testing…</value></data>
<data name="Settings.ResetSection" xml:space="preserve"><value>Reset section</value></data> <data name="Settings.ResetSection" xml:space="preserve"><value>Reset section</value></data>
<data name="Settings.Search" xml:space="preserve"><value>Search settings</value></data> <data name="Settings.Search" xml:space="preserve"><value>Search settings</value></data>
<data name="Settings.Server.Announce" xml:space="preserve"><value>Announce on LAN</value></data>
<data name="Settings.Server.Cache" xml:space="preserve"><value>Server cache</value></data>
<data name="Settings.Server.Certificates" xml:space="preserve"><value>Trusted certificates</value></data> <data name="Settings.Server.Certificates" xml:space="preserve"><value>Trusted certificates</value></data>
<data name="Settings.Server.Default" xml:space="preserve"><value>Default server</value></data> <data name="Settings.Server.Default" xml:space="preserve"><value>Default server</value></data>
<data name="Settings.Server.Discovery" xml:space="preserve"><value>LAN discovery</value></data>
<data name="Settings.Server.ForgetName" xml:space="preserve"><value>Forget: {0}</value></data> <data name="Settings.Server.ForgetName" xml:space="preserve"><value>Forget: {0}</value></data>
<data name="Settings.Server.HttpPort" xml:space="preserve"><value>HTTP port</value></data>
<data name="Settings.Server.HttpsPort" xml:space="preserve"><value>HTTPS port</value></data>
<data name="Settings.Server.Known" xml:space="preserve"><value>Known servers</value></data>
<data name="Settings.Server.NoCertificates" xml:space="preserve"><value>None</value></data> <data name="Settings.Server.NoCertificates" xml:space="preserve"><value>None</value></data>
<data name="Settings.Server.OfferPc" xml:space="preserve"><value>Offer this PC</value></data> <data name="Settings.Server.OfferPc" xml:space="preserve"><value>Offer this PC</value></data>
<data name="Settings.Server.Offline" xml:space="preserve"><value>Offline</value></data>
<data name="Settings.Server.Originals" xml:space="preserve"><value>Originals folder</value></data>
<data name="Settings.Server.PublicHttpPort" xml:space="preserve"><value>Public HTTP port</value></data>
<data name="Settings.Server.PublicHttpsPort" xml:space="preserve"><value>Public HTTPS port</value></data>
<data name="Settings.Server.RenderNode" xml:space="preserve"><value>Render node</value></data> <data name="Settings.Server.RenderNode" xml:space="preserve"><value>Render node</value></data>
<data name="Settings.Server.ServerId" xml:space="preserve"><value>Server ID</value></data>
<data name="Settings.Server.Share" xml:space="preserve"><value>Sharing</value></data>
<data name="Settings.Server.ShareFolder" xml:space="preserve"><value>Server data</value></data>
<data name="Settings.Server.ShareLibrary" xml:space="preserve"><value>Share this library</value></data>
<data name="Settings.Server.ShareName" xml:space="preserve"><value>Library name</value></data>
<data name="Settings.Server.SignedIn" xml:space="preserve"><value>Signed in</value></data>
<data name="Settings.Storage.Clear" xml:space="preserve"><value>Clear</value></data> <data name="Settings.Storage.Clear" xml:space="preserve"><value>Clear</value></data>
<data name="Settings.Storage.ClearMessage" xml:space="preserve"><value>Spilled frames and decoded thumbnails are deleted and rebuilt when needed. Originals, proxies and renders are not touched.</value><comment>long</comment></data> <data name="Settings.Storage.ClearMessage" xml:space="preserve"><value>Spilled frames and decoded thumbnails are deleted and rebuilt when needed. Originals, proxies and renders are not touched.</value><comment>long</comment></data>
<data name="Settings.Storage.ClearTitle" xml:space="preserve"><value>Clear the cache?</value></data> <data name="Settings.Storage.ClearTitle" xml:space="preserve"><value>Clear the cache?</value></data>
@@ -206,11 +222,13 @@
<data name="Settings.Workspace.Changed" xml:space="preserve"><value>Workspace folder changed</value></data> <data name="Settings.Workspace.Changed" xml:space="preserve"><value>Workspace folder changed</value></data>
<data name="Settings.Workspace.ChooseTitle" xml:space="preserve"><value>Choose the workspace folder</value><comment>long; folder picker title</comment></data> <data name="Settings.Workspace.ChooseTitle" xml:space="preserve"><value>Choose the workspace folder</value><comment>long; folder picker title</comment></data>
<data name="Settings.Workspace.Folder" xml:space="preserve"><value>Folder</value></data> <data name="Settings.Workspace.Folder" xml:space="preserve"><value>Folder</value></data>
<data name="Settings.Workspace.Homes" xml:space="preserve"><value>Home folders</value></data>
<data name="Settings.Workspace.Kept" xml:space="preserve"><value>Kept versions</value></data> <data name="Settings.Workspace.Kept" xml:space="preserve"><value>Kept versions</value></data>
<data name="Settings.Workspace.NotChanged" xml:space="preserve"><value>Folder not changed</value></data> <data name="Settings.Workspace.NotChanged" xml:space="preserve"><value>Folder not changed</value></data>
<data name="Settings.Workspace.ProjectsFound" xml:space="preserve"><value>Projects found: {0}</value><comment>{0} count of the projects the folder chosen holds</comment></data> <data name="Settings.Workspace.ProjectsFound" xml:space="preserve"><value>Projects found: {0}</value><comment>{0} count of the projects the folder chosen holds</comment></data>
<data name="Settings.Workspace.ProjectsLeft" xml:space="preserve"><value>Projects left: {0}</value><comment>{0} count of the projects the folder in use keeps</comment></data> <data name="Settings.Workspace.ProjectsLeft" xml:space="preserve"><value>Projects left: {0}</value><comment>{0} count of the projects the folder in use keeps</comment></data>
<data name="Settings.Workspace.Sync" xml:space="preserve"><value>Sync</value></data> <data name="Settings.Workspace.Sync" xml:space="preserve"><value>Sync</value></data>
<data name="Settings.Workspace.ThisPc" xml:space="preserve"><value>This PC</value></data>
<data name="Settings.Workspace.Use" xml:space="preserve"><value>Use folder</value></data> <data name="Settings.Workspace.Use" xml:space="preserve"><value>Use folder</value></data>
<data name="Settings.Workspace.Versions.one" xml:space="preserve"><value>{0} version</value></data> <data name="Settings.Workspace.Versions.one" xml:space="preserve"><value>{0} version</value></data>
<data name="Settings.Workspace.Versions.other" xml:space="preserve"><value>{0} versions</value></data> <data name="Settings.Workspace.Versions.other" xml:space="preserve"><value>{0} versions</value></data>
+7
View File
@@ -5,6 +5,13 @@
<resheader name="reader"><value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</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> <resheader name="writer"><value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
<data name="Shell.AppName" xml:space="preserve"><value>Chronos</value><comment>invariant</comment></data> <data name="Shell.AppName" xml:space="preserve"><value>Chronos</value><comment>invariant</comment></data>
<data name="Shell.Homes.Clash" xml:space="preserve"><value>Server ID clash</value></data>
<data name="Shell.Homes.Moved.one" xml:space="preserve"><value>{0} project moved</value><comment>{0} count</comment></data>
<data name="Shell.Homes.Moved.other" xml:space="preserve"><value>{0} projects moved</value><comment>{0} count</comment></data>
<data name="Shell.Homes.Originals" xml:space="preserve"><value>Originals folder made</value></data>
<data name="Shell.Homes.Pending" xml:space="preserve"><value>Folders pending</value></data>
<data name="Shell.Homes.PendingText" xml:space="preserve"><value>Projects in use, or a workspace being moved, follow at the next start.</value><comment>long; toast message under Folders pending</comment></data>
<data name="Shell.Homes.Sorted" xml:space="preserve"><value>Folders sorted</value></data>
<data name="Shell.Job.Done" xml:space="preserve"><value>Job finished</value></data> <data name="Shell.Job.Done" xml:space="preserve"><value>Job finished</value></data>
<data name="Shell.Job.DonePlural.one" xml:space="preserve"><value>{0} job finished</value></data> <data name="Shell.Job.DonePlural.one" xml:space="preserve"><value>{0} job finished</value></data>
<data name="Shell.Job.DonePlural.other" xml:space="preserve"><value>{0} jobs finished</value></data> <data name="Shell.Job.DonePlural.other" xml:space="preserve"><value>{0} jobs finished</value></data>
+34 -1
View File
@@ -708,6 +708,18 @@
<data name="Tooltips.Server.Role.Editor" xml:space="preserve"><value>Editors import, edit and render; only admins manage users</value></data> <data name="Tooltips.Server.Role.Editor" xml:space="preserve"><value>Editors import, edit and render; only admins manage users</value></data>
<data name="Tooltips.Server.Role.Uploader" xml:space="preserve"><value>Uploaders send photos; editing needs an editor</value></data> <data name="Tooltips.Server.Role.Uploader" xml:space="preserve"><value>Uploaders send photos; editing needs an editor</value></data>
<data name="Tooltips.Server.Role.Viewer" xml:space="preserve"><value>Viewers browse and download</value></data> <data name="Tooltips.Server.Role.Viewer" xml:space="preserve"><value>Viewers browse and download</value></data>
<data name="Tooltips.Server.Share.AdminPanel" xml:space="preserve"><value>Open the admin panel in your browser to manage accounts; the browser warns once about the self-signed certificate: compare its fingerprint with the one here</value></data>
<data name="Tooltips.Server.Share.AdminPassword" xml:space="preserve"><value>Temporary password of the account admin; change it at the first sign-in, then this row goes</value></data>
<data name="Tooltips.Server.Share.Clients" xml:space="preserve"><value>Programs that used this library in the last 5 minutes, and the render nodes online</value></data>
<data name="Tooltips.Server.Share.Copy" xml:space="preserve"><value>Copy this address for the Uploader or another Chronos</value></data>
<data name="Tooltips.Server.Share.CopyFingerprint" xml:space="preserve"><value>Copy the fingerprint</value></data>
<data name="Tooltips.Server.Share.CopyPassword" xml:space="preserve"><value>Copy the temporary password</value></data>
<data name="Tooltips.Server.Share.Fingerprint" xml:space="preserve"><value>Clients see this fingerprint the first time they connect; it must match</value></data>
<data name="Tooltips.Server.Share.Ports" xml:space="preserve"><value>The ports the shared library listens on</value></data>
<data name="Tooltips.Server.Share.Restart" xml:space="preserve"><value>Try to start sharing again</value></data>
<data name="Tooltips.Server.Share.Settings" xml:space="preserve"><value>Open Settings › Server to share this library</value></data>
<data name="Tooltips.Server.Share.Show" xml:space="preserve"><value>Show or hide the password</value></data>
<data name="Tooltips.Server.Share.State" xml:space="preserve"><value>Whether other PCs and the Uploader can use this PC's library now</value></data>
<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.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.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.Status" xml:space="preserve"><value>Connection to the server</value></data>
@@ -780,10 +792,13 @@
<data name="Tooltips.Settings.DefaultServer" xml:space="preserve"><value>Server Chronos connects to at start; changing it signs out · Enter applies, Esc reverts</value></data> <data name="Tooltips.Settings.DefaultServer" xml:space="preserve"><value>Server Chronos connects to at start; changing it signs out · Enter applies, Esc reverts</value></data>
<data name="Tooltips.Settings.Diagnostics" xml:space="preserve"><value>Zip the logs, a system and codec report, settings and recent failed jobs into a folder you choose; passwords, tokens and photos are left out</value></data> <data name="Tooltips.Settings.Diagnostics" xml:space="preserve"><value>Zip the logs, a system and codec report, settings and recent failed jobs into a folder you choose; passwords, tokens and photos are left out</value></data>
<data name="Tooltips.Settings.DiagnosticsLogs" xml:space="preserve"><value>How much of the end of each log file the diagnostics bundle includes</value></data> <data name="Tooltips.Settings.DiagnosticsLogs" xml:space="preserve"><value>How much of the end of each log file the diagnostics bundle includes</value></data>
<data name="Tooltips.Settings.Discovery" xml:space="preserve"><value>Announce this library to Chronos programs on the local network</value></data>
<data name="Tooltips.Settings.EarlierData" xml:space="preserve"><value>Open the data this portable copy kept beside it before it ran from OneDrive. Chronos no longer uses it and leaves it as it is</value></data> <data name="Tooltips.Settings.EarlierData" xml:space="preserve"><value>Open the data this portable copy kept beside it before it ran from OneDrive. Chronos no longer uses it and leaves it as it is</value></data>
<data name="Tooltips.Settings.Export" xml:space="preserve"><value>Save every setting as JSON, without the session token</value></data> <data name="Tooltips.Settings.Export" xml:space="preserve"><value>Save every setting as JSON, without the session token</value></data>
<data name="Tooltips.Settings.FileTemplate" xml:space="preserve"><value>File name of each frame, for example {date}_{time}_{n:0000}; the extension is added · Enter applies, Esc reverts</value></data> <data name="Tooltips.Settings.FileTemplate" xml:space="preserve"><value>File name of each frame, for example {date}_{time}_{n:0000}; the extension is added · Enter applies, Esc reverts</value></data>
<data name="Tooltips.Settings.FolderTemplate" xml:space="preserve"><value>Archive folders, for example {year}/{date} {camera}; a slash starts a subfolder · Enter applies, Esc reverts</value></data> <data name="Tooltips.Settings.FolderTemplate" xml:space="preserve"><value>Archive folders, for example {year}/{date} {camera}; a slash starts a subfolder · Enter applies, Esc reverts</value></data>
<data name="Tooltips.Settings.HttpPort" xml:space="preserve"><value>Port the shared library listens on for HTTP (8080 by default); a change restarts sharing · Enter applies, Esc reverts</value></data>
<data name="Tooltips.Settings.HttpsPort" xml:space="preserve"><value>Port the shared library listens on for HTTPS (8443 by default); a change restarts sharing · Enter applies, Esc reverts</value></data>
<data name="Tooltips.Settings.Import" xml:space="preserve"><value>Load settings from a JSON file; the session and the window layout stay as they are</value></data> <data name="Tooltips.Settings.Import" xml:space="preserve"><value>Load settings from a JSON file; the session and the window layout stay as they are</value></data>
<data name="Tooltips.Settings.Install" xml:space="preserve"><value>Open the Microsoft Store page of this free or paid extension; Re-detect after installing it</value></data> <data name="Tooltips.Settings.Install" xml:space="preserve"><value>Open the Microsoft Store page of this free or paid extension; Re-detect after installing it</value></data>
<data name="Tooltips.Settings.InterfacePriority" xml:space="preserve"><value>While Chronos is in front, its interface runs ahead of the jobs so it stays fluid during renders and analyses</value></data> <data name="Tooltips.Settings.InterfacePriority" xml:space="preserve"><value>While Chronos is in front, its interface runs ahead of the jobs so it stays fluid during renders and analyses</value></data>
@@ -806,7 +821,17 @@
<data name="Tooltips.Settings.MissingCodec" xml:space="preserve"><value>Without this extension some formats are read only from their embedded preview, or not at all, on this PC</value></data> <data name="Tooltips.Settings.MissingCodec" xml:space="preserve"><value>Without this extension some formats are read only from their embedded preview, or not at all, on this PC</value></data>
<data name="Tooltips.Settings.Night" xml:space="preserve"><value>Frames whose mean brightness is at most this share of white count as night (star fields, night presets) · Enter applies, Esc reverts</value></data> <data name="Tooltips.Settings.Night" xml:space="preserve"><value>Frames whose mean brightness is at most this share of white count as night (star fields, night presets) · Enter applies, Esc reverts</value></data>
<data name="Tooltips.Settings.OpenDataFolder" xml:space="preserve"><value>Open the data folder in Explorer</value></data> <data name="Tooltips.Settings.OpenDataFolder" xml:space="preserve"><value>Open the data folder in Explorer</value></data>
<data name="Tooltips.Settings.OpenShareFolder" xml:space="preserve"><value>Open the shared library's data folder in Explorer</value></data>
<data name="Tooltips.Settings.OpenWorkspace" xml:space="preserve"><value>Show the workspace folder in Explorer</value></data> <data name="Tooltips.Settings.OpenWorkspace" xml:space="preserve"><value>Show the workspace folder in Explorer</value></data>
<data name="Tooltips.Settings.PublicPorts" xml:space="preserve"><value>Port clients reach when a router forwards another port to this PC; empty: the one above · Enter applies, Esc reverts</value></data>
<data name="Tooltips.Settings.Server.Cache" xml:space="preserve"><value>This server's proxies, render-node files and staged imports, inside the cache folder</value></data>
<data name="Tooltips.Settings.Server.Known" xml:space="preserve"><value>Servers this PC has signed in to, with the folders kept for each</value></data>
<data name="Tooltips.Settings.Server.Offline" xml:space="preserve"><value>Not signed in: its projects open from the workspace and wait to sync</value></data>
<data name="Tooltips.Settings.Server.OpenCache" xml:space="preserve"><value>Show this server's share of the cache in Explorer</value></data>
<data name="Tooltips.Settings.Server.OpenOriginals" xml:space="preserve"><value>Show the archive of this server's downloaded originals in Explorer</value></data>
<data name="Tooltips.Settings.Server.Originals" xml:space="preserve"><value>Where Download originals puts this server's photos, apart from this PC's archive</value></data>
<data name="Tooltips.Settings.Server.ServerId" xml:space="preserve"><value>Identifies the server even when its address or name changes: {0}</value><comment>{0} the whole id</comment></data>
<data name="Tooltips.Settings.Server.SignedIn" xml:space="preserve"><value>This PC is signed in to this server now</value></data>
<data name="Tooltips.Settings.Page.About" xml:space="preserve"><value>Version, build, system, licence, third-party code</value></data> <data name="Tooltips.Settings.Page.About" xml:space="preserve"><value>Version, build, system, licence, third-party code</value></data>
<data name="Tooltips.Settings.Page.Advanced" xml:space="preserve"><value>Portable mode, logs, diagnostics, database backup and restore, reset</value></data> <data name="Tooltips.Settings.Page.Advanced" xml:space="preserve"><value>Portable mode, logs, diagnostics, database backup and restore, reset</value></data>
<data name="Tooltips.Settings.Page.Analysis" xml:space="preserve"><value>Analysis width, night and star thresholds, deep analysis</value></data> <data name="Tooltips.Settings.Page.Analysis" xml:space="preserve"><value>Analysis width, night and star thresholds, deep analysis</value></data>
@@ -816,7 +841,7 @@
<data name="Tooltips.Settings.Page.Import" xml:space="preserve"><value>Session rules, verification, duplicates, after-import actions</value></data> <data name="Tooltips.Settings.Page.Import" xml:space="preserve"><value>Session rules, verification, duplicates, after-import actions</value></data>
<data name="Tooltips.Settings.OsNotifications" xml:space="preserve"><value>While Chronos is minimised or in the background, inserted cards, finished jobs and server messages also appear as Windows notifications</value></data> <data name="Tooltips.Settings.OsNotifications" xml:space="preserve"><value>While Chronos is minimised or in the background, inserted cards, finished jobs and server messages also appear as Windows notifications</value></data>
<data name="Tooltips.Settings.Page.Rendering" xml:space="preserve"><value>Quality profile, memory budget, parallelism, encoders</value></data> <data name="Tooltips.Settings.Page.Rendering" xml:space="preserve"><value>Quality profile, memory budget, parallelism, encoders</value></data>
<data name="Tooltips.Settings.Page.Server" xml:space="preserve"><value>Default server, render node, trusted certificates</value></data> <data name="Tooltips.Settings.Page.Server" xml:space="preserve"><value>Sharing, default server, render node, trusted certificates</value></data>
<data name="Tooltips.Settings.Page.Storage" xml:space="preserve"><value>Cache folder, thumbnails in memory, cache limit</value></data> <data name="Tooltips.Settings.Page.Storage" xml:space="preserve"><value>Cache folder, thumbnails in memory, cache limit</value></data>
<data name="Tooltips.Settings.Page.Updates" xml:space="preserve"><value>Update check on start</value></data> <data name="Tooltips.Settings.Page.Updates" xml:space="preserve"><value>Update check on start</value></data>
<data name="Tooltips.Settings.Page.Workspace" xml:space="preserve"><value>Where projects are edited on this PC: the folder, sync and versions kept</value></data> <data name="Tooltips.Settings.Page.Workspace" xml:space="preserve"><value>Where projects are edited on this PC: the folder, sync and versions kept</value></data>
@@ -845,6 +870,9 @@
<data name="Tooltips.Settings.Search" xml:space="preserve"><value>Find a setting by name</value></data> <data name="Tooltips.Settings.Search" xml:space="preserve"><value>Find a setting by name</value></data>
<data name="Tooltips.Settings.SelfTest" xml:space="preserve"><value>Encode a short synthetic clip with every encoder and report pass or fail and speed · about a minute</value></data> <data name="Tooltips.Settings.SelfTest" xml:space="preserve"><value>Encode a short synthetic clip with every encoder and report pass or fail and speed · about a minute</value></data>
<data name="Tooltips.Settings.SelfTestResult" xml:space="preserve"><value>Speed on the synthetic 1280×720 test clip</value></data> <data name="Tooltips.Settings.SelfTestResult" xml:space="preserve"><value>Speed on the synthetic 1280×720 test clip</value></data>
<data name="Tooltips.Settings.ShareFolder" xml:space="preserve"><value>Certificate, server settings, partial uploads and logs of the shared library; its accounts are in the index and its backups</value></data>
<data name="Tooltips.Settings.ShareLibrary" xml:space="preserve"><value>Other PCs and the Uploader on your network use this PC's library as a Chronos Server, while Chronos runs and you are signed in</value></data>
<data name="Tooltips.Settings.ShareName" xml:space="preserve"><value>The name clients see on sign-in and in LAN discovery; empty: this PC's name · Enter applies, Esc reverts</value></data>
<data name="Tooltips.Settings.SoftwareOnly" xml:space="preserve"><value>Always the Microsoft software H.264 encoder; slower, identical everywhere</value></data> <data name="Tooltips.Settings.SoftwareOnly" xml:space="preserve"><value>Always the Microsoft software H.264 encoder; slower, identical everywhere</value></data>
<data name="Tooltips.Settings.SkipCreateArchive" xml:space="preserve"><value>Remember the folder and leave it as it is</value></data> <data name="Tooltips.Settings.SkipCreateArchive" xml:space="preserve"><value>Remember the folder and leave it as it is</value></data>
<data name="Tooltips.Settings.Stars" xml:space="preserve"><value>Stars per megapixel from which a night frame counts as a star field · Enter applies, Esc reverts</value></data> <data name="Tooltips.Settings.Stars" xml:space="preserve"><value>Stars per megapixel from which a night frame counts as a star field · Enter applies, Esc reverts</value></data>
@@ -902,6 +930,7 @@
<data name="Tooltips.Setup.Update" xml:space="preserve"><value>Update the installed programs in place and apply the changes listed · your data is kept</value></data> <data name="Tooltips.Setup.Update" xml:space="preserve"><value>Update the installed programs in place and apply the changes listed · your data is kept</value></data>
<data name="Tooltips.Shell.CollapseRail" xml:space="preserve"><value>Collapse navigation to icons · Ctrl+B</value></data> <data name="Tooltips.Shell.CollapseRail" xml:space="preserve"><value>Collapse navigation to icons · Ctrl+B</value></data>
<data name="Tooltips.Shell.ExpandRail" xml:space="preserve"><value>Show navigation names · Ctrl+B</value></data> <data name="Tooltips.Shell.ExpandRail" xml:space="preserve"><value>Show navigation names · Ctrl+B</value></data>
<data name="Tooltips.Shell.Homes.Logs" xml:space="preserve"><value>Show the logs folder in Explorer: the log says which folder could not be sorted</value></data>
<data name="Tooltips.Shell.PauseJob" xml:space="preserve"><value>Pause the job shown; it continues from its checkpoint when resumed</value></data> <data name="Tooltips.Shell.PauseJob" xml:space="preserve"><value>Pause the job shown; it continues from its checkpoint when resumed</value></data>
<data name="Tooltips.Shell.StopJob" xml:space="preserve"><value>Stop the current job · it can be resumed later</value></data> <data name="Tooltips.Shell.StopJob" xml:space="preserve"><value>Stop the current job · it can be resumed later</value></data>
<data name="Tooltips.Uploader.AddWatchFolder" xml:space="preserve"><value>Add a folder to watch</value></data> <data name="Tooltips.Uploader.AddWatchFolder" xml:space="preserve"><value>Add a folder to watch</value></data>
@@ -996,6 +1025,10 @@
<data name="Tooltips.Settings.Workspace.TrashPlan.Keep" xml:space="preserve"><value>Keep the workspace's trash as it is</value></data> <data name="Tooltips.Settings.Workspace.TrashPlan.Keep" xml:space="preserve"><value>Keep the workspace's trash as it is</value></data>
<data name="Tooltips.Settings.Workspace.Used" xml:space="preserve"><value>What the workspace folder takes on its drive, its trash included</value></data> <data name="Tooltips.Settings.Workspace.Used" xml:space="preserve"><value>What the workspace folder takes on its drive, its trash included</value></data>
<data name="Tooltips.Settings.Workspace.Folder" xml:space="preserve"><value>The workspace's folder (a fast disk is best); Change uses another one, Move takes the projects along</value></data> <data name="Tooltips.Settings.Workspace.Folder" xml:space="preserve"><value>The workspace's folder (a fast disk is best); Change uses another one, Move takes the projects along</value></data>
<data name="Tooltips.Settings.Workspace.Homes" xml:space="preserve"><value>Each home keeps its projects in its own folder inside the workspace</value></data>
<data name="Tooltips.Settings.Workspace.OpenHome" xml:space="preserve"><value>Open this home's folder in Explorer</value></data>
<data name="Tooltips.Settings.Workspace.ServerHome" xml:space="preserve"><value>Projects of sequences on {0}: {1}</value><comment>{0} the server's name, {1} the folder</comment></data>
<data name="Tooltips.Settings.Workspace.ThisPc" xml:space="preserve"><value>Projects of sequences in this PC's archive: {0}</value><comment>{0} the folder</comment></data>
<data name="Tooltips.Settings.Workspace.Move" xml:space="preserve"><value>Move the workspace folder with its projects to another folder, after a plan; each file is checked before its source goes</value></data> <data name="Tooltips.Settings.Workspace.Move" xml:space="preserve"><value>Move the workspace folder with its projects to another folder, after a plan; each file is checked before its source goes</value></data>
<data name="Tooltips.Settings.Workspace.SizeLimit" xml:space="preserve"><value>Past this size, the media of the projects used longest ago are removed once they are in step with their home; their versions stay</value></data> <data name="Tooltips.Settings.Workspace.SizeLimit" xml:space="preserve"><value>Past this size, the media of the projects used longest ago are removed once they are in step with their home; their versions stay</value></data>
<data name="Tooltips.Settings.Workspace.NoLimit" xml:space="preserve"><value>The workspace grows as needed; only Clean after removes media</value></data> <data name="Tooltips.Settings.Workspace.NoLimit" xml:space="preserve"><value>The workspace grows as needed; only Clean after removes media</value></data>
+1
View File
@@ -862,6 +862,7 @@
<data name="Admin.Settings.Level.Warning" xml:space="preserve"><value>Avviso</value></data> <data name="Admin.Settings.Level.Warning" xml:space="preserve"><value>Avviso</value></data>
<data name="Admin.Settings.Limits" xml:space="preserve"><value>Limiti e conservazione</value></data> <data name="Admin.Settings.Limits" xml:space="preserve"><value>Limiti e conservazione</value></data>
<data name="Admin.Settings.Locked.Tip" xml:space="preserve"><value>Impostato dalla variabile d'ambiente {0}; rimuovi la variabile per cambiarlo qui</value></data> <data name="Admin.Settings.Locked.Tip" xml:space="preserve"><value>Impostato dalla variabile d'ambiente {0}; rimuovi la variabile per cambiarlo qui</value></data>
<data name="Admin.Settings.LockedByDesktop.Tip" xml:space="preserve"><value>Impostato in Chronos Desktop; cambialo nelle Impostazioni del PC che condivide questa libreria</value></data>
<data name="Admin.Settings.LogLevel" xml:space="preserve"><value>Livello file</value></data> <data name="Admin.Settings.LogLevel" xml:space="preserve"><value>Livello file</value></data>
<data name="Admin.Settings.LogLevel.Tip" xml:space="preserve"><value>Livello minimo scritto nei file di log; Debug e Trace aiutano a trovare i problemi ma riempiono i file in fretta</value></data> <data name="Admin.Settings.LogLevel.Tip" xml:space="preserve"><value>Livello minimo scritto nei file di log; Debug e Trace aiutano a trovare i problemi ma riempiono i file in fretta</value></data>
<data name="Admin.Settings.LogMaxFileMb" xml:space="preserve"><value>Dimensione file (MB)</value></data> <data name="Admin.Settings.LogMaxFileMb" xml:space="preserve"><value>Dimensione file (MB)</value></data>
+1
View File
@@ -285,6 +285,7 @@
<data name="Archive.Maintenance.Restore" xml:space="preserve"><value>Ripristina database…</value></data> <data name="Archive.Maintenance.Restore" xml:space="preserve"><value>Ripristina database…</value></data>
<data name="Archive.Maintenance.Run" xml:space="preserve"><value>Esegui manutenzione</value></data> <data name="Archive.Maintenance.Run" xml:space="preserve"><value>Esegui manutenzione</value></data>
<data name="Archive.Maintenance.Trash" xml:space="preserve"><value>Cestino…</value></data> <data name="Archive.Maintenance.Trash" xml:space="preserve"><value>Cestino…</value></data>
<data name="Archive.Name.ServerOriginals" xml:space="preserve"><value>{0} (server)</value></data>
<data name="Archive.Orphans.Count.one" xml:space="preserve"><value>{0:N0} problema</value></data> <data name="Archive.Orphans.Count.one" xml:space="preserve"><value>{0:N0} problema</value></data>
<data name="Archive.Orphans.Count.other" xml:space="preserve"><value>{0:N0} problemi</value></data> <data name="Archive.Orphans.Count.other" xml:space="preserve"><value>{0:N0} problemi</value></data>
<data name="Archive.Orphans.Failed" xml:space="preserve"><value>Ricerca degli orfani interrotta</value></data> <data name="Archive.Orphans.Failed" xml:space="preserve"><value>Ricerca degli orfani interrotta</value></data>
+7
View File
@@ -9,6 +9,8 @@
<data name="Errors.Archive.Open" xml:space="preserve"><value>Impossibile aprire l'archivio.</value></data> <data name="Errors.Archive.Open" xml:space="preserve"><value>Impossibile aprire l'archivio.</value></data>
<data name="Errors.Backup.Deferred" xml:space="preserve"><value>Non è stato possibile copiare o sostituire l'indice attuale; il ripristino riparte al prossimo avvio.</value></data> <data name="Errors.Backup.Deferred" xml:space="preserve"><value>Non è stato possibile copiare o sostituire l'indice attuale; il ripristino riparte al prossimo avvio.</value></data>
<data name="Errors.Backup.Unreadable" xml:space="preserve"><value>Questa copia non si può ripristinare; scegline un'altra.</value></data> <data name="Errors.Backup.Unreadable" xml:space="preserve"><value>Questa copia non si può ripristinare; scegline un'altra.</value></data>
<data name="Errors.Homes.Clash" xml:space="preserve"><value>{0} presenta l'ID di {1} con un altro certificato; verifica che non sia una copia di quel server.</value></data>
<data name="Errors.Homes.Failed" xml:space="preserve"><value>Non è stato possibile riordinare le cartelle: {0}. Non è stato eliminato nulla; Chronos riprova al prossimo avvio.</value></data>
<data name="Errors.Number.DecimalRange" xml:space="preserve"><value>Inserisci un numero da {0} a {1}.</value></data> <data name="Errors.Number.DecimalRange" xml:space="preserve"><value>Inserisci un numero da {0} a {1}.</value></data>
<data name="Errors.Number.Range" xml:space="preserve"><value>Inserisci un numero intero da {0} a {1}.</value></data> <data name="Errors.Number.Range" xml:space="preserve"><value>Inserisci un numero intero da {0} a {1}.</value></data>
<data name="Errors.Path.Empty" xml:space="preserve"><value>Inserisci una cartella.</value></data> <data name="Errors.Path.Empty" xml:space="preserve"><value>Inserisci una cartella.</value></data>
@@ -27,6 +29,10 @@
<data name="Errors.Render.Sequence" xml:space="preserve"><value>La sequenza da renderizzare non è più nell'archivio.</value></data> <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://chronos.example.com.</value></data> <data name="Errors.Server.Address" xml:space="preserve"><value>Inserisci l'indirizzo di un server, ad esempio nas.local:8443 o https://chronos.example.com.</value></data>
<data name="Errors.Settings.Import" xml:space="preserve"><value>Questo file non contiene impostazioni di Chronos.</value></data> <data name="Errors.Settings.Import" xml:space="preserve"><value>Questo file non contiene impostazioni di Chronos.</value></data>
<data name="Errors.Share.Failed" xml:space="preserve"><value>Impossibile avviare la condivisione: {0}</value></data>
<data name="Errors.Share.NoArchive" xml:space="preserve"><value>Apri o crea un archivio prima di condividerlo.</value></data>
<data name="Errors.Share.NotReady" xml:space="preserve"><value>La libreria non è ancora aperta; la condivisione parte appena lo è.</value></data>
<data name="Errors.Share.PortInUse" xml:space="preserve"><value>La porta {0} è usata da un altro programma. Scegline un'altra in Impostazioni › Server.</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.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.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.one" xml:space="preserve"><value>{0} render non è più su questo PC; gli altri sono stati inviati.</value></data>
@@ -34,6 +40,7 @@
<data name="Errors.Sync.Hash" xml:space="preserve"><value>{0} non è arrivato integro; scaricalo di nuovo.</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.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.NoArchive" xml:space="preserve"><value>Apri o crea un archivio su questo PC per ricevere gli originali.</value></data>
<data name="Errors.Sync.NoOriginalsFolder" xml:space="preserve"><value>Non è stato possibile creare una cartella per gli originali di {0}; verifica che il disco dell'archivio di questo PC sia scrivibile.</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.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.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.NothingSent" xml:space="preserve"><value>Nessun originale è arrivato al server: mancano qui o sono già in un'altra sequenza del server.</value></data>
+24
View File
@@ -83,6 +83,7 @@
<data name="Server.Error.NotFound" xml:space="preserve"><value>Non trovato.</value></data> <data name="Server.Error.NotFound" xml:space="preserve"><value>Non trovato.</value></data>
<data name="Server.Error.NotChronos" xml:space="preserve"><value>Questo indirizzo non è un Chronos Server.</value></data> <data name="Server.Error.NotChronos" xml:space="preserve"><value>Questo indirizzo non è un Chronos Server.</value></data>
<data name="Server.Error.NothingToConvert" xml:space="preserve"><value>Il piano non converte nulla: ogni foto è esclusa o ogni sequenza è bloccata.</value></data> <data name="Server.Error.NothingToConvert" xml:space="preserve"><value>Il piano non converte nulla: ogni foto è esclusa o ogni sequenza è bloccata.</value></data>
<data name="Server.Error.OwnLibrary" xml:space="preserve"><value>Questo indirizzo è la libreria condivisa di questo PC, già aperta qui.</value><comment>long</comment></data>
<data name="Server.Error.PasswordChangeRequired" xml:space="preserve"><value>Cambia prima la password.</value></data> <data name="Server.Error.PasswordChangeRequired" xml:space="preserve"><value>Cambia prima la password.</value></data>
<data name="Server.Error.PhotoRemoved" xml:space="preserve"><value>La foto è stata eliminata dalla sequenza mentre veniva caricata, quindi non è stata aggiunta.</value><comment>long</comment></data> <data name="Server.Error.PhotoRemoved" xml:space="preserve"><value>La foto è stata eliminata dalla sequenza mentre veniva caricata, quindi non è stata aggiunta.</value><comment>long</comment></data>
<data name="Server.Error.PhotoUnreadable" xml:space="preserve"><value>Impossibile leggere {0}: senza il suo hash le altre copie non saprebbero che è stato eliminato. Chiudi il programma che lo usa o controlla i permessi, poi riprova.</value></data> <data name="Server.Error.PhotoUnreadable" xml:space="preserve"><value>Impossibile leggere {0}: senza il suo hash le altre copie non saprebbero che è stato eliminato. Chiudi il programma che lo usa o controlla i permessi, poi riprova.</value></data>
@@ -134,6 +135,7 @@
<data name="Server.Label.Server" xml:space="preserve"><value>Server</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> <data name="Server.Label.Status" xml:space="preserve"><value>Stato</value></data>
<data name="Server.Latency" xml:space="preserve"><value>{0} ms</value></data> <data name="Server.Latency" xml:space="preserve"><value>{0} ms</value></data>
<data name="Server.Log.SharingOff" xml:space="preserve"><value>Condivisione spenta: nulla da ripulire.</value><comment>long</comment></data>
<data name="Server.Log.UploadsSwept" xml:space="preserve"><value>Caricamenti scaduti: {0}, file rimossi: {1}, record rimossi: {2}, token rimossi: {3}</value><comment>long: job log line</comment></data> <data name="Server.Log.UploadsSwept" xml:space="preserve"><value>Caricamenti scaduti: {0}, file rimossi: {1}, record rimossi: {2}, token rimossi: {3}</value><comment>long: job log line</comment></data>
<data name="Server.Login.Cancel" xml:space="preserve"><value>Annulla</value></data> <data name="Server.Login.Cancel" xml:space="preserve"><value>Annulla</value></data>
<data name="Server.Login.Password" xml:space="preserve"><value>Password</value></data> <data name="Server.Login.Password" xml:space="preserve"><value>Password</value></data>
@@ -197,6 +199,28 @@
<data name="Server.Setting.TrailLength" xml:space="preserve"><value>Lunghezza scie</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.Transitions" xml:space="preserve"><value>Transizioni</value></data>
<data name="Server.Setting.WhiteBalance" xml:space="preserve"><value>Livellamento WB</value></data> <data name="Server.Setting.WhiteBalance" xml:space="preserve"><value>Livellamento WB</value></data>
<data name="Server.Share.Addresses" xml:space="preserve"><value>Indirizzi</value></data>
<data name="Server.Share.AdminPanel" xml:space="preserve"><value>Pannello admin</value></data>
<data name="Server.Share.AdminPassword" xml:space="preserve"><value>Password admin</value></data>
<data name="Server.Share.ClientCount.one" xml:space="preserve"><value>{0} client</value></data>
<data name="Server.Share.ClientCount.other" xml:space="preserve"><value>{0} client</value></data>
<data name="Server.Share.ClientRow" xml:space="preserve"><value>{0} · {1} · {2}</value></data>
<data name="Server.Share.Clients" xml:space="preserve"><value>Client</value></data>
<data name="Server.Share.Copy" xml:space="preserve"><value>Copia</value></data>
<data name="Server.Share.Fingerprint" xml:space="preserve"><value>Impronta</value></data>
<data name="Server.Share.Hide" xml:space="preserve"><value>Nascondi</value></data>
<data name="Server.Share.NoClients" xml:space="preserve"><value>Nessuno</value></data>
<data name="Server.Share.Ports" xml:space="preserve"><value>Porte</value></data>
<data name="Server.Share.PortsValue" xml:space="preserve"><value>HTTPS {0} · HTTP {1}</value></data>
<data name="Server.Share.RenderNode" xml:space="preserve"><value>Nodo di rendering</value></data>
<data name="Server.Share.Restart" xml:space="preserve"><value>Riavvia</value></data>
<data name="Server.Share.Settings" xml:space="preserve"><value>Impostazioni condivisione</value></data>
<data name="Server.Share.Show" xml:space="preserve"><value>Mostra</value></data>
<data name="Server.Share.State.Failed" xml:space="preserve"><value>Non avviata</value></data>
<data name="Server.Share.State.Off" xml:space="preserve"><value>Non condivisa</value></data>
<data name="Server.Share.State.On" xml:space="preserve"><value>In condivisione</value></data>
<data name="Server.Share.State.Starting" xml:space="preserve"><value>Avvio…</value></data>
<data name="Server.Share.Title" xml:space="preserve"><value>Questa libreria</value></data>
<data name="Server.SignOut" xml:space="preserve"><value>Esci</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.Connected" xml:space="preserve"><value>Connesso</value></data>
<data name="Server.Status.Connecting" xml:space="preserve"><value>Connessione…</value></data> <data name="Server.Status.Connecting" xml:space="preserve"><value>Connessione…</value></data>
+18
View File
@@ -175,12 +175,28 @@
<data name="Settings.Rendering.Testing" xml:space="preserve"><value>in prova…</value></data> <data name="Settings.Rendering.Testing" xml:space="preserve"><value>in prova…</value></data>
<data name="Settings.ResetSection" xml:space="preserve"><value>Ripristina sezione</value></data> <data name="Settings.ResetSection" xml:space="preserve"><value>Ripristina sezione</value></data>
<data name="Settings.Search" xml:space="preserve"><value>Cerca impostazioni</value></data> <data name="Settings.Search" xml:space="preserve"><value>Cerca impostazioni</value></data>
<data name="Settings.Server.Announce" xml:space="preserve"><value>Annuncia in LAN</value></data>
<data name="Settings.Server.Cache" xml:space="preserve"><value>Cache del server</value></data>
<data name="Settings.Server.Certificates" xml:space="preserve"><value>Certificati attendibili</value></data> <data name="Settings.Server.Certificates" xml:space="preserve"><value>Certificati attendibili</value></data>
<data name="Settings.Server.Default" xml:space="preserve"><value>Server predefinito</value></data> <data name="Settings.Server.Default" xml:space="preserve"><value>Server predefinito</value></data>
<data name="Settings.Server.Discovery" xml:space="preserve"><value>Rilevamento LAN</value></data>
<data name="Settings.Server.ForgetName" xml:space="preserve"><value>Dimentica: {0}</value></data> <data name="Settings.Server.ForgetName" xml:space="preserve"><value>Dimentica: {0}</value></data>
<data name="Settings.Server.HttpPort" xml:space="preserve"><value>Porta HTTP</value></data>
<data name="Settings.Server.HttpsPort" xml:space="preserve"><value>Porta HTTPS</value></data>
<data name="Settings.Server.Known" xml:space="preserve"><value>Server noti</value></data>
<data name="Settings.Server.NoCertificates" xml:space="preserve"><value>Nessuno</value></data> <data name="Settings.Server.NoCertificates" xml:space="preserve"><value>Nessuno</value></data>
<data name="Settings.Server.OfferPc" xml:space="preserve"><value>Offri questo PC</value></data> <data name="Settings.Server.OfferPc" xml:space="preserve"><value>Offri questo PC</value></data>
<data name="Settings.Server.Offline" xml:space="preserve"><value>Non in linea</value></data>
<data name="Settings.Server.Originals" xml:space="preserve"><value>Cartella originali</value></data>
<data name="Settings.Server.PublicHttpPort" xml:space="preserve"><value>Porta HTTP pubblica</value></data>
<data name="Settings.Server.PublicHttpsPort" xml:space="preserve"><value>Porta HTTPS pubblica</value></data>
<data name="Settings.Server.RenderNode" xml:space="preserve"><value>Nodo di rendering</value></data> <data name="Settings.Server.RenderNode" xml:space="preserve"><value>Nodo di rendering</value></data>
<data name="Settings.Server.ServerId" xml:space="preserve"><value>ID server</value></data>
<data name="Settings.Server.Share" xml:space="preserve"><value>Condivisione</value></data>
<data name="Settings.Server.ShareFolder" xml:space="preserve"><value>Dati server</value></data>
<data name="Settings.Server.ShareLibrary" xml:space="preserve"><value>Condividi questa libreria</value></data>
<data name="Settings.Server.ShareName" xml:space="preserve"><value>Nome libreria</value></data>
<data name="Settings.Server.SignedIn" xml:space="preserve"><value>Connesso</value></data>
<data name="Settings.Storage.Clear" xml:space="preserve"><value>Svuota</value></data> <data name="Settings.Storage.Clear" xml:space="preserve"><value>Svuota</value></data>
<data name="Settings.Storage.ClearMessage" xml:space="preserve"><value>I fotogrammi temporanei e le miniature vengono eliminati e ricreati quando servono. Originali, proxy ed esportazioni restano intatti.</value></data> <data name="Settings.Storage.ClearMessage" xml:space="preserve"><value>I fotogrammi temporanei e le miniature vengono eliminati e ricreati quando servono. Originali, proxy ed esportazioni restano intatti.</value></data>
<data name="Settings.Storage.ClearTitle" xml:space="preserve"><value>Svuotare la cache?</value></data> <data name="Settings.Storage.ClearTitle" xml:space="preserve"><value>Svuotare la cache?</value></data>
@@ -203,11 +219,13 @@
<data name="Settings.Workspace.Changed" xml:space="preserve"><value>Cartella cambiata</value></data> <data name="Settings.Workspace.Changed" xml:space="preserve"><value>Cartella cambiata</value></data>
<data name="Settings.Workspace.ChooseTitle" xml:space="preserve"><value>Scegli la cartella dello spazio di lavoro</value></data> <data name="Settings.Workspace.ChooseTitle" xml:space="preserve"><value>Scegli la cartella dello spazio di lavoro</value></data>
<data name="Settings.Workspace.Folder" xml:space="preserve"><value>Cartella</value></data> <data name="Settings.Workspace.Folder" xml:space="preserve"><value>Cartella</value></data>
<data name="Settings.Workspace.Homes" xml:space="preserve"><value>Cartelle per origine</value></data>
<data name="Settings.Workspace.Kept" xml:space="preserve"><value>Versioni tenute</value></data> <data name="Settings.Workspace.Kept" xml:space="preserve"><value>Versioni tenute</value></data>
<data name="Settings.Workspace.NotChanged" xml:space="preserve"><value>Cartella non cambiata</value></data> <data name="Settings.Workspace.NotChanged" xml:space="preserve"><value>Cartella non cambiata</value></data>
<data name="Settings.Workspace.ProjectsFound" xml:space="preserve"><value>Progetti trovati: {0}</value></data> <data name="Settings.Workspace.ProjectsFound" xml:space="preserve"><value>Progetti trovati: {0}</value></data>
<data name="Settings.Workspace.ProjectsLeft" xml:space="preserve"><value>Progetti lasciati: {0}</value></data> <data name="Settings.Workspace.ProjectsLeft" xml:space="preserve"><value>Progetti lasciati: {0}</value></data>
<data name="Settings.Workspace.Sync" xml:space="preserve"><value>Sincronizzazione</value></data> <data name="Settings.Workspace.Sync" xml:space="preserve"><value>Sincronizzazione</value></data>
<data name="Settings.Workspace.ThisPc" xml:space="preserve"><value>Questo PC</value></data>
<data name="Settings.Workspace.Use" xml:space="preserve"><value>Usa cartella</value></data> <data name="Settings.Workspace.Use" xml:space="preserve"><value>Usa cartella</value></data>
<data name="Settings.Workspace.Versions.one" xml:space="preserve"><value>{0} versione</value></data> <data name="Settings.Workspace.Versions.one" xml:space="preserve"><value>{0} versione</value></data>
<data name="Settings.Workspace.Versions.other" xml:space="preserve"><value>{0} versioni</value></data> <data name="Settings.Workspace.Versions.other" xml:space="preserve"><value>{0} versioni</value></data>
+7
View File
@@ -4,6 +4,13 @@
<resheader name="version"><value>2.0</value></resheader> <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="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> <resheader name="writer"><value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
<data name="Shell.Homes.Clash" xml:space="preserve"><value>ID server in conflitto</value></data>
<data name="Shell.Homes.Moved.one" xml:space="preserve"><value>{0} progetto spostato</value></data>
<data name="Shell.Homes.Moved.other" xml:space="preserve"><value>{0} progetti spostati</value></data>
<data name="Shell.Homes.Originals" xml:space="preserve"><value>Cartella originali creata</value></data>
<data name="Shell.Homes.Pending" xml:space="preserve"><value>Cartelle in attesa</value></data>
<data name="Shell.Homes.PendingText" xml:space="preserve"><value>I progetti in uso, o uno spazio di lavoro in spostamento, seguono al prossimo avvio.</value></data>
<data name="Shell.Homes.Sorted" xml:space="preserve"><value>Cartelle riordinate</value></data>
<data name="Shell.Job.Done" xml:space="preserve"><value>Attività completata</value></data> <data name="Shell.Job.Done" xml:space="preserve"><value>Attività completata</value></data>
<data name="Shell.Job.DonePlural.one" xml:space="preserve"><value>{0} attività completata</value></data> <data name="Shell.Job.DonePlural.one" xml:space="preserve"><value>{0} attività completata</value></data>
<data name="Shell.Job.DonePlural.other" xml:space="preserve"><value>{0} attività completate</value></data> <data name="Shell.Job.DonePlural.other" xml:space="preserve"><value>{0} attività completate</value></data>
+34 -1
View File
@@ -779,6 +779,18 @@
<data name="Tooltips.Server.Role.Editor" xml:space="preserve"><value>Gli editor importano, modificano ed esportano; solo gli amministratori gestiscono gli utenti</value></data> <data name="Tooltips.Server.Role.Editor" xml:space="preserve"><value>Gli editor importano, modificano ed esportano; solo gli amministratori gestiscono gli utenti</value></data>
<data name="Tooltips.Server.Role.Uploader" xml:space="preserve"><value>I caricatori inviano foto; per modificare serve un editor</value></data> <data name="Tooltips.Server.Role.Uploader" xml:space="preserve"><value>I caricatori inviano foto; per modificare serve un editor</value></data>
<data name="Tooltips.Server.Role.Viewer" xml:space="preserve"><value>I visualizzatori sfogliano e scaricano</value></data> <data name="Tooltips.Server.Role.Viewer" xml:space="preserve"><value>I visualizzatori sfogliano e scaricano</value></data>
<data name="Tooltips.Server.Share.AdminPanel" xml:space="preserve"><value>Apri il pannello admin nel browser per gestire gli account; il browser avvisa una volta del certificato autofirmato: confronta l'impronta con quella qui</value></data>
<data name="Tooltips.Server.Share.AdminPassword" xml:space="preserve"><value>Password temporanea dell'account admin; cambiala al primo accesso, poi questa riga sparisce</value></data>
<data name="Tooltips.Server.Share.Clients" xml:space="preserve"><value>Programmi che hanno usato questa libreria negli ultimi 5 minuti, e i nodi di rendering online</value></data>
<data name="Tooltips.Server.Share.Copy" xml:space="preserve"><value>Copia questo indirizzo per l'Uploader o un altro Chronos</value></data>
<data name="Tooltips.Server.Share.CopyFingerprint" xml:space="preserve"><value>Copia l'impronta</value></data>
<data name="Tooltips.Server.Share.CopyPassword" xml:space="preserve"><value>Copia la password temporanea</value></data>
<data name="Tooltips.Server.Share.Fingerprint" xml:space="preserve"><value>I client vedono questa impronta la prima volta che si connettono; deve coincidere</value></data>
<data name="Tooltips.Server.Share.Ports" xml:space="preserve"><value>Le porte su cui ascolta la libreria condivisa</value></data>
<data name="Tooltips.Server.Share.Restart" xml:space="preserve"><value>Riprova ad avviare la condivisione</value></data>
<data name="Tooltips.Server.Share.Settings" xml:space="preserve"><value>Apri Impostazioni › Server per condividere questa libreria</value></data>
<data name="Tooltips.Server.Share.Show" xml:space="preserve"><value>Mostra o nascondi la password</value></data>
<data name="Tooltips.Server.Share.State" xml:space="preserve"><value>Se altri PC e l'Uploader possono usare ora la libreria di questo PC</value></data>
<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.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.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.Status" xml:space="preserve"><value>Connessione al server</value></data>
@@ -851,10 +863,13 @@
<data name="Tooltips.Settings.DefaultServer" xml:space="preserve"><value>Server a cui Chronos si connette all'avvio; cambiarlo chiude l'accesso · Invio applica, Esc annulla</value></data> <data name="Tooltips.Settings.DefaultServer" xml:space="preserve"><value>Server a cui Chronos si connette all'avvio; cambiarlo chiude l'accesso · Invio applica, Esc annulla</value></data>
<data name="Tooltips.Settings.Diagnostics" xml:space="preserve"><value>Comprime log, rapporto su sistema e codec, impostazioni e attività fallite di recente in una cartella a tua scelta; password, token e foto restano fuori</value></data> <data name="Tooltips.Settings.Diagnostics" xml:space="preserve"><value>Comprime log, rapporto su sistema e codec, impostazioni e attività fallite di recente in una cartella a tua scelta; password, token e foto restano fuori</value></data>
<data name="Tooltips.Settings.DiagnosticsLogs" xml:space="preserve"><value>Quanta parte finale di ogni file di log include il pacchetto di diagnostica</value></data> <data name="Tooltips.Settings.DiagnosticsLogs" xml:space="preserve"><value>Quanta parte finale di ogni file di log include il pacchetto di diagnostica</value></data>
<data name="Tooltips.Settings.Discovery" xml:space="preserve"><value>Annuncia questa libreria ai programmi Chronos della rete locale</value></data>
<data name="Tooltips.Settings.EarlierData" xml:space="preserve"><value>Apri i dati che questa copia portatile teneva accanto a sé prima di trovarsi in OneDrive. Chronos non li usa più e li lascia com'erano</value></data> <data name="Tooltips.Settings.EarlierData" xml:space="preserve"><value>Apri i dati che questa copia portatile teneva accanto a sé prima di trovarsi in OneDrive. Chronos non li usa più e li lascia com'erano</value></data>
<data name="Tooltips.Settings.Export" xml:space="preserve"><value>Salva tutte le impostazioni in JSON, senza il token di sessione</value></data> <data name="Tooltips.Settings.Export" xml:space="preserve"><value>Salva tutte le impostazioni in JSON, senza il token di sessione</value></data>
<data name="Tooltips.Settings.FileTemplate" xml:space="preserve"><value>Nome del file di ogni fotogramma, ad esempio {date}_{time}_{n:0000}; l'estensione viene aggiunta · Invio applica, Esc annulla</value></data> <data name="Tooltips.Settings.FileTemplate" xml:space="preserve"><value>Nome del file di ogni fotogramma, ad esempio {date}_{time}_{n:0000}; l'estensione viene aggiunta · Invio applica, Esc annulla</value></data>
<data name="Tooltips.Settings.FolderTemplate" xml:space="preserve"><value>Cartelle dell'archivio, ad esempio {year}/{date} {camera}; la barra crea una sottocartella · Invio applica, Esc annulla</value></data> <data name="Tooltips.Settings.FolderTemplate" xml:space="preserve"><value>Cartelle dell'archivio, ad esempio {year}/{date} {camera}; la barra crea una sottocartella · Invio applica, Esc annulla</value></data>
<data name="Tooltips.Settings.HttpPort" xml:space="preserve"><value>Porta su cui la libreria condivisa ascolta in HTTP (8080 di default); cambiarla riavvia la condivisione · Invio applica, Esc annulla</value></data>
<data name="Tooltips.Settings.HttpsPort" xml:space="preserve"><value>Porta su cui la libreria condivisa ascolta in HTTPS (8443 di default); cambiarla riavvia la condivisione · Invio applica, Esc annulla</value></data>
<data name="Tooltips.Settings.Import" xml:space="preserve"><value>Carica le impostazioni da un file JSON; la sessione e la disposizione della finestra restano invariate</value></data> <data name="Tooltips.Settings.Import" xml:space="preserve"><value>Carica le impostazioni da un file JSON; la sessione e la disposizione della finestra restano invariate</value></data>
<data name="Tooltips.Settings.Install" xml:space="preserve"><value>Apri la pagina del Microsoft Store di questa estensione, gratuita o a pagamento; dopo averla installata premi Rileva di nuovo</value></data> <data name="Tooltips.Settings.Install" xml:space="preserve"><value>Apri la pagina del Microsoft Store di questa estensione, gratuita o a pagamento; dopo averla installata premi Rileva di nuovo</value></data>
<data name="Tooltips.Settings.InterfacePriority" xml:space="preserve"><value>Mentre Chronos è in primo piano, l'interfaccia ha la precedenza sulle attività e resta fluida durante rendering e analisi</value></data> <data name="Tooltips.Settings.InterfacePriority" xml:space="preserve"><value>Mentre Chronos è in primo piano, l'interfaccia ha la precedenza sulle attività e resta fluida durante rendering e analisi</value></data>
@@ -877,7 +892,17 @@
<data name="Tooltips.Settings.MissingCodec" xml:space="preserve"><value>Senza questa estensione alcuni formati si leggono solo dall'anteprima incorporata, o per niente, su questo PC</value></data> <data name="Tooltips.Settings.MissingCodec" xml:space="preserve"><value>Senza questa estensione alcuni formati si leggono solo dall'anteprima incorporata, o per niente, su questo PC</value></data>
<data name="Tooltips.Settings.Night" xml:space="preserve"><value>I fotogrammi con luminosità media al massimo pari a questa quota del bianco contano come notturni (campi stellari, preset notturni) · Invio applica, Esc annulla</value></data> <data name="Tooltips.Settings.Night" xml:space="preserve"><value>I fotogrammi con luminosità media al massimo pari a questa quota del bianco contano come notturni (campi stellari, preset notturni) · Invio applica, Esc annulla</value></data>
<data name="Tooltips.Settings.OpenDataFolder" xml:space="preserve"><value>Apri la cartella dati in Esplora file</value></data> <data name="Tooltips.Settings.OpenDataFolder" xml:space="preserve"><value>Apri la cartella dati in Esplora file</value></data>
<data name="Tooltips.Settings.OpenShareFolder" xml:space="preserve"><value>Apri in Esplora risorse la cartella dati della libreria condivisa</value></data>
<data name="Tooltips.Settings.OpenWorkspace" xml:space="preserve"><value>Mostra la cartella dello spazio di lavoro in Esplora file</value></data> <data name="Tooltips.Settings.OpenWorkspace" xml:space="preserve"><value>Mostra la cartella dello spazio di lavoro in Esplora file</value></data>
<data name="Tooltips.Settings.PublicPorts" xml:space="preserve"><value>Porta che i client raggiungono quando un router inoltra un'altra porta a questo PC; vuoto: quella sopra · Invio applica, Esc annulla</value></data>
<data name="Tooltips.Settings.Server.Cache" xml:space="preserve"><value>Proxy, file del nodo di rendering e importazioni in attesa di questo server, dentro la cartella della cache</value></data>
<data name="Tooltips.Settings.Server.Known" xml:space="preserve"><value>I server a cui questo PC ha effettuato l'accesso, con le cartelle tenute per ciascuno</value></data>
<data name="Tooltips.Settings.Server.Offline" xml:space="preserve"><value>Accesso non effettuato: i suoi progetti si aprono dallo spazio di lavoro e attendono la sincronizzazione</value></data>
<data name="Tooltips.Settings.Server.OpenCache" xml:space="preserve"><value>Mostra la parte della cache di questo server in Esplora file</value></data>
<data name="Tooltips.Settings.Server.OpenOriginals" xml:space="preserve"><value>Mostra l'archivio degli originali scaricati da questo server in Esplora file</value></data>
<data name="Tooltips.Settings.Server.Originals" xml:space="preserve"><value>Dove Scarica originali mette le foto di questo server, separate dall'archivio di questo PC</value></data>
<data name="Tooltips.Settings.Server.ServerId" xml:space="preserve"><value>Identifica il server anche quando cambiano indirizzo o nome: {0}</value></data>
<data name="Tooltips.Settings.Server.SignedIn" xml:space="preserve"><value>Questo PC ha effettuato l'accesso a questo server ora</value></data>
<data name="Tooltips.Settings.OsNotifications" xml:space="preserve"><value>Quando Chronos è ridotto a icona o in secondo piano, schede inserite, attività finite e messaggi del server compaiono anche come notifiche di Windows</value></data> <data name="Tooltips.Settings.OsNotifications" xml:space="preserve"><value>Quando Chronos è ridotto a icona o in secondo piano, schede inserite, attività finite e messaggi del server compaiono anche come notifiche di Windows</value></data>
<data name="Tooltips.Settings.Page.About" xml:space="preserve"><value>Versione, build, sistema, licenza, codice di terze parti</value></data> <data name="Tooltips.Settings.Page.About" xml:space="preserve"><value>Versione, build, sistema, licenza, codice di terze parti</value></data>
<data name="Tooltips.Settings.Page.Advanced" xml:space="preserve"><value>Modalità portatile, log, diagnostica, backup e ripristino del database, valori predefiniti</value></data> <data name="Tooltips.Settings.Page.Advanced" xml:space="preserve"><value>Modalità portatile, log, diagnostica, backup e ripristino del database, valori predefiniti</value></data>
@@ -887,7 +912,7 @@
<data name="Tooltips.Settings.Page.General" xml:space="preserve"><value>Lingua, tema, avvio, notifiche</value></data> <data name="Tooltips.Settings.Page.General" xml:space="preserve"><value>Lingua, tema, avvio, notifiche</value></data>
<data name="Tooltips.Settings.Page.Import" xml:space="preserve"><value>Regole delle sessioni, verifica, duplicati, azioni dopo l'importazione</value></data> <data name="Tooltips.Settings.Page.Import" xml:space="preserve"><value>Regole delle sessioni, verifica, duplicati, azioni dopo l'importazione</value></data>
<data name="Tooltips.Settings.Page.Rendering" xml:space="preserve"><value>Profilo di qualità, memoria, parallelismo, encoder</value></data> <data name="Tooltips.Settings.Page.Rendering" xml:space="preserve"><value>Profilo di qualità, memoria, parallelismo, encoder</value></data>
<data name="Tooltips.Settings.Page.Server" xml:space="preserve"><value>Server predefinito, nodo di rendering, certificati attendibili</value></data> <data name="Tooltips.Settings.Page.Server" xml:space="preserve"><value>Condivisione, server predefinito, nodo di rendering, certificati attendibili</value></data>
<data name="Tooltips.Settings.Page.Storage" xml:space="preserve"><value>Cartella della cache, miniature in memoria, limite della cache</value></data> <data name="Tooltips.Settings.Page.Storage" xml:space="preserve"><value>Cartella della cache, miniature in memoria, limite della cache</value></data>
<data name="Tooltips.Settings.Page.Updates" xml:space="preserve"><value>Controllo degli aggiornamenti all'avvio</value></data> <data name="Tooltips.Settings.Page.Updates" xml:space="preserve"><value>Controllo degli aggiornamenti all'avvio</value></data>
<data name="Tooltips.Settings.Page.Workspace" xml:space="preserve"><value>Dove si modificano i progetti su questo PC: cartella, sincronizzazione e versioni tenute</value></data> <data name="Tooltips.Settings.Page.Workspace" xml:space="preserve"><value>Dove si modificano i progetti su questo PC: cartella, sincronizzazione e versioni tenute</value></data>
@@ -916,6 +941,9 @@
<data name="Tooltips.Settings.Search" xml:space="preserve"><value>Trova un'impostazione per nome</value></data> <data name="Tooltips.Settings.Search" xml:space="preserve"><value>Trova un'impostazione per nome</value></data>
<data name="Tooltips.Settings.SelfTest" xml:space="preserve"><value>Codifica una breve clip sintetica con ogni encoder e ne riporta esito e velocità · circa un minuto</value></data> <data name="Tooltips.Settings.SelfTest" xml:space="preserve"><value>Codifica una breve clip sintetica con ogni encoder e ne riporta esito e velocità · circa un minuto</value></data>
<data name="Tooltips.Settings.SelfTestResult" xml:space="preserve"><value>Velocità sulla clip di prova sintetica 1280×720</value></data> <data name="Tooltips.Settings.SelfTestResult" xml:space="preserve"><value>Velocità sulla clip di prova sintetica 1280×720</value></data>
<data name="Tooltips.Settings.ShareFolder" xml:space="preserve"><value>Certificato, impostazioni del server, upload parziali e log della libreria condivisa; i suoi account sono nell'indice e nei suoi backup</value></data>
<data name="Tooltips.Settings.ShareLibrary" xml:space="preserve"><value>Altri PC e l'Uploader della tua rete usano la libreria di questo PC come Chronos Server, finché Chronos è aperto e hai effettuato l'accesso</value></data>
<data name="Tooltips.Settings.ShareName" xml:space="preserve"><value>Il nome che i client vedono all'accesso e nel rilevamento LAN; vuoto: il nome di questo PC · Invio applica, Esc annulla</value></data>
<data name="Tooltips.Settings.SoftwareOnly" xml:space="preserve"><value>Sempre l'encoder software H.264 di Microsoft; più lento, identico ovunque</value></data> <data name="Tooltips.Settings.SoftwareOnly" xml:space="preserve"><value>Sempre l'encoder software H.264 di Microsoft; più lento, identico ovunque</value></data>
<data name="Tooltips.Settings.SkipCreateArchive" xml:space="preserve"><value>Ricorda la cartella e lasciala com'è</value></data> <data name="Tooltips.Settings.SkipCreateArchive" xml:space="preserve"><value>Ricorda la cartella e lasciala com'è</value></data>
<data name="Tooltips.Settings.Stars" xml:space="preserve"><value>Stelle per megapixel da cui un fotogramma notturno conta come campo stellare · Invio applica, Esc annulla</value></data> <data name="Tooltips.Settings.Stars" xml:space="preserve"><value>Stelle per megapixel da cui un fotogramma notturno conta come campo stellare · Invio applica, Esc annulla</value></data>
@@ -937,6 +965,10 @@
<data name="Tooltips.Settings.Workspace.EmptyTrash" xml:space="preserve"><value>Svuota per sempre il cestino dello spazio di lavoro, dopo un elenco di ciò che contiene e una conferma scritta</value></data> <data name="Tooltips.Settings.Workspace.EmptyTrash" xml:space="preserve"><value>Svuota per sempre il cestino dello spazio di lavoro, dopo un elenco di ciò che contiene e una conferma scritta</value></data>
<data name="Tooltips.Settings.Workspace.EmptyTrash.Disabled" xml:space="preserve"><value>Il cestino dello spazio di lavoro è vuoto</value></data> <data name="Tooltips.Settings.Workspace.EmptyTrash.Disabled" xml:space="preserve"><value>Il cestino dello spazio di lavoro è vuoto</value></data>
<data name="Tooltips.Settings.Workspace.Folder" xml:space="preserve"><value>La cartella dello spazio di lavoro (meglio un disco veloce); Cambia ne usa un'altra, Sposta porta con sé i progetti</value></data> <data name="Tooltips.Settings.Workspace.Folder" xml:space="preserve"><value>La cartella dello spazio di lavoro (meglio un disco veloce); Cambia ne usa un'altra, Sposta porta con sé i progetti</value></data>
<data name="Tooltips.Settings.Workspace.Homes" xml:space="preserve"><value>Ogni origine tiene i suoi progetti in una cartella propria dentro lo spazio di lavoro</value></data>
<data name="Tooltips.Settings.Workspace.OpenHome" xml:space="preserve"><value>Apri la cartella di questa origine in Esplora file</value></data>
<data name="Tooltips.Settings.Workspace.ServerHome" xml:space="preserve"><value>Progetti delle sequenze su {0}: {1}</value></data>
<data name="Tooltips.Settings.Workspace.ThisPc" xml:space="preserve"><value>Progetti delle sequenze nell'archivio di questo PC: {0}</value></data>
<data name="Tooltips.Settings.Workspace.LastUsed" xml:space="preserve"><value>Il progetto che hai aperto per ultimo per la sequenza</value></data> <data name="Tooltips.Settings.Workspace.LastUsed" xml:space="preserve"><value>Il progetto che hai aperto per ultimo per la sequenza</value></data>
<data name="Tooltips.Settings.Workspace.Main" xml:space="preserve"><value>Il progetto Principale della sequenza, che ne tiene le impostazioni</value></data> <data name="Tooltips.Settings.Workspace.Main" xml:space="preserve"><value>Il progetto Principale della sequenza, che ne tiene le impostazioni</value></data>
<data name="Tooltips.Settings.Workspace.Move" xml:space="preserve"><value>Sposta la cartella dello spazio di lavoro con i suoi progetti in un'altra cartella, dopo un piano; ogni file è verificato prima di rimuovere l'origine</value></data> <data name="Tooltips.Settings.Workspace.Move" xml:space="preserve"><value>Sposta la cartella dello spazio di lavoro con i suoi progetti in un'altra cartella, dopo un piano; ogni file è verificato prima di rimuovere l'origine</value></data>
@@ -999,6 +1031,7 @@
<data name="Tooltips.Setup.Update" xml:space="preserve"><value>Aggiorna sul posto i programmi installati e applica le modifiche elencate · i tuoi dati restano</value></data> <data name="Tooltips.Setup.Update" xml:space="preserve"><value>Aggiorna sul posto i programmi installati e applica le modifiche elencate · i tuoi dati restano</value></data>
<data name="Tooltips.Shell.CollapseRail" xml:space="preserve"><value>Riduci la navigazione alle icone · Ctrl+B</value></data> <data name="Tooltips.Shell.CollapseRail" xml:space="preserve"><value>Riduci la navigazione alle icone · Ctrl+B</value></data>
<data name="Tooltips.Shell.ExpandRail" xml:space="preserve"><value>Mostra i nomi della navigazione · Ctrl+B</value></data> <data name="Tooltips.Shell.ExpandRail" xml:space="preserve"><value>Mostra i nomi della navigazione · Ctrl+B</value></data>
<data name="Tooltips.Shell.Homes.Logs" xml:space="preserve"><value>Mostra la cartella dei log in Esplora file: il log dice quale cartella non è stata riordinata</value></data>
<data name="Tooltips.Shell.PauseJob" xml:space="preserve"><value>Mette in pausa l'attività mostrata; quando la riprendi continua dal punto di ripresa</value></data> <data name="Tooltips.Shell.PauseJob" xml:space="preserve"><value>Mette in pausa l'attività mostrata; quando la riprendi continua dal punto di ripresa</value></data>
<data name="Tooltips.Shell.StopJob" xml:space="preserve"><value>Ferma l'attività in corso · potrai riprenderla</value></data> <data name="Tooltips.Shell.StopJob" xml:space="preserve"><value>Ferma l'attività in corso · potrai riprenderla</value></data>
<data name="Tooltips.Uploader.AddWatchFolder" xml:space="preserve"><value>Aggiungi una cartella da controllare</value></data> <data name="Tooltips.Uploader.AddWatchFolder" xml:space="preserve"><value>Aggiungi una cartella da controllare</value></data>
+5
View File
@@ -13,8 +13,13 @@
<ProjectReference Include="..\Chronos.Core.Windows\Chronos.Core.Windows.csproj" /> <ProjectReference Include="..\Chronos.Core.Windows\Chronos.Core.Windows.csproj" />
<ProjectReference Include="..\Chronos.Data\Chronos.Data.csproj" /> <ProjectReference Include="..\Chronos.Data\Chronos.Data.csproj" />
<ProjectReference Include="..\Chronos.Protocol\Chronos.Protocol.csproj" /> <ProjectReference Include="..\Chronos.Protocol\Chronos.Protocol.csproj" />
<ProjectReference Include="..\Chronos.Server\Chronos.Server.csproj" />
<ProjectReference Include="..\Chronos.Ui\Chronos.Ui.csproj" /> <ProjectReference Include="..\Chronos.Ui\Chronos.Ui.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<!-- Share this library hosts the server in-process (owner review 5, #67): ASP.NET Core is a shared framework, no package. -->
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<InternalsVisibleTo Include="Chronos.App.Tests" /> <InternalsVisibleTo Include="Chronos.App.Tests" />
</ItemGroup> </ItemGroup>
+41 -1
View File
@@ -69,6 +69,36 @@ public sealed class SampleData
/// <summary>The server-only sequence whose proxies <see cref="CacheProxiesAsync"/> keeps on this PC (Sunrise over Superga).</summary> /// <summary>The server-only sequence whose proxies <see cref="CacheProxiesAsync"/> keeps on this PC (Sunrise over Superga).</summary>
public Guid ProxiedSequenceId => _sunrise; public Guid ProxiedSequenceId => _sunrise;
/// <summary>The certificate fingerprint of this PC's shared library in the captures.</summary>
public const string ShareFingerprint = "4F:0B:E2:91:7C:3A:D5:68:B0:1E:29:C7:83:5D:F4:A6:12:9E:7B:40:D8:6C:35:E1:A9:52:0F:BD:74:C3:86:2E";
/// <summary>Server › This library shared (owner review 5, #67): sample addresses, two clients, the temporary password.</summary>
public static void ShowShare(AppServices services)
{
ArgumentNullException.ThrowIfNull(services);
var pc = AppEnvironment.SamplePcName;
services.Share.ShowSample(ShareState.On, null,
[$"https://{pc}:8443", $"https://{pc}.studio.lan:8443", "https://192.168.1.20:8443", "https://100.88.14.3:8443"], 8443, 8080, ShareFingerprint,
"kT7p-Qm2x-Wf9r", [
new ShareClient("anna", "Chronos Uploader (ANNA-LAPTOP)", "192.168.1.31", Now.AddMinutes(-1)),
new ShareClient("admin", Chronos.Server.Security.ClientActivity.AdminPanel, "127.0.0.1", Now.AddMinutes(-3)),
]);
}
/// <summary>Server › This library that could not start: the port is taken.</summary>
public static void ShowShareFailed(AppServices services)
{
ArgumentNullException.ThrowIfNull(services);
services.Share.ShowSample(ShareState.Failed, Loc.L("Errors.Share.PortInUse", 8443), [], 0, 0, null, null, []);
}
/// <summary>Server › This library not shared, as before <see cref="ShowShare"/>.</summary>
public static void HideShare(AppServices services)
{
ArgumentNullException.ThrowIfNull(services);
services.Share.ShowSample(ShareState.Off, null, [], 0, 0, null, null, []);
}
/// <summary>Points the services at fakes (server, encoders, update check) for an empty first-run state.</summary> /// <summary>Points the services at fakes (server, encoders, update check) for an empty first-run state.</summary>
public static SampleData Configure(AppServices services) public static SampleData Configure(AppServices services)
{ {
@@ -84,7 +114,7 @@ public sealed class SampleData
services.CheckForUpdateAsync = _ => Task.FromResult<ReleaseInfo?>(null); services.CheckForUpdateAsync = _ => Task.FromResult<ReleaseInfo?>(null);
services.Devices.Dispose(); services.Devices.Dispose();
services.Devices = new SampleDeviceMonitor(); services.Devices = new SampleDeviceMonitor();
services.Sync.RemoteFactory = (_, _, _) => sample._remote; services.Sync.RemoteFactory = (_, _, _, _) => sample._remote;
services.Sync.EditorFactory = (_, _, _) => sample._remote; services.Sync.EditorFactory = (_, _, _) => sample._remote;
// The schedules keep the sample's moment: nothing becomes due while the screenshots are taken. // The schedules keep the sample's moment: nothing becomes due while the screenshots are taken.
services.SchedulerTime = new FixedTime(Now); services.SchedulerTime = new FixedTime(Now);
@@ -134,6 +164,16 @@ public sealed class SampleData
settings.ProtectedToken = "sample-token"; settings.ProtectedToken = "sample-token";
settings.TrustedCertificates = [new TrustedCertificate { Fingerprint = ServerFingerprint, Server = "https://nas.local:8443", TrustedAt = new DateTimeOffset(2026, 9, 1, 9, 30, 0, TimeSpan.Zero) }]; settings.TrustedCertificates = [new TrustedCertificate { Fingerprint = ServerFingerprint, Server = "https://nas.local:8443", TrustedAt = new DateTimeOffset(2026, 9, 1, 9, 30, 0, TimeSpan.Zero) }];
settings.RecentServers = ["https://nas.local:8443"]; settings.RecentServers = ["https://nas.local:8443"];
// Settings › Server › Known servers (owner review 5): the sample's server, known by its id.
settings.KnownServers =
[
new KnownServer
{
Id = Guid.Parse("5a3c1f0e-7d2b-4c8e-9f10-2b6d4e8a1c37"), Name = "Studio NAS", LastAddress = "https://nas.local:8443", Fingerprint = ServerFingerprint,
Aliases = [Chronos.Data.Sync.SyncService.ServerKey(new Uri("https://nas.local:8443"))], LastSeen = Now,
},
];
_services.Sync.KnownServersChanged();
settings.RenderNodeOptIn = true; settings.RenderNodeOptIn = true;
// The jobs sample shows a deep analysis that yielded to the render (owner review 1). // The jobs sample shows a deep analysis that yielded to the render (owner review 1).
settings.PriorityQueue = true; settings.PriorityQueue = true;
+1 -1
View File
@@ -74,7 +74,7 @@ public sealed class ProjectFiles(ShellViewModel shell)
if (bundle.Workspace is { } workspace) if (bundle.Workspace is { } workspace)
{ {
// A workspace's own working state opens as it is; a copy of one (saved elsewhere, another PC's) gives its project its settings. // A workspace's own working state opens as it is; a copy of one (saved elsewhere, another PC's) gives its project its settings.
var own = shell.Services.Workspace.Store.Find(workspace.ProjectId) is { } project var own = shell.Services.Workspace.Find(workspace.ProjectId) is { } project
&& string.Equals(Path.GetFullPath(project.BundlePath), Path.GetFullPath(path), StringComparison.OrdinalIgnoreCase); && string.Equals(Path.GetFullPath(project.BundlePath), Path.GetFullPath(path), StringComparison.OrdinalIgnoreCase);
await shell.Sequence.ShowAsync(sequence.Id, new ProjectRequest(sequence.Id, workspace.ProjectId), own ? null : editor => Apply(editor, bundle)); await shell.Sequence.ShowAsync(sequence.Id, new ProjectRequest(sequence.Id, workspace.ProjectId), own ? null : editor => Apply(editor, bundle));
return; return;
@@ -44,6 +44,16 @@ public sealed class AppEnvironment
public string LogDirectory => Path.Combine(DataDirectory, "logs"); public string LogDirectory => Path.Combine(DataDirectory, "logs");
public string CacheDirectory => Path.Combine(DataDirectory, "cache"); public string CacheDirectory => Path.Combine(DataDirectory, "cache");
public string BackupDirectory => Path.Combine(DataDirectory, "backups"); public string BackupDirectory => Path.Combine(DataDirectory, "backups");
/// <summary>The private folder of the server this PC runs while it shares its library: certificate, settings, uploads, logs.</summary>
public string ShareDirectory => Path.Combine(DataDirectory, "server");
/// <summary>The PC's name as the screens show it: a capture shows <see cref="SamplePcName"/>.</summary>
public string PcName => IsCapture ? SamplePcName : Environment.MachineName;
/// <summary>The PC name captures show.</summary>
public const string SamplePcName = "STUDIO-PC";
public string DatabasePath => Path.Combine(DataDirectory, AppPaths.DatabaseFileName); public string DatabasePath => Path.Combine(DataDirectory, AppPaths.DatabaseFileName);
public string SettingsPath => Path.Combine(DataDirectory, AppPaths.SettingsFileName); public string SettingsPath => Path.Combine(DataDirectory, AppPaths.SettingsFileName);
+99 -7
View File
@@ -12,6 +12,7 @@ using Chronos.App.Workspace;
using Chronos.Core.Archiving; using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics; using Chronos.Core.Diagnostics;
using Chronos.Core.Export; using Chronos.Core.Export;
using Chronos.Core.IO;
using Chronos.Core.Imaging; using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Decoders; using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Model; using Chronos.Core.Model;
@@ -21,6 +22,7 @@ using Chronos.Core.Windows.MediaFoundation;
using Chronos.Core.Windows.Wic; using Chronos.Core.Windows.Wic;
using Chronos.Data; using Chronos.Data;
using Chronos.Data.Archiving; using Chronos.Data.Archiving;
using Chronos.Data.Homes;
using Chronos.Data.Jobs; using Chronos.Data.Jobs;
using Chronos.Data.Processing; using Chronos.Data.Processing;
using Chronos.Data.Scheduling; using Chronos.Data.Scheduling;
@@ -72,12 +74,15 @@ public sealed class AppServices : IAsyncDisposable
// The editor's open and closed groups survive a restart (owner review 1, R3). // The editor's open and closed groups survive a restart (owner review 1, R3).
Chronos.App.Editor.EditorSettings.Groups.Bind(settings.EditorGroups, saveSettings); Chronos.App.Editor.EditorSettings.Groups.Bind(settings.EditorGroups, saveSettings);
_renderNode = new RenderNodeHost(StartRenderNode); _renderNode = new RenderNodeHost(StartRenderNode);
Share = new LibraryShare(this);
ArchiveSetup = new EngineArchiveSetup(this); ArchiveSetup = new EngineArchiveSetup(this);
Sync = new SyncHost(this); Sync = new SyncHost(this);
ScheduleHost = new DesktopScheduleHost(settings, () => Database, () => Archives); ScheduleHost = new DesktopScheduleHost(settings, () => Database, () => Archives);
Workspace = new WorkspaceHost(environment, settings, saveSettings, () => Database, () => Archives, () => Engine); Workspace = new WorkspaceHost(environment, settings, saveSettings, () => Database, () => Archives, () => Engine);
// A server that keeps projects is the home of the workspace projects of its sequences (owner review 2, R8, phase 5b). // A server that keeps projects is the home of the workspace projects of its sequences (owner review 2, R8, phase 5b).
Workspace.ServerHomes = Sync.ProjectHome; Workspace.ServerHomes = Sync.ProjectHome;
// A server home's folder is named by its server's id, whichever address reached it (owner review 5, #66).
Workspace.Identity = () => Sync.Identity;
Sync.ProjectChanged += Workspace.OnServerProjectChanged; Sync.ProjectChanged += Workspace.OnServerProjectChanged;
Server = new ServerSession(settings, saveSettings, new ChronosServerApiFactory(), new DpapiTokenProtector()); Server = new ServerSession(settings, saveSettings, new ChronosServerApiFactory(), new DpapiTokenProtector());
Encoders = new MediaFoundationInventory(); Encoders = new MediaFoundationInventory();
@@ -110,6 +115,7 @@ public sealed class AppServices : IAsyncDisposable
{ {
if (_server is not null) _server.PropertyChanged -= OnServerChanged; if (_server is not null) _server.PropertyChanged -= OnServerChanged;
_server = value; _server = value;
_server.IsOwnLibrary = Share.IsOwn;
_server.PropertyChanged += OnServerChanged; _server.PropertyChanged += OnServerChanged;
UpdateRenderNode(); UpdateRenderNode();
Sync.Update(); Sync.Update();
@@ -119,6 +125,9 @@ public sealed class AppServices : IAsyncDisposable
/// <summary>Sync with the signed-in server: engine, job connection, background comparison.</summary> /// <summary>Sync with the signed-in server: engine, job connection, background comparison.</summary>
public SyncHost Sync { get; } public SyncHost Sync { get; }
/// <summary>Settings › Server › Share this library: this PC's library served to the LAN while Chronos runs (owner review 5, #67).</summary>
public LibraryShare Share { get; }
/// <summary> /// <summary>
/// A job of this PC moved a sequence's folder or changed its title or file names (a Reorganize step), or replaced its /// A job of this PC moved a sequence's folder or changed its title or file names (a Reorganize step), or replaced its
/// frames' files (a conversion), with the sequence's id (any thread): an open editor reads it again where and as it is now. /// frames' files (a conversion), with the sequence's id (any thread): an open editor reads it again where and as it is now.
@@ -151,6 +160,12 @@ public sealed class AppServices : IAsyncDisposable
/// <summary>How the restore staged in Settings › Advanced went when the index opened; null when none was staged.</summary> /// <summary>How the restore staged in Settings › Advanced went when the index opened; null when none was staged.</summary>
public StagedRestoreResult? StagedRestore { get; private set; } public StagedRestoreResult? StagedRestore { get; private set; }
/// <summary>What the sorting of the folders into homes did when the index opened (owner review 5, #66); null when it had nothing to do.</summary>
public HomeLayoutResult? HomeLayout { get; private set; }
/// <summary>Why the folders could not be sorted into homes when the index opened; null when they were, or had nothing to sort.</summary>
public Exception? HomeLayoutError { get; private set; }
/// <summary>Card detection, eject and format (BRIEF §13); started with the index, replaced by a fake in capture.</summary> /// <summary>Card detection, eject and format (BRIEF §13); started with the index, replaced by a fake in capture.</summary>
public IDeviceMonitor Devices { get; set; } = new WindowsDeviceMonitor(); public IDeviceMonitor Devices { get; set; } = new WindowsDeviceMonitor();
@@ -201,7 +216,8 @@ public sealed class AppServices : IAsyncDisposable
new(services.Processing?.Options ?? WorkspaceJobOptions.For(archives).Processing, new(services.Processing?.Options ?? WorkspaceJobOptions.For(archives).Processing,
() => services.Settings.PauseUploadsOnMetered && MeteredNetwork.IsMetered(), () => services.Settings.PauseUploadsOnMetered && MeteredNetwork.IsMetered(),
services.Workspace.MovedAsync, services.Workspace.MovedAsync,
() => services.Workspace.Root); () => services.Workspace.Root,
services.Workspace.SameServer);
/// <summary> /// <summary>
/// Queues a scan of <paramref name="archive"/> unless one is already waiting or running; the sequences it indexes get /// Queues a scan of <paramref name="archive"/> unless one is already waiting or running; the sequences it indexes get
@@ -228,6 +244,7 @@ public sealed class AppServices : IAsyncDisposable
SaveSettingsAction(); SaveSettingsAction();
UpdateRenderNode(); UpdateRenderNode();
ApplyJobSettings(); ApplyJobSettings();
if (!Environment.IsCapture) Share.Apply();
} }
/// <summary>Writes the settings file and nothing else: for choices that change only what is shown (the rail, the sequence edited last).</summary> /// <summary>Writes the settings file and nothing else: for choices that change only what is shown (the rail, the sequence edited last).</summary>
@@ -284,6 +301,8 @@ public sealed class AppServices : IAsyncDisposable
_schedulerReady.TrySetResult(false); _schedulerReady.TrySetResult(false);
return; return;
} }
// Before any job runs: the folders of the workspace and the cache go to their homes (owner review 5, #66).
await SortHomesAsync(Database, ct);
try try
{ {
await StartJobsAsync(Database, startEngine: true, ct); await StartJobsAsync(Database, startEngine: true, ct);
@@ -316,6 +335,8 @@ public sealed class AppServices : IAsyncDisposable
{ {
await _stopping.CancelAsync().ConfigureAwait(false); await _stopping.CancelAsync().ConfigureAwait(false);
await _schedules.ConfigureAwait(false); await _schedules.ConfigureAwait(false);
// First: the shared library's clients and its subscriptions to the engine and the scheduler go before they do.
await Share.DisposeAsync().ConfigureAwait(false);
_schedulerReady.TrySetResult(false); _schedulerReady.TrySetResult(false);
if (Scheduler is not null) await Scheduler.DisposeAsync().ConfigureAwait(false); if (Scheduler is not null) await Scheduler.DisposeAsync().ConfigureAwait(false);
_stopping.Dispose(); _stopping.Dispose();
@@ -348,6 +369,7 @@ public sealed class AppServices : IAsyncDisposable
await StartSchedulerAsync(ct).ConfigureAwait(false); await StartSchedulerAsync(ct).ConfigureAwait(false);
if (reopen is null) if (reopen is null)
{ {
await Share.StartAsync(ct).ConfigureAwait(false);
await ScanNowAsync(started, ct).ConfigureAwait(false); await ScanNowAsync(started, ct).ConfigureAwait(false);
return; return;
} }
@@ -356,6 +378,7 @@ public sealed class AppServices : IAsyncDisposable
{ {
if (!string.Equals(reopen, Settings.LastArchivePath, StringComparison.OrdinalIgnoreCase)) return; if (!string.Equals(reopen, Settings.LastArchivePath, StringComparison.OrdinalIgnoreCase)) return;
if (!await ReopenAsync(reopen, ct).ConfigureAwait(false)) continue; if (!await ReopenAsync(reopen, ct).ConfigureAwait(false)) continue;
await Share.StartAsync(ct).ConfigureAwait(false);
await ScanNowAsync(null, ct).ConfigureAwait(false); await ScanNowAsync(null, ct).ConfigureAwait(false);
Scheduler?.Wake(); Scheduler?.Wake();
return; return;
@@ -474,6 +497,66 @@ public sealed class AppServices : IAsyncDisposable
} }
} }
/// <summary>
/// Sorts the workspace's projects and the cache's server folders into their homes (owner review 5, #66:
/// <see cref="HomeLayoutMigration"/>; renames only, a clash to the trash, never deleted), or takes up a sorting a previous
/// start left half done. Projects in use or a workspace being moved wait for a later start; a failure is logged and kept
/// for Settings to tell (<see cref="HomeLayoutError"/>), and the start goes on: the folders not sorted read as before.
/// </summary>
private async Task SortHomesAsync(ChronosDatabase database, CancellationToken ct)
{
try
{
var migration = new HomeLayoutMigration(new HomeLayoutOptions
{
DataDirectory = Environment.DataDirectory,
WorkspaceRoot = Workspace.IsEnabled ? Workspace.Root : null,
CacheRoot = CacheStore.Folder(Environment, Settings),
Identity = Sync.Identity,
CurrentServer = Sync.LastServer,
Database = database,
});
var result = await Task.Run(() => migration.ApplyAsync(ct), ct);
if (result != HomeLayoutResult.Nothing)
{
HomeLayout = result;
Log.Info("app", $"Folders sorted into homes: {result.ProjectsMoved} project(s), {result.EntriesMoved} entr(ies), {result.InUse} in use, "
+ $"{result.Clashes} clash(es){(result.Deferred is { } deferred ? $", the workspace waits ({deferred})" : string.Empty)}");
}
}
catch (Exception ex) when (ex is HomeLayoutException or IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException)
{
HomeLayoutError = ex;
Log.Error("app", "The folders could not be sorted into homes; the next start tries again", ex);
}
finally
{
Workspace.Reopen();
}
}
/// <summary>
/// The scan schedule scanned this PC's archive (any thread): the archives of the servers' downloaded originals are scanned
/// after it (owner review 5, Q1: they are archives of their own, which the schedule, made for one archive, does not name).
/// </summary>
private void OnScheduledScanDone(Job job)
{
if (job is not { Kind: JobKind.Scan, State: JobState.Done, ScheduleId: not null, TargetIds: [var scanned] }) return;
_ = Task.Run(async () =>
{
try
{
var archives = await Sync.OriginalsArchivesAsync(_stopping.Token).ConfigureAwait(false);
if (archives.Any(a => a.Id == scanned)) return;
foreach (var originals in archives) await QueueScanAsync(originals, full: false, _stopping.Token).ConfigureAwait(false);
}
catch (Exception ex) when (ex is DatabaseException or InvalidOperationException or OperationCanceledException)
{
Log.Warning("app", "The archives of the servers' originals could not be queued to be scanned", ex);
}
});
}
private async Task StartJobsAsync(ChronosDatabase database, bool startEngine, CancellationToken ct) private async Task StartJobsAsync(ChronosDatabase database, bool startEngine, CancellationToken ct)
{ {
_wic = new WicDecoderProvider(); _wic = new WicDecoderProvider();
@@ -486,19 +569,24 @@ public sealed class AppServices : IAsyncDisposable
MemoryBudget = () => ProcessingTuning.MemoryBudget(Settings, GC.GetGCMemoryInfo().TotalAvailableMemoryBytes), MemoryBudget = () => ProcessingTuning.MemoryBudget(Settings, GC.GetGCMemoryInfo().TotalAvailableMemoryBytes),
// The housekeeping schedule trims the cache to Settings › Storage › Cache limit (owner review 2, R10). // The housekeeping schedule trims the cache to Settings › Storage › Cache limit (owner review 2, R10).
// The workspace-cleanup schedule removes the media past Settings › Workspace's Clean after and Size limit, and reports its trash (phase 5c). // The workspace-cleanup schedule removes the media past Settings › Workspace's Clean after and Size limit, and reports its trash (phase 5c).
// The shared library's upload-cleanup schedule runs on this PC's scheduler (owner review 5, #67).
CleanupSteps = [new CacheTrimStep(() => CacheStore.Folder(Environment, Settings), () => Settings.CacheLimitGb * (1L << 30)), CleanupSteps = [new CacheTrimStep(() => CacheStore.Folder(Environment, Settings), () => Settings.CacheLimitGb * (1L << 30)),
new WorkspaceCleanStep(() => Workspace), new WorkspaceTrashStep(() => Workspace)], new WorkspaceCleanStep(() => Workspace), new WorkspaceTrashStep(() => Workspace), new ShareUploadsStep(() => Share)],
BackupDirectory = Environment.BackupDirectory, BackupDirectory = Environment.BackupDirectory,
// Told after each step of a Reorganize, and each sequence a conversion replaced or made, while the rest of the job runs. // While the library is shared, its clients see thumbnails and proxies of what a scan finds, as a server's do.
SequenceChanged = (id, _, _) => ImagesAfterScanWhen = () => Share.IsOn,
// Told after each step of a Reorganize, and each sequence a conversion replaced or made, while the rest of the job
// runs; the shared library's clients are told too.
SequenceChanged = (id, change, token) =>
{ {
SequenceReorganized?.Invoke(id); SequenceReorganized?.Invoke(id);
return Task.CompletedTask; return Share.SequenceChangedAsync(id, change, token);
}, },
ProjectsChanged = (changed, token) => Share.ProjectsChangedAsync(changed, token),
}; };
Archives = new ArchiveService(database, archive); Archives = new ArchiveService(database, archive);
// The videos folder may not lie in the workspace either, and a copy of a server's renders downloads through its connection (phase 5). // The videos folder may not lie in the workspace either, and a copy of a server's renders downloads through its connection (phase 5).
Archives.Videos.ProtectedFolders = () => [Workspace.Root]; Archives.Videos.ProtectedFolders = () => [Workspace.Root, Share.Folder];
Archives.Videos.Servers = Sync; Archives.Videos.Servers = Sync;
Processing = new ProcessingService(database, ProcessingOptions(archive)); Processing = new ProcessingService(database, ProcessingOptions(archive));
Sync.Open(database, Archives, archive); Sync.Open(database, Archives, archive);
@@ -508,6 +596,7 @@ public sealed class AppServices : IAsyncDisposable
Engine = new JobEngine(database, handlers, new JobEngineOptions { WorkerId = WorkerId, Kinds = kinds, PriorityQueue = () => PriorityQueue }); Engine = new JobEngine(database, handlers, new JobEngineOptions { WorkerId = WorkerId, Kinds = kinds, PriorityQueue = () => PriorityQueue });
// The workspace's size limit runs after each copy of media into it (phase 5c). // The workspace's size limit runs after each copy of media into it (phase 5c).
Engine.JobChanged += Workspace.OnJobChanged; Engine.JobChanged += Workspace.OnJobChanged;
Engine.JobChanged += OnScheduledScanDone;
// Sync follows the engine's jobs before it runs any: a render resumed at start that finishes at once is still sent (Export "Sync"). // Sync follows the engine's jobs before it runs any: a render resumed at start that finishes at once is still sent (Export "Sync").
Sync.Update(); Sync.Update();
// With no handler the engine must not run: an empty kind list would let workers claim (and fail) every job. // With no handler the engine must not run: an empty kind list would let workers claim (and fail) every job.
@@ -528,6 +617,8 @@ public sealed class AppServices : IAsyncDisposable
AllowsHardware = presetId => AllowsHardware(Settings.HardwareEncoding, presetId), AllowsHardware = presetId => AllowsHardware(Settings.HardwareEncoding, presetId),
Host = EncoderHost.Client, Host = EncoderHost.Client,
ProducedBy = System.Environment.MachineName, ProducedBy = System.Environment.MachineName,
// A render or an advice recorded on this PC reaches the shared library's clients (owner review 5, #67).
SequenceChanged = (id, change, token) => Share.SequenceChangedAsync(id, change, token),
Tune = basis => ProcessingTuning.Apply(basis, Settings, GC.GetGCMemoryInfo().TotalAvailableMemoryBytes, System.Environment.ProcessorCount, Tune = basis => ProcessingTuning.Apply(basis, Settings, GC.GetGCMemoryInfo().TotalAvailableMemoryBytes, System.Environment.ProcessorCount,
CacheStore.Folder(Environment, Settings)), CacheStore.Folder(Environment, Settings)),
}; };
@@ -554,7 +645,8 @@ public sealed class AppServices : IAsyncDisposable
var node = new RenderNodeClient(client, processing.Options, new RenderNodeOptions var node = new RenderNodeClient(client, processing.Options, new RenderNodeOptions
{ {
ClientName = System.Environment.MachineName, ClientName = System.Environment.MachineName,
CacheDirectory = Path.Combine(cache, "render-node"), // Each server keeps its own downloads (owner review 5, #66: the render-node folder of its home in the cache).
CacheDirectory = Path.Combine(CacheStore.ServerFolder(cache, Sync.KeyOf(session.Address), Sync.Identity), HomeFolders.RenderNode),
CacheLimitBytes = Settings.CacheLimitGb * (1L << 30), CacheLimitBytes = Settings.CacheLimitGb * (1L << 30),
}); });
node.Start(); node.Start();
@@ -10,6 +10,7 @@ using Chronos.Core.Naming;
using Chronos.Core.Project; using Chronos.Core.Project;
using Chronos.Data.Archiving; using Chronos.Data.Archiving;
using Chronos.Data.Repositories; using Chronos.Data.Repositories;
using Chronos.Data.Sync;
using Chronos.Ui.Theming; using Chronos.Ui.Theming;
namespace Chronos.App.Infrastructure; namespace Chronos.App.Infrastructure;
@@ -66,6 +67,61 @@ public sealed class TrustedCertificate
public DateTimeOffset TrustedAt { get; set; } public DateTimeOffset TrustedAt { get; set; }
} }
/// <summary>
/// A server this PC signed in to that announced its stable id (owner review 5, #66): its name and last address, the TLS
/// fingerprint it presented, the address keys it was reached under before (or besides) its id
/// (<see cref="Chronos.Data.Sync.SyncService.ServerKey"/>: projects, links and jobs made then still name them), the archive its
/// downloaded originals go to, and when it was last seen. Its folders (<c>servers\&lt;id&gt;</c> in the workspace and the
/// cache) are named by the id, never by the name.
/// </summary>
public sealed class KnownServer
{
public Guid Id { get; set; }
public string? Name { get; set; }
public string? LastAddress { get; set; }
public string? Fingerprint { get; set; }
public List<string> Aliases { get; set; } = [];
/// <summary>The archive of this PC that holds the server's downloaded originals (owner review 5, Q1); null until the first download.</summary>
public Guid? OriginalsArchiveId { get; set; }
public DateTimeOffset LastSeen { get; set; }
}
/// <summary>
/// Settings › Server › Sharing (owner review 5, #67): this PC's library served to the LAN by the server Chronos hosts
/// while it runs. Absent in a 1.0 settings file: off, on Docker's ports.
/// </summary>
public sealed class ShareSettings
{
public const int DefaultHttpsPort = 8443;
public const int DefaultHttpPort = 8080;
public bool Enabled { get; set; }
/// <summary>The name clients see; empty: this PC's name.</summary>
public string? Name { get; set; }
public int HttpsPort { get; set; } = DefaultHttpsPort;
public int HttpPort { get; set; } = DefaultHttpPort;
/// <summary>The ports clients reach when a router forwards others to this PC; null: the ones above.</summary>
public int? PublicHttpsPort { get; set; }
public int? PublicHttpPort { get; set; }
/// <summary>Announce the library to Chronos programs on the local network.</summary>
public bool Discovery { get; set; } = true;
/// <summary>What restarts a running share when it changes (the name, the ports, the discovery); the rest applies live.</summary>
public bool SameEndpoint(ShareSettings other)
{
ArgumentNullException.ThrowIfNull(other);
return string.Equals(Name?.Trim() ?? string.Empty, other.Name?.Trim() ?? string.Empty, StringComparison.Ordinal) && HttpsPort == other.HttpsPort &&
HttpPort == other.HttpPort && PublicHttpsPort == other.PublicHttpsPort && PublicHttpPort == other.PublicHttpPort && Discovery == other.Discovery;
}
}
/// <summary> /// <summary>
/// Per-user preferences (language, theme, window layout, archive defaults, server session). Kept in /// Per-user preferences (language, theme, window layout, archive defaults, server session). Kept in
/// <c>settings.json</c> next to the database and written atomically, because language and theme apply before the /// <c>settings.json</c> next to the database and written atomically, because language and theme apply before the
@@ -257,6 +313,22 @@ public sealed class AppSettings
public List<TrustedCertificate> TrustedCertificates { get; set; } = []; public List<TrustedCertificate> TrustedCertificates { get; set; } = [];
public List<string> RecentServers { get; set; } = []; public List<string> RecentServers { get; set; } = [];
/// <summary>
/// The servers known by their stable id and the address keys each was reached under (owner review 5, #66): a server's
/// projects, links and jobs stay its own whatever address it is reached by. This PC's state: Reset and Import keep it,
/// Export leaves it out.
/// </summary>
public List<KnownServer> KnownServers { get; set; } = [];
/// <summary>The alias table of <see cref="KnownServers"/>, as the sync and the workspace compare server keys through it.</summary>
public ServerIdentity KnownIdentity() => new([.. KnownServers.Where(k => k.Id != Guid.Empty).Select(k => new KnownServerKey(k.Id, [.. k.Aliases]))]);
/// <summary>The known server of <paramref name="id"/>; null when this PC has none.</summary>
public KnownServer? FindKnownServer(Guid id) => KnownServers.FirstOrDefault(k => k.Id == id);
/// <summary>Settings › Server › Sharing: this PC's library shared to the LAN while Chronos runs (owner review 5, #67).</summary>
public ShareSettings Share { get; set; } = new();
/// <summary>Let the server send render jobs to this PC (BRIEF §14.7).</summary> /// <summary>Let the server send render jobs to this PC (BRIEF §14.7).</summary>
public bool RenderNodeOptIn { get; set; } public bool RenderNodeOptIn { get; set; }
@@ -377,6 +449,7 @@ public sealed class AppSettings
ProtectedToken = ProtectedToken, ProtectedToken = ProtectedToken,
TrustedCertificates = TrustedCertificates, TrustedCertificates = TrustedCertificates,
RecentServers = RecentServers, RecentServers = RecentServers,
KnownServers = KnownServers,
Window = Window, Window = Window,
RailCollapsed = RailCollapsed, RailCollapsed = RailCollapsed,
EditorGroups = EditorGroups, EditorGroups = EditorGroups,
@@ -400,6 +473,7 @@ public sealed class AppSettings
copy.WorkspaceFolder = null; copy.WorkspaceFolder = null;
copy.WorkspaceRecent = []; copy.WorkspaceRecent = [];
copy.WorkspaceOpened = []; copy.WorkspaceOpened = [];
copy.KnownServers = [];
return copy; return copy;
} }
@@ -423,6 +497,7 @@ public sealed class AppSettings
imported.WorkspaceFolder = WorkspaceFolder; imported.WorkspaceFolder = WorkspaceFolder;
imported.WorkspaceRecent = WorkspaceRecent; imported.WorkspaceRecent = WorkspaceRecent;
imported.WorkspaceOpened = WorkspaceOpened; imported.WorkspaceOpened = WorkspaceOpened;
imported.KnownServers = KnownServers;
return imported; return imported;
} }
} }
@@ -5,10 +5,12 @@ using System.Text;
using Chronos.App.Settings; using Chronos.App.Settings;
using Chronos.Core.Diagnostics; using Chronos.Core.Diagnostics;
using Chronos.Core.Export; using Chronos.Core.Export;
using Chronos.Core.IO;
using Chronos.Core.Model; using Chronos.Core.Model;
using Chronos.Core.Windows.Codecs; using Chronos.Core.Windows.Codecs;
using Chronos.Data; using Chronos.Data;
using Chronos.Data.Sqlite; using Chronos.Data.Sqlite;
using Chronos.Data.Sync;
namespace Chronos.App.Infrastructure; namespace Chronos.App.Infrastructure;
@@ -34,8 +36,11 @@ public static class DiagnosticsBundle
var settings = services.Settings.ToJson(); var settings = services.Settings.ToJson();
var tailBytes = AppLogging.DiagnosticsTailBytes(services.Settings); var tailBytes = AppLogging.DiagnosticsTailBytes(services.Settings);
var report = Report(services.Environment, extraLines) + DatabaseLine(services.Database); var report = Report(services.Environment, extraLines) + DatabaseLine(services.Database);
var workspace = services.Workspace;
var cache = CacheStore.Folder(services.Environment, services.Settings);
return Task.Run(async () => return Task.Run(async () =>
{ {
report += HomesLines(workspace, cache);
var failures = services.Database is { } db ? (await db.Jobs.ListAsync(JobState.Failed, FailedJobs, null, ct).ConfigureAwait(false)).Items : []; var failures = services.Database is { } db ? (await db.Jobs.ListAsync(JobState.Failed, FailedJobs, null, ct).ConfigureAwait(false)).Items : [];
var codecs = Codecs(services.Encoders); var codecs = Codecs(services.Encoders);
var path = ExportNaming.Unique(folder, $"Chronos diagnostics {DateTime.Now.ToString("yyyy-MM-dd HHmm", CultureInfo.InvariantCulture)}", ".zip"); var path = ExportNaming.Unique(folder, $"Chronos diagnostics {DateTime.Now.ToString("yyyy-MM-dd HHmm", CultureInfo.InvariantCulture)}", ".zip");
@@ -76,6 +81,33 @@ public static class DiagnosticsBundle
return sb.ToString(); return sb.ToString();
} }
/// <summary>The homes' folders (owner review 5, #66): the workspace's, each with its projects, and the servers' in the cache.</summary>
private static string HomesLines(Chronos.App.Workspace.WorkspaceHost workspace, string cache)
{
var sb = new StringBuilder();
try
{
if (workspace.IsEnabled && Directory.Exists(workspace.Root))
{
var homes = workspace.Homes;
sb.AppendLine(CultureInfo.InvariantCulture, $"Workspace {homes.Root} ({(homes.IsSplit ? "homes" : "1.0 layout")})");
foreach (var home in homes.Homes())
sb.AppendLine(CultureInfo.InvariantCulture, $" {(home.IsLegacy ? "(parent)" : home.Folder)}: {home.Store.List().Count} project(s){(home.Server?.Name is { } name ? " · " + name : string.Empty)}");
}
var servers = CacheStore.ServersFolder(cache);
if (Directory.Exists(servers))
{
foreach (var folder in Directory.EnumerateDirectories(servers).Order(StringComparer.Ordinal))
sb.AppendLine(CultureInfo.InvariantCulture, $"Cache home {Path.GetFileName(folder)}");
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
{
sb.AppendLine("The homes could not be listed: " + ex.Message);
}
return sb.ToString();
}
private static string DatabaseLine(ChronosDatabase? database) private static string DatabaseLine(ChronosDatabase? database)
{ {
if (database is null) return "Index not open\n"; if (database is null) return "Index not open\n";
@@ -135,6 +167,19 @@ public static class CacheStore
public static string Folder(AppEnvironment environment, AppSettings settings) => public static string Folder(AppEnvironment environment, AppSettings settings) =>
string.IsNullOrWhiteSpace(settings.CacheFolder) ? environment.CacheDirectory : settings.CacheFolder!; string.IsNullOrWhiteSpace(settings.CacheFolder) ? environment.CacheDirectory : settings.CacheFolder!;
/// <summary>The servers' homes in the cache (<c>&lt;cache&gt;\servers</c>, owner review 5, #66).</summary>
public static string ServersFolder(string cache) => Path.Combine(cache, HomeFolders.Servers);
/// <summary>
/// The home of server <paramref name="serverKey"/> in the cache (<c>&lt;cache&gt;\servers\&lt;folder&gt;</c>, named by its
/// canonical key through <paramref name="identity"/>): its proxies, render-node downloads and staged imports.
/// </summary>
public static string ServerFolder(string cache, string serverKey, ServerIdentity identity)
{
ArgumentNullException.ThrowIfNull(identity);
return Path.Combine(ServersFolder(cache), identity.FolderName(serverKey));
}
/// <summary>Creates the folder (if needed) and marks it as Chronos's.</summary> /// <summary>Creates the folder (if needed) and marks it as Chronos's.</summary>
public static void Prepare(string folder) public static void Prepare(string folder)
{ {
+10 -3
View File
@@ -67,6 +67,8 @@ public sealed class DesktopScheduleHost(AppSettings settings, Func<ChronosDataba
// The ages and the limit are Settings › Workspace's, read at each run: the schedule holds no days of its own. // The ages and the limit are Settings › Workspace's, read at each run: the schedule holds no days of its own.
new(WorkspaceCleanup, "Workspace clean-up", ScheduleActions.Cleanup, ScheduleRecurrence.DailyAt(WorkspaceCleanupTime), new(WorkspaceCleanup, "Workspace clean-up", ScheduleActions.Cleanup, ScheduleRecurrence.DailyAt(WorkspaceCleanupTime),
new ScheduleParametersDto(Steps: [WorkspaceCleanStep.StepName, WorkspaceTrashStep.StepName], OlderThanDays: 0)), new ScheduleParametersDto(Steps: [WorkspaceCleanStep.StepName, WorkspaceTrashStep.StepName], OlderThanDays: 0)),
// While this PC shares its library (owner review 5, #67): the shared library's own clean-ups, which its Reset restores.
.. settings.Share.Enabled ? Chronos.Server.Jobs.ServerScheduleHost.ShareSchedules(0) : [],
]; ];
public IReadOnlyList<string> CleanupSteps => archives()?.CleanupSteps.Select(s => s.Name).ToList() ?? []; public IReadOnlyList<string> CleanupSteps => archives()?.CleanupSteps.Select(s => s.Name).ToList() ?? [];
@@ -84,7 +86,11 @@ public sealed class DesktopScheduleHost(AppSettings settings, Func<ChronosDataba
public async ValueTask<Archive?> GetArchiveAsync(CancellationToken cancellationToken) public async ValueTask<Archive?> GetArchiveAsync(CancellationToken cancellationToken)
{ {
if (database() is not { } db || archives() is not { } service) return null; if (database() is not { } db || archives() is not { } service) return null;
var archive = CurrentArchive.Pick(await db.Archives.ListAsync(cancellationToken).ConfigureAwait(false), settings.LastArchivePath); var listed = await db.Archives.ListAsync(cancellationToken).ConfigureAwait(false);
// Never a server's originals archive in place of this PC's (owner review 5): the app scans those after this one.
var originals = settings.KnownServers.Select(k => k.OriginalsArchiveId).OfType<Guid>().ToHashSet();
var archive = (settings.LastArchivePath is { Length: > 0 } last ? CurrentArchive.At(listed, last) : null)
?? CurrentArchive.Pick([.. listed.Where(a => !originals.Contains(a.Id))], null) ?? CurrentArchive.Pick(listed, null);
if (archive is null || ArchiveService.GetAvailability(archive) == ArchiveAvailability.Offline) return null; if (archive is null || ArchiveService.GetAvailability(archive) == ArchiveAvailability.Offline) return null;
try try
{ {
@@ -110,14 +116,15 @@ public sealed class DesktopScheduleHost(AppSettings settings, Func<ChronosDataba
/// The desktop's clean-up step <c>cache-trim</c> (owner review 2, R10): brings the cache folder down to Settings › Storage › /// The desktop's clean-up step <c>cache-trim</c> (owner review 2, R10): brings the cache folder down to Settings › Storage ›
/// Cache limit, oldest files first, skipping files in use (<see cref="CacheStore.Trim"/>). The proxies of server sequences /// Cache limit, oldest files first, skipping files in use (<see cref="CacheStore.Trim"/>). The proxies of server sequences
/// (complete sets the sync keeps), the render node's folder (it trims its own downloads to the same limit) and the copies an /// (complete sets the sync keeps), the render node's folder (it trims its own downloads to the same limit) and the copies an
/// import to the server stages are never trimmed; Settings › Storage › Clear still empties everything. /// import to the server stages are never trimmed, in the former shared folders and in each server's own (<c>servers</c>,
/// owner review 5); Settings › Storage › Clear still empties everything.
/// </summary> /// </summary>
public sealed class CacheTrimStep(Func<string> folder, Func<long> limitBytes) : ICleanupStep public sealed class CacheTrimStep(Func<string> folder, Func<long> limitBytes) : ICleanupStep
{ {
public const string StepName = "cache-trim"; public const string StepName = "cache-trim";
/// <summary>Folders of the cache the trim leaves whole.</summary> /// <summary>Folders of the cache the trim leaves whole.</summary>
public static IReadOnlyList<string> Kept { get; } = ["proxies", "render-node", "server-import"]; public static IReadOnlyList<string> Kept { get; } = ["proxies", "render-node", "server-import", Chronos.Core.IO.HomeFolders.Servers];
public string Name => StepName; public string Name => StepName;
+1 -5
View File
@@ -117,11 +117,7 @@ public sealed class LibraryActions(ShellViewModel shell)
await remote.Service.EnqueueSendExportsAsync(engine, remote.Server, selected.Sequence); await remote.Service.EnqueueSendExportsAsync(engine, remote.Server, selected.Sequence);
return true; return true;
case SyncAction.DownloadOriginals when entry is not null: case SyncAction.DownloadOriginals when entry is not null:
if ((entry.Local?.ArchiveId ?? (await Services.Sync.CurrentArchiveAsync())?.Id) is not { } archive) if (await Services.Sync.OriginalsForDownloadAsync(entry.Local, (title, message, isError) => shell.Notify(title, message, isError: isError)) is not { } archive) return false;
{
shell.Notify(Loc.L("Errors.Sync.NoArchive"));
return false;
}
await remote.Service.EnqueueDownloadAsync(engine, remote.Server, entry.Id, entry.Title, SyncDownloadMode.Originals, archive); await remote.Service.EnqueueDownloadAsync(engine, remote.Server, entry.Id, entry.Title, SyncDownloadMode.Originals, archive);
return true; return true;
case SyncAction.GetExports when entry is not null: case SyncAction.GetExports when entry is not null:
+14 -1
View File
@@ -989,7 +989,20 @@ public sealed class ImportViewModel : SectionViewModel
/// <summary>What the signed-in user may still store on the server; null without a quota.</summary> /// <summary>What the signed-in user may still store on the server; null without a quota.</summary>
private long? ServerSpace() => Services.Server.User is { QuotaBytes: > 0 } user ? System.Math.Max(0, user.QuotaBytes - user.UsedBytes) : null; private long? ServerSpace() => Services.Server.User is { QuotaBytes: > 0 } user ? System.Math.Max(0, user.QuotaBytes - user.UsedBytes) : null;
private string ServerStagingRoot => Path.Combine(CacheStore.Folder(Services.Environment, Services.Settings), "server-import"); /// <summary>
/// Where an import to the server is staged before it is uploaded: the signed-in server's own folder of the cache
/// (<c>servers\&lt;id&gt;\import</c>, owner review 5); signed out, the cache's former shared folder.
/// </summary>
private string ServerStagingRoot
{
get
{
var cache = CacheStore.Folder(Services.Environment, Services.Settings);
return Services.Sync.Server is { } server
? Path.Combine(CacheStore.ServerFolder(cache, server, Services.Sync.Identity), Chronos.Core.IO.HomeFolders.Import)
: Path.Combine(cache, Chronos.Data.Homes.HomeLayoutMigration.LegacyServerImport);
}
}
private async Task PlanAsync() private async Task PlanAsync()
{ {
@@ -189,7 +189,7 @@ public sealed class SequencePickerViewModel : LocalizedViewModel
{ {
var generation = _generation; var generation = _generation;
foreach (var item in WorkspaceItems.Where(i => change.ProjectId is { } id ? i.ProjectId == id foreach (var item in WorkspaceItems.Where(i => change.ProjectId is { } id ? i.ProjectId == id
: i.Entry.IsServerHome && string.Equals(i.Entry.Home.Server, change.Server, StringComparison.OrdinalIgnoreCase)).ToList()) : i.Entry.IsServerHome && Shell.Services.Workspace.SameServer(i.Entry.Home.Server, change.Server)).ToList())
{ {
if (generation != _generation) return; if (generation != _generation) return;
try try
@@ -643,7 +643,7 @@ public sealed class SequenceViewModel : SectionViewModel
{ {
workspace.Remember(row.Id, entry.ProjectId); workspace.Remember(row.Id, entry.ProjectId);
workspace.RecordOpened(entry.ProjectId); workspace.RecordOpened(entry.ProjectId);
return (new WorkspaceSequenceSource(workspace.Sync, entry.ProjectId, db, decoder, services.Engine), row.DisplayTitle); return (new WorkspaceSequenceSource(workspace.SyncOf(entry.ProjectId), entry.ProjectId, db, decoder, services.Engine), row.DisplayTitle);
} }
var projectId = entry?.ProjectId ?? request?.ProjectId; var projectId = entry?.ProjectId ?? request?.ProjectId;
string? newName = null; string? newName = null;
@@ -748,9 +748,9 @@ public sealed class SequenceViewModel : SectionViewModel
// Its analyses and renders travel on a connection of the signed-in session, when that is the project's server: // Its analyses and renders travel on a connection of the signed-in session, when that is the project's server:
// made again whenever the sign-in changes, so a project opened signed out renders once signed in. // made again whenever the sign-in changes, so a project opened signed out renders once signed in.
var server = entry.Home.Server; var server = entry.Home.Server;
var editorHome = new WorkspaceServerHome(() => string.Equals(sync.Server, server, StringComparison.OrdinalIgnoreCase) ? sync.ConnectEditor() : null, var editorHome = new WorkspaceServerHome(() => sync.Identity.Same(sync.Server, server) ? sync.ConnectEditor() : null,
() => sync.Session); () => sync.Session);
return new ServerOpen((new WorkspaceSequenceSource(workspace.Sync, entry.ProjectId, db, decoder, services.Engine, editorHome), entry.SequenceTitle)); return new ServerOpen((new WorkspaceSequenceSource(workspace.SyncOf(entry.ProjectId), entry.ProjectId, db, decoder, services.Engine, editorHome), entry.SequenceTitle));
} }
// An account that may not edit checks nothing out: it is shown with proxies, read-only, as on an older server. // An account that may not edit checks nothing out: it is shown with proxies, read-only, as on an older server.
if (!sync.Policy.CanEdit || sync.ServerHome(remoteId) is not { } home) return null; if (!sync.Policy.CanEdit || sync.ServerHome(remoteId) is not { } home) return null;
+79 -5
View File
@@ -5,7 +5,8 @@
xmlns:l="clr-namespace:Chronos.Ui.Localization;assembly=Chronos.Ui" xmlns:l="clr-namespace:Chronos.Ui.Localization;assembly=Chronos.Ui"
xmlns:infra="clr-namespace:Chronos.App.Infrastructure" xmlns:infra="clr-namespace:Chronos.App.Infrastructure"
xmlns:shell="clr-namespace:Chronos.App.Shell" xmlns:shell="clr-namespace:Chronos.App.Shell"
xmlns:srv="clr-namespace:Chronos.App.Server"> xmlns:srv="clr-namespace:Chronos.App.Server"
xmlns:sec="clr-namespace:Chronos.App.Sections">
<UserControl.Resources> <UserControl.Resources>
<Style x:Key="Text.RowLabel" TargetType="TextBlock" BasedOn="{StaticResource Text.Label}"> <Style x:Key="Text.RowLabel" TargetType="TextBlock" BasedOn="{StaticResource Text.Label}">
<Setter Property="MinWidth" Value="60" /> <Setter Property="MinWidth" Value="60" />
@@ -42,15 +43,88 @@
</Style> </Style>
</UserControl.Resources> </UserControl.Resources>
<!-- Server.html: the connection panel, the server's jobs while any run or wait paused, then the sync table. The render-node status panel is not built (see the decisions). --> <!-- Server.html: this PC's shared library, the connection panel, the server's jobs while any run or wait paused, then the sync
table. The render-node status panel is not built (see the decisions). -->
<Grid Margin="20,16,20,12"> <Grid Margin="20,16,20,12">
<Grid.RowDefinitions> <Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" /> <RowDefinition Height="Auto" />
<RowDefinition Height="Auto" /> <RowDefinition Height="Auto" />
<RowDefinition Height="*" /> <RowDefinition Height="*" />
</Grid.RowDefinitions> </Grid.RowDefinitions>
<Border Style="{StaticResource Border.Panel}" Padding="16,14"> <!-- This library (owner review 5, #67): sharing state, addresses with Copy, ports, fingerprint, temporary admin password,
clients and the admin panel; off, one row and Sharing settings. -->
<Border Style="{StaticResource Border.Panel}" Padding="16,12" DataContext="{Binding SharePanel}">
<StackPanel>
<DockPanel>
<TextBlock Style="{StaticResource Text.RowLabel}" Text="{l:Loc Server.Share.Title}" FontWeight="SemiBold" VerticalAlignment="Center" />
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Compact}" Content="{l:Loc Server.Share.AdminPanel}" Command="{Binding AdminPanelCommand}"
ToolTip="{l:Loc Tooltips.Server.Share.AdminPanel}" Visibility="{Binding IsOn, Converter={StaticResource BoolToVisibility}}" />
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Compact}" Content="{l:Loc Server.Share.Settings}" Command="{Binding SettingsCommand}"
ToolTip="{l:Loc Tooltips.Server.Share.Settings}" Visibility="{Binding IsNotShared, Converter={StaticResource BoolToVisibility}}" />
<WrapPanel VerticalAlignment="Center">
<ui:StatusGlyph Kind="{Binding StatusKind}" Text="{Binding StateText}" FontSize="13" VerticalAlignment="Center" ToolTip="{l:Loc Tooltips.Server.Share.State}"
AutomationProperties.LiveSetting="Polite" infra:LiveRegion.Text="{Binding StateText}" />
<Button Style="{StaticResource Button.Compact}" Content="{l:Loc Server.Share.Restart}" Command="{Binding RestartCommand}" ToolTip="{l:Loc Tooltips.Server.Share.Restart}"
Margin="12,0,0,0" Visibility="{Binding HasFailed, Converter={StaticResource BoolToVisibility}}" />
</WrapPanel>
</DockPanel>
<ui:StatusGlyph Kind="Error" Text="{Binding Reason}" FontSize="12" Margin="0,8,0,0" HorizontalAlignment="Left"
Visibility="{Binding Reason, Converter={x:Static ui:NullToCollapsedConverter.Instance}}" />
<Grid Margin="0,10,0,0" Visibility="{Binding IsOn, Converter={StaticResource BoolToVisibility}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Style="{StaticResource Text.RowLabel}" Text="{l:Loc Server.Share.Addresses}" Margin="0,4,10,0" VerticalAlignment="Top" />
<ItemsControl Grid.Column="1" ItemsSource="{Binding Addresses}" ItemsPanel="{StaticResource Panel.Wrap}" Focusable="False">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type sec:ShareAddressRow}">
<StackPanel Orientation="Horizontal" Margin="0,0,18,4">
<TextBlock Text="{Binding Address}" FlowDirection="LeftToRight" VerticalAlignment="Center" Typography.NumeralAlignment="Tabular" />
<Button Style="{StaticResource Button.Compact}" Content="{l:Loc Server.Share.Copy}" Command="{Binding CopyCommand}" CommandParameter="{Binding Address}"
ToolTip="{l:Loc Tooltips.Server.Share.Copy}" AutomationProperties.Name="{Binding Address}" Margin="8,0,0,0" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<TextBlock Grid.Row="1" Style="{StaticResource Text.RowLabel}" Text="{l:Loc Server.Share.Ports}" Margin="0,6,10,0" />
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding PortsText}" Margin="0,6,0,0" Typography.NumeralAlignment="Tabular" ToolTip="{l:Loc Tooltips.Server.Share.Ports}" />
<TextBlock Grid.Row="2" Style="{StaticResource Text.RowLabel}" Text="{l:Loc Server.Share.Fingerprint}" Margin="0,10,10,0" VerticalAlignment="Center" />
<StackPanel Grid.Row="2" Grid.Column="1" Orientation="Horizontal" Margin="0,6,0,0">
<TextBlock Text="{Binding Fingerprint}" FontFamily="{DynamicResource Font.Mono}" FontSize="12" VerticalAlignment="Center" TextTrimming="CharacterEllipsis"
ToolTip="{l:Loc Tooltips.Server.Share.Fingerprint}" />
<Button Style="{StaticResource Button.Compact}" Content="{l:Loc Server.Share.Copy}" Command="{Binding CopyFingerprintCommand}"
ToolTip="{l:Loc Tooltips.Server.Share.CopyFingerprint}" Margin="8,0,0,0" />
</StackPanel>
<TextBlock Grid.Row="3" Style="{StaticResource Text.RowLabel}" Text="{l:Loc Server.Share.AdminPassword}" Margin="0,10,10,0" VerticalAlignment="Center"
Visibility="{Binding HasAdminPassword, Converter={StaticResource BoolToVisibility}}" />
<StackPanel Grid.Row="3" Grid.Column="1" Orientation="Horizontal" Margin="0,6,0,0" Visibility="{Binding HasAdminPassword, Converter={StaticResource BoolToVisibility}}">
<TextBlock Text="{Binding PasswordText}" FontFamily="{DynamicResource Font.Mono}" FontSize="12" VerticalAlignment="Center" FlowDirection="LeftToRight"
ToolTip="{l:Loc Tooltips.Server.Share.AdminPassword}" />
<Button Style="{StaticResource Button.Compact}" Content="{Binding ShowPasswordText}" Command="{Binding ShowPasswordCommand}" ToolTip="{l:Loc Tooltips.Server.Share.Show}"
Margin="8,0,0,0" />
<Button Style="{StaticResource Button.Compact}" Content="{l:Loc Server.Share.Copy}" Command="{Binding CopyPasswordCommand}"
ToolTip="{l:Loc Tooltips.Server.Share.CopyPassword}" Margin="8,0,0,0" />
</StackPanel>
<TextBlock Grid.Row="4" Style="{StaticResource Text.RowLabel}" Text="{l:Loc Server.Share.Clients}" Margin="0,10,10,0" VerticalAlignment="Top" />
<StackPanel Grid.Row="4" Grid.Column="1" Margin="0,10,0,0" ToolTip="{l:Loc Tooltips.Server.Share.Clients}">
<TextBlock Text="{Binding ClientsText}" Foreground="{DynamicResource Brush.TextMuted}" />
<ItemsControl ItemsSource="{Binding Clients}" Focusable="False" Visibility="{Binding HasClients, Converter={StaticResource BoolToVisibility}}" />
</StackPanel>
</Grid>
</StackPanel>
</Border>
<Border Grid.Row="1" Style="{StaticResource Border.Panel}" Padding="16,14" Margin="0,14,0,0">
<Grid> <Grid>
<Grid.ColumnDefinitions> <Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" />
@@ -168,10 +242,10 @@
</Border> </Border>
<!-- The server's running and paused jobs, live, while there are any (owner review 5, #65). --> <!-- The server's running and paused jobs, live, while there are any (owner review 5, #65). -->
<srv:ServerJobsView Grid.Row="1" Margin="0,14,0,0" DataContext="{Binding Jobs}" Visibility="{Binding HasRows, Converter={StaticResource BoolToVisibility}}" /> <srv:ServerJobsView Grid.Row="2" Margin="0,14,0,0" DataContext="{Binding Jobs}" Visibility="{Binding HasRows, Converter={StaticResource BoolToVisibility}}" />
<!-- Sequences of this PC and of the server: chips, search, Upload all local; table; footer. --> <!-- Sequences of this PC and of the server: chips, search, Upload all local; table; footer. -->
<Border Grid.Row="2" Style="{StaticResource Border.Panel}" Margin="0,14,0,0" DataContext="{Binding Sync}"> <Border Grid.Row="3" Style="{StaticResource Border.Panel}" Margin="0,14,0,0" DataContext="{Binding Sync}">
<Grid> <Grid>
<Grid.RowDefinitions> <Grid.RowDefinitions>
<RowDefinition Height="Auto" /> <RowDefinition Height="Auto" />
@@ -44,6 +44,7 @@ public sealed class ServerViewModel : SectionViewModel
_conflicts.PropertyChanged += OnConflictsChanged; _conflicts.PropertyChanged += OnConflictsChanged;
Jobs = new ServerJobsViewModel(() => ServerJobsViewModel.AccountOf(Session), () => JobsConnection(Session), SynchronizationContext.Current, Jobs = new ServerJobsViewModel(() => ServerJobsViewModel.AccountOf(Session), () => JobsConnection(Session), SynchronizationContext.Current,
(title, message) => Shell.Notify(title, message, isError: true)); (title, message) => Shell.Notify(title, message, isError: true));
SharePanel = new SharePanelViewModel(shell);
} }
/// <summary>Sequences of this PC and of the server, where they stand and what can be done.</summary> /// <summary>Sequences of this PC and of the server, where they stand and what can be done.</summary>
@@ -55,6 +56,9 @@ public sealed class ServerViewModel : SectionViewModel
/// <summary>Opens the job list's connection for a session; the screenshots put the sample server's jobs here.</summary> /// <summary>Opens the job list's connection for a session; the screenshots put the sample server's jobs here.</summary>
internal Func<ServerSession, IServerJobsApi?> JobsConnection { get; set; } = ServerJobsViewModel.ConnectionOf; internal Func<ServerSession, IServerJobsApi?> JobsConnection { get; set; } = ServerJobsViewModel.ConnectionOf;
/// <summary>This PC's library shared to the LAN (owner review 5, #67).</summary>
public SharePanelViewModel SharePanel { get; }
public ShellViewModel Shell { get; } public ShellViewModel Shell { get; }
private ServerSession Session => _session ?? Shell.Services.Server; private ServerSession Session => _session ?? Shell.Services.Server;
@@ -233,6 +237,7 @@ public sealed class ServerViewModel : SectionViewModel
Shell.Settings.Encoders.CollectionChanged -= OnEncodersChanged; Shell.Settings.Encoders.CollectionChanged -= OnEncodersChanged;
Sync.Dispose(); Sync.Dispose();
Jobs.Dispose(); Jobs.Dispose();
SharePanel.Dispose();
base.Dispose(); base.Dispose();
} }
+119
View File
@@ -563,6 +563,28 @@
Visibility="{Binding WorkspaceRows.HasUsageText, Converter={StaticResource BoolToVisibility}}" /> Visibility="{Binding WorkspaceRows.HasUsageText, Converter={StaticResource BoolToVisibility}}" />
</StackPanel> </StackPanel>
</HeaderedContentControl> </HeaderedContentControl>
<!-- Each home keeps its projects in its own folder of the workspace (owner review 5): this PC's archive, then each server. -->
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Workspace.Homes}" ToolTip="{l:Loc Tooltips.Settings.Workspace.Homes}"
Visibility="{Binding HasHomeFolderRows, Converter={StaticResource BoolToVisibility}}">
<ItemsControl ItemsSource="{Binding HomeFolderRows}" Focusable="False">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type st:HomeFolderRow}">
<Grid Height="36">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="160" />
<ColumnDefinition Width="*" MinWidth="160" MaxWidth="360" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Cell}" Text="{Binding Name}" ToolTip="{Binding ToolTip}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding Path}" ToolTip="{Binding ToolTip}" Foreground="{DynamicResource Brush.TextMuted}"
FlowDirection="LeftToRight" HorizontalAlignment="Left" Margin="10,0,0,0" />
<Button Grid.Column="2" Style="{StaticResource Button.Row}" Content="{l:Loc Common.Open}" Command="{Binding OpenCommand}"
ToolTip="{l:Loc Tooltips.Settings.Workspace.OpenHome}" AutomationProperties.Name="{Binding Name}" Margin="10,0,0,0" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Workspace.SizeLimit}"> <HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Workspace.SizeLimit}">
<ComboBox Width="170" HorizontalAlignment="Left" ItemsSource="{Binding WorkspaceRows.SizeLimitChoices}" SelectedItem="{Binding WorkspaceRows.SelectedSizeLimit}" <ComboBox Width="170" HorizontalAlignment="Left" ItemsSource="{Binding WorkspaceRows.SizeLimitChoices}" SelectedItem="{Binding WorkspaceRows.SelectedSizeLimit}"
DisplayMemberPath="Label" ToolTip="{Binding WorkspaceRows.SizeLimitToolTip}" AutomationProperties.Name="{l:Loc Settings.Workspace.SizeLimit}" /> DisplayMemberPath="Label" ToolTip="{Binding WorkspaceRows.SizeLimitToolTip}" AutomationProperties.Name="{l:Loc Settings.Workspace.SizeLimit}" />
@@ -613,6 +635,47 @@
<!-- ================= Server ================= --> <!-- ================= Server ================= -->
<StackPanel Style="{StaticResource Page}" Visibility="{Binding Page, Converter={x:Static shell:EqualsToVisibilityConverter.Instance}, ConverterParameter=Server}"> <StackPanel Style="{StaticResource Page}" Visibility="{Binding Page, Converter={x:Static shell:EqualsToVisibilityConverter.Instance}, ConverterParameter=Server}">
<!-- Sharing (owner review 5, #67): this PC's library served to the LAN while Chronos runs. -->
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.Share}">
<CheckBox Content="{l:Loc Settings.Server.ShareLibrary}" IsChecked="{Binding ShareRows.Enabled}" ToolTip="{l:Loc Tooltips.Settings.ShareLibrary}" Margin="0,4,0,0" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.ShareName}">
<TextBox Style="{StaticResource TextBox.Setting}" Text="{Binding ShareRows.Name.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding ShareRows.Name}" ToolTip="{Binding ShareRows.Name.ToolTip}" ui:Field.Placeholder="{Binding ShareRows.PcName}"
AutomationProperties.Name="{l:Loc Settings.Server.ShareName}" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.HttpsPort}">
<TextBox Style="{StaticResource TextBox.SettingNumber}" Text="{Binding ShareRows.HttpsPort.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding ShareRows.HttpsPort}" ToolTip="{Binding ShareRows.HttpsPort.ToolTip}" AutomationProperties.Name="{l:Loc Settings.Server.HttpsPort}" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.HttpPort}">
<TextBox Style="{StaticResource TextBox.SettingNumber}" Text="{Binding ShareRows.HttpPort.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding ShareRows.HttpPort}" ToolTip="{Binding ShareRows.HttpPort.ToolTip}" AutomationProperties.Name="{l:Loc Settings.Server.HttpPort}" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.PublicHttpsPort}">
<TextBox Style="{StaticResource TextBox.SettingNumber}" Text="{Binding ShareRows.PublicHttpsPort.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding ShareRows.PublicHttpsPort}" ToolTip="{Binding ShareRows.PublicHttpsPort.ToolTip}"
AutomationProperties.Name="{l:Loc Settings.Server.PublicHttpsPort}" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.PublicHttpPort}">
<TextBox Style="{StaticResource TextBox.SettingNumber}" Text="{Binding ShareRows.PublicHttpPort.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding ShareRows.PublicHttpPort}" ToolTip="{Binding ShareRows.PublicHttpPort.ToolTip}"
AutomationProperties.Name="{l:Loc Settings.Server.PublicHttpPort}" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.Discovery}">
<CheckBox Content="{l:Loc Settings.Server.Announce}" IsChecked="{Binding ShareRows.Discovery}" ToolTip="{l:Loc Tooltips.Settings.Discovery}" Margin="0,4,0,0" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.ShareFolder}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" MinWidth="160" MaxWidth="360" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBox Style="{StaticResource TextBox.Path}" IsReadOnly="True" Text="{Binding ShareRows.Folder, Mode=OneWay}" ToolTip="{l:Loc Tooltips.Settings.ShareFolder}"
AutomationProperties.Name="{l:Loc Settings.Server.ShareFolder}" />
<Button Grid.Column="1" Content="{l:Loc Common.Open}" Command="{Binding ShareRows.OpenFolderCommand}" ToolTip="{l:Loc Tooltips.Settings.OpenShareFolder}" Margin="10,0,0,0" />
</Grid>
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.Default}"> <HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.Default}">
<TextBox Style="{StaticResource TextBox.Setting}" Text="{Binding DefaultServer.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" <TextBox Style="{StaticResource TextBox.Setting}" Text="{Binding DefaultServer.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding DefaultServer}" ToolTip="{Binding DefaultServer.ToolTip}" ui:Field.Placeholder="{l:Loc Server.AddressPlaceholder}" shell:EditBehavior.Field="{Binding DefaultServer}" ToolTip="{Binding DefaultServer.ToolTip}" ui:Field.Placeholder="{l:Loc Server.AddressPlaceholder}"
@@ -648,6 +711,62 @@
</ItemsControl> </ItemsControl>
</Grid> </Grid>
</HeaderedContentControl> </HeaderedContentControl>
<!-- The servers this PC signed in to (owner review 5): id, whether signed in now, the archive of their originals and their share of the cache. -->
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.Known}" ToolTip="{l:Loc Tooltips.Settings.Server.Known}"
Visibility="{Binding HasKnownServers, Converter={StaticResource BoolToVisibility}}">
<ItemsControl ItemsSource="{Binding KnownServers}" Focusable="False">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type st:KnownServerRow}">
<StackPanel Margin="0,0,0,8">
<Grid Height="36">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" MinWidth="120" />
<ColumnDefinition Width="170" />
<ColumnDefinition Width="90" />
<ColumnDefinition Width="90" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Cell}" Text="{Binding Name}" ToolTip="{Binding Name}" HorizontalAlignment="Left" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding Address}" ToolTip="{Binding Address}" FlowDirection="LeftToRight"
HorizontalAlignment="Left" Margin="10,0,0,0" />
<TextBlock Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding ShortId}" ToolTip="{Binding IdToolTip}" FontFamily="{StaticResource Font.Mono}"
FontSize="12" FlowDirection="LeftToRight" HorizontalAlignment="Left" Margin="10,0,0,0"
AutomationProperties.Name="{l:Loc Settings.Server.ServerId}" />
<TextBlock Grid.Column="3" Style="{StaticResource Text.Cell}" Text="{Binding StateText}" ToolTip="{Binding StateToolTip}"
Foreground="{DynamicResource Brush.TextMuted}" Margin="10,0,0,0" />
</Grid>
<Grid Height="32">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="140" />
<ColumnDefinition Width="*" MinWidth="160" MaxWidth="360" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Cell}" Text="{l:Loc Settings.Server.Originals}" ToolTip="{l:Loc Tooltips.Settings.Server.Originals}"
Foreground="{DynamicResource Brush.TextMuted}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding OriginalsPath}" ToolTip="{l:Loc Tooltips.Settings.Server.Originals}"
FlowDirection="LeftToRight" HorizontalAlignment="Left" Margin="10,0,0,0" />
<Button Grid.Column="2" Style="{StaticResource Button.Row}" Content="{l:Loc Common.Open}" Command="{Binding OpenOriginalsCommand}"
ToolTip="{l:Loc Tooltips.Settings.Server.OpenOriginals}" ToolTipService.ShowOnDisabled="True"
AutomationProperties.Name="{l:Loc Settings.Server.Originals}" Margin="10,0,0,0" />
</Grid>
<Grid Height="32">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="140" />
<ColumnDefinition Width="*" MinWidth="160" MaxWidth="360" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Cell}" Text="{l:Loc Settings.Server.Cache}" ToolTip="{l:Loc Tooltips.Settings.Server.Cache}"
Foreground="{DynamicResource Brush.TextMuted}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding CachePath}" ToolTip="{l:Loc Tooltips.Settings.Server.Cache}"
FlowDirection="LeftToRight" HorizontalAlignment="Left" Margin="10,0,0,0" />
<Button Grid.Column="2" Style="{StaticResource Button.Row}" Content="{l:Loc Common.Open}" Command="{Binding OpenCacheCommand}"
ToolTip="{l:Loc Tooltips.Settings.Server.OpenCache}" ToolTipService.ShowOnDisabled="True"
AutomationProperties.Name="{l:Loc Settings.Server.Cache}" Margin="10,0,0,0" />
</Grid>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</HeaderedContentControl>
</StackPanel> </StackPanel>
<!-- ================= Updates ================= --> <!-- ================= Updates ================= -->
+102 -4
View File
@@ -90,8 +90,9 @@ public sealed class SettingsViewModel : SectionViewModel
new(SettingsPage.Storage, ["Settings.Storage.Folder", "Settings.Storage.Thumbnails", "Settings.Storage.Limit"]), new(SettingsPage.Storage, ["Settings.Storage.Folder", "Settings.Storage.Thumbnails", "Settings.Storage.Limit"]),
new(SettingsPage.Workspace, ["Settings.Workspace.Folder", "Settings.Workspace.Move", "Settings.Workspace.SizeLimit", "Settings.Workspace.DefaultMedia", new(SettingsPage.Workspace, ["Settings.Workspace.Folder", "Settings.Workspace.Move", "Settings.Workspace.SizeLimit", "Settings.Workspace.DefaultMedia",
"Settings.Workspace.Sync", "Settings.Workspace.AfterSave", "Settings.Workspace.VersionOnRender", "Settings.Workspace.SaveBeforeRender", "Settings.Workspace.Sync", "Settings.Workspace.AfterSave", "Settings.Workspace.VersionOnRender", "Settings.Workspace.SaveBeforeRender",
"Settings.Workspace.Kept", "Settings.Workspace.CleanAfter", "Settings.Workspace.OpenProject", "Settings.Workspace.Trash"]), "Settings.Workspace.Kept", "Settings.Workspace.CleanAfter", "Settings.Workspace.OpenProject", "Settings.Workspace.Trash", "Settings.Workspace.Homes"]),
new(SettingsPage.Server, ["Settings.Server.Default", "Settings.Server.RenderNode", "Settings.Server.Certificates"]), new(SettingsPage.Server, ["Settings.Server.Share", "Settings.Server.ShareName", "Settings.Server.HttpsPort", "Settings.Server.HttpPort",
"Settings.Server.PublicHttpsPort", "Settings.Server.PublicHttpPort", "Settings.Server.Discovery", "Settings.Server.ShareFolder", "Settings.Server.Default", "Settings.Server.RenderNode", "Settings.Server.Certificates", "Settings.Server.Known"]),
new(SettingsPage.Updates, ["Settings.General.CheckOnStart", "Settings.Updates.Latest", "About.Update.Check", "About.Releases"]), new(SettingsPage.Updates, ["Settings.General.CheckOnStart", "Settings.Updates.Latest", "About.Update.Check", "About.Releases"]),
new(SettingsPage.Advanced, ["Settings.Advanced.DataFolder", "Settings.Advanced.Logs", "Settings.Advanced.LogLevel", "Settings.Advanced.KeepLogs", new(SettingsPage.Advanced, ["Settings.Advanced.DataFolder", "Settings.Advanced.Logs", "Settings.Advanced.LogLevel", "Settings.Advanced.KeepLogs",
"Settings.Advanced.FileSize", "Settings.Advanced.LogsTotal", "Settings.Advanced.Rotation", "Settings.Advanced.Diagnostics", "Settings.Advanced.FileSize", "Settings.Advanced.LogsTotal", "Settings.Advanced.Rotation", "Settings.Advanced.Diagnostics",
@@ -177,6 +178,9 @@ public sealed class SettingsViewModel : SectionViewModel
// Saving applies them to the log files (App.SaveSettings). // Saving applies them to the log files (App.SaveSettings).
Logs = new LogSettingsRows(_s, Save); Logs = new LogSettingsRows(_s, Save);
// ---- Server › Sharing (owner review 5, #67); saving applies it to the share (AppServices.SaveSettings). ----
ShareRows = new ShareSettingsRows(_s, Save, Shell.Services.Environment.ShareDirectory, Shell.Services.Environment.PcName);
// ---- Workspace ---- // ---- Workspace ----
WorkspaceRows = new WorkspaceSettingsRows(_s, Save, () => AppEnvironment.Shown(Shell.Services.Workspace.Root), OpenWorkspaceFolder, ChangeWorkspaceFolderAsync, WorkspaceRows = new WorkspaceSettingsRows(_s, Save, () => AppEnvironment.Shown(Shell.Services.Workspace.Root), OpenWorkspaceFolder, ChangeWorkspaceFolderAsync,
WorkspaceSettingsServices.For(Shell.Services.Workspace, Shell.Services.Dialogs, (title, message, isError) => Shell.Notify(title, message, isError: isError), WorkspaceSettingsServices.For(Shell.Services.Workspace, Shell.Services.Dialogs, (title, message, isError) => Shell.Notify(title, message, isError: isError),
@@ -272,7 +276,12 @@ public sealed class SettingsViewModel : SectionViewModel
if (value == SettingsPage.Rendering && Encoders.Count == 0 && !_isDetecting) _ = DetectEncodersAsync(); if (value == SettingsPage.Rendering && Encoders.Count == 0 && !_isDetecting) _ = DetectEncodersAsync();
if (value == SettingsPage.Formats && Formats.Count == 0 && !_isDetectingFormats) _ = DetectFormatsAsync(refresh: false); if (value == SettingsPage.Formats && Formats.Count == 0 && !_isDetectingFormats) _ = DetectFormatsAsync(refresh: false);
if (value == SettingsPage.Storage) _ = UpdateCacheUsageAsync(); if (value == SettingsPage.Storage) _ = UpdateCacheUsageAsync();
if (value == SettingsPage.Workspace) _ = WorkspaceRows.MeasureAsync(); if (value == SettingsPage.Workspace)
{
_ = WorkspaceRows.MeasureAsync();
_ = LoadHomeFoldersAsync();
}
if (value == SettingsPage.Server) _ = LoadKnownServersAsync();
if (value == SettingsPage.Advanced) LoadBackups(); if (value == SettingsPage.Advanced) LoadBackups();
} }
} }
@@ -741,7 +750,7 @@ public sealed class SettingsViewModel : SectionViewModel
{ {
try try
{ {
ShellActions.Reveal(Shell.Services.Workspace.Store.Root); ShellActions.Reveal(Shell.Services.Workspace.Homes.Root);
} }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException) catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
{ {
@@ -793,6 +802,16 @@ public sealed class SettingsViewModel : SectionViewModel
public bool HasCertificates => Certificates.Count > 0; public bool HasCertificates => Certificates.Count > 0;
/// <summary>Settings › Server › Known servers (owner review 5, #66): the servers this PC signed in to, with their folders.</summary>
public ObservableCollection<KnownServerRow> KnownServers { get; } = [];
public bool HasKnownServers => KnownServers.Count > 0;
/// <summary>Settings › Workspace › Home folders (owner review 5, #66): where each home keeps its projects.</summary>
public ObservableCollection<HomeFolderRow> HomeFolderRows { get; } = [];
public bool HasHomeFolderRows => HomeFolderRows.Count > 0;
// ---------------- Updates ---------------- // ---------------- Updates ----------------
public bool CheckForUpdates public bool CheckForUpdates
@@ -816,6 +835,9 @@ public sealed class SettingsViewModel : SectionViewModel
/// <summary>Level, retention, size limits and rotation of the log files, and the diagnostics bundle's share of each.</summary> /// <summary>Level, retention, size limits and rotation of the log files, and the diagnostics bundle's share of each.</summary>
public LogSettingsRows Logs { get; } public LogSettingsRows Logs { get; }
/// <summary>Settings › Server › Sharing: this PC's library shared to the LAN (owner review 5, #67).</summary>
public ShareSettingsRows ShareRows { get; }
public ICommand OpenDataFolderCommand { get; } public ICommand OpenDataFolderCommand { get; }
public ICommand OpenLogsCommand { get; } public ICommand OpenLogsCommand { get; }
public ICommand ExportDiagnosticsCommand { get; } public ICommand ExportDiagnosticsCommand { get; }
@@ -897,6 +919,8 @@ public sealed class SettingsViewModel : SectionViewModel
Shell.Notify(Loc.L("Settings.Advanced.RestoreFailed"), Loc.L("Errors.Backup.Deferred"), isError: true); Shell.Notify(Loc.L("Settings.Advanced.RestoreFailed"), Loc.L("Errors.Backup.Deferred"), isError: true);
break; break;
} }
NotifyHomeLayout();
Shell.Services.Sync.IdentityClash += (name, was) => Shell.Notify(Loc.L("Shell.Homes.Clash"), Loc.L("Errors.Homes.Clash", name, was), isError: true);
// BRIEF §6.2: a portable copy in a folder OneDrive synchronises keeps its data in this user's folder instead, and // BRIEF §6.2: a portable copy in a folder OneDrive synchronises keeps its data in this user's folder instead, and
// leaves the data it kept beside it before where it is. Only a user folder that is itself synchronised is unsafe. // leaves the data it kept beside it before where it is. Only a user folder that is itself synchronised is unsafe.
var environment = Shell.Services.Environment; var environment = Shell.Services.Environment;
@@ -1559,6 +1583,27 @@ public sealed class SettingsViewModel : SectionViewModel
} }
} }
/// <summary>
/// How the sorting of the folders into homes went at start (owner review 5, #66): sorted, with Open on the workspace;
/// pending, when projects in use or a workspace being moved wait for the next start; or failed, with Open on the logs.
/// </summary>
private void NotifyHomeLayout()
{
var services = Shell.Services;
if (services.HomeLayoutError is { } error)
{
Shell.Notify(Loc.L("Shell.Homes.Pending"), Loc.L("Errors.Homes.Failed", error.Message), Loc.L("Settings.Advanced.Logs"),
Loc.L("Tooltips.Shell.Homes.Logs"), () => ShellActions.Reveal(services.Environment.LogDirectory), isError: true);
return;
}
if (services.HomeLayout is not { } result) return;
if (result.Deferred is not null || result.InUse > 0)
Shell.Notify(Loc.L("Shell.Homes.Pending"), Loc.L("Shell.Homes.PendingText"));
else if (result.ProjectsMoved > 0)
Shell.Notify(Loc.L("Shell.Homes.Sorted"), Loc.Plural("Shell.Homes.Moved", result.ProjectsMoved), Loc.L("Common.Open"),
Loc.L("Tooltips.Settings.OpenWorkspace"), OpenWorkspaceFolder);
}
private void CancelRestore() private void CancelRestore()
{ {
try try
@@ -1629,6 +1674,7 @@ public sealed class SettingsViewModel : SectionViewModel
break; break;
case SettingsPage.Server: case SettingsPage.Server:
_s.RenderNodeOptIn = defaults.RenderNodeOptIn; _s.RenderNodeOptIn = defaults.RenderNodeOptIn;
ShareRows.Reset();
break; break;
case SettingsPage.Updates: case SettingsPage.Updates:
_s.CheckForUpdates = defaults.CheckForUpdates; _s.CheckForUpdates = defaults.CheckForUpdates;
@@ -1736,6 +1782,7 @@ public sealed class SettingsViewModel : SectionViewModel
foreach (var row in JobPriorities) row.Refresh(); foreach (var row in JobPriorities) row.Refresh();
Logs.Refresh(); Logs.Refresh();
WorkspaceRows.Refresh(); WorkspaceRows.Refresh();
ShareRows.Refresh();
UpdatePreview(); UpdatePreview();
LoadCertificates(); LoadCertificates();
OnAllPropertiesChanged(); OnAllPropertiesChanged();
@@ -1781,6 +1828,57 @@ public sealed class SettingsViewModel : SectionViewModel
Shell.Notify(Loc.L("Settings.Import.Done")); Shell.Notify(Loc.L("Settings.Import.Done"));
} }
/// <summary>The home folders of the workspace as they are now (read off the UI thread; none while the workspace cannot be read).</summary>
private async Task LoadHomeFoldersAsync()
{
var workspace = Shell.Services.Workspace;
if (!workspace.IsEnabled) return;
var known = _s.KnownServers.ToList();
IReadOnlyList<HomeFolderRow> rows;
try
{
rows = await Task.Run(() => HomeFolderRow.Of(workspace.Homes, known, RevealFolder));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
{
Log.Info("settings", $"The home folders of the workspace could not be read: {ex.Message}");
rows = [];
}
HomeFolderRows.Clear();
foreach (var row in rows) HomeFolderRows.Add(row);
OnPropertyChanged(nameof(HasHomeFolderRows));
}
/// <summary>The known servers, most recently seen first, with the archive of their originals and their share of the cache.</summary>
private async Task LoadKnownServersAsync()
{
var services = Shell.Services;
IReadOnlyList<Archive> archives = services.Database is { } db ? await db.Archives.ListAsync() : [];
var cache = CacheStore.Folder(services.Environment, services.Settings);
var signedIn = services.Sync.Server;
KnownServers.Clear();
foreach (var server in _s.KnownServers.Where(k => k.Id != Guid.Empty).OrderByDescending(k => k.LastSeen))
{
var key = HomeFolders.IdKey(server.Id);
var originals = server.OriginalsArchiveId is { } id ? archives.FirstOrDefault(a => a.Id == id)?.RootPath : null;
KnownServers.Add(new KnownServerRow(server, services.Sync.Identity.Same(signedIn, key), originals,
CacheStore.ServerFolder(cache, key, services.Sync.Identity), RevealFolder));
}
OnPropertyChanged(nameof(HasKnownServers));
}
private void RevealFolder(string folder)
{
try
{
ShellActions.Reveal(folder);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Shell.ReportError(ex);
}
}
private void LoadCertificates() private void LoadCertificates()
{ {
Certificates.Clear(); Certificates.Clear();
@@ -0,0 +1,171 @@
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using Chronos.App.Infrastructure;
using Chronos.App.Server;
using Chronos.App.Settings;
using Chronos.App.Shell;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Ui.Controls;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Sections;
/// <summary>An address of the shared library with its Copy button.</summary>
public sealed record ShareAddressRow(string Address, ICommand CopyCommand);
/// <summary>
/// Server › This library (owner review 5, #67): whether this PC shares its library, why not when it could not start
/// (with Restart), the addresses with Copy, the ports, the certificate's fingerprint with Copy, the first administrator's
/// temporary password while it exists (Show, Copy), the clients of the last minutes and the admin panel. Off, one row and
/// Sharing settings. Follows <see cref="LibraryShare"/> on the UI thread; the clients are read again every few seconds.
/// </summary>
public sealed class SharePanelViewModel : LocalizedViewModel
{
private static readonly TimeSpan RefreshInterval = TimeSpan.FromSeconds(10);
private readonly ShellViewModel _shell;
private readonly LibraryShare _share;
private readonly DispatcherTimer? _timer;
private bool _showPassword;
public SharePanelViewModel(ShellViewModel shell)
{
_shell = shell;
_share = shell.Services.Share;
_share.PropertyChanged += OnShareChanged;
CopyCommand = new RelayCommand(p => Copy(p as string));
CopyFingerprintCommand = new RelayCommand(() => Copy(_share.Fingerprint), () => _share.Fingerprint is not null);
ShowPasswordCommand = new RelayCommand(() =>
{
_showPassword = !_showPassword;
OnPropertyChanged(nameof(PasswordText));
OnPropertyChanged(nameof(ShowPasswordText));
}, () => _share.AdminPassword is not null);
CopyPasswordCommand = new RelayCommand(() => Copy(_share.AdminPassword), () => _share.AdminPassword is not null);
AdminPanelCommand = new RelayCommand(() => ShellActions.OpenUrl($"https://localhost:{_share.HttpsPort}/admin"), () => _share.IsOn && _share.HttpsPort > 0);
RestartCommand = new RelayCommand(() => _ = RestartAsync(), () => _share.State is ShareState.Failed);
SettingsCommand = new RelayCommand(() =>
{
_shell.Settings.Page = SettingsPage.Server;
_shell.Navigate(SectionKey.Settings);
});
if (Application.Current is not null && !shell.Services.Environment.IsCapture)
{
_timer = new DispatcherTimer(DispatcherPriority.Background) { Interval = RefreshInterval };
_timer.Tick += (_, _) =>
{
if (_share.IsOn) _ = RefreshAsync();
};
_timer.Start();
}
}
public ICommand CopyCommand { get; }
public ICommand CopyFingerprintCommand { get; }
public ICommand ShowPasswordCommand { get; }
public ICommand CopyPasswordCommand { get; }
public ICommand AdminPanelCommand { get; }
public ICommand RestartCommand { get; }
public ICommand SettingsCommand { get; }
/// <summary>Sharing is on in the settings, whether it runs or not: the details show.</summary>
public bool IsShared => _share.State is not ShareState.Off;
public bool IsNotShared => !IsShared;
public bool IsOn => _share.IsOn;
public bool HasFailed => _share.State is ShareState.Failed;
public StatusKind StatusKind => _share.State switch
{
ShareState.On => StatusKind.Online,
ShareState.Starting => StatusKind.Running,
ShareState.Failed => StatusKind.Error,
_ => StatusKind.Offline,
};
public string StateText => Loc.L("Server.Share.State." + _share.State);
public string? Reason => _share.Reason;
public IReadOnlyList<ShareAddressRow> Addresses => [.. _share.Addresses.Select(a => new ShareAddressRow(a, CopyCommand))];
public string? PortsText => _share.IsOn ? Loc.L("Server.Share.PortsValue", _share.HttpsPort, _share.HttpPort) : null;
public string? Fingerprint => _share.Fingerprint is { } fingerprint ? Formatting.LeftToRight(fingerprint) : null;
public bool HasAdminPassword => _share.AdminPassword is not null;
/// <summary>The temporary password, masked until Show.</summary>
public string? PasswordText => _share.AdminPassword is not { } password ? null : _showPassword ? password : new string('•', 12);
public string ShowPasswordText => Loc.L(_showPassword ? "Server.Share.Hide" : "Server.Share.Show");
/// <summary>"anna · Chronos Uploader · 192.168.1.20", the latest first.</summary>
public IReadOnlyList<string> Clients => [.. _share.Clients.Select(c => Loc.L("Server.Share.ClientRow", c.User, c.Program, c.Address).TrimEnd(' ', '·'))];
public bool HasClients => _share.Clients.Count > 0;
public string ClientsText => HasClients ? Loc.Plural("Server.Share.ClientCount", _share.Clients.Count) : Loc.L("Server.Share.NoClients");
public override void Dispose()
{
_timer?.Stop();
_share.PropertyChanged -= OnShareChanged;
base.Dispose();
}
private async Task RestartAsync()
{
await _share.RestartAsync();
CommandManager.InvalidateRequerySuggested();
}
private async Task RefreshAsync()
{
try
{
await _share.RefreshAsync();
}
catch (Exception ex) when (ex is InvalidOperationException or ObjectDisposedException)
{
Log.Warning("share", "The clients of the shared library could not be read", ex);
}
}
private static void Copy(string? text)
{
if (string.IsNullOrEmpty(text)) return;
try
{
Clipboard.SetText(text);
}
catch (ExternalException ex)
{
// Another program holds the clipboard: nothing was copied, as the next try may.
Log.Warning("share", "The clipboard is busy", ex);
}
}
private void OnShareChanged(object? sender, PropertyChangedEventArgs e)
{
if (Application.Current?.Dispatcher is { } dispatcher && !dispatcher.CheckAccess())
{
dispatcher.BeginInvoke(Changed);
return;
}
Changed();
}
private void Changed()
{
if (!_share.IsOn) _showPassword = false;
OnAllPropertiesChanged();
CommandManager.InvalidateRequerySuggested();
}
}
+1 -1
View File
@@ -551,7 +551,7 @@ public sealed class VideosViewModel : SectionViewModel, Chronos.App.Editor.IVide
var workspace = services.Workspace; var workspace = services.Workspace;
if (!workspace.IsAvailable || !Directory.Exists(workspace.Root)) return []; if (!workspace.IsAvailable || !Directory.Exists(workspace.Root)) return [];
var projects = await workspace.ListAsync(cancellationToken); var projects = await workspace.ListAsync(cancellationToken);
return await Task.Run(() => VideoSources.ReadWorkspace(workspace.Store, projects), cancellationToken); return await Task.Run(() => VideoSources.ReadWorkspace(workspace.Homes, projects), cancellationToken);
} }
/// <summary>The signed-in session's server, its capability and the account's rights.</summary> /// <summary>The signed-in session's server, its capability and the account's rights.</summary>
+11
View File
@@ -75,6 +75,9 @@ public enum ConnectError
/// <summary>The certificate differs from the trusted one; the saved session was dropped.</summary> /// <summary>The certificate differs from the trusted one; the saved session was dropped.</summary>
CertificateChanged, CertificateChanged,
Failed, Failed,
/// <summary>The address is this PC's own shared library (owner review 5, #67), which this desktop already has open.</summary>
OwnLibrary,
} }
/// <summary> /// <summary>
@@ -112,6 +115,12 @@ public sealed class ConnectFlow(IServerApiFactory factory, ITrustStore trust) :
/// <summary>Raised after every step change.</summary> /// <summary>Raised after every step change.</summary>
public event EventHandler? Changed; public event EventHandler? Changed;
/// <summary>
/// True for this PC's own shared library, by its certificate fingerprint or its server id (owner review 5, #67): the
/// flow refuses it before any trust question or password.
/// </summary>
public Func<string?, Guid?, bool>? IsOwnLibrary { get; set; }
/// <summary>Identifies the server at <paramref name="address"/>: ends in AwaitingTrust, AwaitingCredentials or Failed.</summary> /// <summary>Identifies the server at <paramref name="address"/>: ends in AwaitingTrust, AwaitingCredentials or Failed.</summary>
public async Task<ConnectStep> ProbeAsync(string address, CancellationToken ct = default) public async Task<ConnectStep> ProbeAsync(string address, CancellationToken ct = default)
{ {
@@ -221,10 +230,12 @@ public sealed class ConnectFlow(IServerApiFactory factory, ITrustStore trust) :
var clock = Stopwatch.StartNew(); var clock = Stopwatch.StartNew();
Info = await _api.GetInfoAsync(ct); Info = await _api.GetInfoAsync(ct);
Latency = clock.Elapsed; Latency = clock.Elapsed;
if (IsOwnLibrary?.Invoke(Info.TlsFingerprint, Info.ServerId) == true) return Fail(ConnectError.OwnLibrary);
return Set(ConnectStep.AwaitingCredentials, ConnectError.None); return Set(ConnectStep.AwaitingCredentials, ConnectError.None);
} }
catch (UntrustedCertificateException untrusted) catch (UntrustedCertificateException untrusted)
{ {
if (IsOwnLibrary?.Invoke(untrusted.Fingerprint, null) == true) return Fail(ConnectError.OwnLibrary);
PendingFingerprint = untrusted.Fingerprint; PendingFingerprint = untrusted.Fingerprint;
return Set(ConnectStep.AwaitingTrust, ConnectError.None); return Set(ConnectStep.AwaitingTrust, ConnectError.None);
} }
+495
View File
@@ -0,0 +1,495 @@
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using Chronos.App.Infrastructure;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Data;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Housekeeping;
using Chronos.Data.Projects;
using Chronos.Server.Configuration;
using Chronos.Server.Hosting;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Server;
/// <summary>Where sharing this PC's library stands (Server › This library).</summary>
public enum ShareState
{
/// <summary>Settings › Server › Share this library is off.</summary>
Off,
Starting,
/// <summary>The library is served: clients connect to <see cref="LibraryShare.Addresses"/>.</summary>
On,
/// <summary>Sharing is on in the settings but could not start: <see cref="LibraryShare.Reason"/> says why.</summary>
Failed,
}
/// <summary>A program that used the shared library lately, as the Server section lists it.</summary>
public sealed record ShareClient(string User, string Program, string Address, DateTimeOffset? LastSeen);
/// <summary>
/// Settings › Server › Share this library (owner review 5, #67): the server Chronos hosts in its own process to serve this
/// PC's current archive to the LAN, over the index, engines, job engine and scheduler of <see cref="AppServices"/> (one
/// engine, one index). Started after the schedules, stopped before them; started, stopped and restarted off the UI thread,
/// one at a time. A settings save applies the live values at once and restarts on a new name, port, discovery choice or
/// archive. Its state, addresses, fingerprint, clients and the first administrator's temporary password are what the Server
/// section shows. Property changes are raised on any thread (scalar values and whole lists only).
/// </summary>
public sealed class LibraryShare : ObservableObject, IAsyncDisposable
{
private readonly AppServices _services;
private readonly SemaphoreSlim _gate = new(1, 1);
private HostedServer? _server;
private ShareSettings? _running;
private string? _archiveRoot;
private ShareState _state = ShareState.Off;
private string? _reason;
private IReadOnlyList<string> _addresses = [];
private IReadOnlyList<ShareClient> _clients = [];
private string? _fingerprint;
private string? _adminPassword;
private int _httpsPort;
private int _httpPort;
private bool _sample;
private bool _disposed;
public LibraryShare(AppServices services)
{
_services = services;
}
public ShareState State
{
get => _state;
private set
{
if (!Set(ref _state, value)) return;
OnPropertyChanged(nameof(IsOn));
Changed?.Invoke();
}
}
/// <summary>True while the library is served.</summary>
public bool IsOn => _state == ShareState.On;
/// <summary>One sentence on why sharing did not start; null otherwise.</summary>
public string? Reason
{
get => _reason;
private set => Set(ref _reason, value);
}
/// <summary>The addresses clients reach this library at, one per name and network address of this PC.</summary>
public IReadOnlyList<string> Addresses
{
get => _addresses;
private set => Set(ref _addresses, value);
}
/// <summary>The certificate's SHA-256 fingerprint, colon hex, as clients see it on their first connection.</summary>
public string? Fingerprint
{
get => _fingerprint;
private set => Set(ref _fingerprint, value);
}
/// <summary>The port the HTTPS listener got; 0 while not shared.</summary>
public int HttpsPort
{
get => _httpsPort;
private set => Set(ref _httpsPort, value);
}
/// <summary>The port the HTTP listener got; 0 while not shared.</summary>
public int HttpPort
{
get => _httpPort;
private set => Set(ref _httpPort, value);
}
/// <summary>The first administrator's temporary password while its file exists; null once an administrator set their own.</summary>
public string? AdminPassword
{
get => _adminPassword;
private set => Set(ref _adminPassword, value);
}
/// <summary>The programs of the last minutes and the render nodes online (<see cref="RefreshAsync"/>).</summary>
public IReadOnlyList<ShareClient> Clients
{
get => _clients;
private set => Set(ref _clients, value);
}
/// <summary>The server while the library is served (tests, the change bridge); null otherwise.</summary>
public HostedServer? Server => _server;
/// <summary>The private folder of the shared library's own state: certificate, settings, partial uploads, logs.</summary>
public string Folder => _services.Environment.ShareDirectory;
/// <summary>The state changed (any thread).</summary>
public event Action? Changed;
/// <summary>
/// Starts sharing when Settings › Server says so and it is not running: the current archive of Settings › Archive is
/// served. Never throws: a failure is the state <see cref="ShareState.Failed"/> with its <see cref="Reason"/>.
/// </summary>
public async Task StartAsync(CancellationToken cancellationToken = default)
{
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
if (_disposed || _sample || _server is not null || !_services.Settings.Share.Enabled) return;
await StartCoreAsync(cancellationToken).ConfigureAwait(false);
}
finally
{
_gate.Release();
}
}
/// <summary>Stops sharing (the desktop's engines run on); the state reads as the settings say.</summary>
public async Task StopAsync()
{
await _gate.WaitAsync().ConfigureAwait(false);
try
{
await StopCoreAsync().ConfigureAwait(false);
State = ShareState.Off;
Reason = null;
}
finally
{
_gate.Release();
}
}
/// <summary>Stops sharing if it runs and starts it again (Server › Restart, a new port or archive).</summary>
public async Task RestartAsync(CancellationToken cancellationToken = default)
{
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
if (_disposed || _sample) return;
await StopCoreAsync().ConfigureAwait(false);
if (_services.Settings.Share.Enabled) await StartCoreAsync(cancellationToken).ConfigureAwait(false);
else State = ShareState.Off;
}
finally
{
_gate.Release();
}
}
/// <summary>
/// The settings were saved: sharing turned off stops, turned on starts, a new name, port, discovery choice or archive
/// restarts; the parallelism, the priority queue, the language and the logs apply to the running server at once.
/// </summary>
public void Apply()
{
if (_disposed || _sample) return;
var share = _services.Settings.Share;
if (!share.Enabled)
{
if (_server is not null || _state != ShareState.Off) _ = Run(StopAsync());
return;
}
if (_server is not { } server)
{
// Not running yet: the start after the schedules starts it, or it waits for the index; a failed one tries again.
if (_services.Scheduler is not null && _state != ShareState.Starting) _ = Run(StartAsync());
return;
}
if (_running is { } running && running.SameEndpoint(share) && string.Equals(_archiveRoot, _services.Settings.LastArchivePath, StringComparison.OrdinalIgnoreCase))
{
try
{
server.ApplyDesktop(DesktopValues(_archiveRoot!));
}
catch (InvalidOperationException ex)
{
Log.Warning("share", "The settings could not be applied to the shared library", ex);
}
return;
}
_ = Run(RestartAsync());
}
/// <summary>True for this PC's own shared library, by its certificate or its server id: the desktop never connects to itself.</summary>
public bool IsOwn(string? fingerprint, Guid? serverId)
{
if (_server is not { } server) return false;
if (serverId is { } id && server.ServerId == id) return true;
return fingerprint is { Length: > 0 } && string.Equals(fingerprint, server.Fingerprint, StringComparison.OrdinalIgnoreCase);
}
/// <summary>Reads the programs of the last minutes, the render nodes online and the temporary password again.</summary>
public async Task RefreshAsync(CancellationToken cancellationToken = default)
{
if (_sample || _server is not { } server) return;
var clients = server.Clients.Recent().Select(c => new ShareClient(c.User, c.Client, c.Address, c.LastSeen)).ToList();
try
{
foreach (var node in await server.RenderNodesAsync(cancellationToken).ConfigureAwait(false))
clients.Add(new ShareClient(node, Loc.L("Server.Share.RenderNode"), string.Empty, null));
}
catch (Exception ex) when (ex is DatabaseException or InvalidOperationException or ObjectDisposedException)
{
Log.Warning("share", "The render nodes online could not be read", ex);
}
Clients = clients;
AdminPassword = server.AdminPassword();
}
/// <summary>The <c>uploads</c> clean-up step while sharing (<see cref="ShareUploadsStep"/>): the server's sweep, or nothing.</summary>
public Task<string> SweepUploadsAsync(CleanupContext context, CleanupParameters parameters) =>
_server is { } server ? server.SweepUploadsAsync(context, parameters) : Task.FromResult(Loc.L("Server.Log.SharingOff"));
/// <summary>The desktop's archive or processing service changed sequence <paramref name="id"/>: the clients are told.</summary>
public Task SequenceChangedAsync(Guid id, string change, CancellationToken cancellationToken) =>
_server is { } server ? server.SequenceChangedAsync(id, change, cancellationToken) : Task.CompletedTask;
/// <summary>The desktop's archive service changed a sequence's projects: the clients are told.</summary>
public Task ProjectsChangedAsync(ProjectChangeSet changed, CancellationToken cancellationToken) =>
_server is { } server ? server.ProjectsChangedAsync(changed, cancellationToken) : Task.CompletedTask;
/// <summary>Capture and design time: a shared library with sample values, no server.</summary>
internal void ShowSample(ShareState state, string? reason, IReadOnlyList<string> addresses, int httpsPort, int httpPort, string? fingerprint,
string? adminPassword, IReadOnlyList<ShareClient> clients)
{
_sample = true;
Reason = reason;
Addresses = addresses;
HttpsPort = httpsPort;
HttpPort = httpPort;
Fingerprint = fingerprint;
AdminPassword = adminPassword;
Clients = clients;
State = state;
}
public async ValueTask DisposeAsync()
{
await _gate.WaitAsync().ConfigureAwait(false);
try
{
if (_disposed) return;
_disposed = true;
await StopCoreAsync().ConfigureAwait(false);
}
finally
{
_gate.Release();
}
}
/// <summary>The addresses of <paramref name="port"/> on this PC: its name, its full name, and each network address that is up.</summary>
public static IReadOnlyList<string> AddressesOf(int port)
{
var hosts = new List<string> { System.Environment.MachineName };
try
{
if (IPGlobalProperties.GetIPGlobalProperties().DomainName is { Length: > 0 } domain) hosts.Add(System.Environment.MachineName + "." + domain);
foreach (var network in NetworkInterface.GetAllNetworkInterfaces())
{
if (network.OperationalStatus != OperationalStatus.Up || network.NetworkInterfaceType == NetworkInterfaceType.Loopback) continue;
foreach (var unicast in network.GetIPProperties().UnicastAddresses)
{
var ip = unicast.Address;
if (IPAddress.IsLoopback(ip)) continue;
if (ip.AddressFamily == AddressFamily.InterNetwork && !ip.ToString().StartsWith("169.254.", StringComparison.Ordinal)) hosts.Add(ip.ToString());
else if (ip.AddressFamily == AddressFamily.InterNetworkV6 && !ip.IsIPv6LinkLocal && !ip.IsIPv6SiteLocal && !ip.IsIPv6Multicast)
hosts.Add("[" + new IPAddress(ip.GetAddressBytes()) + "]");
}
}
}
catch (NetworkInformationException ex)
{
Log.Warning("share", "The network addresses of this PC could not be read", ex);
}
return [.. hosts.Distinct(StringComparer.OrdinalIgnoreCase).Select(h => $"https://{h}:{port}")];
}
private async Task StartCoreAsync(CancellationToken cancellationToken)
{
var s = _services;
if (s.Database is not { } db || s.Archives is not { } archives || s.Processing is not { } processing || s.Engine is not { } engine
|| s.Scheduler is not { } scheduler)
{
Fail(Loc.L("Errors.Share.NotReady"));
return;
}
Reason = null;
State = ShareState.Starting;
var archive = await s.ScheduleHost.GetArchiveAsync(cancellationToken).ConfigureAwait(false);
if (archive is null)
{
Fail(Loc.L("Errors.Share.NoArchive"));
return;
}
var share = Snapshot(s.Settings.Share);
HostedServer? server = null;
try
{
server = await Task.Run(() =>
{
var options = ServerOptions.ForHosted(Folder, DesktopValues(archive.RootPath));
return ServerHost.BuildHosted(options, new HostedEngine(db, archives, processing, engine, scheduler, archive));
}, cancellationToken).ConfigureAwait(false);
// Off the caller's thread: the server's own services never continue on the UI thread.
await Task.Run(() => server.StartAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException && Failure(ex, share) is { } reason)
{
if (server is not null) await DisposeQuietlyAsync(server).ConfigureAwait(false);
Log.Error("share", "This library could not be shared", ex);
Fail(reason);
return;
}
_server = server;
_running = share;
_archiveRoot = archive.RootPath;
server.JobChangedOutside += OnJobChangedOutside;
HttpsPort = server.HttpsPort;
HttpPort = server.HttpPort;
Fingerprint = server.Fingerprint;
Addresses = AddressesOf(server.HttpsPort);
NetworkChange.NetworkAddressChanged += OnNetworkChanged;
await RefreshAsync(cancellationToken).ConfigureAwait(false);
Log.Info("share", $"Sharing {archive.RootPath} on HTTPS {server.HttpsPort} and HTTP {server.HttpPort}");
State = ShareState.On;
}
private async Task StopCoreAsync()
{
if (_server is not { } server) return;
_server = null;
_running = null;
_archiveRoot = null;
NetworkChange.NetworkAddressChanged -= OnNetworkChanged;
server.JobChangedOutside -= OnJobChangedOutside;
await DisposeQuietlyAsync(server).ConfigureAwait(false);
Addresses = [];
Clients = [];
Fingerprint = null;
AdminPassword = null;
HttpsPort = 0;
HttpPort = 0;
Log.Info("share", "Sharing stopped");
}
private void Fail(string reason)
{
Reason = reason;
State = ShareState.Failed;
}
/// <summary>The desktop's values the shared library takes: Settings › Server, Rendering, Videos and Advanced › Logs.</summary>
private HostedSettings DesktopValues(string archiveRoot)
{
var s = _services.Settings;
var share = s.Share;
return new HostedSettings(string.IsNullOrWhiteSpace(share.Name) ? null : share.Name.Trim(), share.HttpPort, share.HttpsPort, share.PublicHttpPort,
share.PublicHttpsPort, share.Discovery, archiveRoot, string.IsNullOrWhiteSpace(s.VideosFolder) ? null : s.VideosFolder, _services.Parallelism,
s.PriorityQueue, new Dictionary<string, string>(s.JobPriorities, StringComparer.OrdinalIgnoreCase), Loc.Culture.TwoLetterISOLanguageName,
s.LogLevel, s.LogRetentionDays, s.LogMaxFileMb, s.LogMaxTotalMb, s.LogRotation, s.DiagnosticsLogMb);
}
/// <summary>The sentence for a start that failed; null for an exception that is not an expected failure.</summary>
private static string? Failure(Exception ex, ShareSettings share)
{
if (IsAddressInUse(ex)) return Loc.L("Errors.Share.PortInUse", PortInUse(share));
return ex is InvalidOperationException or IOException or UnauthorizedAccessException or System.Security.Cryptography.CryptographicException
or DatabaseException or ArgumentException
? Loc.L("Errors.Share.Failed", ex.Message)
: null;
}
private static bool IsAddressInUse(Exception ex)
{
for (var e = ex; e is not null; e = e.InnerException)
{
if (e is Microsoft.AspNetCore.Connections.AddressInUseException or SocketException { SocketErrorCode: SocketError.AddressAlreadyInUse }) return true;
}
return false;
}
/// <summary>The configured port another program listens on (the HTTPS one when neither can be told).</summary>
private static int PortInUse(ShareSettings share)
{
try
{
var listening = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners().Select(e => e.Port).ToHashSet();
if (!listening.Contains(share.HttpsPort) && listening.Contains(share.HttpPort)) return share.HttpPort;
}
catch (NetworkInformationException)
{
}
return share.HttpsPort;
}
private static ShareSettings Snapshot(ShareSettings share) => new()
{
Enabled = share.Enabled,
Name = share.Name,
HttpsPort = share.HttpsPort,
HttpPort = share.HttpPort,
PublicHttpsPort = share.PublicHttpsPort,
PublicHttpPort = share.PublicHttpPort,
Discovery = share.Discovery,
};
private static async Task DisposeQuietlyAsync(HostedServer server)
{
try
{
// The app's exit waits for this on the UI thread: nothing the server's services await may continue on it.
await Task.Run(() => server.DisposeAsync().AsTask()).ConfigureAwait(false);
}
catch (Exception ex) when (ex is InvalidOperationException or IOException or ObjectDisposedException or OperationCanceledException or AggregateException)
{
Log.Warning("share", "The shared library did not stop cleanly", ex);
}
}
private void OnNetworkChanged(object? sender, EventArgs e)
{
if (_server is { } server) Addresses = AddressesOf(server.HttpsPort);
}
/// <summary>A render node changed a job outside the engine: the Jobs section follows it as it follows the engine's own changes.</summary>
private void OnJobChangedOutside(Chronos.Core.Model.Job job) => JobChangedOutside?.Invoke(job);
/// <summary>A render node changed a job's state outside this PC's engine (any thread).</summary>
public event Action<Chronos.Core.Model.Job>? JobChangedOutside;
/// <summary>Runs a fire-and-forget step, logging what it throws.</summary>
private static async Task Run(Task task)
{
try
{
await task.ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Error("share", "Sharing could not be updated", ex);
}
}
}
/// <summary>
/// The desktop's clean-up step <c>uploads</c> (owner review 5, #67): the upload-cleanup schedule the shared library adds runs
/// on this PC's scheduler, so the step is the desktop's, and it sweeps the shared library's abandoned uploads while it runs.
/// </summary>
public sealed class ShareUploadsStep(Func<LibraryShare> share) : ICleanupStep
{
public string Name => Chronos.Server.Storage.UploadCleanupStep.StepName;
public Task<string> RunAsync(CleanupContext context, CleanupParameters parameters) => share().SweepUploadsAsync(context, parameters);
}
+3 -2
View File
@@ -70,7 +70,8 @@ public sealed class DpapiTokenProtector : ITokenProtector
} }
/// <summary>A Chronos Server announced on the LAN.</summary> /// <summary>A Chronos Server announced on the LAN.</summary>
public sealed record DiscoveredServer(string Name, string Address); /// <summary>A server announced on the LAN; <paramref name="Fingerprint"/> is its beacon's certificate fingerprint, if any.</summary>
public sealed record DiscoveredServer(string Name, string Address, string? Fingerprint = null);
/// <summary> /// <summary>
/// Listens for the server's UDP beacon (<see cref="DiscoveryBeacon.Port"/>) and reports each server once. /// Listens for the server's UDP beacon (<see cref="DiscoveryBeacon.Port"/>) and reports each server once.
@@ -120,7 +121,7 @@ public sealed class DiscoveryListener : IDisposable
{ {
var datagram = await udp.ReceiveAsync(ct).ConfigureAwait(false); var datagram = await udp.ReceiveAsync(ct).ConfigureAwait(false);
if (DiscoveryBeacon.TryParse(datagram.Buffer) is not { } beacon) continue; if (DiscoveryBeacon.TryParse(datagram.Buffer) is not { } beacon) continue;
var server = new DiscoveredServer(beacon.Name, AddressOf(beacon, datagram.RemoteEndPoint.Address)); var server = new DiscoveredServer(beacon.Name, AddressOf(beacon, datagram.RemoteEndPoint.Address), beacon.TlsFingerprint);
lock (_seen) lock (_seen)
{ {
if (!_seen.Add(server.Address)) continue; if (!_seen.Add(server.Address)) continue;
+9
View File
@@ -32,6 +32,13 @@ public sealed class ServerSession : ObservableObject, ITrustStore, IDisposable
public ConnectFlow Flow => _flow; public ConnectFlow Flow => _flow;
/// <summary>True for this PC's own shared library (by fingerprint or server id): never connected to, never listed as found.</summary>
public Func<string?, Guid?, bool>? IsOwnLibrary
{
get => _flow.IsOwnLibrary;
set => _flow.IsOwnLibrary = value;
}
/// <summary>Servers that announced themselves on this network.</summary> /// <summary>Servers that announced themselves on this network.</summary>
public ObservableCollection<DiscoveredServer> Discovered { get; } = []; public ObservableCollection<DiscoveredServer> Discovered { get; } = [];
@@ -185,6 +192,8 @@ public sealed class ServerSession : ObservableObject, ITrustStore, IDisposable
_discovery = new DiscoveryListener(); _discovery = new DiscoveryListener();
_discovery.Found += server => _discovery.Found += server =>
{ {
// This PC's own shared library announces itself too: it is open here already (owner review 5, #67).
if (_flow.IsOwnLibrary?.Invoke(server.Fingerprint, null) == true) return;
if (Discovered.Any(d => d.Address.Equals(server.Address, StringComparison.OrdinalIgnoreCase))) return; if (Discovered.Any(d => d.Address.Equals(server.Address, StringComparison.OrdinalIgnoreCase))) return;
Discovered.Add(server); Discovered.Add(server);
}; };
+232 -28
View File
@@ -1,10 +1,14 @@
using System.IO; using System.IO;
using Chronos.App.Archiving;
using Chronos.App.Editor; using Chronos.App.Editor;
using Chronos.App.Infrastructure; using Chronos.App.Infrastructure;
using Chronos.Core.Diagnostics; using Chronos.Core.Diagnostics;
using Chronos.Core.IO;
using Chronos.Core.Localization;
using Chronos.Core.Model; using Chronos.Core.Model;
using Chronos.Core.Project; using Chronos.Core.Project;
using Chronos.Data; using Chronos.Data;
using Chronos.Data.Homes;
using Chronos.Data.Jobs; using Chronos.Data.Jobs;
using Chronos.Data.Projects; using Chronos.Data.Projects;
using Chronos.Data.Sync; using Chronos.Data.Sync;
@@ -13,8 +17,14 @@ using Chronos.Protocol.Client;
namespace Chronos.App.Server; namespace Chronos.App.Server;
/// <summary>Makes the sync connection of a signed-in session.</summary> /// <summary>Makes the sync connection of a signed-in session; <paramref name="server"/> is the key it names the server by (<see cref="SyncHost.Server"/>).</summary>
public delegate ISyncRemote SyncRemoteFactory(Uri address, string token, IReadOnlyCollection<string> trustedFingerprints); public delegate ISyncRemote SyncRemoteFactory(Uri address, string token, IReadOnlyCollection<string> trustedFingerprints, string server);
/// <summary>
/// Where Download originals puts a server sequence's photos (<see cref="SyncHost.OriginalsArchiveAsync"/>): the archive's id,
/// and its root when it was made just now (the first download from that server); a null id when there is none to use.
/// </summary>
public sealed record OriginalsTarget(Guid? ArchiveId, string? Created = null);
/// <summary> /// <summary>
/// This PC's sync with the signed-in server (BRIEF §4.4, §14.5): the <see cref="SyncService"/> of the index, the /// This PC's sync with the signed-in server (BRIEF §4.4, §14.5): the <see cref="SyncService"/> of the index, the
@@ -24,25 +34,37 @@ public delegate ISyncRemote SyncRemoteFactory(Uri address, string token, IReadOn
/// (<see cref="ConnectEditor"/>), the server as the home of workspace projects when it keeps projects (owner review 2, R8, /// (<see cref="ConnectEditor"/>), the server as the home of workspace projects when it keeps projects (owner review 2, R8,
/// phase 5b: <see cref="ProjectHome"/>, <see cref="ProjectChanged"/>) and the Export "Sync" of finished renders /// phase 5b: <see cref="ProjectHome"/>, <see cref="ProjectChanged"/>) and the Export "Sync" of finished renders
/// (<see cref="ExportSync"/>). Options come from <see cref="AppSettings.SyncSettingsAutomatically"/>, /// (<see cref="ExportSync"/>). Options come from <see cref="AppSettings.SyncSettingsAutomatically"/>,
/// <see cref="AppSettings.KeepProxiesOffline"/> and <see cref="AppSettings.PauseUploadsOnMetered"/>. /// <see cref="AppSettings.KeepProxiesOffline"/> and <see cref="AppSettings.PauseUploadsOnMetered"/>. A server that announces
/// its stable id (owner review 5, #66) is keyed by it (<see cref="Server"/>) and recorded in
/// <see cref="AppSettings.KnownServers"/> with the address keys it was reached under, which match it all the same
/// (<see cref="Identity"/>); at a sign-in that tells its id, what this PC keeps under those addresses moves to its id
/// (<see cref="HomeLayoutMigration.RekeyAsync"/>) before the agent starts.
/// </summary> /// </summary>
public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDisposable 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> /// <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 static readonly TimeSpan RestoreWait = TimeSpan.FromSeconds(30);
/// <summary>Jobs that write into the workspace or the servers' homes in the cache: a re-key waits for them.</summary>
private static readonly JobKind[] RekeyHeldBy =
[JobKind.WorkspaceCopy, JobKind.WorkspaceRender, JobKind.WorkspaceSend, JobKind.WorkspaceMove, JobKind.Download, JobKind.UploadCommit, JobKind.VideoCopy];
private readonly Lock _gate = new(); private readonly Lock _gate = new();
private Task _switch = Task.CompletedTask; private Task _switch = Task.CompletedTask;
private Credentials? _credentials; private Credentials? _credentials;
private Running? _running; private Running? _running;
private JobEngine? _renders; private JobEngine? _renders;
/// <summary>The alias table of <see cref="AppSettings.KnownServers"/>, made again whenever a sign-in records a server.</summary>
private ServerIdentity _identity = services.Settings.KnownIdentity();
/// <summary>The client project homes of the session share, made at first use for the credentials it holds.</summary> /// <summary>The client project homes of the session share, made at first use for the credentials it holds.</summary>
private SharedClient? _projects; private SharedClient? _projects;
/// <summary>Connections over <see cref="ChronosClient"/>; screenshots substitute a fake server.</summary> /// <summary>Connections over <see cref="ChronosClient"/>; screenshots substitute a fake server.</summary>
public SyncRemoteFactory RemoteFactory { get; set; } = (address, token, trusted) => public SyncRemoteFactory RemoteFactory { get; set; } = (address, token, trusted, server) =>
new ChronosSyncRemote(new ChronosClient(address, new CertificatePinning(trusted), $"Chronos ({Environment.MachineName})") { Token = token }, ownsClient: true); new ChronosSyncRemote(new ChronosClient(address, new CertificatePinning(trusted), $"Chronos ({Environment.MachineName})") { Token = token }, ownsClient: true,
server);
/// <summary>Connections of editors of server sequences over <see cref="ChronosClient"/>; screenshots substitute a fake server.</summary> /// <summary>Connections of editors of server sequences over <see cref="ChronosClient"/>; screenshots substitute a fake server.</summary>
public RemoteSequenceApiFactory EditorFactory { get; set; } = (address, token, trusted) => public RemoteSequenceApiFactory EditorFactory { get; set; } = (address, token, trusted) =>
@@ -61,8 +83,28 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
/// <summary>The agent's connection, for the table's own calls (conflict resolution); null while signed out.</summary> /// <summary>The agent's connection, for the table's own calls (conflict resolution); null while signed out.</summary>
public ISyncRemote? Remote => Volatile.Read(ref _running)?.Remote; public ISyncRemote? Remote => Volatile.Read(ref _running)?.Remote;
/// <summary>Key of the signed-in server (<see cref="SyncService.ServerKey"/>); null while signed out.</summary> /// <summary>
public string? Server => Volatile.Read(ref _credentials) is { } c ? SyncService.ServerKey(c.Address) : null; /// Key of the signed-in server: its id key when it announced its id (<see cref="ServerIdentity.Key(Guid?, Uri)"/>), else
/// its address key (<see cref="SyncService.ServerKey"/>); null while signed out.
/// </summary>
public string? Server => Volatile.Read(ref _credentials) is { } c ? c.Key : null;
/// <summary>The servers known by id and the address keys each was reached under (any thread).</summary>
public ServerIdentity Identity => Volatile.Read(ref _identity);
/// <summary>
/// A known server id came back with another TLS certificate and another name (owner review 5: a copied server database,
/// two servers sharing one id): the server's name now, and the name it had (UI thread).
/// </summary>
public event Action<string, string>? IdentityClash;
/// <summary>The key a server reached at <paramref name="address"/> goes by: the signed-in one's when it is that server, else its address key mapped through the aliases.</summary>
public string KeyOf(Uri address)
{
ArgumentNullException.ThrowIfNull(address);
if (Volatile.Read(ref _credentials) is { } c && c.Address == address) return c.Key;
return Identity.Canonical(SyncService.ServerKey(address));
}
/// <summary>The options, and whether the account may change server sequences (without it this PC's edits are not sent).</summary> /// <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, Allows(Permissions.Edit)); public SyncPolicy Policy => new(services.Settings.SyncSettingsAutomatically, services.Settings.KeepProxiesOffline, Allows(Permissions.Edit));
@@ -97,15 +139,15 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
/// <summary> /// <summary>
/// The project home of a workspace project whose home is a server (<see cref="ServerProjectHome"/> over the session's /// The project home of a workspace project whose home is a server (<see cref="ServerProjectHome"/> over the session's
/// client); null while signed out, signed in to another server, or when the server keeps no projects: the workspace then /// client); null while signed out, signed in to another server, or when the server keeps no projects: the workspace then
/// shows the project offline and its work waits. /// shows the project offline and its work waits. A home named by an address the signed-in server was reached under before
/// it told its id is that server's all the same (owner review 5).
/// </summary> /// </summary>
public IProjectHome? ProjectHome(BundleHome home) public IProjectHome? ProjectHome(BundleHome home)
{ {
ArgumentNullException.ThrowIfNull(home); ArgumentNullException.ThrowIfNull(home);
if (home.IsArchive || !HasProjects || Volatile.Read(ref _credentials) is not { } credentials if (home.IsArchive || !HasProjects || Volatile.Read(ref _credentials) is not { } credentials || !Identity.Same(home.Server, credentials.Key))
|| !string.Equals(home.Server, SyncService.ServerKey(credentials.Address), StringComparison.OrdinalIgnoreCase))
return null; return null;
return new ServerProjectHome(SessionClient(credentials), home.SequenceId, services.Server.ServerName, SettingsFormat); return new ServerProjectHome(SessionClient(credentials), home.SequenceId, services.Server.ServerName, SettingsFormat, credentials.Key);
} }
/// <summary> /// <summary>
@@ -121,14 +163,23 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
/// <summary>The agent started, stopped or compared, or the table of the signed-in server changed (any thread).</summary> /// <summary>The agent started, stopped or compared, or the table of the signed-in server changed (any thread).</summary>
public event Action? Changed; public event Action? Changed;
/// <summary>Creates the engine over the open index; the proxy cache lives in the client's cache folder.</summary> /// <summary>
/// Creates the engine over the open index; the proxy cache lives in the client's cache folder, one home per server
/// (<c>&lt;cache&gt;\servers\&lt;folder&gt;\proxies</c>, owner review 5), read where 1.0 put it until it is moved.
/// </summary>
public SyncService Open(ChronosDatabase database, Chronos.Data.Archiving.ArchiveService archives, Chronos.Data.Archiving.ArchiveServiceOptions options) public SyncService Open(ChronosDatabase database, Chronos.Data.Archiving.ArchiveService archives, Chronos.Data.Archiving.ArchiveServiceOptions options)
{ {
var cache = CacheStore.Folder(services.Environment, services.Settings); var cache = CacheStore.Folder(services.Environment, services.Settings);
Service = new SyncService(database, archives, new SyncOptions { Archive = options, ProxyCacheDirectory = Path.Combine(cache, "proxies") }); Service = new SyncService(database, archives, new SyncOptions
{
Archive = options,
ProxyCacheDirectory = Path.Combine(cache, HomeLayoutMigration.LegacyProxies),
ServersDirectory = CacheStore.ServersFolder(cache),
Identity = () => Identity,
});
Service.Changed += server => Service.Changed += server =>
{ {
if (server == Server) Changed?.Invoke(); if (Server is { } signedIn && Identity.Same(server, signedIn)) Changed?.Invoke();
}; };
return Service; return Service;
} }
@@ -138,8 +189,9 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
{ {
var session = services.Server; var session = services.Server;
Credentials? wanted = session.IsConnected && session.Flow is { Address: { } address, Token: { } token } Credentials? wanted = session.IsConnected && session.Flow is { Address: { } address, Token: { } token }
? new Credentials(address, token, session.Fingerprints) ? new Credentials(address, token, session.Fingerprints, session.Flow.Info?.ServerId is { } id && id != Guid.Empty ? id : null)
: null; : null;
if (wanted is { ServerId: { } serverId } && session.Flow.Info is { } info) Remember(serverId, wanted.Address, info);
Volatile.Write(ref _credentials, wanted); Volatile.Write(ref _credentials, wanted);
_switch = SwitchAsync(_switch, wanted); _switch = SwitchAsync(_switch, wanted);
if (services.Engine is not { } engine) return; if (services.Engine is not { } engine) return;
@@ -150,6 +202,9 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
engine.JobChanged += OnJobChanged; engine.JobChanged += OnJobChanged;
} }
/// <summary>The servers known by id were changed elsewhere (Settings › Server › Forget, an import): the alias table follows (UI thread).</summary>
public void KnownServersChanged() => Volatile.Write(ref _identity, services.Settings.KnownIdentity());
/// <summary>The sign-in <see cref="ConnectEditor"/> uses now (another object once signed in anew); null while signed out.</summary> /// <summary>The sign-in <see cref="ConnectEditor"/> uses now (another object once signed in anew); null while signed out.</summary>
public object? Session => Volatile.Read(ref _credentials); public object? Session => Volatile.Read(ref _credentials);
@@ -167,18 +222,73 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
/// <summary>Compares again soon (an option changed, an edit on this PC).</summary> /// <summary>Compares again soon (an option changed, an edit on this PC).</summary>
public void RequestRefresh() => Agent?.RequestRefresh(); 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> /// <summary>This PC's archive: the one at Settings › Archive's folder, else the only one that is not a server's originals archive.</summary>
public async Task<Archive?> CurrentArchiveAsync(CancellationToken ct = default) public async Task<Archive?> CurrentArchiveAsync(CancellationToken ct = default)
{ {
if (services.Database is not { } db) return null; if (services.Database is not { } db) return null;
var archives = await db.Archives.ListAsync(ct); var archives = await db.Archives.ListAsync(ct);
if (services.Settings.LastArchivePath is { Length: > 0 } root) if (services.Settings.LastArchivePath is { Length: > 0 } root && CurrentArchive.At(archives, root) is { } current) return current;
var originals = services.Settings.KnownServers.Select(k => k.OriginalsArchiveId).OfType<Guid>().ToHashSet();
var own = archives.Where(a => !originals.Contains(a.Id)).ToList();
return own.Count == 1 ? own[0] : null;
}
/// <summary>
/// Where Download originals puts the photos of a server sequence (owner review 5, Q1; UI thread): the archive of its local
/// copy when it has one (a copy keeps receiving where it is), else the signed-in server's own originals archive
/// (<see cref="KnownServer.OriginalsArchiveId"/>), made at the first download beside this PC's archive
/// (<see cref="HomeFolders.OriginalsArchiveRoot"/>: <c>D:\ChronosArchive - Studio NAS</c>, named "Studio NAS (server)").
/// A server that announces no id (an older one) has no home of its own: its originals go to this PC's archive, as in 1.0.
/// </summary>
/// <exception cref="IOException">The originals archive's folder cannot be made.</exception>
public async Task<OriginalsTarget> OriginalsArchiveAsync(Sequence? local, CancellationToken ct = default)
{
if (local?.ArchiveId is { } held) return new OriginalsTarget(held);
if (services.Database is not { } db || services.Archives is not { } archives) return new OriginalsTarget(null);
if (Volatile.Read(ref _credentials) is not { ServerId: { } id } || services.Settings.FindKnownServer(id) is not { } known)
return new OriginalsTarget((await CurrentArchiveAsync(ct))?.Id);
var listed = await db.Archives.ListAsync(ct);
if (known.OriginalsArchiveId is { } chosen && listed.Any(a => a.Id == chosen)) return new OriginalsTarget(chosen);
var name = known.Name is { Length: > 0 } n ? n : services.Server.ServerName ?? known.LastAddress ?? id.ToString("N");
var mine = await CurrentArchiveAsync(ct);
var root = HomeFolders.OriginalsArchiveRoot(mine?.RootPath ?? services.Settings.LastArchivePath, name, ArchiveLocations.SuggestRoot(),
path => Directory.Exists(path) || File.Exists(path) || CurrentArchive.At(listed, path) is not null);
var made = await archives.CreateAsync(root, Loc.L("Archive.Name.ServerOriginals", name), cancellationToken: ct);
known.OriginalsArchiveId = made.Id;
services.SavePreferences();
Log.Info("sync", $"The originals of {name} ({id}) go to their own archive {made.RootPath}");
return new OriginalsTarget(made.Id, made.RootPath);
}
/// <summary>
/// The archive Download originals puts a sequence's photos in (<see cref="OriginalsArchiveAsync"/>; UI thread), with what
/// the user is told: where a new originals archive went, or why there is none (<paramref name="notify"/>: title, message, is error).
/// </summary>
public async Task<Guid?> OriginalsForDownloadAsync(Sequence? local, Action<string, string?, bool> notify)
{
ArgumentNullException.ThrowIfNull(notify);
try
{ {
var full = Path.GetFullPath(root).TrimEnd(Path.DirectorySeparatorChar); var target = await OriginalsArchiveAsync(local);
if (archives.FirstOrDefault(a => string.Equals(Path.GetFullPath(a.RootPath).TrimEnd(Path.DirectorySeparatorChar), full, StringComparison.OrdinalIgnoreCase)) if (target.ArchiveId is null) notify(Loc.L("Errors.Sync.NoArchive"), null, true);
is { } current) return current; else if (target.Created is { } made) notify(Loc.L("Shell.Homes.Originals"), AppEnvironment.Shown(made), false);
return target.ArchiveId;
} }
return archives.Count == 1 ? archives[0] : null; catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException or DatabaseException)
{
Log.Warning("sync", "The originals archive of the signed-in server could not be made", ex);
notify(Loc.L("Errors.Sync.NoOriginalsFolder", services.Server.ServerName ?? Server ?? string.Empty), null, true);
return null;
}
}
/// <summary>The archives of the known servers' downloaded originals that the index holds (the scan schedule scans them too).</summary>
public async Task<IReadOnlyList<Archive>> OriginalsArchivesAsync(CancellationToken ct = default)
{
if (services.Database is not { } db) return [];
var ids = services.Settings.KnownServers.Select(k => k.OriginalsArchiveId).OfType<Guid>().ToHashSet();
if (ids.Count == 0) return [];
return [.. (await db.Archives.ListAsync(ct).ConfigureAwait(false)).Where(a => ids.Contains(a.Id))];
} }
public async ValueTask<ISyncRemote?> ConnectAsync(string server, CancellationToken cancellationToken) public async ValueTask<ISyncRemote?> ConnectAsync(string server, CancellationToken cancellationToken)
@@ -187,9 +297,10 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
var until = DateTime.UtcNow + RestoreWait; var until = DateTime.UtcNow + RestoreWait;
while (Volatile.Read(ref _credentials) is null && services.Settings.ProtectedToken is not null && DateTime.UtcNow < until) while (Volatile.Read(ref _credentials) is null && services.Settings.ProtectedToken is not null && DateTime.UtcNow < until)
await Task.Delay(500, cancellationToken); await Task.Delay(500, cancellationToken);
if (Volatile.Read(ref _credentials) is not { } c || SyncService.ServerKey(c.Address) != server) return null; // A job queued under an address the server was reached under before it told its id reaches it all the same.
if (Volatile.Read(ref _credentials) is not { } c || !Identity.Same(c.Key, server)) return null;
CacheStore.Prepare(CacheStore.Folder(services.Environment, services.Settings)); CacheStore.Prepare(CacheStore.Folder(services.Environment, services.Settings));
return RemoteFactory(c.Address, c.Token, c.Fingerprints); return RemoteFactory(c.Address, c.Token, c.Fingerprints, c.Key);
} }
/// <summary> /// <summary>
@@ -240,9 +351,12 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
_ = SendRenderAsync(new ExportSync(db, service, engine), job, signedIn ?? SavedServer(), signedIn is null || CanUpload); _ = SendRenderAsync(new ExportSync(db, service, engine), job, signedIn ?? SavedServer(), signedIn is null || CanUpload);
} }
/// <summary>Key of the server of the saved session (Disconnect keeps it); null without one.</summary> /// <summary>The key of the server this PC is signed in to, else of the saved session's; null without either.</summary>
public string? LastServer => Server ?? SavedServer();
/// <summary>Key of the server of the saved session (Disconnect keeps it), its id key when it is known by id; null without one.</summary>
private string? SavedServer() => private string? SavedServer() =>
services.Server.HasSavedSession && ServerAddress.TryParse(services.Settings.ServerUrl, out var address) ? SyncService.ServerKey(address) : null; services.Server.HasSavedSession && ServerAddress.TryParse(services.Settings.ServerUrl, out var address) ? Identity.Canonical(SyncService.ServerKey(address)) : null;
private static async Task SendRenderAsync(ExportSync exports, Job job, string? server, bool canUpload) private static async Task SendRenderAsync(ExportSync exports, Job job, string? server, bool canUpload)
{ {
@@ -265,6 +379,89 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
} }
} }
/// <summary>
/// Records the signed-in server in <see cref="AppSettings.KnownServers"/> (UI thread): its id, name, address, certificate,
/// and the address key it was reached by as an alias; the settings are written only when something changed. A known id
/// presented with another certificate and another name is told (<see cref="IdentityClash"/>).
/// </summary>
private void Remember(Guid id, Uri address, ServerInfo info)
{
var settings = services.Settings;
var alias = SyncService.ServerKey(address);
var shown = ServerAddress.Display(address);
var known = settings.FindKnownServer(id);
var changed = false;
if (known is null)
{
known = new KnownServer { Id = id, Name = info.Name, LastAddress = shown, Fingerprint = info.TlsFingerprint };
settings.KnownServers.Add(known);
changed = true;
Log.Info("sync", $"Server {info.Name} is known by its id {id} from now on (reached at {shown})");
}
else if (known.Fingerprint is { Length: > 0 } before && info.TlsFingerprint is { Length: > 0 } now
&& !string.Equals(before, now, StringComparison.OrdinalIgnoreCase)
&& !string.Equals(known.Name, info.Name, StringComparison.Ordinal))
{
Log.Warning("sync", $"Server id {id} was {known.Name} with another certificate; it is {info.Name} now: two servers may share one copied database");
IdentityClash?.Invoke(info.Name, known.Name ?? shown);
}
if (!known.Aliases.Contains(alias, StringComparer.OrdinalIgnoreCase))
{
known.Aliases.Add(alias);
changed = true;
}
if (!string.Equals(known.Name, info.Name, StringComparison.Ordinal) || !string.Equals(known.LastAddress, shown, StringComparison.OrdinalIgnoreCase)
|| (info.TlsFingerprint is { Length: > 0 } fingerprint
&& !string.Equals(known.Fingerprint, fingerprint, StringComparison.OrdinalIgnoreCase)))
{
(known.Name, known.LastAddress, known.Fingerprint) = (info.Name, shown, info.TlsFingerprint ?? known.Fingerprint);
changed = true;
}
if (DateTimeOffset.UtcNow - known.LastSeen > TimeSpan.FromHours(1))
{
known.LastSeen = DateTimeOffset.UtcNow;
changed = true;
}
if (!changed) return;
Volatile.Write(ref _identity, settings.KnownIdentity());
services.SavePreferences();
}
/// <summary>
/// Whatever this PC keeps under the address keys the server of <paramref name="credentials"/> was reached by moves to its
/// id (owner review 5, #66: <see cref="HomeLayoutMigration.RekeyAsync"/>), before the agent starts. Skipped while a job
/// writes into the workspace or the cache, or the workspace is being moved: a later sign-in does it, and the aliases match
/// meanwhile. A failure is logged: nothing is lost, and the next sign-in goes on.
/// </summary>
private async Task RekeyAsync(Credentials credentials)
{
if (credentials.ServerId is not { } id || services.Database is not { } db) return;
var aliases = Identity.AliasesOf(id);
if (aliases.Count == 0) return;
try
{
if (await db.Jobs.HasPendingAsync(RekeyHeldBy).ConfigureAwait(false))
{
Log.Info("sync", $"Server {id}: what this PC keeps under its addresses moves to its id at a later sign-in (jobs are under way)");
return;
}
var workspace = services.Workspace;
var migration = new HomeLayoutMigration(new HomeLayoutOptions
{
DataDirectory = services.Environment.DataDirectory,
WorkspaceRoot = workspace.IsEnabled && !workspace.IsMoving ? workspace.Root : null,
CacheRoot = CacheStore.Folder(services.Environment, services.Settings),
Identity = Identity,
Database = db,
});
await migration.RekeyAsync(id, aliases).ConfigureAwait(false);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException)
{
Log.Warning("sync", $"What this PC keeps under the addresses of server {id} could not all move to its id; the next sign-in goes on", ex);
}
}
/// <summary> /// <summary>
/// Switches are chained (each waits for the previous one) and continue on the thread pool: a switch still stopping /// Switches are chained (each waits for the previous one) and continue on the thread pool: a switch still stopping
/// the old agent when the app exits must not need the UI thread its exit blocks. /// the old agent when the app exits must not need the UI thread its exit blocks.
@@ -272,7 +469,8 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
private async Task SwitchAsync(Task previous, Credentials? wanted) private async Task SwitchAsync(Task previous, Credentials? wanted)
{ {
await previous.ConfigureAwait(false); await previous.ConfigureAwait(false);
if (Volatile.Read(ref _running) is { } running && wanted is { } same && running.Credentials.Address == same.Address && running.Credentials.Token == same.Token) if (Volatile.Read(ref _running) is { } running && wanted is { } same && running.Credentials.Address == same.Address && running.Credentials.Token == same.Token
&& running.Credentials.ServerId == same.ServerId)
return; return;
var stopped = Volatile.Read(ref _running)?.Remote.Server; var stopped = Volatile.Read(ref _running)?.Remote.Server;
await StopAsync().ConfigureAwait(false); await StopAsync().ConfigureAwait(false);
@@ -283,7 +481,8 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
Changed?.Invoke(); Changed?.Invoke();
return; return;
} }
var remote = RemoteFactory(start.Address, start.Token, start.Fingerprints); await RekeyAsync(start).ConfigureAwait(false);
var remote = RemoteFactory(start.Address, start.Token, start.Fingerprints, start.Key);
var agent = new SyncAgent(service, remote, () => Policy, services.Engine); var agent = new SyncAgent(service, remote, () => Policy, services.Engine);
agent.Changed += () => Changed?.Invoke(); agent.Changed += () => Changed?.Invoke();
agent.ProjectChanged += e => ProjectChanged?.Invoke(remote.Server, e); agent.ProjectChanged += e => ProjectChanged?.Invoke(remote.Server, e);
@@ -302,7 +501,12 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
Changed?.Invoke(); Changed?.Invoke();
} }
private sealed record Credentials(Uri Address, string Token, IReadOnlyCollection<string> Fingerprints); /// <param name="ServerId">The id the server announced (owner review 5); null for an older server.</param>
private sealed record Credentials(Uri Address, string Token, IReadOnlyCollection<string> Fingerprints, Guid? ServerId)
{
/// <summary>The key the server goes by (<see cref="ServerIdentity.Key(Guid?, Uri)"/>).</summary>
public string Key => ServerIdentity.Key(ServerId, Address);
}
/// <summary>The client project homes share, and the session it was made for.</summary> /// <summary>The client project homes share, and the session it was made for.</summary>
private sealed record SharedClient(Uri Address, string Token, ChronosClient Client); private sealed record SharedClient(Uri Address, string Token, ChronosClient Client);
+1 -5
View File
@@ -316,11 +316,7 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
await service.EnqueueSendExportsAsync(engine, server, entry.Local!); await service.EnqueueSendExportsAsync(engine, server, entry.Local!);
break; break;
case SyncAction.DownloadOriginals: case SyncAction.DownloadOriginals:
if ((entry.Local?.ArchiveId ?? (await Host.CurrentArchiveAsync())?.Id) is not { } archive) if (await Host.OriginalsForDownloadAsync(entry.Local, (title, message, isError) => _shell.Notify(title, message, isError: isError)) is not { } archive) return;
{
_shell.Notify(Loc.L("Errors.Sync.NoArchive"), isError: true);
return;
}
await service.EnqueueDownloadAsync(engine, server, entry.Id, entry.Title, SyncDownloadMode.Originals, archive); await service.EnqueueDownloadAsync(engine, server, entry.Id, entry.Title, SyncDownloadMode.Originals, archive);
break; break;
case SyncAction.GetExports: case SyncAction.GetExports:
+97
View File
@@ -0,0 +1,97 @@
using System.IO;
using System.Windows.Input;
using Chronos.App.Infrastructure;
using Chronos.Core.Localization;
using Chronos.Data.Workspaces;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Settings;
/// <summary>
/// One home's folder in Settings › Workspace › Home folders (owner review 5, #66): "This PC" for the projects of this PC's
/// archive (<c>local</c>), one row per server for its projects (<c>servers\&lt;id&gt;</c>), with Open.
/// </summary>
public sealed class HomeFolderRow(string name, string path, string toolTip, Action<string> open)
{
public string Name { get; } = name;
/// <summary>The folder as shown (a capture's own folders stand for the real ones).</summary>
public string Path { get; } = AppEnvironment.Shown(path);
public string ToolTip { get; } = toolTip;
public ICommand OpenCommand { get; } = new RelayCommand(() => open(path));
/// <summary>The rows of the workspace's homes: this PC first, then each server by name; none while the workspace is not made.</summary>
public static IReadOnlyList<HomeFolderRow> Of(WorkspaceHomes homes, IReadOnlyList<KnownServer> known, Action<string> open)
{
ArgumentNullException.ThrowIfNull(homes);
ArgumentNullException.ThrowIfNull(known);
ArgumentNullException.ThrowIfNull(open);
if (!homes.IsSplit) return [new HomeFolderRow(Loc.L("Settings.Workspace.ThisPc"), homes.Root, Loc.L("Tooltips.Settings.Workspace.ThisPc", AppEnvironment.Shown(homes.Root)), open)];
var rows = new List<HomeFolderRow>
{
new(Loc.L("Settings.Workspace.ThisPc"), homes.LocalRoot, Loc.L("Tooltips.Settings.Workspace.ThisPc", AppEnvironment.Shown(homes.LocalRoot)), open),
};
foreach (var home in homes.Homes().Where(h => h is { IsLocal: false, IsLegacy: false }).OrderBy(h => NameOf(h, known), StringComparer.CurrentCultureIgnoreCase))
{
var name = NameOf(home, known);
rows.Add(new HomeFolderRow(name, home.Store.Root,
Loc.L("Tooltips.Settings.Workspace.ServerHome", name, AppEnvironment.Shown(home.Store.Root)), open));
}
return rows;
}
/// <summary>The server's name as this PC knows it, else as its folder records it, else the folder's name.</summary>
private static string NameOf(WorkspaceHome home, IReadOnlyList<KnownServer> known) =>
(home.Server?.Id is { } id ? known.FirstOrDefault(k => k.Id == id)?.Name : null)
?? home.Server?.Name ?? home.Server?.Address ?? System.IO.Path.GetFileName(home.Store.Root);
}
/// <summary>
/// A server this PC signed in to, in Settings › Server › Known servers (owner review 5, #66): its name, last address, id
/// (short, the whole one in the tooltip), whether this PC is signed in to it now, and its folders: the archive of its
/// downloaded originals and its share of the cache, each with Open.
/// </summary>
public sealed class KnownServerRow
{
private readonly string? _originals;
private readonly string _cache;
public KnownServerRow(KnownServer server, bool signedIn, string? originalsRoot, string cacheFolder, Action<string> open)
{
ArgumentNullException.ThrowIfNull(server);
ArgumentNullException.ThrowIfNull(open);
Server = server;
IsSignedIn = signedIn;
_originals = originalsRoot;
_cache = cacheFolder;
OpenOriginalsCommand = new RelayCommand(() => open(_originals!), () => _originals is not null && Directory.Exists(_originals));
OpenCacheCommand = new RelayCommand(() => open(_cache), () => Directory.Exists(_cache));
}
public KnownServer Server { get; }
public string Name => Server.Name is { Length: > 0 } name ? name : Server.LastAddress ?? Server.Id.ToString("N");
public string Address => Server.LastAddress ?? "—";
/// <summary>The first 8 hex digits of the id; the tooltip has it whole.</summary>
public string ShortId => Server.Id.ToString("N")[..8];
public string IdToolTip => Loc.L("Tooltips.Settings.Server.ServerId", Server.Id.ToString("D"));
public bool IsSignedIn { get; }
public string StateText => Loc.L(IsSignedIn ? "Settings.Server.SignedIn" : "Settings.Server.Offline");
public string StateToolTip => Loc.L(IsSignedIn ? "Tooltips.Settings.Server.SignedIn" : "Tooltips.Settings.Server.Offline");
public string OriginalsPath => _originals is null ? "—" : AppEnvironment.Shown(_originals);
public string CachePath => AppEnvironment.Shown(_cache);
public ICommand OpenOriginalsCommand { get; }
public ICommand OpenCacheCommand { get; }
}
@@ -0,0 +1,117 @@
using System.Globalization;
using System.Windows.Input;
using Chronos.App.Infrastructure;
using Chronos.Core.Localization;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Settings;
/// <summary>
/// The sharing rows of Settings › Server (owner review 5, #67): Share this library, its name, its ports (the public ones
/// may stay empty), the LAN announcement and the shared library's own data folder. Each value is stored and saved at once;
/// saving applies it to the share (<see cref="AppServices.SaveSettings"/>), which restarts on a new name, port or
/// announcement. The rows read <see cref="AppSettings.Share"/> each time: Reset and Import replace it.
/// </summary>
public sealed class ShareSettingsRows : ObservableObject
{
private readonly AppSettings _settings;
private readonly Action _save;
public ShareSettingsRows(AppSettings settings, Action save, string folder, string pcName)
{
_settings = settings;
_save = save;
PcName = pcName;
Folder = AppEnvironment.Shown(folder);
Name = new EditableField(Share.Name ?? string.Empty, _ => null, v =>
{
Share.Name = v.Trim().Length == 0 ? null : v.Trim();
_save();
}, () => Loc.L("Tooltips.Settings.ShareName"));
HttpsPort = Port(() => Share.HttpsPort, v => Share.HttpsPort = v, "Tooltips.Settings.HttpsPort");
HttpPort = Port(() => Share.HttpPort, v => Share.HttpPort = v, "Tooltips.Settings.HttpPort");
PublicHttpsPort = PublicPort(() => Share.PublicHttpsPort, v => Share.PublicHttpsPort = v);
PublicHttpPort = PublicPort(() => Share.PublicHttpPort, v => Share.PublicHttpPort = v);
OpenFolderCommand = new RelayCommand(() => ShellActions.Reveal(folder));
}
private ShareSettings Share => _settings.Share;
public bool Enabled
{
get => Share.Enabled;
set
{
if (Share.Enabled == value) return;
Share.Enabled = value;
_save();
OnPropertyChanged();
}
}
public EditableField Name { get; }
public EditableField HttpsPort { get; }
public EditableField HttpPort { get; }
public EditableField PublicHttpsPort { get; }
public EditableField PublicHttpPort { get; }
public bool Discovery
{
get => Share.Discovery;
set
{
if (Share.Discovery == value) return;
Share.Discovery = value;
_save();
OnPropertyChanged();
}
}
/// <summary>The name clients see while <see cref="Name"/> is empty: this PC's.</summary>
public string PcName { get; }
/// <summary>The shared library's private folder, as the screens show paths.</summary>
public string Folder { get; }
public ICommand OpenFolderCommand { get; }
/// <summary>Settings › Server › Reset: sharing off, on the default ports.</summary>
public void Reset()
{
_settings.Share = new ShareSettings();
Refresh();
}
/// <summary>Shows the values as they are now (after Reset all, Import, or a reset of the page).</summary>
public void Refresh()
{
Name.Load(Share.Name ?? string.Empty);
HttpsPort.Load(Text(Share.HttpsPort));
HttpPort.Load(Text(Share.HttpPort));
PublicHttpsPort.Load(Share.PublicHttpsPort is { } https ? Text(https) : string.Empty);
PublicHttpPort.Load(Share.PublicHttpPort is { } http ? Text(http) : string.Empty);
OnPropertyChanged(nameof(Enabled));
OnPropertyChanged(nameof(Discovery));
}
private EditableField Port(Func<int> read, Action<int> write, string toolTip) =>
new(Text(read()), v => ValidatePort(v), v =>
{
write(int.Parse(v.Trim(), NumberStyles.Integer, CultureInfo.CurrentCulture));
_save();
}, () => Loc.L(toolTip));
private EditableField PublicPort(Func<int?> read, Action<int?> write) =>
new(read() is { } port ? Text(port) : string.Empty, v => v.Trim().Length == 0 ? null : ValidatePort(v), v =>
{
write(v.Trim().Length == 0 ? null : int.Parse(v.Trim(), NumberStyles.Integer, CultureInfo.CurrentCulture));
_save();
}, () => Loc.L("Tooltips.Settings.PublicPorts"));
private static string Text(int port) => port.ToString(CultureInfo.InvariantCulture);
private static string? ValidatePort(string text) =>
int.TryParse(text.Trim(), NumberStyles.Integer, CultureInfo.CurrentCulture, out var n) && n is >= 1 and <= 65535
? null
: Loc.L("Errors.Number.Range", 1.ToString("N0", Loc.Culture), 65535.ToString("N0", Loc.Culture));
}
+6
View File
@@ -117,6 +117,12 @@ public static class ScreenCapture
shell.Navigate(SectionKey.Server); shell.Navigate(SectionKey.Server);
written += await SaveAsync(window, directory, "server", theme); written += await SaveAsync(window, directory, "server", theme);
// This PC's library shared (owner review 5, #67), then one that could not start.
SampleData.ShowShare(shell.Services);
written += await SaveAsync(window, directory, "server-share", theme);
SampleData.ShowShareFailed(shell.Services);
written += await SaveAsync(window, directory, "server-share-failed", theme);
SampleData.HideShare(shell.Services);
// Every page, About last (owner review 2, R5). // Every page, About last (owner review 2, R5).
shell.Navigate(SectionKey.Settings); shell.Navigate(SectionKey.Settings);
+16 -4
View File
@@ -429,25 +429,37 @@ public static class VideoSources
public static IReadOnlyList<VideoEntry> ReadWorkspace(WorkspaceStore store, IEnumerable<WorkspaceEntry> projects) public static IReadOnlyList<VideoEntry> ReadWorkspace(WorkspaceStore store, IEnumerable<WorkspaceEntry> projects)
{ {
ArgumentNullException.ThrowIfNull(store); ArgumentNullException.ThrowIfNull(store);
return ReadWorkspace(store.Project, projects);
}
/// <summary>The workspace renders of every project, each read in its own home's folder (<c>local\</c>, <c>servers\&lt;id&gt;\</c>).</summary>
public static IReadOnlyList<VideoEntry> ReadWorkspace(WorkspaceHomes homes, IEnumerable<WorkspaceEntry> projects)
{
ArgumentNullException.ThrowIfNull(homes);
return ReadWorkspace(id => homes.Find(id) ?? homes.Local.Project(id), projects);
}
private static List<VideoEntry> ReadWorkspace(Func<Guid, WorkspaceProject> project, IEnumerable<WorkspaceEntry> projects)
{
ArgumentNullException.ThrowIfNull(projects); ArgumentNullException.ThrowIfNull(projects);
var entries = new List<VideoEntry>(); var entries = new List<VideoEntry>();
foreach (var project in projects.Where(p => p.IsReadable)) foreach (var entry in projects.Where(p => p.IsReadable))
{ {
try try
{ {
var folder = store.Project(project.ProjectId); var folder = project(entry.ProjectId);
foreach (var render in folder.ReadRenders().Entries) foreach (var render in folder.ReadRenders().Entries)
{ {
var path = folder.ExportFile(render.File); var path = folder.ExportFile(render.File);
var exists = File.Exists(path) || Directory.Exists(path); var exists = File.Exists(path) || Directory.Exists(path);
// A sent render whose file left exports/ is safe at its home, whose entry stands for it: never "missing". // A sent render whose file left exports/ is safe at its home, whose entry stands for it: never "missing".
if (render.IsSent && !exists) continue; if (render.IsSent && !exists) continue;
entries.Add(FromWorkspace(render, project, path, exists)); entries.Add(FromWorkspace(render, entry, path, exists));
} }
} }
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException) catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{ {
Log.Warning("videos", $"The render ledger of workspace project {project.ProjectId} cannot be read", ex); Log.Warning("videos", $"The render ledger of workspace project {entry.ProjectId} cannot be read", ex);
} }
} }
return entries; return entries;
@@ -986,7 +986,7 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
/// </summary> /// </summary>
private void OnHomeChanged(WorkspaceHomeChange change) private void OnHomeChanged(WorkspaceHomeChange change)
{ {
if (_disposed || (change.ProjectId is { } id ? id != ProjectId : !IsServerHome || !string.Equals(change.Server, Home.Server, StringComparison.OrdinalIgnoreCase))) if (_disposed || (change.ProjectId is { } id ? id != ProjectId : !IsServerHome || !_host.SameServer(change.Server, Home.Server)))
return; return;
if (_context is { } context) context.Post(_ => _ = HomeChangedAsync(change), null); if (_context is { } context) context.Post(_ => _ = HomeChangedAsync(change), null);
else _ = HomeChangedAsync(change); else _ = HomeChangedAsync(change);
@@ -36,6 +36,12 @@ public sealed record WorkspaceTrashPlan(string Folder, IReadOnlyList<WorkspaceTr
{ {
/// <summary>Nothing to erase: Empty… is disabled.</summary> /// <summary>Nothing to erase: Empty… is disabled.</summary>
public bool IsEmpty => Items.Count == 0; public bool IsEmpty => Items.Count == 0;
/// <summary>
/// The trash of each home the plan lists (owner review 5, separate homes: <c>local\</c> and each <c>servers\&lt;id&gt;\</c>
/// keep their own), each with its own fingerprint; emptying erases each one only while all of them still match.
/// </summary>
public IReadOnlyList<WorkspaceTrashListing> Listings { get; init; } = [];
} }
/// <summary>What emptying the workspace's trash erased.</summary> /// <summary>What emptying the workspace's trash erased.</summary>
@@ -63,21 +69,28 @@ public sealed partial class WorkspaceHost
var root = Root; var root = Root;
if (!Directory.Exists(root)) return WorkspaceUsage.None; if (!Directory.Exists(root)) return WorkspaceUsage.None;
var media = 0L; var media = 0L;
foreach (var folder in Directory.EnumerateDirectories(root).Where(d => Guid.TryParseExact(Path.GetFileName(d), "N", out _))) foreach (var store in Homes.All())
{ {
cancellationToken.ThrowIfCancellationRequested(); if (!Directory.Exists(store.Root)) continue;
media += WorkspaceCleaner.Measure(Path.Combine(folder, WorkspaceProject.MediaFolder)).Bytes; foreach (var folder in Directory.EnumerateDirectories(store.Root).Where(d => Guid.TryParseExact(Path.GetFileName(d), "N", out _)))
{
cancellationToken.ThrowIfCancellationRequested();
media += WorkspaceCleaner.Measure(Path.Combine(folder, WorkspaceProject.MediaFolder)).Bytes;
}
} }
var trash = WorkspaceTrash.List(root, cancellationToken); var trash = Homes.Trash(cancellationToken);
return new WorkspaceUsage(media, WorkspaceCleaner.Measure(root).Bytes, trash.Bytes, trash.Entries.Count); return new WorkspaceUsage(media, WorkspaceCleaner.Measure(root).Bytes, trash.Sum(t => t.Bytes), trash.Sum(t => t.Entries.Count));
}, cancellationToken); }, cancellationToken);
/// <summary>The plan of emptying the workspace's trash (<see cref="WorkspaceTrashPlan"/>); nothing is erased.</summary> /// <summary>The plan of emptying the trash of every home of the workspace (<see cref="WorkspaceTrashPlan"/>); nothing is erased.</summary>
public Task<WorkspaceTrashPlan> PlanTrashAsync(CancellationToken cancellationToken = default) => Task.Run(() => public Task<WorkspaceTrashPlan> PlanTrashAsync(CancellationToken cancellationToken = default) => Task.Run(() =>
{ {
var listing = WorkspaceTrash.List(Root, cancellationToken); var listings = Homes.Trash(cancellationToken);
return new WorkspaceTrashPlan(listing.Folder, [.. listing.Entries.Select(e => new WorkspaceTrashItem(e.Name, e.Bytes, e.Files, e.Trashed))], listing.Bytes, var folder = listings.Count == 1 ? listings[0].Folder : WorkspaceTrash.FolderOf(Root);
listing.Fingerprint); var fingerprint = string.Join('|', listings.Select(l => l.Folder + "=" + l.Fingerprint));
return new WorkspaceTrashPlan(folder, [.. listings.SelectMany(l => l.Entries).Select(e => new WorkspaceTrashItem(e.Name, e.Bytes, e.Files, e.Trashed))
.OrderBy(i => i.Trashed)], listings.Sum(l => l.Bytes), fingerprint)
{ Listings = listings };
}, cancellationToken); }, cancellationToken);
/// <summary> /// <summary>
@@ -92,11 +105,25 @@ public sealed partial class WorkspaceHost
return Task.Run(() => return Task.Run(() =>
{ {
EnsureNotMoving(); EnsureNotMoving();
var listing = new WorkspaceTrashListing(plan.Folder, [.. plan.Items.Select(i => new WorkspaceTrashEntry(i.Name, i.Bytes, i.Files, i.Trashed))], plan.Bytes, IReadOnlyList<WorkspaceTrashListing> listings = plan.Listings.Count > 0 ? plan.Listings
plan.Fingerprint); : [new WorkspaceTrashListing(plan.Folder, [.. plan.Items.Select(i => new WorkspaceTrashEntry(i.Name, i.Bytes, i.Files, i.Trashed))], plan.Bytes,
plan.Fingerprint)];
try try
{ {
var (items, bytes) = WorkspaceTrash.Empty(Root, listing, cancellationToken); // Every trash is checked before any is emptied: a plan is erased whole or not at all.
foreach (var listing in listings)
{
var now = WorkspaceTrash.List(Path.GetDirectoryName(listing.Folder)!, cancellationToken);
if (!string.Equals(now.Fingerprint, listing.Fingerprint, StringComparison.Ordinal))
throw new WorkspaceTrashChangedException($"The trash {now.Folder} changed after it was listed.");
}
var (items, bytes) = (0, 0L);
foreach (var listing in listings.Where(l => !l.IsEmpty))
{
var (erased, freed) = WorkspaceTrash.Empty(Path.GetDirectoryName(listing.Folder)!, listing, cancellationToken);
items += erased;
bytes += freed;
}
return new WorkspaceTrashResult(items, bytes); return new WorkspaceTrashResult(items, bytes);
} }
catch (WorkspaceTrashChangedException ex) catch (WorkspaceTrashChangedException ex)
@@ -130,7 +157,7 @@ public sealed partial class WorkspaceHost
await _cleaning.WaitAsync(cancellationToken).ConfigureAwait(false); await _cleaning.WaitAsync(cancellationToken).ConfigureAwait(false);
try try
{ {
var cleaner = new WorkspaceCleaner(Sync, db, HomeOf) { LockWait = LockWait }; var cleaner = new WorkspaceCleaner(AllSyncs(), db, HomeOf) { LockWait = LockWait };
return await Task.Run(() => cleaner.CleanAsync(options, cancellationToken), cancellationToken).ConfigureAwait(false); return await Task.Run(() => cleaner.CleanAsync(options, cancellationToken), cancellationToken).ConfigureAwait(false);
} }
finally finally
@@ -147,10 +174,7 @@ public sealed partial class WorkspaceHost
{ {
ArgumentNullException.ThrowIfNull(job); ArgumentNullException.ThrowIfNull(job);
if (job is not { Kind: JobKind.WorkspaceCopy, State: JobState.Done } || _settings.WorkspaceSizeLimitGb <= 0) return; if (job is not { Kind: JobKind.WorkspaceCopy, State: JobState.Done } || _settings.WorkspaceSizeLimitGb <= 0) return;
if (WorkspaceJobs.CopyParameters(job) is not { } copied if (WorkspaceJobs.CopyParameters(job) is not { } copied || !IsUnderRoot(copied.WorkspaceRoot)) return;
|| !string.Equals(Path.TrimEndingDirectorySeparator(Path.GetFullPath(copied.WorkspaceRoot)), Path.TrimEndingDirectorySeparator(Path.GetFullPath(Root)),
StringComparison.OrdinalIgnoreCase))
return;
_ = Task.Run(async () => _ = Task.Run(async () =>
{ {
try try
@@ -165,6 +189,16 @@ public sealed partial class WorkspaceHost
}); });
} }
/// <summary>The folder is the workspace's own or one of its homes (<c>local\</c>, <c>servers\&lt;id&gt;\</c>).</summary>
private bool IsUnderRoot(string folder)
{
if (string.IsNullOrWhiteSpace(folder)) return false;
var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(Root));
var full = Path.TrimEndingDirectorySeparator(Path.GetFullPath(folder));
return string.Equals(full, root, StringComparison.OrdinalIgnoreCase)
|| full.StartsWith(root + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase);
}
/// <summary>When each project was opened last, as Settings hold it now (written on the UI thread: copied until a copy reads whole).</summary> /// <summary>When each project was opened last, as Settings hold it now (written on the UI thread: copied until a copy reads whole).</summary>
private IReadOnlyDictionary<Guid, DateTimeOffset> OpenedSnapshot() private IReadOnlyDictionary<Guid, DateTimeOffset> OpenedSnapshot()
{ {
@@ -331,7 +365,7 @@ public sealed partial class WorkspaceHost
if (WorkspaceJobs.SendParameters(pending)?.ProjectId == project.ProjectId) return; if (WorkspaceJobs.SendParameters(pending)?.ProjectId == project.ProjectId) return;
} }
var title = project.ReadBundle().Sequence.Title ?? string.Empty; var title = project.ReadBundle().Sequence.Title ?? string.Empty;
var job = await engine.EnqueueAsync(WorkspaceJobs.Send(workspace.Home.SequenceId, title, Store.Root, project.ProjectId, [], workspace.Home.Server), var job = await engine.EnqueueAsync(WorkspaceJobs.Send(workspace.Home.SequenceId, title, project.Store.Root, project.ProjectId, [], workspace.Home.Server),
cancellationToken: cancellationToken).ConfigureAwait(false); cancellationToken: cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"The renders of project {project.ProjectId} not sent yet are queued to be sent (job {job.Id})"); Log.Info("workspace", $"The renders of project {project.ProjectId} not sent yet are queued to be sent (job {job.Id})");
} }
@@ -268,13 +268,13 @@ public sealed partial class WorkspaceHost
/// <summary>A project as the move's plan lists it, read from the workspace alone (its versions not sent, its ledger, its changes).</summary> /// <summary>A project as the move's plan lists it, read from the workspace alone (its versions not sent, its ledger, its changes).</summary>
private async Task<WorkspaceMoveProject> MoveProjectAsync(WorkspaceMoveFolder folder, CancellationToken cancellationToken) private async Task<WorkspaceMoveProject> MoveProjectAsync(WorkspaceMoveFolder folder, CancellationToken cancellationToken)
{ {
var project = Store.Project(folder.ProjectId); var project = Find(folder.ProjectId) ?? Homes.Local.Project(folder.ProjectId);
var entry = await EntryOrUnreadableAsync(project, cancellationToken).ConfigureAwait(false); var entry = await EntryOrUnreadableAsync(project, cancellationToken).ConfigureAwait(false);
// What a copy this Chronos cannot read holds is not known: it moves as it is, counted as work not at its home. // What a copy this Chronos cannot read holds is not known: it moves as it is, counted as work not at its home.
if (!entry.IsReadable) return new WorkspaceMoveProject(folder.ProjectId, entry.KnownName ?? entry.Name, folder.Files, folder.Bytes, true, false); if (!entry.IsReadable) return new WorkspaceMoveProject(folder.ProjectId, entry.KnownName ?? entry.Name, folder.Files, folder.Bytes, true, false);
try try
{ {
var status = await Sync.StatusAsync(folder.ProjectId, null, cancellationToken).ConfigureAwait(false); var status = await SyncOf(folder.ProjectId).StatusAsync(folder.ProjectId, null, cancellationToken).ConfigureAwait(false);
var renders = WorkspaceCleaner.UnsentRenders(project); var renders = WorkspaceCleaner.UnsentRenders(project);
return new WorkspaceMoveProject(folder.ProjectId, entry.Name, folder.Files, folder.Bytes, status.Ahead + status.Damaged + renders > 0 || status.Conflict is not null, return new WorkspaceMoveProject(folder.ProjectId, entry.Name, folder.Files, folder.Bytes, status.Ahead + status.Damaged + renders > 0 || status.Conflict is not null,
status.Modified && !status.ReadOnly); status.Modified && !status.ReadOnly);
+109 -47
View File
@@ -12,6 +12,7 @@ using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs; using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs; using Chronos.Data.Jobs;
using Chronos.Data.Projects; using Chronos.Data.Projects;
using Chronos.Data.Sync;
using Chronos.Data.Workspaces; using Chronos.Data.Workspaces;
using Chronos.Protocol; using Chronos.Protocol;
@@ -203,27 +204,77 @@ public sealed partial class WorkspaceHost
public AppSettings Settings => _settings; public AppSettings Settings => _settings;
/// <summary>The sync over the workspace folder in use (made, with the folder and its manifest, at first use).</summary> /// <summary>
/// The servers known by id and their aliases (owner review 5, #66; the desktop's <c>SyncHost.Identity</c>): a server home's
/// folder is named by its server's canonical key. Unset, every key is its own.
/// </summary>
public Func<ServerIdentity>? Identity { get; set; }
/// <summary>The two server keys name the same server (its id key and the addresses it was reached by, <see cref="Identity"/>).</summary>
public bool SameServer(string? left, string? right) => (Identity?.Invoke() ?? ServerIdentity.None).Same(left, right);
/// <summary>
/// The workspace folder in use split into its homes (owner review 5, #66: <c>local</c> for this PC's archive,
/// <c>servers\&lt;id&gt;</c> for each server; a folder still in the 1.0 layout is one store until its folders are sorted),
/// made, with the folder and its manifest, at first use.
/// </summary>
/// <exception cref="IOException">The folder cannot be made or read.</exception> /// <exception cref="IOException">The folder cannot be made or read.</exception>
/// <exception cref="InvalidDataException">The folder holds another program's or a newer workspace manifest.</exception> /// <exception cref="InvalidDataException">The folder holds another program's or a newer workspace manifest.</exception>
public WorkspaceSync Sync public WorkspaceHomes Homes
{ {
get get
{ {
var root = Root; var root = Root;
var identity = Identity?.Invoke() ?? ServerIdentity.None;
lock (_gate) lock (_gate)
{ {
if (_open is not { } open || !string.Equals(open.Root, root, StringComparison.OrdinalIgnoreCase)) if (_open is not { } open || !string.Equals(open.Root, root, StringComparison.OrdinalIgnoreCase))
{ _open = open = new OpenWorkspace(root, new WorkspaceHomes(root, identity));
var store = new WorkspaceStore(root); open.Homes.Identity = identity;
_open = open = new OpenWorkspace(root, new WorkspaceSync(store, ClientName) { LockWait = LockWait }); return open.Homes;
}
return open.Sync;
} }
} }
} }
public WorkspaceStore Store => Sync.Store; /// <summary>Opens the folder in use again at next use (after its folders were sorted into homes: its layout changed).</summary>
public void Reopen()
{
lock (_gate) _open = null;
}
/// <summary>The project's folder in whichever home holds it; null when the workspace has none.</summary>
public WorkspaceProject? Find(Guid projectId) => Homes.Find(projectId);
/// <summary>The sync over the store of the home that holds <paramref name="projectId"/>.</summary>
/// <exception cref="WorkspaceException">The workspace has no such project (<c>Errors.Workspace.NotCheckedOut</c>).</exception>
public WorkspaceSync SyncOf(Guid projectId) => SyncOf(Existing(projectId).Store);
/// <summary>The sync over the store a project of <paramref name="home"/> is checked out into (made, with its manifest, when it is not there).</summary>
public WorkspaceSync SyncFor(BundleHome home) => SyncOf(Homes.StoreFor(home));
/// <summary>The sync over <paramref name="store"/> (one per store of the folder in use).</summary>
public WorkspaceSync SyncOf(WorkspaceStore store)
{
ArgumentNullException.ThrowIfNull(store);
_ = Homes;
lock (_gate)
{
var open = _open!;
if (!open.Syncs.TryGetValue(store.Root, out var sync))
{
sync = new WorkspaceSync(store, ClientName) { LockWait = LockWait };
open.Syncs[store.Root] = sync;
}
return sync;
}
}
/// <summary>The syncs of every home's store (the clean-up counts them together).</summary>
private IReadOnlyList<WorkspaceSync> AllSyncs()
{
var stores = Homes.All();
return stores.Count == 0 ? [SyncOf(Homes.Local)] : [.. stores.Select(SyncOf)];
}
/// <summary> /// <summary>
/// The project home of a server home (phase 5b; the desktop's <c>SyncHost.ProjectHome</c>): null while this PC is not /// The project home of a server home (phase 5b; the desktop's <c>SyncHost.ProjectHome</c>): null while this PC is not
@@ -273,8 +324,8 @@ public sealed partial class WorkspaceHost
BundleHome home; BundleHome home;
try try
{ {
if (!IsAvailable || Store.Find(change.ProjectId)?.ReadBundle().Workspace?.Home is not { IsArchive: false } held || held.SequenceId != change.SequenceId if (!IsAvailable || Find(change.ProjectId)?.ReadBundle().Workspace?.Home is not { IsArchive: false } held || held.SequenceId != change.SequenceId
|| !string.Equals(held.Server, server, StringComparison.OrdinalIgnoreCase)) || !SameServer(held.Server, server))
return; return;
home = held; home = held;
} }
@@ -298,7 +349,7 @@ public sealed partial class WorkspaceHost
{ {
// Nothing is written into a folder being moved: the next status read takes the name. // Nothing is written into a folder being moved: the next status read takes the name.
if (IsMoving) Log.Info("workspace", $"The new name of project {change.ProjectId} on {server} waits for the workspace's move"); if (IsMoving) Log.Info("workspace", $"The new name of project {change.ProjectId} on {server} waits for the workspace's move");
else if (HomeOf(home) is { } reached) await Sync.FollowNameAsync(change.ProjectId, reached).ConfigureAwait(false); else if (HomeOf(home) is { } reached) await SyncOf(change.ProjectId).FollowNameAsync(change.ProjectId, reached).ConfigureAwait(false);
} }
catch (Exception ex) when (ex is not OutOfMemoryException) catch (Exception ex) when (ex is not OutOfMemoryException)
{ {
@@ -316,7 +367,7 @@ public sealed partial class WorkspaceHost
{ {
if (!Directory.Exists(Root) && await InsideALibraryAsync(cancellationToken).ConfigureAwait(false)) return []; if (!Directory.Exists(Root) && await InsideALibraryAsync(cancellationToken).ConfigureAwait(false)) return [];
var entries = new List<WorkspaceEntry>(); var entries = new List<WorkspaceEntry>();
foreach (var project in Store.List()) foreach (var project in Homes.List())
{ {
try try
{ {
@@ -345,7 +396,7 @@ public sealed partial class WorkspaceHost
{ {
EnsureNotMoving(); EnsureNotMoving();
if (!Directory.Exists(Root) && await InsideALibraryAsync(cancellationToken).ConfigureAwait(false)) return null; if (!Directory.Exists(Root) && await InsideALibraryAsync(cancellationToken).ConfigureAwait(false)) return null;
return Store.Find(projectId) is { } project ? await EntryOrUnreadableAsync(project, cancellationToken).ConfigureAwait(false) : null; return Find(projectId) is { } project ? await EntryOrUnreadableAsync(project, cancellationToken).ConfigureAwait(false) : null;
}, cancellationToken); }, cancellationToken);
/// <summary>Why a copy this Chronos cannot read neither opens nor is checked out over: a newer Chronos wrote it, or it is damaged.</summary> /// <summary>Why a copy this Chronos cannot read neither opens nor is checked out over: a newer Chronos wrote it, or it is damaged.</summary>
@@ -381,7 +432,7 @@ public sealed partial class WorkspaceHost
if (plan.IsSame) return; if (plan.IsSame) return;
if (plan.InsideLibrary) throw new WorkspaceException(Loc.L("Errors.Workspace.InsideLibraryFolder", plan.Folder)) { FolderRefused = true }; if (plan.InsideLibrary) throw new WorkspaceException(Loc.L("Errors.Workspace.InsideLibraryFolder", plan.Folder)) { FolderRefused = true };
// Opened before it is named: a folder that is no workspace is refused while the one in use still is. // Opened before it is named: a folder that is no workspace is refused while the one in use still is.
await Task.Run(() => new WorkspaceStore(plan.Folder), cancellationToken).ConfigureAwait(false); await Task.Run(() => new WorkspaceHomes(plan.Folder), cancellationToken).ConfigureAwait(false);
// Back on the caller's thread (the UI's): the settings are written there. // Back on the caller's thread (the UI's): the settings are written there.
_settings.WorkspaceFolder = string.Equals(plan.Folder, Path.GetFullPath(DefaultRoot(_environment)), StringComparison.OrdinalIgnoreCase) ? null : plan.Folder; _settings.WorkspaceFolder = string.Equals(plan.Folder, Path.GetFullPath(DefaultRoot(_environment)), StringComparison.OrdinalIgnoreCase) ? null : plan.Folder;
_savePreferences(); _savePreferences();
@@ -470,10 +521,10 @@ public sealed partial class WorkspaceHost
: listed.FirstOrDefault(p => p.IsMain) ?? throw new ProjectException(ProjectError.SequenceEmpty, $"Sequence {sequenceId} has no projects yet."); : listed.FirstOrDefault(p => p.IsMain) ?? throw new ProjectException(ProjectError.SequenceEmpty, $"Sequence {sequenceId} has no projects yet.");
} }
// A copy here this Chronos cannot read (damaged, or a newer Chronos's): nothing is checked out or copied over it. // A copy here this Chronos cannot read (damaged, or a newer Chronos's): nothing is checked out or copied over it.
if (Store.Find(project.Id) is { } here && await EntryOrUnreadableAsync(here, cancellationToken).ConfigureAwait(false) is { IsReadable: false } unreadable) if (Find(project.Id) is { } here && await EntryOrUnreadableAsync(here, cancellationToken).ConfigureAwait(false) is { IsReadable: false } unreadable)
throw Unreadable(unreadable); throw Unreadable(unreadable);
var folder = await Sync.CheckoutAsync(reached, project.Id, media, cancellationToken).ConfigureAwait(false); var folder = await SyncFor(home).CheckoutAsync(reached, project.Id, media, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Project {project.Id} ('{project.Name}') of sequence {sequenceId} checked out into {Store.Root}"); Log.Info("workspace", $"Project {project.Id} ('{project.Name}') of sequence {sequenceId} checked out into {folder.Store.Root}");
var title = folder.ReadBundle().Sequence.Title ?? string.Empty; var title = folder.ReadBundle().Sequence.Title ?? string.Empty;
return new WorkspaceCheckout(project, await QueueCopyCoreAsync(home, project.Id, media, title, cancellationToken).ConfigureAwait(false)); return new WorkspaceCheckout(project, await QueueCopyCoreAsync(home, project.Id, media, title, cancellationToken).ConfigureAwait(false));
}, cancellationToken); }, cancellationToken);
@@ -507,14 +558,14 @@ public sealed partial class WorkspaceHost
var home = askHome ? HomeOf(named) : null; var home = askHome ? HomeOf(named) : null;
try try
{ {
if (askHome && home is null && !named.IsArchive) return Offline(await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false)); if (askHome && home is null && !named.IsArchive) return Offline(await SyncOf(projectId).StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
return await Sync.StatusAsync(projectId, home, cancellationToken).ConfigureAwait(false); return await SyncOf(projectId).StatusAsync(projectId, home, cancellationToken).ConfigureAwait(false);
} }
catch (Exception ex) when (home is not null && ex is ProjectException or DatabaseException or IOException) catch (Exception ex) when (home is not null && ex is ProjectException or DatabaseException or IOException)
{ {
var gone = ex is ProjectException { Reason: ProjectError.SequenceNotFound or ProjectError.NotFound }; var gone = ex is ProjectException { Reason: ProjectError.SequenceNotFound or ProjectError.NotFound };
Log.Info("workspace", gone ? $"The home no longer has project {projectId}: {ex.Message}" : $"The home of project {projectId} could not be asked: {ex.Message}"); Log.Info("workspace", gone ? $"The home no longer has project {projectId}: {ex.Message}" : $"The home of project {projectId} could not be asked: {ex.Message}");
var local = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false); var local = await SyncOf(projectId).StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
return local with return local with
{ {
Offline = true, Offline = true,
@@ -545,8 +596,8 @@ public sealed partial class WorkspaceHost
var version = await Task.Run(async () => var version = await Task.Run(async () =>
{ {
EnsureNotMoving(); EnsureNotMoving();
EnsureWritable(await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false)); EnsureWritable(await SyncOf(projectId).StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
return await Sync.CommitAsync(projectId, note, null, cancellationToken).ConfigureAwait(false); return await SyncOf(projectId).CommitAsync(projectId, note, null, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false);
if (version is not null) Log.Info("workspace", $"Version {version.Number} of project {projectId} saved"); if (version is not null) Log.Info("workspace", $"Version {version.Number} of project {projectId} saved");
if (!_settings.WorkspaceAutoSync) return new WorkspaceSaveResult(version, null, await StatusAsync(projectId, cancellationToken: cancellationToken).ConfigureAwait(false), null); if (!_settings.WorkspaceAutoSync) return new WorkspaceSaveResult(version, null, await StatusAsync(projectId, cancellationToken: cancellationToken).ConfigureAwait(false), null);
@@ -568,8 +619,8 @@ public sealed partial class WorkspaceHost
public Task<ProjectVersion?> CommitAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () => public Task<ProjectVersion?> CommitAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{ {
EnsureNotMoving(); EnsureNotMoving();
EnsureWritable(await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false)); EnsureWritable(await SyncOf(projectId).StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
return await Sync.CommitAsync(projectId, null, null, cancellationToken).ConfigureAwait(false); return await SyncOf(projectId).CommitAsync(projectId, null, null, cancellationToken).ConfigureAwait(false);
}, cancellationToken); }, cancellationToken);
/// <summary> /// <summary>
@@ -583,10 +634,10 @@ public sealed partial class WorkspaceHost
{ {
EnsureNotMoving(); EnsureNotMoving();
var home = HomeOfProject(projectId); var home = HomeOfProject(projectId);
var pulled = await Sync.PullAsync(projectId, home, cancellationToken).ConfigureAwait(false); var pulled = await SyncOf(projectId).PullAsync(projectId, home, cancellationToken).ConfigureAwait(false);
// Deleted at the library: nothing to send, nothing to prune; the copy stays as it is. // Deleted at the library: nothing to send, nothing to prune; the copy stays as it is.
if (pulled.Status.State is WorkspaceState.Conflict or WorkspaceState.Gone) return pulled; if (pulled.Status.State is WorkspaceState.Conflict or WorkspaceState.Gone) return pulled;
var pushed = await Sync.PushAsync(projectId, home, cancellationToken).ConfigureAwait(false); var pushed = await SyncOf(projectId).PushAsync(projectId, home, cancellationToken).ConfigureAwait(false);
await PruneQuietlyAsync(projectId, home, cancellationToken).ConfigureAwait(false); await PruneQuietlyAsync(projectId, home, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Project {projectId} synced: {pushed.Pushed.Count} sent, {pulled.Pulled.Count + pushed.Pulled.Count} taken, {pushed.Status.State}"); Log.Info("workspace", $"Project {projectId} synced: {pushed.Pushed.Count} sent, {pulled.Pulled.Count + pushed.Pulled.Count} taken, {pushed.Status.State}");
return new WorkspaceSyncResult(pushed.Status, pushed.Pushed, [.. pulled.Pulled, .. pushed.Pulled]); return new WorkspaceSyncResult(pushed.Status, pushed.Pushed, [.. pulled.Pulled, .. pushed.Pulled]);
@@ -609,16 +660,16 @@ public sealed partial class WorkspaceHost
var name = SiblingName(Existing(projectId).ReadBundle().Workspace!.Name); var name = SiblingName(Existing(projectId).ReadBundle().Workspace!.Name);
try try
{ {
resolved = await Sync.ResolveAsync(projectId, home, choice, takeServer, name, shown, cancellationToken).ConfigureAwait(false); resolved = await SyncOf(projectId).ResolveAsync(projectId, home, choice, takeServer, name, shown, cancellationToken).ConfigureAwait(false);
} }
catch (ProjectException ex) when (ex.Reason is ProjectError.NameTaken or ProjectError.InvalidName) catch (ProjectException ex) when (ex.Reason is ProjectError.NameTaken or ProjectError.InvalidName)
{ {
resolved = await Sync.ResolveAsync(projectId, home, choice, takeServer, null, shown, cancellationToken).ConfigureAwait(false); resolved = await SyncOf(projectId).ResolveAsync(projectId, home, choice, takeServer, null, shown, cancellationToken).ConfigureAwait(false);
} }
} }
else else
{ {
resolved = await Sync.ResolveAsync(projectId, home, choice, takeServer, null, shown, cancellationToken).ConfigureAwait(false); resolved = await SyncOf(projectId).ResolveAsync(projectId, home, choice, takeServer, null, shown, cancellationToken).ConfigureAwait(false);
} }
if (resolved.Status.State == WorkspaceState.Conflict) if (resolved.Status.State == WorkspaceState.Conflict)
{ {
@@ -628,7 +679,7 @@ public sealed partial class WorkspaceHost
// Deleted in the library: nothing more to send (a Save both's copy holds the versions already). // Deleted in the library: nothing more to send (a Save both's copy holds the versions already).
if (resolved.Status.State == WorkspaceState.Gone) return resolved; if (resolved.Status.State == WorkspaceState.Gone) return resolved;
Log.Info("workspace", $"Conflict of project {projectId} settled: {choice}{(resolved.SavedAs is { } copy ? $", saved as '{copy.Name}'" : string.Empty)}"); Log.Info("workspace", $"Conflict of project {projectId} settled: {choice}{(resolved.SavedAs is { } copy ? $", saved as '{copy.Name}'" : string.Empty)}");
var pushed = await Sync.PushAsync(projectId, home, cancellationToken).ConfigureAwait(false); var pushed = await SyncOf(projectId).PushAsync(projectId, home, cancellationToken).ConfigureAwait(false);
return new WorkspaceSyncResult(pushed.Status, [.. resolved.Pushed, .. pushed.Pushed], [.. resolved.Pulled, .. pushed.Pulled], resolved.SavedAs) return new WorkspaceSyncResult(pushed.Status, [.. resolved.Pushed, .. pushed.Pushed], [.. resolved.Pulled, .. pushed.Pulled], resolved.SavedAs)
{ {
Kept = resolved.Kept, Kept = resolved.Kept,
@@ -652,11 +703,11 @@ public sealed partial class WorkspaceHost
public Task<ProjectSettings> RestoreAsync(Guid projectId, Guid versionId, CancellationToken cancellationToken = default) => Task.Run(async () => public Task<ProjectSettings> RestoreAsync(Guid projectId, Guid versionId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{ {
EnsureNotMoving(); EnsureNotMoving();
var status = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false); var status = await SyncOf(projectId).StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
if (status.ReadOnly) throw new WorkspaceException(Loc.L("Errors.Workspace.ReadOnly")); if (status.ReadOnly) throw new WorkspaceException(Loc.L("Errors.Workspace.ReadOnly"));
if (status.MediaRemoved) throw new WorkspaceException(Loc.L("Errors.Workspace.MediaMissing")); if (status.MediaRemoved) throw new WorkspaceException(Loc.L("Errors.Workspace.MediaMissing"));
var home = HomeOf(Existing(projectId).ReadBundle().Workspace!.Home); var home = HomeOf(Existing(projectId).ReadBundle().Workspace!.Home);
var restored = await Sync.RestoreAsync(projectId, versionId, home, cancellationToken).ConfigureAwait(false); var restored = await SyncOf(projectId).RestoreAsync(projectId, versionId, home, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Version {versionId} of project {projectId} restored as the working state"); Log.Info("workspace", $"Version {versionId} of project {projectId} restored as the working state");
return restored; return restored;
}, cancellationToken); }, cancellationToken);
@@ -665,7 +716,7 @@ public sealed partial class WorkspaceHost
public Task<WorkspaceHistory> HistoryAsync(Guid projectId, int limit = 50, CancellationToken cancellationToken = default) => Task.Run(async () => public Task<WorkspaceHistory> HistoryAsync(Guid projectId, int limit = 50, CancellationToken cancellationToken = default) => Task.Run(async () =>
{ {
var project = Existing(projectId); var project = Existing(projectId);
var unsent = Sync.Unpushed(projectId); var unsent = SyncOf(projectId).Unpushed(projectId);
var home = HomeOf(project.ReadBundle().Workspace!.Home); var home = HomeOf(project.ReadBundle().Workspace!.Home);
IReadOnlyList<ProjectVersion> stored; IReadOnlyList<ProjectVersion> stored;
var offline = false; var offline = false;
@@ -740,9 +791,9 @@ public sealed partial class WorkspaceHost
var workspace = project.ReadBundle().Workspace!; var workspace = project.ReadBundle().Workspace!;
if (workspace.IsMain) throw new ProjectException(ProjectError.MainCannotBeDeleted, "The Main project cannot be deleted."); if (workspace.IsMain) throw new ProjectException(ProjectError.MainCannotBeDeleted, "The Main project cannot be deleted.");
var home = HomeOfProject(projectId); var home = HomeOfProject(projectId);
var local = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false); var local = await SyncOf(projectId).StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
if (local.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict")); if (local.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
if (!local.ReadOnly) await Sync.CommitAsync(projectId, null, null, cancellationToken).ConfigureAwait(false); if (!local.ReadOnly) await SyncOf(projectId).CommitAsync(projectId, null, null, cancellationToken).ConfigureAwait(false);
var status = (await SendAsync(projectId, home, cancellationToken).ConfigureAwait(false)).Status; var status = (await SendAsync(projectId, home, cancellationToken).ConfigureAwait(false)).Status;
if (status.State == WorkspaceState.Gone) throw new WorkspaceException(Loc.L("Errors.Workspace.DeletedAtHome")); if (status.State == WorkspaceState.Gone) throw new WorkspaceException(Loc.L("Errors.Workspace.DeletedAtHome"));
if (status.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict")); if (status.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
@@ -773,7 +824,7 @@ public sealed partial class WorkspaceHost
/// <exception cref="WorkspaceException">A conflict waits (open the project and Sync to settle it), or something is still not at the home.</exception> /// <exception cref="WorkspaceException">A conflict waits (open the project and Sync to settle it), or something is still not at the home.</exception>
public async Task SendAllAsync(Guid projectId, CancellationToken cancellationToken = default) public async Task SendAllAsync(Guid projectId, CancellationToken cancellationToken = default)
{ {
var local = await Task.Run(() => Sync.StatusAsync(projectId, null, cancellationToken), cancellationToken).ConfigureAwait(false); var local = await Task.Run(() => SyncOf(projectId).StatusAsync(projectId, null, cancellationToken), cancellationToken).ConfigureAwait(false);
if (local is { Conflict: null, ReadOnly: false, MediaRemoved: false }) await CommitAsync(projectId, cancellationToken).ConfigureAwait(false); if (local is { Conflict: null, ReadOnly: false, MediaRemoved: false }) await CommitAsync(projectId, cancellationToken).ConfigureAwait(false);
var status = (await SyncAsync(projectId, cancellationToken).ConfigureAwait(false)).Status; var status = (await SyncAsync(projectId, cancellationToken).ConfigureAwait(false)).Status;
if (status.State == WorkspaceState.Gone) throw new WorkspaceException(Loc.L("Errors.Workspace.DeletedAtHome")); if (status.State == WorkspaceState.Gone) throw new WorkspaceException(Loc.L("Errors.Workspace.DeletedAtHome"));
@@ -837,7 +888,7 @@ public sealed partial class WorkspaceHost
var workspace = project.ReadBundle().Workspace!; var workspace = project.ReadBundle().Workspace!;
if (!discard) if (!discard)
{ {
var status = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false); var status = await SyncOf(projectId).StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
// A version saved here that cannot be read may be one the home never had: only discarding keeps it aside. // A version saved here that cannot be read may be one the home never had: only discarding keeps it aside.
if (status.Ahead > 0 || status.Damaged > 0 || (status.Modified && !status.ReadOnly) || status.Conflict is not null) if (status.Ahead > 0 || status.Damaged > 0 || (status.Modified && !status.ReadOnly) || status.Conflict is not null)
throw new WorkspaceException(Unsent(workspace.Home)); throw new WorkspaceException(Unsent(workspace.Home));
@@ -894,8 +945,8 @@ public sealed partial class WorkspaceHost
/// <summary>The local versions sent (after the home's new ones were taken), as one sync without the pruning.</summary> /// <summary>The local versions sent (after the home's new ones were taken), as one sync without the pruning.</summary>
private async Task<WorkspaceSyncResult> SendAsync(Guid projectId, IProjectHome home, CancellationToken cancellationToken) private async Task<WorkspaceSyncResult> SendAsync(Guid projectId, IProjectHome home, CancellationToken cancellationToken)
{ {
var pulled = await Sync.PullAsync(projectId, home, cancellationToken).ConfigureAwait(false); var pulled = await SyncOf(projectId).PullAsync(projectId, home, cancellationToken).ConfigureAwait(false);
return pulled.Status.State is WorkspaceState.Conflict or WorkspaceState.Gone ? pulled : await Sync.PushAsync(projectId, home, cancellationToken).ConfigureAwait(false); return pulled.Status.State is WorkspaceState.Conflict or WorkspaceState.Gone ? pulled : await SyncOf(projectId).PushAsync(projectId, home, cancellationToken).ConfigureAwait(false);
} }
/// <summary>The home holds this copy's work: its head and the base this copy was last in step with read back, each matching its hash.</summary> /// <summary>The home holds this copy's work: its head and the base this copy was last in step with read back, each matching its hash.</summary>
@@ -948,7 +999,7 @@ public sealed partial class WorkspaceHost
{ State: JobState.Queued or JobState.Running or JobState.Paused }) { State: JobState.Queued or JobState.Running or JobState.Paused })
await engine.CancelAsync(copy, cancellationToken).ConfigureAwait(false); await engine.CancelAsync(copy, cancellationToken).ConfigureAwait(false);
// Filled under a staging name Empty… never lists, and named once whole. // Filled under a staging name Empty… never lists, and named once whole.
using var trash = WorkspaceTrash.Begin(Store.Root, project.ProjectId, DateTime.UtcNow); using var trash = WorkspaceTrash.Begin(project.Store.Root, project.ProjectId, DateTime.UtcNow);
var aside = trash.Path; var aside = trash.Path;
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false)) using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
{ {
@@ -1087,11 +1138,12 @@ public sealed partial class WorkspaceHost
{ {
var sequence = await db.Sequences.GetAsync(home.SequenceId, cancellationToken).ConfigureAwait(false) var sequence = await db.Sequences.GetAsync(home.SequenceId, cancellationToken).ConfigureAwait(false)
?? throw new ProjectException(ProjectError.SequenceNotFound, $"Sequence {home.SequenceId} is not in the index."); ?? throw new ProjectException(ProjectError.SequenceNotFound, $"Sequence {home.SequenceId} is not in the index.");
request = WorkspaceJobs.Copy(sequence, Store.Root, projectId, media); request = WorkspaceJobs.Copy(sequence, Existing(projectId).Store.Root, projectId, media);
} }
else else
{ {
request = WorkspaceJobs.CopyFromServer(home.SequenceId, title, home.Server ?? throw new InvalidDataException("A server home names no server."), Store.Root, request = WorkspaceJobs.CopyFromServer(home.SequenceId, title, home.Server ?? throw new InvalidDataException("A server home names no server."),
Existing(projectId).Store.Root,
projectId, media); projectId, media);
} }
var job = await engine.EnqueueAsync(request, cancellationToken: cancellationToken).ConfigureAwait(false); var job = await engine.EnqueueAsync(request, cancellationToken: cancellationToken).ConfigureAwait(false);
@@ -1108,7 +1160,7 @@ public sealed partial class WorkspaceHost
: "This PC is not signed in to the server of the project, or it keeps no projects."); : "This PC is not signed in to the server of the project, or it keeps no projects.");
} }
private WorkspaceProject Existing(Guid projectId) => Store.Find(projectId) ?? throw new WorkspaceException(Loc.L("Errors.Workspace.NotCheckedOut")); private WorkspaceProject Existing(Guid projectId) => Find(projectId) ?? throw new WorkspaceException(Loc.L("Errors.Workspace.NotCheckedOut"));
private static WorkspaceEntry Entry(WorkspaceProject project, ProjectBundle bundle) private static WorkspaceEntry Entry(WorkspaceProject project, ProjectBundle bundle)
{ {
@@ -1206,14 +1258,20 @@ public sealed partial class WorkspaceHost
} }
} }
/// <summary>The projects a workspace folder holds (folders named by a project id with a working state), without making or opening it.</summary> /// <summary>
/// The projects a workspace folder holds (folders named by a project id with a working state), in it and in its homes'
/// folders (<c>local</c>, <c>servers\&lt;folder&gt;</c>, owner review 5), without making or opening it.
/// </summary>
private static int CountProjects(string folder) private static int CountProjects(string folder)
{ {
if (!Directory.Exists(folder)) return 0; if (!Directory.Exists(folder)) return 0;
try try
{ {
return Directory.EnumerateDirectories(folder).Count(d => Guid.TryParseExact(Path.GetFileName(d), "N", out _) var stores = new List<string> { folder, HomeFolders.LocalPath(folder) };
&& File.Exists(Path.Combine(d, WorkspaceProject.BundleFile))); var servers = Path.Combine(folder, HomeFolders.Servers);
if (Directory.Exists(servers)) stores.AddRange(Directory.EnumerateDirectories(servers).Where(d => HomeFolders.IsServerFolder(Path.GetFileName(d))));
return stores.Where(Directory.Exists).Sum(store => Directory.EnumerateDirectories(store).Count(d => Guid.TryParseExact(Path.GetFileName(d), "N", out _)
&& File.Exists(Path.Combine(d, WorkspaceProject.BundleFile))));
} }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{ {
@@ -1236,5 +1294,9 @@ public sealed partial class WorkspaceHost
return (files, bytes); return (files, bytes);
} }
private sealed record OpenWorkspace(string Root, WorkspaceSync Sync); /// <summary>The workspace folder in use, its homes and the sync of each of its stores (by root).</summary>
private sealed record OpenWorkspace(string Root, WorkspaceHomes Homes)
{
public Dictionary<string, WorkspaceSync> Syncs { get; } = new(StringComparer.OrdinalIgnoreCase);
}
} }
+1 -15
View File
@@ -7,7 +7,7 @@ namespace Chronos.Core.Windows.Shell;
/// <c>.\data</c> next to the executable in portable mode. SQLite corrupts inside synchronised folders, so a portable /// <c>.\data</c> next to the executable in portable mode. SQLite corrupts inside synchronised folders, so a portable
/// copy in a OneDrive folder keeps its data in <c>%LOCALAPPDATA%\Chronos</c> instead (<see cref="PortableSyncRoot"/> /// copy in a OneDrive folder keeps its data in <c>%LOCALAPPDATA%\Chronos</c> instead (<see cref="PortableSyncRoot"/>
/// names that folder to tell the user, <see cref="EarlierPortableData"/> the data it kept there before), and a data /// names that folder to tell the user, <see cref="EarlierPortableData"/> the data it kept there before), and a data
/// root still under OneDrive is reported by <see cref="SyncedFolder"/> and refused by <see cref="CreateDirectories"/>. /// root still under OneDrive is reported by <see cref="SyncedFolder"/>.
/// </summary> /// </summary>
public sealed class AppPaths public sealed class AppPaths
{ {
@@ -35,8 +35,6 @@ public sealed class AppPaths
public string CacheDirectory => Path.Combine(DataRoot, "cache"); public string CacheDirectory => Path.Combine(DataRoot, "cache");
public string ThumbnailsDirectory => Path.Combine(DataRoot, "thumbnails");
/// <summary>The OneDrive sync root containing <see cref="DataRoot"/>, or null when the location is safe.</summary> /// <summary>The OneDrive sync root containing <see cref="DataRoot"/>, or null when the location is safe.</summary>
public string? SyncedFolder { get; } public string? SyncedFolder { get; }
@@ -69,16 +67,4 @@ public sealed class AppPaths
: null; : null;
return new AppPaths(location, earlier); return new AppPaths(location, earlier);
} }
/// <summary>Creates the data, logs, cache and thumbnails folders.</summary>
/// <exception cref="InvalidOperationException">The data root lies inside a OneDrive-synced folder.</exception>
public void CreateDirectories()
{
if (SyncedFolder is not null)
throw new InvalidOperationException($"The data folder '{DataRoot}' is inside the OneDrive folder '{SyncedFolder}'; the database would be corrupted by synchronisation.");
Directory.CreateDirectory(DataRoot);
Directory.CreateDirectory(LogsDirectory);
Directory.CreateDirectory(CacheDirectory);
Directory.CreateDirectory(ThumbnailsDirectory);
}
} }
+178
View File
@@ -0,0 +1,178 @@
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
namespace Chronos.Core.IO;
/// <summary>
/// The folders each home of the desktop keeps apart (owner review 5, #66): this PC's archive is the home <see cref="Local"/>,
/// and every Chronos Server is a home of its own under <see cref="Servers"/>, named by the server's stable id
/// (<c>servers\&lt;id:N&gt;</c>), or, for a server that announces none (an older server), by a hash of its address key
/// (<c>servers\addr-&lt;16 hex&gt;</c>: the hash the 1.0 proxy cache named its folders by, so moving them is a rename).
/// The same names are used in the workspace (<c>&lt;workspace&gt;\local</c>, <c>&lt;workspace&gt;\servers\&lt;folder&gt;</c>)
/// and in the cache (<c>&lt;cache&gt;\servers\&lt;folder&gt;\{proxies,render-node,import}</c>). A folder name is never renamed
/// after the server: its name lives in <see cref="ServerFile"/> beside it.
/// </summary>
public static class HomeFolders
{
/// <summary>The folder of this PC's archive's home.</summary>
public const string Local = "local";
/// <summary>The folder that holds one folder per server home.</summary>
public const string Servers = "servers";
/// <summary>What a server home's folder says about its server (id, name, last address), for someone browsing it.</summary>
public const string ServerFile = "server.json";
/// <summary>A server home's proxies of its sequences, in the cache.</summary>
public const string Proxies = "proxies";
/// <summary>A server home's render-node downloads, in the cache.</summary>
public const string RenderNode = "render-node";
/// <summary>A server home's staged card imports, in the cache.</summary>
public const string Import = "import";
/// <summary>The start of a server key made from the server's announced id (<c>id:&lt;32 hex&gt;</c>).</summary>
public const string IdKeyPrefix = "id:";
/// <summary>The start of the folder of a server known by its address only.</summary>
public const string AddressPrefix = "addr-";
/// <summary>Hex digits of the address hash in a folder name (as the 1.0 proxy cache used).</summary>
public const int HashLength = 16;
/// <summary>
/// The folder of a server home: the 32 hex digits of the id of an id key (<c>id:&lt;N&gt;</c>), else <c>addr-</c> and the
/// first 16 hex digits of the SHA-256 of the key (an address key, as <c>SyncService.ServerKey</c> makes it).
/// </summary>
public static string ServerFolder(string serverKey)
{
ArgumentException.ThrowIfNullOrWhiteSpace(serverKey);
return IdOfKey(serverKey) is { } id ? id.ToString("N") : AddressPrefix + AddressHash(serverKey);
}
/// <summary>The 16 hex digits the 1.0 proxy cache named a server's folder by: the start of the SHA-256 of its key.</summary>
public static string AddressHash(string serverKey)
{
ArgumentNullException.ThrowIfNull(serverKey);
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(serverKey)))[..HashLength];
}
/// <summary>The id an id key names (<c>id:&lt;N&gt;</c>); null for an address key.</summary>
public static Guid? IdOfKey(string? serverKey) =>
serverKey is { Length: > 0 } key && key.StartsWith(IdKeyPrefix, StringComparison.OrdinalIgnoreCase)
&& Guid.TryParseExact(key.AsSpan(IdKeyPrefix.Length), "N", out var id) && id != Guid.Empty
? id
: null;
/// <summary>The key of a server known by its announced id.</summary>
public static string IdKey(Guid serverId)
{
if (serverId == Guid.Empty) throw new ArgumentException("A server id is never empty.", nameof(serverId));
return IdKeyPrefix + serverId.ToString("N");
}
/// <summary>
/// A name a server home's folder can have: 32 lower-case hex digits (an id) or <c>addr-</c> with 16 lower-case hex
/// digits. Anything else under <see cref="Servers"/> is not a home (left alone).
/// </summary>
public static bool IsServerFolder(string? name) => name is { Length: > 0 } && (IdOfFolder(name) is not null || IsAddressFolder(name));
/// <summary>The server id a folder named by one stands for; null for an address folder or another name.</summary>
public static Guid? IdOfFolder(string? name) =>
name is { Length: 32 } && IsLowerHex(name) && Guid.TryParseExact(name, "N", out var id) && id != Guid.Empty ? id : null;
/// <summary>A folder of a server known by its address only (<c>addr-</c> and 16 lower-case hex digits).</summary>
public static bool IsAddressFolder(string? name) =>
name is { Length: > 0 } && name.Length == AddressPrefix.Length + HashLength && name.StartsWith(AddressPrefix, StringComparison.Ordinal)
&& IsLowerHex(name.AsSpan(AddressPrefix.Length));
/// <summary>The folder of this PC's home under <paramref name="root"/> (a workspace or a cache folder).</summary>
public static string LocalPath(string root)
{
ArgumentException.ThrowIfNullOrWhiteSpace(root);
return Path.Combine(root, Local);
}
/// <summary>The folder of the home of <paramref name="serverKey"/> under <paramref name="root"/> (a workspace or a cache folder).</summary>
public static string ServerPath(string root, string serverKey)
{
ArgumentException.ThrowIfNullOrWhiteSpace(root);
return Path.Combine(root, Servers, ServerFolder(serverKey));
}
/// <summary>
/// Where the originals a server's sequences download go by default (owner review 5, Q1): an archive of their own beside
/// this PC's, <c>&lt;parent of the archive&gt;\&lt;archive folder name&gt; - &lt;server name&gt;</c>, for example
/// <c>D:\ChronosArchive - Studio NAS</c>. The server's name is made safe as a folder name (<see cref="SafeName"/>); a
/// folder <paramref name="taken"/> says is taken gets " (2)", " (3)"… With no archive of this PC's,
/// <paramref name="fallbackArchiveRoot"/> (where a first archive would go) stands for it.
/// </summary>
/// <param name="localArchiveRoot">The root of this PC's archive; null when there is none.</param>
/// <param name="serverName">The server's name as its <c>server/info</c> gives it.</param>
/// <param name="fallbackArchiveRoot">Where this PC's first archive would go (the desktop's default archive folder).</param>
/// <param name="taken">Whether a folder is taken (it exists, or another archive uses it); null takes an existing folder or file.</param>
public static string OriginalsArchiveRoot(string? localArchiveRoot, string serverName, string fallbackArchiveRoot, Func<string, bool>? taken = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(fallbackArchiveRoot);
var archive = Path.TrimEndingDirectorySeparator(Path.GetFullPath(string.IsNullOrWhiteSpace(localArchiveRoot) ? fallbackArchiveRoot : localArchiveRoot));
var parent = Path.GetDirectoryName(archive) ?? archive;
var name = Path.GetFileName(archive);
if (string.IsNullOrEmpty(name)) name = SafeName(Path.GetFileName(Path.TrimEndingDirectorySeparator(fallbackArchiveRoot)));
var stem = name + " - " + SafeName(serverName);
taken ??= path => Directory.Exists(path) || File.Exists(path);
for (var n = 1; ; n++)
{
var candidate = Path.Combine(parent, n == 1 ? stem : stem + " (" + n.ToString(CultureInfo.InvariantCulture) + ")");
if (!taken(candidate)) return candidate;
}
}
/// <summary>Characters no folder name may hold on Windows (and so on any PC a folder may be copied to).</summary>
private static readonly char[] Unsafe = ['<', '>', ':', '"', '/', '\\', '|', '?', '*'];
private static readonly string[] Reserved =
[
"CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5",
"LPT6", "LPT7", "LPT8", "LPT9",
];
/// <summary>The longest folder name <see cref="SafeName"/> gives.</summary>
public const int MaxNameLength = 60;
/// <summary>
/// <paramref name="name"/> as a folder name every Windows file system takes: characters it refuses and control characters
/// become spaces, runs of spaces one, leading and trailing spaces and dots go, a device name (CON, NUL, COM1…) gets an
/// underscore, and it is cut to <see cref="MaxNameLength"/>. "Server" when nothing is left.
/// </summary>
public static string SafeName(string? name)
{
var text = new StringBuilder(name?.Length ?? 0);
foreach (var c in name ?? string.Empty)
{
var bad = char.IsControl(c) || Array.IndexOf(Unsafe, c) >= 0;
var space = bad || char.IsWhiteSpace(c);
if (space)
{
if (text.Length > 0 && text[^1] != ' ') text.Append(' ');
continue;
}
text.Append(c);
}
var safe = text.ToString().Trim(' ', '.');
if (safe.Length > MaxNameLength) safe = safe[..MaxNameLength].TrimEnd(' ', '.');
if (safe.Length == 0) return "Server";
var stem = safe.Split('.')[0];
return Reserved.Contains(stem, StringComparer.OrdinalIgnoreCase) ? safe + "_" : safe;
}
private static bool IsLowerHex(ReadOnlySpan<char> text)
{
foreach (var c in text)
{
if (c is not ((>= '0' and <= '9') or (>= 'a' and <= 'f'))) return false;
}
return true;
}
}
+4 -1
View File
@@ -23,7 +23,10 @@ public sealed record BundleSequence(Guid Id, string Folder, string? Title, int F
/// <summary> /// <summary>
/// Where a workspace project's versions live (owner review 2, R8): this PC's archive (<see cref="ArchiveKind"/>, with the /// Where a workspace project's versions live (owner review 2, R8): this PC's archive (<see cref="ArchiveKind"/>, with the
/// archive's id) or a server (<see cref="ServerKind"/>, with its address), and the sequence there. /// archive's id) or a server (<see cref="ServerKind"/>, with its key), and the sequence there. A server's key is its id key
/// (<c>id:&lt;N&gt;</c>, <see cref="IO.HomeFolders.IdKey"/>) once the server announced its stable id (owner review 5, #66),
/// else the address it was reached at (<c>https://nas.local:8443</c>, the 1.0 key, which an id-keyed server keeps as an
/// alias); the format does not change.
/// </summary> /// </summary>
public sealed record BundleHome(string Kind, Guid SequenceId, Guid? ArchiveId = null, string? Server = null) public sealed record BundleHome(string Kind, Guid SequenceId, Guid? ArchiveId = null, string? Server = null)
{ {
+1 -1
View File
@@ -372,7 +372,7 @@ public sealed class ArchiveIndexer
/// the flags in the sidecar are the writer's that added the frames (which analyses them, and on a server draws them /// the flags in the sidecar are the writer's that added the frames (which analyses them, and on a server draws them
/// after every upload), and clearing them there would have the server make everything again. /// after every upload), and clearing them there would have the server make everything again.
/// </summary> /// </summary>
private SequenceStatus Uncovered => _writer.Options.ImagesAfterScan ? CoveringStatus : SequenceStatus.None; private SequenceStatus Uncovered => _writer.Options.QueuesImagesAfterScan ? CoveringStatus : SequenceStatus.None;
/// <summary> /// <summary>
/// The projects of a sequence brought in line with their sidecars (<see cref="ProjectIndexer"/>), under its lease, in the /// The projects of a sequence brought in line with their sidecars (<see cref="ProjectIndexer"/>), under its lease, in the
+3 -3
View File
@@ -104,8 +104,8 @@ public sealed class ArchiveService : IJobHandlerProvider
/// </summary> /// </summary>
public IReadOnlyList<IJobHandler> CreateJobHandlers() => public IReadOnlyList<IJobHandler> CreateJobHandlers() =>
[ [
new ScanJobHandler(_db, Indexer, JobKind.Scan, _writer.Options.ImagesAfterScan), new ScanJobHandler(_db, Indexer, JobKind.Scan, () => _writer.Options.QueuesImagesAfterScan),
new ScanJobHandler(_db, Indexer, JobKind.Rebuild, _writer.Options.ImagesAfterScan), new ScanJobHandler(_db, Indexer, JobKind.Rebuild, () => _writer.Options.QueuesImagesAfterScan),
new VerifyJobHandler(_db, Verifier), new VerifyJobHandler(_db, Verifier),
new ImportJobHandler(_db, Imports), new ImportJobHandler(_db, Imports),
new ImageJobHandler(_db, Images, JobKind.Thumbs), new ImageJobHandler(_db, Images, JobKind.Thumbs),
@@ -450,7 +450,7 @@ public sealed class ArchiveService : IJobHandlerProvider
List<ArchiveJobRequest> requests = [ProcessingJobs.LightAnalysis([sequenceId], sequence.DisplayTitle)]; List<ArchiveJobRequest> requests = [ProcessingJobs.LightAnalysis([sequenceId], sequence.DisplayTitle)];
// BRIEF §10.2: background, low priority. // BRIEF §10.2: background, low priority.
if (deepAnalysis) requests.Add(ProcessingJobs.DeepAnalysis([sequenceId], sequence.DisplayTitle) with { Priority = JobPriority.Background }); if (deepAnalysis) requests.Add(ProcessingJobs.DeepAnalysis([sequenceId], sequence.DisplayTitle) with { Priority = JobPriority.Background });
if (_writer.Options.ImagesAfterScan) if (_writer.Options.QueuesImagesAfterScan)
{ {
requests.Add(ArchiveJobs.Thumbnails([sequenceId], sequence.DisplayTitle)); requests.Add(ArchiveJobs.Thumbnails([sequenceId], sequence.DisplayTitle));
// An archive whose policy makes no proxies would get a pass that does nothing. // An archive whose policy makes no proxies would get a pass that does nothing.
+1 -1
View File
@@ -627,7 +627,7 @@ public sealed partial class FrameTrash
var label = sequence.DisplayTitle; var label = sequence.DisplayTitle;
List<ArchiveJobRequest> requests = [ProcessingJobs.LightAnalysis([sequence.Id], label)]; List<ArchiveJobRequest> requests = [ProcessingJobs.LightAnalysis([sequence.Id], label)];
if ((had & SequenceStatus.AnalyzedDeep) != 0) requests.Add(ProcessingJobs.DeepAnalysis([sequence.Id], label) with { Priority = JobPriority.Background }); if ((had & SequenceStatus.AnalyzedDeep) != 0) requests.Add(ProcessingJobs.DeepAnalysis([sequence.Id], label) with { Priority = JobPriority.Background });
var images = _writer.Options.ImagesAfterScan; var images = _writer.Options.QueuesImagesAfterScan;
if (images || (had & SequenceStatus.ThumbsBuilt) != 0) requests.Add(ArchiveJobs.Thumbnails([sequence.Id], label)); if (images || (had & SequenceStatus.ThumbsBuilt) != 0) requests.Add(ArchiveJobs.Thumbnails([sequence.Id], label));
if ((images || (had & SequenceStatus.ProxiesBuilt) != 0) && archive.ProxyLongEdge != ProxyPolicy.Disabled) if ((images || (had & SequenceStatus.ProxiesBuilt) != 0) && archive.ProxyLongEdge != ProxyPolicy.Disabled)
requests.Add(ArchiveJobs.Proxies([sequence.Id], label)); requests.Add(ArchiveJobs.Proxies([sequence.Id], label));
@@ -21,11 +21,11 @@ internal static class JobArchive
/// <see cref="JobKind.Rebuild"/>. Checkpoint: <c>after:&lt;folder&gt;</c>, the last folder indexed. When anything was /// <see cref="JobKind.Rebuild"/>. Checkpoint: <c>after:&lt;folder&gt;</c>, the last folder indexed. When anything was
/// indexed, the sequences without a current light analysis (adopted folders, new sidecars, photos added to a folder) are /// indexed, the sequences without a current light analysis (adopted folders, new sidecars, photos added to a folder) are
/// queued for it, and for a background deep analysis too when <see cref="ScanParameters.DeepAnalysis"/> asks. On the /// queued for it, and for a background deep analysis too when <see cref="ScanParameters.DeepAnalysis"/> asks. On the
/// server (<paramref name="imagesAfterScan"/>, <see cref="ArchiveServiceOptions.ImagesAfterScan"/>) the sequences it indexed /// server (<paramref name="imagesAfterScan"/>, <see cref="ArchiveServiceOptions.QueuesImagesAfterScan"/>, read at each run) the sequences it indexed
/// without thumbnails or proxies are queued for them too, one pass per sequence as after an upload. Sequences waiting for /// without thumbnails or proxies are queued for them too, one pass per sequence as after an upload. Sequences waiting for
/// their first frame (<see cref="ArchiveIndexer.AwaitingFolderAsync"/>) have nothing to analyse or draw yet and are left out. /// their first frame (<see cref="ArchiveIndexer.AwaitingFolderAsync"/>) have nothing to analyse or draw yet and are left out.
/// </summary> /// </summary>
internal sealed class ScanJobHandler(ChronosDatabase db, ArchiveIndexer indexer, JobKind kind, bool imagesAfterScan = false) : IJobHandler internal sealed class ScanJobHandler(ChronosDatabase db, ArchiveIndexer indexer, JobKind kind, Func<bool>? imagesAfterScan = null) : IJobHandler
{ {
private const string Prefix = "after:"; private const string Prefix = "after:";
@@ -53,7 +53,7 @@ internal sealed class ScanJobHandler(ChronosDatabase db, ArchiveIndexer indexer,
.Where(id => !awaiting.Contains(id)).ToList(); .Where(id => !awaiting.Contains(id)).ToList();
await AnalysisFollowUp.QueueAsync(db, context, unanalysed).ConfigureAwait(false); await AnalysisFollowUp.QueueAsync(db, context, unanalysed).ConfigureAwait(false);
if (kind == JobKind.Scan && parameters.DeepAnalysis) await AnalysisFollowUp.QueueDeepAsync(db, context, unanalysed).ConfigureAwait(false); if (kind == JobKind.Scan && parameters.DeepAnalysis) await AnalysisFollowUp.QueueDeepAsync(db, context, unanalysed).ConfigureAwait(false);
if (imagesAfterScan) if (imagesAfterScan?.Invoke() == true)
{ {
var resumed = resume is not null; var resumed = resume is not null;
await QueueImagesAsync(context, archive, JobKind.Thumbs, SequenceStatus.ThumbsBuilt, summary.Sequences, resumed, awaiting).ConfigureAwait(false); await QueueImagesAsync(context, archive, JobKind.Thumbs, SequenceStatus.ThumbsBuilt, summary.Sequences, resumed, awaiting).ConfigureAwait(false);
@@ -26,6 +26,16 @@ public sealed record ArchiveServiceOptions
/// </summary> /// </summary>
public bool ImagesAfterScan { get; init; } public bool ImagesAfterScan { get; init; }
/// <summary>
/// Whether <see cref="ImagesAfterScan"/> holds now, read at every scan and trash restore (owner review 5, #67): Chronos
/// Desktop makes thumbnails and proxies after its scans while it shares its library, as a server does. Null: the fixed
/// <see cref="ImagesAfterScan"/>.
/// </summary>
public Func<bool>? ImagesAfterScanWhen { get; init; }
/// <summary><see cref="ImagesAfterScanWhen"/> as it is now, else <see cref="ImagesAfterScan"/>.</summary>
public bool QueuesImagesAfterScan => ImagesAfterScanWhen?.Invoke() ?? ImagesAfterScan;
/// <summary> /// <summary>
/// The index may hold settings newer than a sequence's <c>project.json</c>: the server, whose <c>PATCH</c> wrote the /// The index may hold settings newer than a sequence's <c>project.json</c>: the server, whose <c>PATCH</c> wrote the
/// settings a client sent into the index alone before owner review 2 phase 5b. When the projects meet a sequence whose two /// settings a client sent into the index alone before owner review 2 phase 5b. When the projects meet a sequence whose two
+102
View File
@@ -0,0 +1,102 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using Chronos.Core.Diagnostics;
using Chronos.Core.IO;
namespace Chronos.Data.Homes;
/// <summary>What one entry of the sorting of the folders into homes moves (<see cref="HomeLayoutEntry"/>).</summary>
public enum HomeEntryKind
{
/// <summary>A workspace project's folder (<c>&lt;workspace&gt;\&lt;project id&gt;</c>) into its home's store.</summary>
Project,
/// <summary>An entry of the workspace's trash (<c>&lt;workspace&gt;\.trash\&lt;name&gt;</c>) into its home's trash.</summary>
Trash,
/// <summary>A server's proxy cache (<c>&lt;cache&gt;\proxies\&lt;hash&gt;</c>, or one sequence of it) into its home in the cache.</summary>
Proxies,
/// <summary>The render node's downloads (<c>&lt;cache&gt;\render-node</c>) into the home of the server they came from.</summary>
RenderNode,
/// <summary>A card import staged for a server (<c>&lt;cache&gt;\server-import</c>) into that server's home in the cache.</summary>
Import,
}
/// <summary>Why the workspace part of the sorting waits for a later start (the cache part runs all the same).</summary>
public enum HomeLayoutDeferral
{
/// <summary>The workspace folder cannot be reached (an unplugged drive).</summary>
Offline,
/// <summary>A move of the workspace folder is under way or stopped (its journal, or a move job not finished): it is taken up or undone first.</summary>
Moving,
}
/// <summary>
/// One rename of the sorting (<see cref="HomeLayoutMigration"/>): what it is, the folder it is in (<paramref name="Root"/>: the
/// workspace or the cache), the path it leaves and the path it takes (both full, in <paramref name="Root"/>, so on one
/// volume), and the inventory read at planning: files and bytes, and the SHA-256 of their relative names and sizes, which the
/// target must show after the rename. Leases are left out of the inventory.
/// </summary>
/// <param name="ServerKey">The server key of the home it goes to (canonical); null for this PC's home and for a server known only by hash.</param>
/// <param name="ServerName">The server's name as the project's file gives it, for the home's <c>server.json</c>.</param>
public sealed record HomeLayoutEntry(HomeEntryKind Kind, string Root, string Source, string Target, int Files, long Bytes, string Inventory,
string? ServerKey = null, string? ServerName = null);
/// <summary>How far the sorting went.</summary>
public enum HomeLayoutStage
{
/// <summary>Entries are being renamed; the workspace's parent manifest is not split yet.</summary>
Moving,
/// <summary>Every entry was renamed or skipped and the parent manifest names the split layout; only the journal is left to go.</summary>
Committed,
}
/// <summary>
/// The journal of the sorting of the folders into homes (<c>&lt;data&gt;\homes-migration.json</c>,
/// <see cref="HomeLayoutMigration.JournalFile"/>): the plan's fingerprint, its entries in order, the ones done (renamed, found
/// renamed, or skipped because in use), whether it splits the workspace's parent, and the stage. Written whole and
/// atomically before the first rename and after each one, so a sorting stopped at any moment is taken up from it.
/// </summary>
public sealed record HomeLayoutJournal(string Format, int FormatVersion, string Fingerprint, IReadOnlyList<HomeLayoutEntry> Entries, IReadOnlyList<int> Done,
string? WorkspaceRoot, bool SplitsWorkspace, HomeLayoutStage Stage, DateTimeOffset Started)
{
public const string FormatName = "chronos-homes-migration";
public const int CurrentFormatVersion = 1;
/// <summary>The journal at <paramref name="path"/>; null when there is none, or it cannot be read (logged).</summary>
public static HomeLayoutJournal? Read(string path)
{
ArgumentException.ThrowIfNullOrWhiteSpace(path);
if (!File.Exists(path)) return null;
try
{
if (JsonSerializer.Deserialize(AtomicFile.ReadAllText(path), HomeLayoutJson.Default.HomeLayoutJournal) is
{ Format: FormatName, Entries: not null, Done: not null } journal && journal.FormatVersion <= CurrentFormatVersion)
return journal;
Log.Warning("homes", $"{path} is not a journal of the sorting of the folders this Chronos reads");
}
catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)
{
Log.Warning("homes", $"{path} cannot be read", ex);
}
return null;
}
/// <summary>Writes the journal whole to a temporary file and moves it into place.</summary>
public static void Write(string path, HomeLayoutJournal journal)
{
ArgumentException.ThrowIfNullOrWhiteSpace(path);
ArgumentNullException.ThrowIfNull(journal);
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
AtomicFile.WriteAllText(path, JsonSerializer.Serialize(journal, HomeLayoutJson.Default.HomeLayoutJournal));
}
}
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
UseStringEnumConverter = true, WriteIndented = true)]
[JsonSerializable(typeof(HomeLayoutJournal))]
internal sealed partial class HomeLayoutJson : JsonSerializerContext;
@@ -0,0 +1,788 @@
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.IO;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Projects;
using Chronos.Data.Sync;
using Chronos.Data.Workspaces;
namespace Chronos.Data.Homes;
/// <summary>What the sorting of the folders into homes works on (<see cref="HomeLayoutMigration"/>).</summary>
public sealed record HomeLayoutOptions
{
/// <summary>The program's data folder, which holds the journal (<see cref="HomeLayoutMigration.JournalFile"/>).</summary>
public required string DataDirectory { get; init; }
/// <summary>The workspace folder (Settings › Workspace › Folder: the parent of the homes); null leaves the workspace alone.</summary>
public string? WorkspaceRoot { get; init; }
/// <summary>The cache folder (Settings › Storage › Cache folder); null leaves the cache alone.</summary>
public string? CacheRoot { get; init; }
/// <summary>The servers known by id and their aliases: a home is named by its server's canonical key.</summary>
public ServerIdentity Identity { get; init; } = ServerIdentity.None;
/// <summary>
/// The server this PC is signed in to, or was last (its key): the 1.0 render-node downloads and staged server import,
/// shared by every server then, go to its home. Null leaves them where they are (the cache trims them).
/// </summary>
public string? CurrentServer { get; init; }
/// <summary>The index: a workspace move job not finished defers the workspace part, and a re-key moves the server's links. Null skips both.</summary>
public ChronosDatabase? Database { get; init; }
public TimeProvider Time { get; init; } = TimeProvider.System;
}
/// <summary>
/// What the sorting would move, read without writing anything (<see cref="HomeLayoutMigration.PlanAsync"/>): its entries, the
/// workspace projects in use now that wait for a later start, why the workspace part waits (null when it does not), whether it
/// splits the workspace's parent (its manifest goes to format <see cref="WorkspaceHomes.ParentFormatVersion"/>), and a
/// fingerprint of what was read.
/// </summary>
public sealed record HomeLayoutPlan(IReadOnlyList<HomeLayoutEntry> Entries, IReadOnlyList<Guid> InUse, HomeLayoutDeferral? Deferred, bool SplitsWorkspace,
string Fingerprint)
{
/// <summary>Nothing to rename and no manifest to write.</summary>
public bool IsEmpty => Entries.Count == 0 && !SplitsWorkspace;
/// <summary>The workspace projects the sorting moves.</summary>
public int Projects => Entries.Count(e => e.Kind == HomeEntryKind.Project);
/// <summary>The bytes of everything it moves (renamed, never copied).</summary>
public long Bytes => Entries.Sum(e => e.Bytes);
}
/// <summary>What a sorting did: projects and entries moved, projects left where they are (in use), why the workspace waits, whether it was taken up from a journal.</summary>
/// <param name="Clashes">Entries whose target was taken: what lost went to its home's trash (workspace) or stayed where it is (cache); never deleted.</param>
public sealed record HomeLayoutResult(int ProjectsMoved, int EntriesMoved, int InUse, HomeLayoutDeferral? Deferred, bool Resumed, int Clashes, bool Split)
{
public static HomeLayoutResult Nothing { get; } = new(0, 0, 0, null, false, 0, false);
}
/// <summary>What a re-key did (<see cref="HomeLayoutMigration.RekeyAsync"/>).</summary>
/// <param name="HomesMoved">Home folders renamed whole to the id's (workspace and cache).</param>
/// <param name="ProjectsMoved">Projects moved one by one into the id's home (the same server reached at two addresses).</param>
/// <param name="ProjectsTrashed">Copies of one project in both homes whose older one went to the trash of the id's home.</param>
/// <param name="BundlesRewritten">Working states whose home now names the id key.</param>
/// <param name="BundlesInUse">Working states held by a writer: left naming an alias, which matches all the same.</param>
public sealed record HomeRekeyResult(int HomesMoved, int ProjectsMoved, int ProjectsTrashed, int BundlesRewritten, int BundlesInUse, int LinksMoved, int LinksDropped);
/// <summary>A rename of the sorting did not leave the folder as planned: it stopped there, its journal kept, and nothing was deleted.</summary>
public sealed class HomeLayoutException(string message, Exception? inner = null) : IOException(message, inner);
/// <summary>
/// The one-time sorting of the desktop's folders into homes (owner review 5, #66), run at the start of 1.1 before the job
/// engine runs, and the re-key of a server's home when it first announces its id.
/// <para>
/// <b>Plan</b> (<see cref="PlanAsync"/>, a dry run): each workspace project folder of the 1.0 layout goes to the store of its
/// home (<see cref="WorkspaceHomes.RootFor"/>: <c>local</c>, or <c>servers\&lt;folder&gt;</c> of its server), one whose working
/// state cannot be read to <c>local</c> (it still lists and opens as damaged); each trash entry goes to its project's home's
/// trash; the 1.0 proxy cache <c>&lt;cache&gt;\proxies\&lt;hash&gt;</c> goes to <c>&lt;cache&gt;\servers\&lt;folder&gt;\proxies</c>
/// (the folder of a known server's id when the hash is one of its aliases', else <c>addr-&lt;hash&gt;</c>, the same hash), and
/// the shared <c>render-node</c> and <c>server-import</c> to the current server's home. A project in use (a live lease) is
/// left for a later start. A workspace folder out of reach, or one being moved, defers the workspace part; the cache part runs.
/// </para>
/// <para>
/// <b>Apply</b> (<see cref="ApplyAsync"/>): the journal is written first and after every rename; every move is a rename inside
/// the folder it is in (so on one volume, no byte copied, nothing half-copied), checked by inventory (the same relative names
/// and sizes at the target, the source gone), which is enough where no byte is rewritten (the rule <see cref="WorkspaceMover"/>
/// uses on one volume). A rename that does not check stops the sorting with its journal; the next start takes it up. A
/// target already taken is a clash: in the workspace the older working state goes to the home's trash, in the cache the
/// entry stays where it is; nothing is deleted. Writing the split parent manifest is the last step: it commits the layout.
/// Running again on sorted folders does nothing.
/// </para>
/// </summary>
public sealed class HomeLayoutMigration
{
/// <summary>The journal of a sorting under way, in the data folder (only while one is unfinished).</summary>
public const string JournalFile = "homes-migration.json";
/// <summary>The 1.0 folder of the proxy cache in the cache folder.</summary>
public const string LegacyProxies = "proxies";
/// <summary>The 1.0 folder of the render node's downloads in the cache folder.</summary>
public const string LegacyRenderNode = "render-node";
/// <summary>The 1.0 folder of card imports staged for a server in the cache folder.</summary>
public const string LegacyServerImport = "server-import";
private const string TrashFolder = WorkspaceTrash.FolderName;
private readonly HomeLayoutOptions _options;
public HomeLayoutMigration(HomeLayoutOptions options)
{
ArgumentNullException.ThrowIfNull(options);
ArgumentException.ThrowIfNullOrWhiteSpace(options.DataDirectory);
_options = options;
}
/// <summary>The journal's path.</summary>
public string JournalPath => Path.Combine(_options.DataDirectory, JournalFile);
/// <summary>
/// Called at named steps with the path concerned (tests: a crash): <c>journal</c> (the journal first written), <c>rename</c>
/// (an entry about to be renamed), <c>renamed</c> (an entry renamed, its journal not written yet), <c>commit</c> (the parent
/// manifest about to be written).
/// </summary>
internal Action<string, string>? Cut { get; init; }
private DateTimeOffset Now => _options.Time.GetUtcNow();
// ---------------- Plan ----------------
/// <summary>What the sorting would move now (<see cref="HomeLayoutPlan"/>); nothing is written.</summary>
/// <exception cref="IOException">A folder cannot be read.</exception>
public async Task<HomeLayoutPlan> PlanAsync(CancellationToken cancellationToken = default)
{
var entries = new List<HomeLayoutEntry>();
var inUse = new List<Guid>();
HomeLayoutDeferral? deferred = null;
var splits = false;
if (_options.WorkspaceRoot is { Length: > 0 } configured)
{
var root = WorkspaceStore.FullRoot(configured);
if (!Directory.Exists(root))
{
// Never made yet (the workspace opens split), or on a drive that is not there.
if (!Reachable(root)) deferred = HomeLayoutDeferral.Offline;
}
else if (WorkspaceMover.HasJournal(root) || await MovePendingAsync(cancellationToken).ConfigureAwait(false))
{
deferred = HomeLayoutDeferral.Moving;
}
else
{
splits = !WorkspaceHomes.IsSplitRoot(root);
PlanWorkspace(root, entries, inUse, cancellationToken);
}
}
if (_options.CacheRoot is { Length: > 0 } cache && Directory.Exists(cache)) PlanCache(Path.GetFullPath(cache), entries, cancellationToken);
var fingerprint = new StringBuilder();
foreach (var entry in entries)
fingerprint.Append(CultureInfo.InvariantCulture, $"{entry.Kind}|{entry.Source}|{entry.Target}|{entry.Files}|{entry.Bytes}|{entry.Inventory}\n");
if (splits) fingerprint.Append("split\n");
var plan = new HomeLayoutPlan(entries, inUse, deferred, splits, Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(fingerprint.ToString()))));
if (!plan.IsEmpty || inUse.Count > 0 || deferred is not null)
{
Log.Info("homes", $"Sorting the folders into homes: {plan.Projects} project(s), {entries.Count} entr(ies), {plan.Bytes} bytes"
+ (splits ? ", the workspace split" : string.Empty) + (inUse.Count > 0 ? $", {inUse.Count} project(s) in use" : string.Empty)
+ (deferred is { } why ? $", the workspace deferred ({why})" : string.Empty));
foreach (var entry in entries) Log.Info("homes", $" {entry.Kind}: {entry.Source} -> {entry.Target} ({entry.Files} files, {entry.Bytes} bytes)");
}
return plan;
}
private void PlanWorkspace(string root, List<HomeLayoutEntry> entries, List<Guid> inUse, CancellationToken cancellationToken)
{
var homes = new Dictionary<Guid, (string Partition, string? Key, string? Name)>();
foreach (var directory in Directory.EnumerateDirectories(root).Order(StringComparer.Ordinal))
{
cancellationToken.ThrowIfCancellationRequested();
if (!Guid.TryParseExact(Path.GetFileName(directory), "N", out var id) || !File.Exists(Path.Combine(directory, WorkspaceProject.BundleFile))) continue;
if (Leased(directory))
{
inUse.Add(id);
continue;
}
var (partition, key, name) = PartitionOf(root, Path.Combine(directory, WorkspaceProject.BundleFile), id);
homes[id] = (partition, key, name);
var (files, bytes, inventory) = Inventory(directory);
entries.Add(new HomeLayoutEntry(HomeEntryKind.Project, root, directory, Path.Combine(partition, id.ToString("N")), files, bytes, inventory, key, name));
}
var trash = Path.Combine(root, TrashFolder);
if (!Directory.Exists(trash)) return;
foreach (var entry in new DirectoryInfo(trash).EnumerateFileSystemInfos().OrderBy(e => e.Name, StringComparer.Ordinal))
{
cancellationToken.ThrowIfCancellationRequested();
var partition = HomeFolders.LocalPath(root);
string? key = null;
string? name = null;
var named = TrashProject(entry.Name);
if (named is { } projectId && homes.TryGetValue(projectId, out var home)) (partition, key, name) = home;
else if (entry is DirectoryInfo && File.Exists(Path.Combine(entry.FullName, WorkspaceProject.BundleFile)))
(partition, key, name) = PartitionOf(root, Path.Combine(entry.FullName, WorkspaceProject.BundleFile), named);
var (files, bytes, inventory) = entry is DirectoryInfo ? Inventory(entry.FullName) : FileInventory(entry.FullName);
entries.Add(new HomeLayoutEntry(HomeEntryKind.Trash, root, entry.FullName, Path.Combine(partition, TrashFolder, entry.Name), files, bytes, inventory, key, name));
}
}
/// <summary>The store a working state's home belongs in, its server's canonical key and name; <c>local</c> when it cannot be read.</summary>
private (string Partition, string? Key, string? Name) PartitionOf(string root, string bundlePath, Guid? projectId)
{
try
{
var bundle = ProjectBundle.Load(bundlePath);
if (bundle.Workspace is { } workspace && (projectId is null || workspace.ProjectId == projectId)
&& workspace.Home is { Kind: BundleHome.ServerKind, Server: { Length: > 0 } server })
{
var key = _options.Identity.Canonical(server);
return (Path.Combine(root, HomeFolders.Servers, HomeFolders.ServerFolder(key)), key, bundle.Archive.Name);
}
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException or System.Text.Json.JsonException)
{
Log.Info("homes", $"{bundlePath} cannot be read: it goes to this PC's home ({ex.Message})");
}
return (HomeFolders.LocalPath(root), null, null);
}
/// <summary>The project a trash entry was set aside from (<c>&lt;id&gt;-&lt;ticks&gt;</c>, also while staged as <c>.incoming-…</c>).</summary>
private static Guid? TrashProject(string name)
{
var text = name.StartsWith(".incoming-", StringComparison.Ordinal) ? name[".incoming-".Length..] : name;
return text.Length >= 32 && Guid.TryParseExact(text.AsSpan(0, 32), "N", out var id) ? id : null;
}
private void PlanCache(string cache, List<HomeLayoutEntry> entries, CancellationToken cancellationToken)
{
var servers = Path.Combine(cache, HomeFolders.Servers);
var proxies = Path.Combine(cache, LegacyProxies);
if (Directory.Exists(proxies))
{
foreach (var directory in Directory.EnumerateDirectories(proxies).Order(StringComparer.Ordinal))
{
cancellationToken.ThrowIfCancellationRequested();
var hash = Path.GetFileName(directory);
if (hash.Length != HomeFolders.HashLength || !hash.All(Uri.IsHexDigit)) continue;
var key = _options.Identity.Servers.SelectMany(s => s.Aliases).FirstOrDefault(a => HomeFolders.AddressHash(a) == hash.ToLowerInvariant());
var folder = key is not null ? _options.Identity.FolderName(key) : HomeFolders.AddressPrefix + hash.ToLowerInvariant();
var target = Path.Combine(servers, folder, HomeFolders.Proxies);
AddCache(HomeEntryKind.Proxies, cache, directory, target, entries, key is null ? null : _options.Identity.Canonical(key));
}
}
if (_options.CurrentServer is not { Length: > 0 } current) return;
var home = Path.Combine(servers, _options.Identity.FolderName(current));
var key2 = _options.Identity.Canonical(current);
var renderNode = Path.Combine(cache, LegacyRenderNode);
if (Directory.Exists(renderNode)) AddCache(HomeEntryKind.RenderNode, cache, renderNode, Path.Combine(home, HomeFolders.RenderNode), entries, key2);
var import = Path.Combine(cache, LegacyServerImport);
if (Directory.Exists(import)) AddCache(HomeEntryKind.Import, cache, import, Path.Combine(home, HomeFolders.Import), entries, key2);
}
/// <summary>
/// A cache folder renamed whole into its home, or, where the home already has one, each of its entries the home lacks (an
/// entry the home has stays where it is: the cache can be made again).
/// </summary>
private static void AddCache(HomeEntryKind kind, string cache, string source, string target, List<HomeLayoutEntry> entries, string? key)
{
if (!Directory.Exists(target))
{
var (files, bytes, inventory) = Inventory(source);
entries.Add(new HomeLayoutEntry(kind, cache, source, target, files, bytes, inventory, key));
return;
}
foreach (var child in new DirectoryInfo(source).EnumerateFileSystemInfos().OrderBy(e => e.Name, StringComparer.Ordinal))
{
var into = Path.Combine(target, child.Name);
if (Directory.Exists(into) || File.Exists(into))
{
Log.Info("homes", $"{child.FullName} stays where it is: {into} is there already");
continue;
}
var (files, bytes, inventory) = child is DirectoryInfo ? Inventory(child.FullName) : FileInventory(child.FullName);
entries.Add(new HomeLayoutEntry(kind, cache, child.FullName, into, files, bytes, inventory, key));
}
}
// ---------------- Apply ----------------
/// <summary>
/// Sorts the folders, or takes up the sorting its journal records (see the class). Projects in use and a workspace that
/// waits are left for a later start; a rename that does not check stops the run with its journal kept.
/// </summary>
/// <exception cref="HomeLayoutException">A rename did not leave the folder as planned; the journal stays for the next start.</exception>
/// <exception cref="IOException">A folder could not be read or renamed; the journal stays for the next start.</exception>
public async Task<HomeLayoutResult> ApplyAsync(CancellationToken cancellationToken = default)
{
var journal = HomeLayoutJournal.Read(JournalPath);
var resumed = journal is not null;
var inUse = 0;
HomeLayoutDeferral? deferred = null;
if (journal is null)
{
if (File.Exists(JournalPath)) throw new HomeLayoutException($"{JournalPath} cannot be read; the folders are left as they are.");
var plan = await PlanAsync(cancellationToken).ConfigureAwait(false);
inUse = plan.InUse.Count;
deferred = plan.Deferred;
if (plan.IsEmpty) return HomeLayoutResult.Nothing with { InUse = inUse, Deferred = deferred };
journal = new HomeLayoutJournal(HomeLayoutJournal.FormatName, HomeLayoutJournal.CurrentFormatVersion, plan.Fingerprint, plan.Entries, [],
_options.WorkspaceRoot is { Length: > 0 } root ? WorkspaceStore.FullRoot(root) : null, plan.SplitsWorkspace, HomeLayoutStage.Moving, Now);
HomeLayoutJournal.Write(JournalPath, journal);
Cut?.Invoke("journal", JournalPath);
}
else
{
Log.Info("homes", $"The sorting of the folders into homes is taken up from {JournalPath} ({journal.Done.Count} of {journal.Entries.Count} done, {journal.Stage})");
}
var (projects, moved, clashes) = (0, 0, 0);
var waiting = false;
if (journal.Stage == HomeLayoutStage.Moving)
{
var done = journal.Done.ToHashSet();
for (var i = 0; i < journal.Entries.Count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
if (done.Contains(i)) continue;
var entry = journal.Entries[i];
if (!Directory.Exists(entry.Root))
{
// The workspace's drive went since the plan: this entry waits, with the journal, for a start that reaches it.
waiting = true;
if (entry.Root == journal.WorkspaceRoot) deferred = HomeLayoutDeferral.Offline;
continue;
}
switch (Move(entry))
{
case Outcome.Moved:
moved++;
if (entry.Kind == HomeEntryKind.Project) projects++;
break;
case Outcome.Clash:
moved++;
clashes++;
if (entry.Kind == HomeEntryKind.Project) projects++;
break;
case Outcome.InUse:
inUse++;
break;
}
done.Add(i);
journal = journal with { Done = [.. done.Order()] };
HomeLayoutJournal.Write(JournalPath, journal);
}
if (waiting)
{
Log.Info("homes", $"The sorting of the folders waits for a folder out of reach; {JournalPath} stays for the next start");
return new HomeLayoutResult(projects, moved, inUse, deferred ?? HomeLayoutDeferral.Offline, resumed, clashes, false);
}
if (journal.WorkspaceRoot is { } workspace)
{
if (journal.SplitsWorkspace)
{
Cut?.Invoke("commit", workspace);
Commit(workspace, journal);
}
TryDeleteEmpty(Path.Combine(workspace, TrashFolder));
}
journal = journal with { Stage = HomeLayoutStage.Committed };
HomeLayoutJournal.Write(JournalPath, journal);
}
File.Delete(JournalPath);
Log.Info("homes", $"The folders are sorted into homes: {projects} project(s) and {moved} entr(ies) moved"
+ (clashes > 0 ? $", {clashes} clash(es) kept in the trash or left in place" : string.Empty)
+ (inUse > 0 ? $", {inUse} project(s) in use left for a later start" : string.Empty));
return new HomeLayoutResult(projects, moved, inUse, deferred, resumed, clashes, journal.SplitsWorkspace);
}
private enum Outcome
{
Moved,
AlreadyMoved,
Clash,
InUse,
}
/// <summary>One entry renamed and checked (see the class).</summary>
private Outcome Move(HomeLayoutEntry entry)
{
if (!Exists(entry.Source))
{
// A run that stopped after the rename: the target holds it.
if (Exists(entry.Target))
{
if (EntryInventory(entry.Target).Inventory != entry.Inventory)
Log.Warning("homes", $"{entry.Target} is not as {entry.Source} was planned; it is taken as moved");
return Outcome.AlreadyMoved;
}
Log.Warning("homes", $"{entry.Source} is neither there nor at {entry.Target}");
return Outcome.AlreadyMoved;
}
if (entry.Kind == HomeEntryKind.Project && Leased(entry.Source))
{
Log.Info("homes", $"{entry.Source} is in use: it stays where it is and moves at a later start");
return Outcome.InUse;
}
var outcome = Outcome.Moved;
if (Exists(entry.Target))
{
if (!IsWorkspaceEntry(entry))
{
Log.Info("homes", $"{entry.Source} stays where it is: {entry.Target} is there already");
return Outcome.Clash;
}
outcome = Outcome.Clash;
if (!ResolveClash(entry)) return Outcome.Clash;
}
Prepare(entry);
Cut?.Invoke("rename", entry.Source);
try
{
if (Directory.Exists(entry.Source)) Directory.Move(entry.Source, entry.Target);
else File.Move(entry.Source, entry.Target);
}
catch (Exception ex) when (entry.Kind == HomeEntryKind.Project && ex is IOException or UnauthorizedAccessException)
{
// A file of the project held open (another Chronos on the same workspace): it moves at a later start.
Log.Info("homes", $"{entry.Source} could not be renamed now ({ex.Message}); it moves at a later start");
return Outcome.InUse;
}
Cut?.Invoke("renamed", entry.Target);
if (Exists(entry.Source) || EntryInventory(entry.Target).Inventory != entry.Inventory)
throw new HomeLayoutException($"{entry.Source} was renamed to {entry.Target}, which does not hold the files planned; the sorting stops there.");
return outcome;
}
private static bool IsWorkspaceEntry(HomeLayoutEntry entry) => entry.Kind is HomeEntryKind.Project or HomeEntryKind.Trash;
/// <summary>
/// A workspace entry whose target is taken: for a project, the copy whose working state was saved last stays at the target,
/// the other goes to its home's trash (never deleted); for a trash entry, another free name is taken. False when the source
/// itself went to the trash (nothing more to rename).
/// </summary>
private bool ResolveClash(HomeLayoutEntry entry)
{
var partition = entry.Kind == HomeEntryKind.Project ? Path.GetDirectoryName(entry.Target)! : Path.GetDirectoryName(Path.GetDirectoryName(entry.Target))!;
if (entry.Kind == HomeEntryKind.Trash)
{
for (var n = 2; ; n++)
{
var free = entry.Target + "-" + n.ToString(CultureInfo.InvariantCulture);
if (Exists(free)) continue;
Prepare(entry);
if (Directory.Exists(entry.Source)) Directory.Move(entry.Source, free);
else File.Move(entry.Source, free);
Log.Info("homes", $"{entry.Source} went to {free}: {entry.Target} is there already");
return false;
}
}
var id = Guid.ParseExact(Path.GetFileName(entry.Target), "N");
var sourceNewer = Saved(entry.Source) > Saved(entry.Target);
var loser = sourceNewer ? entry.Target : entry.Source;
_ = new WorkspaceStore(partition);
var trash = WorkspaceTrash.NewEntry(partition, id, Now.UtcDateTime);
Directory.CreateDirectory(Path.GetDirectoryName(trash)!);
Directory.Move(loser, trash);
Log.Warning("homes", $"Project {id} is in {entry.Source} and in {entry.Target}: the copy saved last stays, the other went to {trash}");
return sourceNewer;
}
/// <summary>When a project folder's working state was saved (its file's time when it names none); the oldest time when it cannot be read.</summary>
private static DateTimeOffset Saved(string folder)
{
var path = Path.Combine(folder, WorkspaceProject.BundleFile);
try
{
return ProjectBundle.Load(path).Saved;
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException or System.Text.Json.JsonException)
{
return File.Exists(path) ? new DateTimeOffset(File.GetLastWriteTimeUtc(path), TimeSpan.Zero) : DateTimeOffset.MinValue;
}
}
/// <summary>The folder an entry goes into is made: a workspace home's store with its manifest (and a server's record), a cache home's folder.</summary>
private void Prepare(HomeLayoutEntry entry)
{
if (IsWorkspaceEntry(entry))
{
var partition = entry.Kind == HomeEntryKind.Project ? Path.GetDirectoryName(entry.Target)! : Path.GetDirectoryName(Path.GetDirectoryName(entry.Target))!;
_ = new WorkspaceStore(partition);
if (entry.ServerKey is { } key && ServerHomeRecord.Read(partition) is null)
ServerHomeRecord.Write(partition, ServerHomeRecord.Of(key, entry.ServerName, ServerIdentity.IsIdKey(key) ? null : key, null, Now));
}
Directory.CreateDirectory(Path.GetDirectoryName(entry.Target)!);
}
/// <summary>The last step: the workspace's parent manifest names the split layout (its id kept), and this PC's home exists.</summary>
private static void Commit(string workspace, HomeLayoutJournal journal)
{
var path = Path.Combine(workspace, WorkspaceStore.ManifestFile);
var known = WorkspaceStore.TryRead(path);
if (known is { Layout: WorkspaceHomes.HomesLayout }) return;
_ = new WorkspaceStore(HomeFolders.LocalPath(workspace));
var manifest = new WorkspaceManifest(WorkspaceStore.FormatName, WorkspaceHomes.ParentFormatVersion, known?.Id ?? Guid.CreateVersion7(),
known?.Created ?? journal.Started, WorkspaceHomes.HomesLayout);
WorkspaceStore.Write(path, manifest);
Log.Info("homes", $"The workspace {workspace} is split into homes (manifest format {WorkspaceHomes.ParentFormatVersion})");
}
// ---------------- Re-key ----------------
/// <summary>
/// The server <paramref name="serverId"/> announced its id: whatever this PC keeps under its address keys
/// <paramref name="aliases"/> moves to its id (owner review 5, #66). The home folder <c>servers\addr-&lt;hash&gt;</c> of each
/// alias is renamed to <c>servers\&lt;id&gt;</c> in the workspace and in the cache (and the 1.0 proxy folder of the alias
/// with it); where the id's home already has one (the server reached at two addresses), projects move one by one and a
/// project in both keeps the copy saved last, the other going to the id home's trash. Working states whose home names an
/// alias name the id key afterwards, each rewritten under its lease (one in use keeps the alias, which matches all the
/// same); and the server's links move to the id key (<see cref="SyncService.RekeyAsync"/>'s rule). Run before the sync
/// agent starts for the server. Nothing is deleted but a home folder left holding only its manifest and record.
/// </summary>
/// <exception cref="IOException">A folder could not be read or renamed; what was done stays done, and a later re-key goes on.</exception>
public async Task<HomeRekeyResult> RekeyAsync(Guid serverId, IReadOnlyCollection<string> aliases, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(aliases);
if (serverId == Guid.Empty) throw new ArgumentException("A server id is never empty.", nameof(serverId));
var idKey = HomeFolders.IdKey(serverId);
var keys = aliases.Where(a => !string.IsNullOrWhiteSpace(a) && !ServerIdentity.IsIdKey(a)).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
var (homes, projects, trashed, rewritten, held, links, dropped) = (0, 0, 0, 0, 0, 0, 0);
string? workspaceHome = null;
if (_options.WorkspaceRoot is { Length: > 0 } configured && WorkspaceHomes.IsSplitRoot(configured))
{
var root = WorkspaceStore.FullRoot(configured);
workspaceHome = Path.Combine(root, HomeFolders.Servers, serverId.ToString("N"));
foreach (var alias in keys)
{
cancellationToken.ThrowIfCancellationRequested();
var from = Path.Combine(root, HomeFolders.Servers, HomeFolders.ServerFolder(alias));
if (!Directory.Exists(from)) continue;
if (!Directory.Exists(workspaceHome) && !Directory.EnumerateDirectories(from).Any(Leased))
{
RenameChecked(from, workspaceHome);
homes++;
continue;
}
var (merged, lost) = MergeWorkspaceHome(from, workspaceHome, serverId);
(projects, trashed) = (projects + merged, trashed + lost);
}
if (Directory.Exists(workspaceHome))
{
var (done, busy) = await RewriteBundlesAsync(workspaceHome, keys, idKey, cancellationToken).ConfigureAwait(false);
(rewritten, held) = (done, busy);
var known = ServerHomeRecord.Read(workspaceHome);
ServerHomeRecord.Write(workspaceHome, (known ?? ServerHomeRecord.Of(idKey, null, keys.FirstOrDefault(), null, Now)) with
{
Key = idKey,
Id = serverId,
Address = known?.Address is { } address && !ServerIdentity.IsIdKey(address) ? address : keys.FirstOrDefault(),
LastSeen = Now,
});
}
}
if (_options.CacheRoot is { Length: > 0 } cacheRoot && Directory.Exists(cacheRoot))
{
var cache = Path.GetFullPath(cacheRoot);
var target = Path.Combine(cache, HomeFolders.Servers, serverId.ToString("N"));
foreach (var alias in keys)
{
cancellationToken.ThrowIfCancellationRequested();
var from = Path.Combine(cache, HomeFolders.Servers, HomeFolders.ServerFolder(alias));
if (Directory.Exists(from))
{
if (!Directory.Exists(target))
{
RenameChecked(from, target);
homes++;
}
else
{
foreach (var area in new DirectoryInfo(from).EnumerateDirectories()) MergeCache(area.FullName, Path.Combine(target, area.Name));
}
}
var legacy = Path.Combine(cache, LegacyProxies, HomeFolders.AddressHash(alias));
if (Directory.Exists(legacy)) MergeCache(legacy, Path.Combine(target, HomeFolders.Proxies));
}
}
if (_options.Database is { } db)
{
var store = new SyncLinkStore(db);
foreach (var alias in keys)
{
var (m, d) = await store.RekeyAsync(alias, idKey, cancellationToken).ConfigureAwait(false);
(links, dropped) = (links + m, dropped + d);
}
}
var result = new HomeRekeyResult(homes, projects, trashed, rewritten, held, links, dropped);
Log.Info("homes", $"Server {serverId} re-keyed from {string.Join(", ", keys)}: {result}");
return result;
}
/// <summary>The projects and trash of the alias home <paramref name="from"/> moved into the id home <paramref name="into"/> (see <see cref="RekeyAsync"/>).</summary>
private (int Moved, int Trashed) MergeWorkspaceHome(string from, string into, Guid serverId)
{
var (moved, trashed) = (0, 0);
_ = new WorkspaceStore(into);
foreach (var directory in Directory.EnumerateDirectories(from).Order(StringComparer.Ordinal))
{
if (!Guid.TryParseExact(Path.GetFileName(directory), "N", out var id)) continue;
if (Leased(directory))
{
Log.Info("homes", $"{directory} is in use: it stays in the home of an address of server {serverId} and moves at a later re-key");
continue;
}
var target = Path.Combine(into, id.ToString("N"));
if (Directory.Exists(target))
{
var sourceNewer = Saved(directory) > Saved(target);
var loser = sourceNewer ? target : directory;
var trash = WorkspaceTrash.NewEntry(into, id, Now.UtcDateTime);
Directory.CreateDirectory(Path.GetDirectoryName(trash)!);
RenameChecked(loser, trash);
trashed++;
Log.Warning("homes", $"Project {id} is in {directory} and in {target}: the copy saved last stays, the other went to {trash}");
if (!sourceNewer) continue;
}
RenameChecked(directory, target);
moved++;
}
var trashFrom = Path.Combine(from, TrashFolder);
if (Directory.Exists(trashFrom))
{
var trashInto = Path.Combine(into, TrashFolder);
Directory.CreateDirectory(trashInto);
foreach (var entry in new DirectoryInfo(trashFrom).EnumerateFileSystemInfos().OrderBy(e => e.Name, StringComparer.Ordinal))
{
var target = Path.Combine(trashInto, entry.Name);
for (var n = 2; Exists(target); n++) target = Path.Combine(trashInto, entry.Name + "-" + n.ToString(CultureInfo.InvariantCulture));
RenameChecked(entry.FullName, target);
}
TryDeleteEmpty(trashFrom);
}
// Left with its manifest and record only: Chronos's own description of a folder that holds nothing now.
var left = Directory.EnumerateFileSystemEntries(from).Select(Path.GetFileName).ToList();
if (left.All(n => n is WorkspaceStore.ManifestFile or HomeFolders.ServerFile))
{
foreach (var name in left) File.Delete(Path.Combine(from, name!));
TryDeleteEmpty(from);
}
return (moved, trashed);
}
/// <summary>Each working state in <paramref name="home"/> whose home names an alias rewritten to name <paramref name="idKey"/>, under its lease.</summary>
private static async Task<(int Rewritten, int InUse)> RewriteBundlesAsync(string home, IReadOnlyList<string> aliases, string idKey, CancellationToken cancellationToken)
{
var (rewritten, inUse) = (0, 0);
var store = new WorkspaceStore(home);
foreach (var project in store.List())
{
cancellationToken.ThrowIfCancellationRequested();
ProjectBundle bundle;
try
{
bundle = project.ReadBundle();
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
Log.Info("homes", $"The project in {project.Folder} cannot be read: its home stays as it is ({ex.Message})");
continue;
}
if (bundle.Workspace is not { Home: { Kind: BundleHome.ServerKind, Server: { } server } } || !aliases.Contains(server, StringComparer.OrdinalIgnoreCase))
continue;
IDisposable lease;
try
{
lease = await project.LockAsync(TimeSpan.Zero, cancellationToken).ConfigureAwait(false);
}
catch (LeaseUnavailableException)
{
inUse++;
continue;
}
using (lease)
{
bundle = project.ReadBundle();
if (bundle.Workspace is not { Home: { Server: { } now } } current || !aliases.Contains(now, StringComparer.OrdinalIgnoreCase)) continue;
var archive = bundle.Archive.Id == ServerProjectHome.ArchiveIdOf(now) ? bundle.Archive with { Id = ServerProjectHome.ArchiveIdOf(idKey) } : bundle.Archive;
project.WriteBundle(bundle with { Archive = archive, Workspace = current with { Home = current.Home with { Server = idKey } } });
rewritten++;
}
}
return (rewritten, inUse);
}
/// <summary>A cache folder's entries moved into <paramref name="into"/> where it lacks them; the source renamed whole when <paramref name="into"/> is not there. What is left stays (the cache trims it).</summary>
private static void MergeCache(string from, string into)
{
if (!Directory.Exists(into))
{
Directory.CreateDirectory(Path.GetDirectoryName(into)!);
RenameChecked(from, into);
return;
}
foreach (var entry in new DirectoryInfo(from).EnumerateFileSystemInfos())
{
var target = Path.Combine(into, entry.Name);
if (Exists(target)) continue;
RenameChecked(entry.FullName, target);
}
TryDeleteEmpty(from);
}
/// <summary>A folder or file renamed, checked by inventory: the same relative names and sizes at the target, the source gone.</summary>
private static void RenameChecked(string source, string target)
{
var directory = Directory.Exists(source);
var before = directory ? Inventory(source).Inventory : FileInventory(source).Inventory;
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
if (directory) Directory.Move(source, target);
else File.Move(source, target);
var after = directory ? Inventory(target).Inventory : FileInventory(target).Inventory;
if (Exists(source) || after != before) throw new HomeLayoutException($"{source} was renamed to {target}, which does not hold the same files.");
}
// ---------------- Helpers ----------------
/// <summary>A workspace move job is waiting, running or stopped (null database: none known).</summary>
private async Task<bool> MovePendingAsync(CancellationToken cancellationToken) =>
_options.Database is { } db && await db.Jobs.HasPendingAsync([JobKind.WorkspaceMove], null, cancellationToken).ConfigureAwait(false);
/// <summary>The folder's volume is there (so a folder missing on it was never made, rather than out of reach).</summary>
private static bool Reachable(string folder)
{
for (var current = Path.GetDirectoryName(folder); !string.IsNullOrEmpty(current); current = Path.GetDirectoryName(current))
{
if (Directory.Exists(current)) return true;
}
return false;
}
/// <summary>The project folder's lease is held now (another Chronos, with another data folder, works on the same workspace).</summary>
private bool Leased(string folder) =>
LeaseFile.Read(Path.Combine(folder, WorkspaceProject.LeaseFileName)) is { } held && held.Expires > Now;
private static bool Exists(string path) => Directory.Exists(path) || File.Exists(path);
/// <summary>The inventory of an entry at <paramref name="path"/>: a folder's, or a single file's (a trash entry that is one).</summary>
private static (int Files, long Bytes, string Inventory) EntryInventory(string path) => File.Exists(path) ? FileInventory(path) : Inventory(path);
/// <summary>A folder's files (leases left out): their count and bytes, and the SHA-256 of their relative names and sizes in ordinal order.</summary>
internal static (int Files, long Bytes, string Inventory) Inventory(string folder)
{
var lines = new List<string>();
var bytes = 0L;
foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*", SearchOption.AllDirectories))
{
if (WorkspaceProject.IsLeaseFile(file.Name)) continue;
bytes += file.Length;
lines.Add(Path.GetRelativePath(folder, file.FullName).Replace('\\', '/') + "|" + file.Length.ToString(CultureInfo.InvariantCulture));
}
lines.Sort(StringComparer.Ordinal);
return (lines.Count, bytes, Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(string.Join('\n', lines)))));
}
private static (int Files, long Bytes, string Inventory) FileInventory(string file)
{
var length = new FileInfo(file).Length;
return (1, length, Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes("|" + length.ToString(CultureInfo.InvariantCulture)))));
}
private static void TryDeleteEmpty(string folder)
{
try
{
if (Directory.Exists(folder) && !Directory.EnumerateFileSystemEntries(folder).Any()) Directory.Delete(folder);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Debug("homes", $"{folder} stays: {ex.Message}");
}
}
}
+17 -2
View File
@@ -28,12 +28,16 @@ public sealed class ServerProjectHome : IProjectHome
/// <param name="serverName">The server's name as its <c>server/info</c> gives it, for the project file; the address's host when null.</param> /// <param name="serverName">The server's name as its <c>server/info</c> gives it, for the project file; the address's host when null.</param>
/// <param name="settingsFormat">The settings format its <c>server/info</c> announces (<see cref="ServerInfo.SettingsFormat"/>); null, an older server's 1.</param> /// <param name="settingsFormat">The settings format its <c>server/info</c> announces (<see cref="ServerInfo.SettingsFormat"/>); null, an older server's 1.</param>
public ServerProjectHome(ChronosClient client, Guid sequenceId, string? serverName = null, int? settingsFormat = null) /// <param name="server">
/// The key workspace projects name the server by (<see cref="ServerIdentity.Key(Guid?, Uri)"/>: its id key once it
/// announced one, owner review 5); null takes the client's address key (<see cref="SyncService.ServerKey"/>).
/// </param>
public ServerProjectHome(ChronosClient client, Guid sequenceId, string? serverName = null, int? settingsFormat = null, string? server = null)
{ {
ArgumentNullException.ThrowIfNull(client); ArgumentNullException.ThrowIfNull(client);
Client = client; Client = client;
SequenceId = sequenceId; SequenceId = sequenceId;
Server = SyncService.ServerKey(client.BaseAddress); Server = string.IsNullOrWhiteSpace(server) ? SyncService.ServerKey(client.BaseAddress) : server;
ServerName = string.IsNullOrWhiteSpace(serverName) ? client.BaseAddress.Host : serverName.Trim(); ServerName = string.IsNullOrWhiteSpace(serverName) ? client.BaseAddress.Host : serverName.Trim();
SettingsFormat = settingsFormat is > 0 and var format ? format : ProjectSettings.BaseVersion; SettingsFormat = settingsFormat is > 0 and var format ? format : ProjectSettings.BaseVersion;
} }
@@ -80,6 +84,17 @@ public sealed class ServerProjectHome : IProjectHome
return new Guid(hash.AsSpan(0, 16), bigEndian: true); return new Guid(hash.AsSpan(0, 16), bigEndian: true);
} }
/// <summary>
/// <paramref name="archiveId"/> is the archive id a project file of a sequence of the server <paramref name="keys"/> name
/// carries (<see cref="ArchiveIdOf"/> of any of them: its id key, or an address key it was reached under before it
/// announced its id, owner review 5).
/// </summary>
public static bool IsArchiveIdOf(Guid archiveId, IEnumerable<string> keys)
{
ArgumentNullException.ThrowIfNull(keys);
return keys.Any(key => !string.IsNullOrWhiteSpace(key) && ArchiveIdOf(key) == archiveId);
}
public Task<IReadOnlyList<SequenceProject>> ListAsync(CancellationToken cancellationToken) => public Task<IReadOnlyList<SequenceProject>> ListAsync(CancellationToken cancellationToken) =>
Reach<IReadOnlyList<SequenceProject>>(async () => Reach<IReadOnlyList<SequenceProject>>(async () =>
[.. (await Client.ListProjectsAsync(SequenceId, cancellationToken).ConfigureAwait(false)).Select(ProjectWire.ToProject)], cancellationToken); [.. (await Client.ListProjectsAsync(SequenceId, cancellationToken).ConfigureAwait(false)).Select(ProjectWire.ToProject)], cancellationToken);
+29 -6
View File
@@ -69,11 +69,15 @@ internal sealed record ProxyCacheIndex(SequenceDto Sequence, string? SettingsJso
internal sealed partial class ProxyCacheJson : JsonSerializerContext; internal sealed partial class ProxyCacheJson : JsonSerializerContext;
/// <summary> /// <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 /// Proxies of server sequences on this PC, one folder per sequence with one JPEG per frame (named by frame id, so
/// frame (named by frame id, so renumbering never mixes them up) and <c>remote.json</c>. Everything here can be /// renumbering never mixes them up) and <c>remote.json</c>. With a servers root (owner review 5, #66) a sequence's folder is
/// downloaded again, so the folder lives in the client's cache. /// <c>&lt;servers&gt;/&lt;home folder&gt;/proxies/&lt;sequence id&gt;/</c> (<see cref="HomeFolders.ServerFolder"/> of the
/// server's canonical key); a folder still where an earlier layout put it (<c>&lt;root&gt;/&lt;address hash&gt;/&lt;sequence
/// id&gt;/</c>, 1.0; or the home folder of one of the server's aliases) is used where it is until it is moved, so a sequence
/// always has one folder. Without a servers root the 1.0 layout stays. Everything here can be downloaded again, so the
/// folder lives in the client's cache.
/// </summary> /// </summary>
internal sealed class ProxyCache(string root) internal sealed class ProxyCache(string root, string? servers = null, Func<ServerIdentity>? identity = null)
{ {
/// <summary>The asset kind of a cached proxy (the server's name for it).</summary> /// <summary>The asset kind of a cached proxy (the server's name for it).</summary>
public const string Proxy = "proxy"; public const string Proxy = "proxy";
@@ -83,8 +87,27 @@ internal sealed class ProxyCache(string root)
private const string IndexFile = "remote.json"; private const string IndexFile = "remote.json";
public string Folder(string server, Guid remoteId) => /// <summary>The 1.0 folder of a server sequence's proxies: <c>&lt;root&gt;/&lt;address hash&gt;/&lt;sequence id&gt;</c>.</summary>
Path.Combine(root, Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(server)))[..16], remoteId.ToString("N")); internal static string LegacyFolder(string root, string server, Guid remoteId) =>
Path.Combine(root, Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(server)))[..HomeFolders.HashLength], remoteId.ToString("N"));
/// <summary>The folder of a server sequence's proxies: where it is now, or where a new one goes (see the class).</summary>
public string Folder(string server, Guid remoteId)
{
if (servers is null) return LegacyFolder(root, server, remoteId);
var known = identity?.Invoke() ?? ServerIdentity.None;
var name = remoteId.ToString("N");
var target = Path.Combine(servers, known.FolderName(server), HomeFolders.Proxies, name);
if (Directory.Exists(target)) return target;
foreach (var key in known.KeysOf(server))
{
var home = Path.Combine(servers, HomeFolders.ServerFolder(key), HomeFolders.Proxies, name);
if (Directory.Exists(home)) return home;
var legacy = LegacyFolder(root, key, remoteId);
if (Directory.Exists(legacy)) return legacy;
}
return target;
}
public static string FileName(Guid frameId) => frameId.ToString("N") + ".jpg"; public static string FileName(Guid frameId) => frameId.ToString("N") + ".jpg";
+121
View File
@@ -0,0 +1,121 @@
using Chronos.Core.IO;
using Chronos.Protocol;
namespace Chronos.Data.Sync;
/// <summary>A server known by its stable id, with the address keys it was reached under (<see cref="SyncService.ServerKey"/>).</summary>
/// <param name="Id">The server's id (<see cref="ServerInfo.ServerId"/>).</param>
/// <param name="Aliases">The legacy address keys this id was reached under, in any case.</param>
public sealed record KnownServerKey(Guid Id, IReadOnlyCollection<string> Aliases);
/// <summary>
/// How the desktop names a server (owner review 5, #66). A server that announces its stable id
/// (<see cref="ServerInfo.ServerId"/>) is keyed <c>id:&lt;N&gt;</c> (<see cref="Key(Guid?, Uri)"/>), the same whatever
/// address it is reached by; an older one keeps its address key (<see cref="SyncService.ServerKey"/>, the 1.0 key, here the
/// <see cref="LegacyKey"/>). An instance holds the alias table: the address keys each known id was reached under, which
/// projects, links and jobs made before the id was known still carry. <see cref="Canonical"/> turns an alias into its id
/// key, <see cref="Same"/> compares two keys through it, and <see cref="FolderName"/> is the home's folder
/// (<see cref="HomeFolders.ServerFolder"/>) of the canonical key. Keys compare ignoring case, as address keys always did.
/// </summary>
public sealed class ServerIdentity
{
private readonly Dictionary<string, string> _canonical = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, List<string>> _aliases = new(StringComparer.OrdinalIgnoreCase);
/// <summary>No server known by id: every key is its own.</summary>
public static ServerIdentity None { get; } = new([]);
public ServerIdentity(IEnumerable<KnownServerKey> servers)
{
ArgumentNullException.ThrowIfNull(servers);
var known = new List<KnownServerKey>();
foreach (var server in servers)
{
if (server.Id == Guid.Empty) continue;
var idKey = HomeFolders.IdKey(server.Id);
if (!_aliases.TryGetValue(idKey, out var list))
{
list = [];
_aliases[idKey] = list;
}
foreach (var alias in server.Aliases ?? [])
{
if (string.IsNullOrWhiteSpace(alias) || string.Equals(alias, idKey, StringComparison.OrdinalIgnoreCase)) continue;
// An address that two ids claim (a server replaced at the same address) stays with the first one listed.
if (!_canonical.TryAdd(alias, idKey)) continue;
list.Add(alias);
}
known.Add(server);
}
Servers = known;
}
/// <summary>The servers this table knows, as it was given them.</summary>
public IReadOnlyList<KnownServerKey> Servers { get; }
/// <summary>The key of a server reached at <paramref name="address"/>: its id key when <paramref name="info"/> announces an id, else its address key.</summary>
public static string Key(ServerInfo? info, Uri address) => Key(info?.ServerId, address);
/// <summary>The key of a server reached at <paramref name="address"/>: <c>id:&lt;N&gt;</c> for an id, else its address key.</summary>
public static string Key(Guid? serverId, Uri address)
{
ArgumentNullException.ThrowIfNull(address);
return serverId is { } id && id != Guid.Empty ? HomeFolders.IdKey(id) : LegacyKey(address);
}
/// <summary>The key of a server known by its id.</summary>
public static string IdKey(Guid serverId) => HomeFolders.IdKey(serverId);
/// <summary>The address key (<see cref="SyncService.ServerKey"/>): how 1.0 named every server, and how an older server is still named.</summary>
public static string LegacyKey(Uri address) => SyncService.ServerKey(address);
/// <summary>The id of an id key; null for an address key.</summary>
public static Guid? IdOf(string? key) => HomeFolders.IdOfKey(key);
/// <summary>The key names the server by its id.</summary>
public static bool IsIdKey(string? key) => IdOf(key) is not null;
/// <summary>The id key an alias stands for; any other key as it is.</summary>
public string Canonical(string key)
{
ArgumentNullException.ThrowIfNull(key);
if (IdOf(key) is { } id) return HomeFolders.IdKey(id);
return _canonical.TryGetValue(key, out var idKey) ? idKey : key;
}
/// <summary>Both keys name one server: equal ignoring case, or one an alias of the other's id (null equals only null).</summary>
public bool Same(string? a, string? b)
{
if (a is null || b is null) return a is null && b is null;
return string.Equals(Canonical(a), Canonical(b), StringComparison.OrdinalIgnoreCase);
}
/// <summary>Every key that names the server of <paramref name="key"/>: its canonical key first, then its aliases.</summary>
public IReadOnlyList<string> KeysOf(string key)
{
var canonical = Canonical(key);
var keys = new List<string> { canonical };
if (_aliases.TryGetValue(canonical, out var aliases)) keys.AddRange(aliases);
if (!keys.Contains(key, StringComparer.OrdinalIgnoreCase)) keys.Add(key);
return keys;
}
/// <summary>The aliases of a server id (its legacy address keys); empty when none is known.</summary>
public IReadOnlyList<string> AliasesOf(Guid serverId) =>
_aliases.TryGetValue(HomeFolders.IdKey(serverId), out var aliases) ? aliases : [];
/// <summary>The folder of the home of <paramref name="key"/> (<see cref="HomeFolders.ServerFolder"/> of its canonical key).</summary>
public string FolderName(string key) => HomeFolders.ServerFolder(Canonical(key));
/// <summary>This table with <paramref name="alias"/> added to the aliases of <paramref name="serverId"/> (an address it was reached under).</summary>
public ServerIdentity With(Guid serverId, string alias)
{
ArgumentException.ThrowIfNullOrWhiteSpace(alias);
var servers = Servers.ToList();
var index = servers.FindIndex(s => s.Id == serverId);
if (index < 0) servers.Add(new KnownServerKey(serverId, [alias]));
else if (!servers[index].Aliases.Contains(alias, StringComparer.OrdinalIgnoreCase)) servers[index] = servers[index] with { Aliases = [.. servers[index].Aliases, alias] };
else return this;
return new ServerIdentity(servers);
}
}
+47
View File
@@ -43,6 +43,53 @@ internal sealed class SyncLinkStore(ChronosDatabase db)
public Task DeleteAsync(string server, Guid remoteId, CancellationToken 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); _db.ExecuteAsync("DELETE FROM sync_links WHERE server = $1 AND remote_id = $2", [server, remoteId], cancellationToken);
/// <summary>
/// Moves every link of <paramref name="from"/> to <paramref name="to"/> in one transaction (owner review 5, #66: an address
/// key becomes the server's id key). Where <paramref name="to"/> already links the same server sequence, or the same local
/// copy, the row compared last (<see cref="SyncLink.SyncedAt"/>, never compared counting oldest) is kept and the other
/// deleted: link rows are recomputed by the next comparison, so nothing is lost.
/// </summary>
public async Task<(int Moved, int Dropped)> RekeyAsync(string from, string to, CancellationToken cancellationToken)
{
ArgumentException.ThrowIfNullOrWhiteSpace(from);
ArgumentException.ThrowIfNullOrWhiteSpace(to);
if (string.Equals(from, to, StringComparison.Ordinal)) return (0, 0);
return await _db.InTransactionAsync(async session =>
{
var inner = new DbAccess(session);
var old = await inner.ListAsync($"SELECT {Columns} FROM sync_links WHERE server = $1 ORDER BY remote_id", [from], Map, cancellationToken)
.ConfigureAwait(false);
if (old.Count == 0) return (0, 0);
var current = (await inner.ListAsync($"SELECT {Columns} FROM sync_links WHERE server = $1 ORDER BY remote_id", [to], Map, cancellationToken)
.ConfigureAwait(false)).ToList();
var (moved, dropped) = (0, 0);
foreach (var link in old)
{
var clashes = current.Where(c => c.RemoteId == link.RemoteId || (link.LocalId is { } local && c.LocalId == local)).ToList();
if (clashes.Any(c => Newer(c, link)))
{
await inner.ExecuteAsync("DELETE FROM sync_links WHERE server = $1 AND remote_id = $2", [from, link.RemoteId], cancellationToken).ConfigureAwait(false);
dropped++;
continue;
}
foreach (var clash in clashes)
{
await inner.ExecuteAsync("DELETE FROM sync_links WHERE server = $1 AND remote_id = $2", [to, clash.RemoteId], cancellationToken).ConfigureAwait(false);
current.Remove(clash);
dropped++;
}
await inner.ExecuteAsync("UPDATE sync_links SET server = $3 WHERE server = $1 AND remote_id = $2", [from, link.RemoteId, to], cancellationToken)
.ConfigureAwait(false);
current.Add(link with { Server = to });
moved++;
}
return (moved, dropped);
}, cancellationToken).ConfigureAwait(false);
// The row already under the new key stays on a tie: it is the one the signed-in session works with.
static bool Newer(SyncLink kept, SyncLink other) => (kept.SyncedAt ?? DateTimeOffset.MinValue) >= (other.SyncedAt ?? DateTimeOffset.MinValue);
}
/// <summary>Records where a local sequence stands for the Library; touches neither its versions nor its update time.</summary> /// <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) => 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); _db.ExecuteAsync("UPDATE sequences SET sync_state = $2 WHERE id = $1 AND sync_state <> $2", [localId, (int)state], cancellationToken);
+6 -2
View File
@@ -115,7 +115,11 @@ public interface ISyncConnector
} }
/// <summary><see cref="ISyncRemote"/> over a signed-in <see cref="ChronosClient"/>, which it disposes when it owns it.</summary> /// <summary><see cref="ISyncRemote"/> over a signed-in <see cref="ChronosClient"/>, which it disposes when it owns it.</summary>
public sealed class ChronosSyncRemote(ChronosClient client, bool ownsClient) : ISyncRemote /// <param name="server">
/// The key links and homes name the server by (<see cref="ServerIdentity.Key(Guid?, Uri)"/>: its id key once it announced
/// one, owner review 5); null takes the client's address key (<see cref="SyncService.ServerKey"/>).
/// </param>
public sealed class ChronosSyncRemote(ChronosClient client, bool ownsClient, string? server = null) : ISyncRemote
{ {
private const int SequencePage = 500; private const int SequencePage = 500;
private const int FramePage = 1000; private const int FramePage = 1000;
@@ -137,7 +141,7 @@ public sealed class ChronosSyncRemote(ChronosClient client, bool ownsClient) : I
/// <summary>The settings format the server announced, and when it was read (a <see cref="System.Diagnostics.Stopwatch"/> timestamp).</summary> /// <summary>The settings format the server announced, and when it was read (a <see cref="System.Diagnostics.Stopwatch"/> timestamp).</summary>
private sealed record KnownFormat(int Format, long Read); private sealed record KnownFormat(int Format, long Read);
public string Server { get; } = SyncService.ServerKey(client.BaseAddress); public string Server { get; } = string.IsNullOrWhiteSpace(server) ? SyncService.ServerKey(client.BaseAddress) : server;
public async Task<IReadOnlyList<SequenceDto>> ListSequencesAsync(CancellationToken cancellationToken) public async Task<IReadOnlyList<SequenceDto>> ListSequencesAsync(CancellationToken cancellationToken)
{ {
+35 -3
View File
@@ -26,9 +26,23 @@ public sealed record SyncOptions
/// <summary>Decoders, lease owner and lease timing for sidecar and project writes (shared with the archive engine).</summary> /// <summary>Decoders, lease owner and lease timing for sidecar and project writes (shared with the archive engine).</summary>
public ArchiveServiceOptions Archive { get; init; } = new(); public ArchiveServiceOptions Archive { get; init; } = new();
/// <summary>Folder of the proxy cache of server sequences (inside the client's cache).</summary> /// <summary>
/// Folder of the proxy cache of server sequences as 1.0 laid it out (<c>&lt;cache&gt;\proxies\&lt;address hash&gt;</c>):
/// where proxies go without <see cref="ServersDirectory"/>, and where a sequence's proxies are still read from, with it,
/// until they are moved into their server's home.
/// </summary>
public required string ProxyCacheDirectory { get; init; } public required string ProxyCacheDirectory { get; init; }
/// <summary>
/// The servers' homes in the client's cache (<c>&lt;cache&gt;\servers</c>, owner review 5, #66): with it, a server's
/// proxies go to <c>&lt;servers&gt;\&lt;home folder&gt;\proxies\&lt;sequence id&gt;</c>
/// (<see cref="Core.IO.HomeFolders.ServerFolder"/>). Null keeps the 1.0 layout under <see cref="ProxyCacheDirectory"/>.
/// </summary>
public string? ServersDirectory { get; init; }
/// <summary>The alias table the cache finds a server's home by (<see cref="ServerIdentity"/>); null: every key is its own.</summary>
public Func<ServerIdentity>? Identity { get; init; }
/// <summary>Concurrent frame downloads of one job.</summary> /// <summary>Concurrent frame downloads of one job.</summary>
public int Downloads { get; init; } = 4; public int Downloads { get; init; } = 4;
@@ -74,7 +88,7 @@ public sealed class SyncService
Options = options; Options = options;
_links = new SyncLinkStore(db); _links = new SyncLinkStore(db);
_writer = new SequenceWriter(options.Archive); _writer = new SequenceWriter(options.Archive);
Proxies = new ProxyCache(options.ProxyCacheDirectory); Proxies = new ProxyCache(options.ProxyCacheDirectory, options.ServersDirectory, options.Identity);
} }
public SyncOptions Options { get; } public SyncOptions Options { get; }
@@ -90,9 +104,27 @@ public sealed class SyncService
internal ArchiveService Archives { get; } internal ArchiveService Archives { get; }
/// <summary>"https://nas.local:8443": the key links are stored under (scheme, lower-case host, port, path).</summary> /// <summary>
/// "https://nas.local:8443": the address key (scheme, lower-case host, port, path), the key every server had in 1.0 and an
/// older server, which announces no id, still has. A server that announces one is keyed by it
/// (<see cref="ServerIdentity.Key(Guid?, Uri)"/>), its address keys kept as aliases.
/// </summary>
public static string ServerKey(Uri address) => address.GetLeftPart(UriPartial.Path).TrimEnd('/').ToLowerInvariant(); public static string ServerKey(Uri address) => address.GetLeftPart(UriPartial.Path).TrimEnd('/').ToLowerInvariant();
/// <summary>
/// Moves the links of <paramref name="from"/> (an address key the server was reached under) to <paramref name="to"/> (its
/// id key, owner review 5, #66) in one transaction. A link both keys hold for one server sequence, or for one local copy,
/// keeps the row compared last (<see cref="SyncLink.SyncedAt"/>); the other row goes, which loses nothing: the next
/// comparison makes links again. Nothing happens when the keys are the same.
/// </summary>
/// <returns>The links moved, and those dropped for a newer one.</returns>
public async Task<(int Moved, int Dropped)> RekeyAsync(string from, string to, CancellationToken cancellationToken)
{
var result = await _links.RekeyAsync(from, to, cancellationToken).ConfigureAwait(false);
if (result.Moved + result.Dropped > 0) Changed?.Invoke(to);
return result;
}
/// <summary>What an upload or download job moves; null for any other job.</summary> /// <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); public static SyncTransferKind? TransferKind(Job job) => SyncJobParameters.Read(job)?.Kind(job.Kind);
@@ -92,21 +92,39 @@ public sealed class WorkspaceCleaner
{ {
private static readonly JobKind[] ProjectJobs = [JobKind.WorkspaceCopy, JobKind.WorkspaceRender, JobKind.WorkspaceSend]; private static readonly JobKind[] ProjectJobs = [JobKind.WorkspaceCopy, JobKind.WorkspaceRender, JobKind.WorkspaceSend];
private readonly WorkspaceSync _sync; private readonly IReadOnlyList<WorkspaceSync> _syncs;
private readonly ChronosDatabase _db; private readonly ChronosDatabase _db;
private readonly Func<BundleHome, IProjectHome?> _homes; private readonly Func<BundleHome, IProjectHome?> _homes;
/// <param name="homes">The home of a workspace project; null for one this PC cannot reach now.</param> /// <param name="homes">The home of a workspace project; null for one this PC cannot reach now.</param>
public WorkspaceCleaner(WorkspaceSync sync, ChronosDatabase db, Func<BundleHome, IProjectHome?> homes) public WorkspaceCleaner(WorkspaceSync sync, ChronosDatabase db, Func<BundleHome, IProjectHome?> homes)
: this([sync ?? throw new ArgumentNullException(nameof(sync))], db, homes)
{ {
ArgumentNullException.ThrowIfNull(sync); }
/// <summary>
/// The clean-up of a workspace split into homes (owner review 5, <see cref="WorkspaceHomes"/>): one sync per home's store,
/// and one run over all of them, so the size limit counts every home's projects together.
/// </summary>
/// <param name="syncs">The sync of each home's store.</param>
/// <param name="homes">The home of a workspace project; null for one this PC cannot reach now.</param>
public WorkspaceCleaner(IReadOnlyList<WorkspaceSync> syncs, ChronosDatabase db, Func<BundleHome, IProjectHome?> homes)
{
ArgumentNullException.ThrowIfNull(syncs);
ArgumentNullException.ThrowIfNull(db); ArgumentNullException.ThrowIfNull(db);
ArgumentNullException.ThrowIfNull(homes); ArgumentNullException.ThrowIfNull(homes);
_sync = sync; if (syncs.Count == 0 || syncs.Any(s => s is null)) throw new ArgumentException("At least one sync, and none null.", nameof(syncs));
_syncs = syncs;
_db = db; _db = db;
_homes = homes; _homes = homes;
} }
/// <summary>The sync of the store <paramref name="project"/> is in.</summary>
private WorkspaceSync SyncOf(WorkspaceProject project) =>
_syncs.FirstOrDefault(s => ReferenceEquals(s.Store, project.Store))
?? _syncs.FirstOrDefault(s => string.Equals(s.Store.Root, project.Store.Root, StringComparison.OrdinalIgnoreCase))
?? _syncs[0];
/// <summary>How long a project another writer holds is waited for; past it the project is kept (<see cref="WorkspaceKeep.Jobs"/>).</summary> /// <summary>How long a project another writer holds is waited for; past it the project is kept (<see cref="WorkspaceKeep.Jobs"/>).</summary>
public TimeSpan LockWait { get; init; } = TimeSpan.FromSeconds(30); public TimeSpan LockWait { get; init; } = TimeSpan.FromSeconds(30);
@@ -120,7 +138,7 @@ public sealed class WorkspaceCleaner
ArgumentNullException.ThrowIfNull(options); ArgumentNullException.ThrowIfNull(options);
var candidates = new List<Candidate>(); var candidates = new List<Candidate>();
var used = 0L; var used = 0L;
foreach (var project in _sync.Store.List()) foreach (var project in _syncs.SelectMany(s => s.Store.List()))
{ {
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
var candidate = Candidate.Of(project, options); var candidate = Candidate.Of(project, options);
@@ -251,7 +269,7 @@ public sealed class WorkspaceCleaner
WorkspaceStatus status; WorkspaceStatus status;
try try
{ {
status = await _sync.StatusAsync(id, home, cancellationToken).ConfigureAwait(false); status = await SyncOf(project).StatusAsync(id, home, cancellationToken).ConfigureAwait(false);
} }
catch (Exception ex) when (ex is ProjectException or DatabaseException or IOException or InvalidDataException or LeaseUnavailableException) catch (Exception ex) when (ex is ProjectException or DatabaseException or IOException or InvalidDataException or LeaseUnavailableException)
{ {
@@ -288,7 +306,7 @@ public sealed class WorkspaceCleaner
{ {
// Asked again under the lease: the editor may have opened it, a save or a render may have come meanwhile. // Asked again under the lease: the editor may have opened it, a save or a render may have come meanwhile.
if (options.IsOpen(id)) return (WorkspaceKeep.Open, 0, 0); if (options.IsOpen(id)) return (WorkspaceKeep.Open, 0, 0);
var local = await _sync.StatusAsync(id, null, cancellationToken).ConfigureAwait(false); var local = await SyncOf(project).StatusAsync(id, null, cancellationToken).ConfigureAwait(false);
if (local.State != WorkspaceState.InSync) return (WorkspaceKeep.NotInSync, 0, 0); if (local.State != WorkspaceState.InSync) return (WorkspaceKeep.NotInSync, 0, 0);
if (ReadLedger(project) is not { } renders) return (WorkspaceKeep.Unreadable, 0, 0); if (ReadLedger(project) is not { } renders) return (WorkspaceKeep.Unreadable, 0, 0);
if (renders.Unsent.Count > 0) return (WorkspaceKeep.UnsentRenders, 0, 0); if (renders.Unsent.Count > 0) return (WorkspaceKeep.UnsentRenders, 0, 0);
@@ -0,0 +1,293 @@
using System.Text.Json;
using Chronos.Core.Diagnostics;
using Chronos.Core.IO;
using Chronos.Core.Project;
using Chronos.Data.Sync;
namespace Chronos.Data.Workspaces;
/// <summary>
/// What a server home's folder says about its server (<see cref="HomeFolders.ServerFile"/>, owner review 5, #66): the key it
/// is named by, the id, the name and last address it was reached at, its TLS fingerprint and when it was first and last seen.
/// Someone browsing the folders, or a workspace moved to another PC, knows from it what the folder is.
/// </summary>
public sealed record ServerHomeRecord(string Format, int FormatVersion, string Key, Guid? Id, string? Name, string? Address, string? TlsFingerprint,
DateTimeOffset FirstSeen, DateTimeOffset LastSeen)
{
public const string FormatName = "chronos-server-home";
public const int CurrentFormatVersion = 1;
/// <summary>A record of <paramref name="key"/> first and last seen <paramref name="now"/>.</summary>
public static ServerHomeRecord Of(string key, string? name, string? address, string? tlsFingerprint, DateTimeOffset now) =>
new(FormatName, CurrentFormatVersion, key, ServerIdentity.IdOf(key), name, address, tlsFingerprint, now, now);
/// <summary>
/// Reads the record in <paramref name="folder"/>; null when there is none or it cannot be read (it only describes the
/// folder: nothing depends on it).
/// </summary>
public static ServerHomeRecord? Read(string folder)
{
ArgumentException.ThrowIfNullOrWhiteSpace(folder);
var path = Path.Combine(folder, HomeFolders.ServerFile);
if (!File.Exists(path)) return null;
try
{
return JsonSerializer.Deserialize(AtomicFile.ReadAllText(path), WorkspaceJson.Default.ServerHomeRecord) is { Format: FormatName, Key.Length: > 0 } record
? record
: null;
}
catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)
{
Log.Debug("workspace", $"{path} cannot be read: {ex.Message}");
return null;
}
}
/// <summary>Writes <paramref name="record"/> into <paramref name="folder"/> (made when it is not there), whole and atomically.</summary>
public static void Write(string folder, ServerHomeRecord record)
{
ArgumentException.ThrowIfNullOrWhiteSpace(folder);
ArgumentNullException.ThrowIfNull(record);
Directory.CreateDirectory(folder);
AtomicFile.WriteAllText(Path.Combine(folder, HomeFolders.ServerFile), JsonSerializer.Serialize(record, WorkspaceJson.Default.ServerHomeRecord));
}
}
/// <summary>One home of a workspace (<see cref="WorkspaceHomes.Homes"/>): its folder and store, and for a server home its key and record.</summary>
/// <param name="Folder">The folder's name: <see cref="HomeFolders.Local"/>, a server folder (<see cref="HomeFolders.ServerFolder"/>), or empty for the projects still in the parent.</param>
/// <param name="ServerKey">The key the server home's folder is named by (from its record, else made from the folder's name); null for this PC's home.</param>
public sealed record WorkspaceHome(string Folder, WorkspaceStore Store, string? ServerKey, ServerHomeRecord? Server)
{
/// <summary>This PC's archive's home.</summary>
public bool IsLocal => Folder == HomeFolders.Local;
/// <summary>Projects 1.0 kept in the parent itself, not moved into their home yet (in use when the folders were sorted).</summary>
public bool IsLegacy => Folder.Length == 0;
}
/// <summary>
/// The desktop's workspace split into one store per home (owner review 5, #66): Settings › Workspace › Folder is the
/// parent, whose <c>workspace.json</c> is of format <see cref="ParentFormatVersion"/> with layout <see cref="HomesLayout"/>
/// (a 1.0 Chronos refuses it as newer, so it never shows the workspace empty), and each home keeps its projects in its own
/// <see cref="WorkspaceStore"/>: <c>&lt;parent&gt;\local</c> for this PC's archive and <c>&lt;parent&gt;\servers\&lt;folder&gt;</c>
/// for each server (<see cref="ServerIdentity.FolderName"/>, with a <see cref="ServerHomeRecord"/> beside its manifest). Each
/// is an ordinary store with its own manifest and <c>.trash</c>, so sync, copies, renders, sends, leases and the trash work
/// on it unchanged. A parent still in the 1.0 layout (projects side by side in it, a manifest of format 1) is used as it is,
/// one store for every home, until <see cref="Chronos.Data.Homes.HomeLayoutMigration"/> sorts it; projects that sorting could not move
/// (in use then) are still listed where they are. A new, empty parent is made split.
/// </summary>
public sealed class WorkspaceHomes
{
/// <summary>The format of a split parent's manifest (a store's is <see cref="WorkspaceStore.FormatVersion"/>).</summary>
public const int ParentFormatVersion = 2;
/// <summary>The layout a split parent's manifest names.</summary>
public const string HomesLayout = "homes";
private readonly Lock _gate = new();
private readonly Dictionary<string, WorkspaceStore> _stores = new(StringComparer.OrdinalIgnoreCase);
private readonly WorkspaceStore? _legacy;
private ServerIdentity _identity;
/// <summary>Opens the workspace at <paramref name="root"/>, making the folder, and a split manifest when it holds none and no project.</summary>
/// <param name="identity">The servers known by id and their aliases (<see cref="Identity"/>).</param>
/// <exception cref="InvalidDataException">The folder's <c>workspace.json</c> is not a workspace manifest, or a newer one.</exception>
/// <exception cref="IOException">The folder cannot be made or read.</exception>
public WorkspaceHomes(string root, ServerIdentity? identity = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(root);
_identity = identity ?? ServerIdentity.None;
Root = WorkspaceStore.FullRoot(root);
Directory.CreateDirectory(Root);
var path = Path.Combine(Root, WorkspaceStore.ManifestFile);
var manifest = File.Exists(path) ? WorkspaceStore.TryRead(path) : null;
if (manifest is { Layout: HomesLayout })
{
if (manifest.FormatVersion > ParentFormatVersion)
throw new InvalidDataException($"{path} uses format {manifest.FormatVersion}, newer than this Chronos ({ParentFormatVersion}).");
Manifest = manifest;
}
else if (manifest is null && !File.Exists(path) && !HoldsProjects(Root))
{
Manifest = CreateSplit(path);
}
else
{
// The 1.0 layout (or a manifest the store makes again or refuses): one store for every home until it is sorted.
_legacy = new WorkspaceStore(Root);
Manifest = _legacy.Manifest;
}
if (IsSplit && HoldsProjects(Root)) _legacy = new WorkspaceStore(Root, Manifest);
}
/// <summary>The parent folder (Settings › Workspace › Folder).</summary>
public string Root { get; }
/// <summary>The parent's manifest: a split one, or the 1.0 store's.</summary>
public WorkspaceManifest Manifest { get; }
/// <summary>The parent is split into homes; false while it is in the 1.0 layout (one store for every home).</summary>
public bool IsSplit => Manifest.Layout == HomesLayout;
/// <summary>The servers known by id and their aliases: a server home's folder is named by its canonical key.</summary>
public ServerIdentity Identity
{
get => Volatile.Read(ref _identity);
set => Volatile.Write(ref _identity, value ?? ServerIdentity.None);
}
/// <summary>The folder of this PC's home (whether it exists or not).</summary>
public string LocalRoot => HomeFolders.LocalPath(Root);
/// <summary>The folder of the home of server <paramref name="serverKey"/> (whether it exists or not).</summary>
public string ServerRoot(string serverKey)
{
ArgumentException.ThrowIfNullOrWhiteSpace(serverKey);
return Path.Combine(Root, HomeFolders.Servers, Identity.FolderName(serverKey));
}
/// <summary>The folder of the store a project of <paramref name="home"/> belongs in: its home's, or the parent while it is not split.</summary>
public string RootFor(BundleHome home)
{
ArgumentNullException.ThrowIfNull(home);
if (!IsSplit) return Root;
return home.Kind == BundleHome.ServerKind && home.Server is { Length: > 0 } server ? ServerRoot(server) : LocalRoot;
}
/// <summary>
/// The store a project of <paramref name="home"/> is checked out into: its home's (made with its manifest, and for a server
/// its <see cref="ServerHomeRecord"/>, when it is not there), or the parent's while it is not split.
/// </summary>
public WorkspaceStore StoreFor(BundleHome home)
{
ArgumentNullException.ThrowIfNull(home);
if (!IsSplit) return _legacy!;
var root = RootFor(home);
var store = Open(root);
if (home.Kind == BundleHome.ServerKind && home.Server is { Length: > 0 } server && ServerHomeRecord.Read(root) is null)
ServerHomeRecord.Write(root, ServerHomeRecord.Of(Identity.Canonical(server), null, ServerIdentity.IsIdKey(server) ? null : server, null, DateTimeOffset.UtcNow));
return store;
}
/// <summary>The store of this PC's home (the parent's while it is not split).</summary>
public WorkspaceStore Local => StoreFor(new BundleHome(BundleHome.ArchiveKind, Guid.Empty));
/// <summary>
/// Records what is known of server <paramref name="serverKey"/> in its home's <see cref="ServerHomeRecord"/> (made with the
/// home when it is not there; its first sighting kept); nothing while the parent is not split.
/// </summary>
public ServerHomeRecord? Describe(string serverKey, string? name, string? address, string? tlsFingerprint, DateTimeOffset now)
{
ArgumentException.ThrowIfNullOrWhiteSpace(serverKey);
if (!IsSplit) return null;
var root = ServerRoot(serverKey);
Open(root);
var key = Identity.Canonical(serverKey);
var known = ServerHomeRecord.Read(root);
var record = ServerHomeRecord.Of(key, name ?? known?.Name, address ?? known?.Address, tlsFingerprint ?? known?.TlsFingerprint, now) with
{
FirstSeen = known?.FirstSeen ?? now,
};
ServerHomeRecord.Write(root, record);
return record;
}
/// <summary>
/// Every home that has a folder (this PC's first, then the servers' by folder name), and the parent's projects not moved
/// into their home yet; while the parent is not split, the parent's store (and any home a sorting stopped half-way made).
/// </summary>
public IReadOnlyList<WorkspaceHome> Homes()
{
var homes = new List<WorkspaceHome>();
if (_legacy is not null) homes.Add(new WorkspaceHome(string.Empty, _legacy, null, null));
if (Directory.Exists(LocalRoot) && HasManifest(LocalRoot)) homes.Add(new WorkspaceHome(HomeFolders.Local, Open(LocalRoot), null, null));
var servers = Path.Combine(Root, HomeFolders.Servers);
if (Directory.Exists(servers))
{
foreach (var folder in Directory.EnumerateDirectories(servers).Order(StringComparer.Ordinal))
{
var name = Path.GetFileName(folder);
if (!HomeFolders.IsServerFolder(name) || !HasManifest(folder)) continue;
var record = ServerHomeRecord.Read(folder);
var key = record?.Key ?? (HomeFolders.IdOfFolder(name) is { } id ? ServerIdentity.IdKey(id) : null);
homes.Add(new WorkspaceHome(name, Open(folder), key, record));
}
}
return homes;
}
/// <summary>The stores of every home that has a folder (<see cref="Homes"/>).</summary>
public IReadOnlyList<WorkspaceStore> All() => [.. Homes().Select(h => h.Store)];
/// <summary>The projects of every home.</summary>
public IReadOnlyList<WorkspaceProject> List() => [.. All().SelectMany(s => s.List())];
/// <summary>The working states of every home's projects (one unreadable is left out, and logged).</summary>
public IReadOnlyList<(WorkspaceProject Project, ProjectBundle Bundle)> ListBundles() => [.. All().SelectMany(s => s.ListBundles())];
/// <summary>The project's folder in whichever home holds it; null when none does.</summary>
public WorkspaceProject? Find(Guid projectId)
{
foreach (var store in All())
{
if (store.Find(projectId) is { } project) return project;
}
return null;
}
/// <summary>The trash of every home (<see cref="WorkspaceTrash.List"/>), each listed with its own fingerprint.</summary>
/// <exception cref="IOException">A trash cannot be read.</exception>
public IReadOnlyList<WorkspaceTrashListing> Trash(CancellationToken cancellationToken = default) =>
[.. All().Select(s => WorkspaceTrash.List(s.Root, cancellationToken))];
/// <summary>The folder at <paramref name="root"/> is the parent of a workspace split into homes (its manifest says so).</summary>
public static bool IsSplitRoot(string root)
{
ArgumentException.ThrowIfNullOrWhiteSpace(root);
var path = Path.Combine(WorkspaceStore.FullRoot(root), WorkspaceStore.ManifestFile);
return File.Exists(path) && WorkspaceStore.TryRead(path) is { Layout: HomesLayout };
}
/// <summary>The folder holds a folder named by a project id with a working state (the 1.0 layout).</summary>
internal static bool HoldsProjects(string root) =>
Directory.Exists(root) && Directory.EnumerateDirectories(root).Any(d => Guid.TryParseExact(Path.GetFileName(d), "N", out _)
&& File.Exists(Path.Combine(d, WorkspaceProject.BundleFile)));
/// <summary>The manifest of a split parent, made now; another program's made at the same moment wins.</summary>
internal static WorkspaceManifest CreateSplit(string path)
{
var manifest = new WorkspaceManifest(WorkspaceStore.FormatName, ParentFormatVersion, Guid.CreateVersion7(), DateTimeOffset.UtcNow, HomesLayout);
var temp = AtomicFile.TempPathFor(path);
try
{
File.WriteAllText(temp, JsonSerializer.Serialize(manifest, WorkspaceJson.Default.WorkspaceManifest));
try
{
File.Move(temp, path, overwrite: false);
}
catch (IOException) when (File.Exists(path))
{
if (WorkspaceStore.TryRead(path) is { Layout: HomesLayout } first) return first;
throw new InvalidDataException($"{path} was made by another program meanwhile and is not a workspace of homes.");
}
}
finally
{
if (File.Exists(temp)) File.Delete(temp);
}
return manifest;
}
private static bool HasManifest(string folder) => File.Exists(Path.Combine(folder, WorkspaceStore.ManifestFile));
private WorkspaceStore Open(string root)
{
lock (_gate)
{
if (_stores.TryGetValue(root, out var store)) return store;
store = new WorkspaceStore(root);
_stores[root] = store;
return store;
}
}
}
+64 -9
View File
@@ -1,5 +1,6 @@
using System.Text.Json; using System.Text.Json;
using Chronos.Core.Diagnostics; using Chronos.Core.Diagnostics;
using Chronos.Core.IO;
using Chronos.Core.Localization; using Chronos.Core.Localization;
using Chronos.Core.Model; using Chronos.Core.Model;
using Chronos.Core.Project; using Chronos.Core.Project;
@@ -30,10 +31,21 @@ namespace Chronos.Data.Workspaces;
/// <param name="CurrentRoot"> /// <param name="CurrentRoot">
/// The workspace folder in use now (the desktop's Settings › Workspace): a copy, render or send queued before the workspace /// The workspace folder in use now (the desktop's Settings › Workspace): a copy, render or send queued before the workspace
/// moved finds its project there when the folder its parameters name no longer holds it; null where only that one counts. /// moved finds its project there when the folder its parameters name no longer holds it; null where only that one counts.
/// A workspace split into homes (owner review 5, <see cref="WorkspaceHomes"/>) is searched in every home, so a job queued
/// before its folders were sorted, or before its server's home was re-keyed, finds its project in the home it went to.
/// </param>
/// <param name="SameServer">
/// Whether two server keys name one server (<see cref="ServerIdentity.Same"/> over the desktop's alias table, owner review
/// 5): a job queued under an address key the server was reached under works on a project whose home names its id key. Null
/// compares the keys ignoring case (<see cref="IsSameServer"/>).
/// </param> /// </param>
public sealed record WorkspaceJobOptions(ProcessingOptions Processing, Func<bool> HoldTransfers, Func<string, string, Task>? Moved = null, public sealed record WorkspaceJobOptions(ProcessingOptions Processing, Func<bool> HoldTransfers, Func<string, string, Task>? Moved = null,
Func<string?>? CurrentRoot = null) Func<string?>? CurrentRoot = null, Func<string?, string?, bool>? SameServer = null)
{ {
/// <summary>Both keys name one server (<see cref="SameServer"/>, else equal ignoring case; null equals only null).</summary>
public bool IsSameServer(string? a, string? b) =>
SameServer is { } same ? same(a, b) : string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
/// <summary>The options of an engine without a processing service of its own: the archive engine's decoders, nothing held, no move followed.</summary> /// <summary>The options of an engine without a processing service of its own: the archive engine's decoders, nothing held, no move followed.</summary>
public static WorkspaceJobOptions For(ArchiveService archives) public static WorkspaceJobOptions For(ArchiveService archives)
{ {
@@ -204,10 +216,16 @@ internal static class WorkspaceJobRoots
/// resource key) when no folder holds the project. /// resource key) when no folder holds the project.
/// </summary> /// </summary>
/// <exception cref="InvalidOperationException">The workspace is being moved, or no folder holds the project.</exception> /// <exception cref="InvalidOperationException">The workspace is being moved, or no folder holds the project.</exception>
/// <remarks>
/// A folder that is a home of a workspace split into homes (owner review 5: <c>&lt;parent&gt;\local</c>,
/// <c>&lt;parent&gt;\servers\&lt;folder&gt;</c>) is moved with its parent, whose journal counts for it; and a split parent is
/// searched in each of its homes (and in itself, for a project not moved into its home yet), so a job queued with the 1.0
/// folder, or with a server's home before it was re-keyed, finds the project in the home it went to.
/// </remarks>
public static string Resolve(string named, Guid projectId, Func<string?>? current, string missing) public static string Resolve(string named, Guid projectId, Func<string?>? current, string missing)
{ {
ArgumentException.ThrowIfNullOrWhiteSpace(named); ArgumentException.ThrowIfNullOrWhiteSpace(named);
var candidates = new List<string>(); var folders = new List<string>();
string? currentRoot = null; string? currentRoot = null;
try try
{ {
@@ -220,23 +238,60 @@ internal static class WorkspaceJobRoots
foreach (var root in new[] { WorkspaceStore.FullRoot(named), currentRoot }) foreach (var root in new[] { WorkspaceStore.FullRoot(named), currentRoot })
{ {
if (root is null) continue; if (root is null) continue;
if (WorkspaceMover.HasJournal(root)) foreach (var folder in new[] { root, SplitParentOf(root) })
{ {
// Past its switch the move's target is the workspace, and what is left here is a source still to clear. if (folder is null) continue;
if (WorkspaceMover.ReadJournal(root) is not { Stage: WorkspaceMoveStage.Switched } journal) throw new InvalidOperationException(Loc.L("Errors.Workspace.Moving")); if (WorkspaceMover.HasJournal(folder))
candidates.Add(WorkspaceStore.FullRoot(journal.To)); {
continue; // Past its switch the move's target is the workspace, and what is left here is a source still to clear.
if (WorkspaceMover.ReadJournal(folder) is not { Stage: WorkspaceMoveStage.Switched } journal)
throw new InvalidOperationException(Loc.L("Errors.Workspace.Moving"));
folders.Add(WorkspaceStore.FullRoot(journal.To));
continue;
}
folders.Add(folder);
} }
candidates.Add(root); }
var candidates = new List<string>();
foreach (var folder in folders.Distinct(StringComparer.OrdinalIgnoreCase))
{
candidates.Add(folder);
if (WorkspaceHomes.IsSplitRoot(folder)) candidates.AddRange(HomesOf(folder));
} }
foreach (var root in candidates.Distinct(StringComparer.OrdinalIgnoreCase)) foreach (var root in candidates.Distinct(StringComparer.OrdinalIgnoreCase))
{ {
if (!File.Exists(Path.Combine(root, projectId.ToString("N"), WorkspaceProject.BundleFile))) continue; if (!File.Exists(Path.Combine(root, projectId.ToString("N"), WorkspaceProject.BundleFile))) continue;
if (WorkspaceMover.HasJournal(root)) throw new InvalidOperationException(Loc.L("Errors.Workspace.Moving")); if (WorkspaceMover.HasJournal(root) || (SplitParentOf(root) is { } parent && WorkspaceMover.HasJournal(parent)))
throw new InvalidOperationException(Loc.L("Errors.Workspace.Moving"));
if (!string.Equals(root, WorkspaceStore.FullRoot(named), StringComparison.OrdinalIgnoreCase)) if (!string.Equals(root, WorkspaceStore.FullRoot(named), StringComparison.OrdinalIgnoreCase))
Log.Info("workspace", $"Project {projectId} is no longer in {named}: the job works in {root}, where the workspace is now"); Log.Info("workspace", $"Project {projectId} is no longer in {named}: the job works in {root}, where the workspace is now");
return root; return root;
} }
throw new InvalidOperationException(Loc.L(missing)); throw new InvalidOperationException(Loc.L(missing));
} }
/// <summary>The split parent <paramref name="root"/> is a home of (<c>local</c>, or a folder in <c>servers</c>); null for any other folder.</summary>
internal static string? SplitParentOf(string root)
{
var name = Path.GetFileName(root);
var up = Path.GetDirectoryName(root);
if (up is null) return null;
string? parent = name == HomeFolders.Local ? up
: HomeFolders.IsServerFolder(name) && Path.GetFileName(up) == HomeFolders.Servers ? Path.GetDirectoryName(up)
: null;
return parent is not null && WorkspaceHomes.IsSplitRoot(parent) ? WorkspaceStore.FullRoot(parent) : null;
}
/// <summary>The homes of the split parent <paramref name="parent"/> that have a folder: this PC's, then the servers'.</summary>
private static IEnumerable<string> HomesOf(string parent)
{
var local = HomeFolders.LocalPath(parent);
if (Directory.Exists(local)) yield return local;
var servers = Path.Combine(parent, HomeFolders.Servers);
if (!Directory.Exists(servers)) yield break;
foreach (var folder in Directory.EnumerateDirectories(servers).Order(StringComparer.Ordinal))
{
if (HomeFolders.IsServerFolder(Path.GetFileName(folder))) yield return folder;
}
}
} }
+55 -5
View File
@@ -79,8 +79,9 @@ internal sealed partial class WorkspaceMoveJson : JsonSerializerContext;
/// <summary> /// <summary>
/// Moves a workspace folder with its projects (phase 5c, <see cref="Core.Model.JobKind.WorkspaceMove"/>). What moves: every /// Moves a workspace folder with its projects (phase 5c, <see cref="Core.Model.JobKind.WorkspaceMove"/>). What moves: every
/// folder named by a project id, then <c>workspace.json</c>, then <c>.trash</c>, in that order; anything else in the folder /// folder named by a project id, then the homes' folders of a workspace split into homes (<c>local</c>, <c>servers</c>,
/// stays where it is. On one volume each entry is renamed into the target (<see cref="Directory.Move(string, string)"/>); /// owner review 5), then <c>workspace.json</c>, then <c>.trash</c>, in that order; anything else in the folder stays where it
/// is. On one volume each entry is renamed into the target (<see cref="Directory.Move(string, string)"/>);
/// across volumes each file is copied into a <c>.part</c> beside its place, hashed as it is read and read back to hash the /// across volumes each file is copied into a <c>.part</c> beside its place, hashed as it is read and read back to hash the
/// copy, and only once both SHA-256 agree renamed into place (with the source's time), so a file at its final name in the /// copy, and only once both SHA-256 agree renamed into place (with the source's time), so a file at its final name in the
/// target is always one verified. The source is the workspace until every entry is at the target: then the desktop is told /// target is always one verified. The source is the workspace until every entry is at the target: then the desktop is told
@@ -185,6 +186,21 @@ public sealed class WorkspaceMover
entries.Add(name); entries.Add(name);
(files, bytes) = (files + count, bytes + size); (files, bytes) = (files + count, bytes + size);
} }
// A workspace split into homes (owner review 5): each home's folder moves whole, its projects counted one by one.
foreach (var home in HomeEntries)
{
var folder = Path.Combine(From, home);
if (!Directory.Exists(folder)) continue;
var (count, size) = Read(folder, home, fingerprint);
foreach (var project in ProjectFolders(folder))
{
var listed = Listed(project);
projects.Add(new WorkspaceMoveFolder(Guid.ParseExact(Path.GetFileName(project), "N"), File.Exists(Path.Combine(project, WorkspaceProject.BundleFile)),
listed.Count, listed.Sum(f => new FileInfo(Path.Combine(project, f)).Length)));
}
entries.Add(home);
(files, bytes) = (files + count, bytes + size);
}
var manifest = Path.Combine(From, WorkspaceStore.ManifestFile); var manifest = Path.Combine(From, WorkspaceStore.ManifestFile);
if (File.Exists(manifest)) if (File.Exists(manifest))
{ {
@@ -303,7 +319,7 @@ public sealed class WorkspaceMover
if (switched is not null) await switched(From, To).ConfigureAwait(false); if (switched is not null) await switched(From, To).ConfigureAwait(false);
Cut?.Invoke("switched", To); Cut?.Invoke("switched", To);
var left = Clean(journal); var left = Clean(journal);
log?.Invoke(Loc.L("Archive.Log.WorkspaceMoved", To, journal.Entries.Count(e => Guid.TryParseExact(e, "N", out _)), survey.Files)); log?.Invoke(Loc.L("Archive.Log.WorkspaceMoved", To, MovedProjects(journal), survey.Files));
if (left > 0) log?.Invoke(Loc.L("Archive.Log.WorkspaceMoveLeft", From, left)); if (left > 0) log?.Invoke(Loc.L("Archive.Log.WorkspaceMoveLeft", From, left));
Log.Info("workspace", $"The workspace moved from {From} to {To}" + (left > 0 ? $"; {left} entr(ies) of the old folder stay there" : string.Empty)); Log.Info("workspace", $"The workspace moved from {From} to {To}" + (left > 0 ? $"; {left} entr(ies) of the old folder stay there" : string.Empty));
return (survey, resumed); return (survey, resumed);
@@ -383,7 +399,7 @@ public sealed class WorkspaceMover
Cut?.Invoke("rename", source); Cut?.Invoke("rename", source);
Rename(source, target); Rename(source, target);
Cut?.Invoke("moved", target); Cut?.Invoke("moved", target);
if (Guid.TryParseExact(entry, "N", out _)) log?.Invoke(Loc.L("Archive.Log.WorkspaceMoveProject", Name(target))); LogProjects(entry, target, log);
} }
else if (!Exists(target)) else if (!Exists(target))
{ {
@@ -435,7 +451,7 @@ public sealed class WorkspaceMover
if (durable) clock.Restart(); if (durable) clock.Restart();
if (progress is not null) await progress(done, total, durable).ConfigureAwait(false); if (progress is not null) await progress(done, total, durable).ConfigureAwait(false);
} }
if (Guid.TryParseExact(entry, "N", out _)) log?.Invoke(Loc.L("Archive.Log.WorkspaceMoveProject", Name(source))); LogProjects(entry, source, log);
} }
journal = journal with { Verified = [.. journal.Verified, entry] }; journal = journal with { Verified = [.. journal.Verified, entry] };
WriteJournal(journal); WriteJournal(journal);
@@ -600,6 +616,40 @@ public sealed class WorkspaceMover
private const string TrashFolder = ".trash"; private const string TrashFolder = ".trash";
/// <summary>The homes' folders of a workspace split into homes, which move whole after the 1.0 project folders and before the manifest.</summary>
private static readonly string[] HomeEntries = [HomeFolders.Local, HomeFolders.Servers];
/// <summary>The project folders in a home's folder: <c>local</c>'s own, or those of every server home in <c>servers</c>.</summary>
private static IEnumerable<string> ProjectFolders(string home)
{
var homes = Path.GetFileName(home) == HomeFolders.Servers
? Directory.EnumerateDirectories(home).Where(d => HomeFolders.IsServerFolder(Path.GetFileName(d))).Order(StringComparer.Ordinal)
: Enumerable.Repeat(home, 1);
foreach (var store in homes)
{
foreach (var folder in Directory.EnumerateDirectories(store).Order(StringComparer.Ordinal))
{
if (Guid.TryParseExact(Path.GetFileName(folder), "N", out _)) yield return folder;
}
}
}
/// <summary>The projects a move took: its 1.0 project folders, and the project folders of the homes it moved (now at the target).</summary>
private int MovedProjects(WorkspaceMoveJournal journal) =>
journal.Entries.Count(e => Guid.TryParseExact(e, "N", out _))
+ journal.Entries.Where(e => HomeEntries.Contains(e) && Directory.Exists(Path.Combine(To, e))).Sum(e => ProjectFolders(Path.Combine(To, e)).Count());
/// <summary>The log line of each project an entry moved: the entry's own, or those of a home's folder.</summary>
private static void LogProjects(string entry, string folder, Action<string>? log)
{
if (log is null) return;
if (Guid.TryParseExact(entry, "N", out _)) log(Loc.L("Archive.Log.WorkspaceMoveProject", Name(folder)));
else if (HomeEntries.Contains(entry) && Directory.Exists(folder))
{
foreach (var project in ProjectFolders(folder)) log(Loc.L("Archive.Log.WorkspaceMoveProject", Name(project)));
}
}
private static readonly TimeSpan CheckpointEvery = TimeSpan.FromSeconds(5); private static readonly TimeSpan CheckpointEvery = TimeSpan.FromSeconds(5);
private static StringComparison PathComparison => OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; private static StringComparison PathComparison => OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
+41 -2
View File
@@ -11,7 +11,12 @@ using Chronos.Data.Sync;
namespace Chronos.Data.Workspaces; namespace Chronos.Data.Workspaces;
/// <summary>The manifest of a workspace folder (<c>workspace.json</c>).</summary> /// <summary>The manifest of a workspace folder (<c>workspace.json</c>).</summary>
public sealed record WorkspaceManifest(string Format, int FormatVersion, Guid Id, DateTimeOffset Created); /// <param name="Layout">
/// <see cref="WorkspaceHomes.HomesLayout"/> in the manifest of format <see cref="WorkspaceHomes.ParentFormatVersion"/> of a
/// workspace split into homes (owner review 5, #66): the folder holds no projects of its own but one store per home; null
/// for a store.
/// </param>
public sealed record WorkspaceManifest(string Format, int FormatVersion, Guid Id, DateTimeOffset Created, string? Layout = null);
/// <summary> /// <summary>
/// A workspace's sync state of one project besides its versions (<c>sync.json</c>): a restore to record, a conflict to /// A workspace's sync state of one project besides its versions (<c>sync.json</c>): a restore to record, a conflict to
@@ -133,13 +138,15 @@ public sealed record WorkspaceMoveParameters(string From, string To, string Plan
[JsonSerializable(typeof(WorkspaceSendParameters))] [JsonSerializable(typeof(WorkspaceSendParameters))]
[JsonSerializable(typeof(WorkspaceMoveParameters))] [JsonSerializable(typeof(WorkspaceMoveParameters))]
[JsonSerializable(typeof(WorkspaceRenders))] [JsonSerializable(typeof(WorkspaceRenders))]
[JsonSerializable(typeof(ServerHomeRecord))]
internal sealed partial class WorkspaceJson : JsonSerializerContext; internal sealed partial class WorkspaceJson : JsonSerializerContext;
/// <summary> /// <summary>
/// The workspace of this PC (owner review 2, R8): a folder on a fast disk where projects are edited, never inside the /// The workspace of this PC (owner review 2, R8): a folder on a fast disk where projects are edited, never inside the
/// library. <c>&lt;root&gt;/workspace.json</c> names it; each project has a folder named by its id /// library. <c>&lt;root&gt;/workspace.json</c> names it; each project has a folder named by its id
/// (<see cref="WorkspaceProject"/>). There is no index: the store lists the folders holding a <c>project.chronos</c>. The /// (<see cref="WorkspaceProject"/>). There is no index: the store lists the folders holding a <c>project.chronos</c>. The
/// desktop puts it in <c>%LOCALAPPDATA%\Chronos\workspace</c> unless set otherwise; the store takes any folder. /// store takes any folder; the desktop's workspace (<c>%LOCALAPPDATA%\Chronos\workspace</c> unless set otherwise) is split
/// into one store per home since owner review 5 (<see cref="WorkspaceHomes"/>: <c>local</c>, <c>servers\&lt;id&gt;</c>).
/// </summary> /// </summary>
public sealed class WorkspaceStore public sealed class WorkspaceStore
{ {
@@ -168,6 +175,17 @@ public sealed class WorkspaceStore
Manifest = Read(path); Manifest = Read(path);
} }
/// <summary>
/// The projects a workspace split into homes still holds where 1.0 kept them (<c>&lt;parent&gt;/&lt;project id&gt;</c>: one in
/// use when the folders were sorted, owner review 5): a view of the parent with its manifest, which makes and writes nothing
/// (<see cref="WorkspaceHomes"/>).
/// </summary>
internal WorkspaceStore(string root, WorkspaceManifest manifest)
{
Root = FullRoot(root);
Manifest = manifest;
}
public string Root { get; } public string Root { get; }
public WorkspaceManifest Manifest { get; } public WorkspaceManifest Manifest { get; }
@@ -319,6 +337,25 @@ public sealed class WorkspaceStore
} }
} }
/// <summary>The manifest of the folder <paramref name="path"/> names, of any format (a store's or a parent's of homes); null when it is not one.</summary>
internal static WorkspaceManifest? TryRead(string path)
{
try
{
return JsonSerializer.Deserialize(AtomicFile.ReadAllText(path), WorkspaceJson.Default.WorkspaceManifest) is { Format: FormatName } manifest && manifest.Id != Guid.Empty
? manifest
: null;
}
catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)
{
return null;
}
}
/// <summary>Writes <paramref name="manifest"/> whole to a temporary file and moves it into place.</summary>
internal static void Write(string path, WorkspaceManifest manifest) =>
AtomicFile.WriteAllText(path, JsonSerializer.Serialize(manifest, WorkspaceJson.Default.WorkspaceManifest));
private static WorkspaceManifest Read(string path) private static WorkspaceManifest Read(string path)
{ {
WorkspaceManifest? manifest; WorkspaceManifest? manifest;
@@ -331,6 +368,8 @@ public sealed class WorkspaceStore
throw new InvalidDataException($"{path} is not a workspace manifest.", ex); throw new InvalidDataException($"{path} is not a workspace manifest.", ex);
} }
if (manifest is null || manifest.Format != FormatName || manifest.Id == Guid.Empty) throw new InvalidDataException($"{path} is not a workspace manifest."); if (manifest is null || manifest.Format != FormatName || manifest.Id == Guid.Empty) throw new InvalidDataException($"{path} is not a workspace manifest.");
if (manifest.Layout == WorkspaceHomes.HomesLayout)
throw new InvalidDataException($"{path} is the manifest of a workspace split into homes, whose projects are in its home folders ({HomeFolders.Local}, {HomeFolders.Servers}).");
if (manifest.FormatVersion > FormatVersion) if (manifest.FormatVersion > FormatVersion)
throw new InvalidDataException($"{path} uses format {manifest.FormatVersion}, newer than this Chronos ({FormatVersion})."); throw new InvalidDataException($"{path} uses format {manifest.FormatVersion}, newer than this Chronos ({FormatVersion}).");
return manifest; return manifest;
+7 -1
View File
@@ -17,6 +17,11 @@ public sealed record ServerLimits(long MaxUploadBytes, int ChunkSizeBytes, int P
/// The highest project settings format the server reads and renders (<c>ProjectSettings.CurrentVersion</c>, owner review 1, /// The highest project settings format the server reads and renders (<c>ProjectSettings.CurrentVersion</c>, owner review 1,
/// phase 4); null from an older server, which reads format 1 only. The desktop holds back a push or a render that needs more. /// phase 4); null from an older server, which reads format 1 only. The desktop holds back a push or a render that needs more.
/// </param> /// </param>
/// <param name="ServerId">
/// The server's stable id (owner review 5, #66): made once, kept in its database, the same whatever address or name it is
/// reached by. A desktop keys the server's homes, links and folders by it. Null from an older server, which a desktop keys by
/// its address.
/// </param>
public sealed record ServerInfo( public sealed record ServerInfo(
string Name, string Name,
string Version, string Version,
@@ -26,7 +31,8 @@ public sealed record ServerInfo(
IReadOnlyList<string> Formats, IReadOnlyList<string> Formats,
ServerLimits Limits, ServerLimits Limits,
IReadOnlyList<string>? Extensions = null, IReadOnlyList<string>? Extensions = null,
int? SettingsFormat = null); int? SettingsFormat = null,
Guid? ServerId = null);
/// <summary>Names of <see cref="ServerInfo.Capabilities"/> that clients act on.</summary> /// <summary>Names of <see cref="ServerInfo.Capabilities"/> that clients act on.</summary>
public static class ServerCapabilities public static class ServerCapabilities
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<!-- The console program of Chronos Server (the Docker image, development runs); the server itself is the
Chronos.Server library, which Chronos Desktop also hosts in-process to share its library (owner review 5, #67). -->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace>Chronos.Server.Host</RootNamespace>
<AssemblyName>Chronos.Server.Host</AssemblyName>
<ApplicationIcon Condition="Exists('$(ChronosIconDir)chronos-server.ico')">$(ChronosIconDir)chronos-server.ico</ApplicationIcon>
<ServerGarbageCollection>true</ServerGarbageCollection>
<InvariantGlobalization>false</InvariantGlobalization>
<UserSecretsId />
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Chronos.Server\Chronos.Server.csproj" />
</ItemGroup>
</Project>
+30
View File
@@ -0,0 +1,30 @@
using Chronos.Server.Configuration;
using Chronos.Server.Hosting;
using Chronos.Server.Storage;
var command = ServerCommandLine.Parse(args);
if (command.Error is not null)
{
await Console.Error.WriteLineAsync(command.Error);
return 2;
}
switch (command.Command)
{
case ServerCommand.Help:
Console.WriteLine(ServerCommandLine.Usage);
return 0;
case ServerCommand.HealthCheck:
return await HealthProbe.RunAsync();
default:
var app = ServerHost.Build(ServerOptions.Load(), [.. command.HostArguments], RegisterModules);
await app.RunAsync();
return 0;
}
// The archive engine, then analysis and managed rendering over it.
static void RegisterModules(IServiceCollection services)
{
ArchiveModule.Register(services);
ProcessingModule.Register(services);
}
@@ -49,7 +49,9 @@ export async function render(root, { api, info, setMeta, actions }) {
// The server names the variable that fixes each locked setting: CHRONOS_LOG_LEVEL fixes the console's level too, unless // The server names the variable that fixes each locked setting: CHRONOS_LOG_LEVEL fixes the console's level too, unless
// CHRONOS_LOG_CONSOLE_LEVEL sets its own (BRIEF §14.9). // CHRONOS_LOG_CONSOLE_LEVEL sets its own (BRIEF §14.9).
const variable = (name) => Object.entries(settings.lockedBy ?? {}).find(([setting]) => same(setting, name))?.[1] ?? name; const variable = (name) => Object.entries(settings.lockedBy ?? {}).find(([setting]) => same(setting, name))?.[1] ?? name;
const lock = (name) => locked(name) ? `disabled title="${attr(t("Admin.Settings.Locked.Tip", variable(name)))}"` : `data-i18n-title="Admin.Settings.${cap(name)}.Tip"`; // Chronos Desktop owns the settings of the library it shares (owner review 5, #67): no variable names them.
const lockTip = (name) => variable(name) === "desktop" ? t("Admin.Settings.LockedByDesktop.Tip") : t("Admin.Settings.Locked.Tip", variable(name));
const lock = (name) => locked(name) ? `disabled title="${attr(lockTip(name))}"` : `data-i18n-title="Admin.Settings.${cap(name)}.Tip"`;
const field = (name, input) => `<label class="field"><span data-i18n="Admin.Settings.${cap(name)}"></span>${input}</label>`; const field = (name, input) => `<label class="field"><span data-i18n="Admin.Settings.${cap(name)}"></span>${input}</label>`;
const number = (name, value, attrs = "") => field(name, `<input class="input narrow num" type="number" name="${name}" value="${attr(value)}" ${attrs} ${lock(name)}>`); const number = (name, value, attrs = "") => field(name, `<input class="input narrow num" type="number" name="${name}" value="${attr(value)}" ${attrs} ${lock(name)}>`);
const text = (name, value, attrs = "dir=\"auto\"") => field(name, `<input class="input" name="${name}" value="${attr(value ?? "")}" ${attrs} ${lock(name)}>`); const text = (name, value, attrs = "dir=\"auto\"") => field(name, `<input class="input" name="${name}" value="${attr(value ?? "")}" ${attrs} ${lock(name)}>`);
+29 -7
View File
@@ -32,8 +32,8 @@ public static class JobEndpoints
var jobs = api.MapGroup("/jobs").Requires(Permissions.Read); var jobs = api.MapGroup("/jobs").Requires(Permissions.Read);
jobs.MapGet("", ListAsync); jobs.MapGet("", ListAsync);
jobs.MapPost("", CreateAsync); jobs.MapPost("", CreateAsync);
jobs.MapGet("/{id:guid}", async (HttpContext context, Guid id, ChronosDatabase db) => jobs.MapGet("/{id:guid}", async (HttpContext context, Guid id, ChronosDatabase db, JobEngineHost host) =>
await db.Jobs.GetAsync(id, context.RequestAborted) is { } job await db.Jobs.GetAsync(id, context.RequestAborted) is { } job && host.Exposes(job.Kind)
? Results.Json(Dto.Job(job), ProtocolJson.Default.JobDto) ? Results.Json(Dto.Job(job), ProtocolJson.Default.JobDto)
: ApiErrors.NotFound(context, "job")); : ApiErrors.NotFound(context, "job"));
jobs.MapPost("/{id:guid}/cancel", (HttpContext c, Caller caller, Guid id, ChronosDatabase db, JobEngineHost host) => jobs.MapPost("/{id:guid}/cancel", (HttpContext c, Caller caller, Guid id, ChronosDatabase db, JobEngineHost host) =>
@@ -47,7 +47,7 @@ public static class JobEndpoints
jobs.MapPost("/{id:guid}/priority", PriorityAsync); jobs.MapPost("/{id:guid}/priority", PriorityAsync);
} }
private static async Task<IResult> ListAsync(HttpContext context, ChronosDatabase db, string? state, string? kind, string? cursor, int? limit) private static async Task<IResult> ListAsync(HttpContext context, ChronosDatabase db, JobEngineHost host, string? state, string? kind, string? cursor, int? limit)
{ {
JobState? stateFilter = null; JobState? stateFilter = null;
JobKind? kindFilter = null; JobKind? kindFilter = null;
@@ -62,8 +62,10 @@ public static class JobEndpoints
kindFilter = k; kindFilter = k;
} }
// A job's answer holds no parameters (a conversion's or an import's can name every sequence or file): the list reads none. // A job's answer holds no parameters (a conversion's or an import's can name every sequence or file): the list reads none.
if (kindFilter is { } wanted && !host.Exposes(wanted)) return Results.Json(new Page<JobDto>([], null, null), ProtocolJson.Default.PageJobDto);
var page = await db.Jobs.ListBriefAsync(stateFilter, kindFilter, limit ?? 50, string.IsNullOrEmpty(cursor) ? null : cursor, context.RequestAborted); var page = await db.Jobs.ListBriefAsync(stateFilter, kindFilter, limit ?? 50, string.IsNullOrEmpty(cursor) ? null : cursor, context.RequestAborted);
return Results.Json(new Page<JobDto>([.. page.Items.Select(Dto.Job)], page.NextCursor, null), ProtocolJson.Default.PageJobDto); // A shared desktop library lists the kinds a server runs alone (owner review 5, #67); the cursor still pages the whole list.
return Results.Json(new Page<JobDto>([.. page.Items.Where(j => host.Exposes(j.Kind)).Select(Dto.Job)], page.NextCursor, null), ProtocolJson.Default.PageJobDto);
} }
private static async Task<IResult> CreateAsync(HttpContext context, Caller caller, CreateJobRequest request, ChronosDatabase db, JobEngineHost host, private static async Task<IResult> CreateAsync(HttpContext context, Caller caller, CreateJobRequest request, ChronosDatabase db, JobEngineHost host,
@@ -90,7 +92,7 @@ public static class JobEndpoints
var titles = new List<string>(ids.Count); var titles = new List<string>(ids.Count);
foreach (var id in ids) foreach (var id in ids)
{ {
if (await db.Sequences.GetAsync(id, ct) is not { } sequence) return ApiErrors.NotFound(context, "sequence"); if (await ServedItems.SequenceAsync(db, archive, id, ct) is not { } sequence) return ApiErrors.NotFound(context, "sequence");
titles.Add(sequence.DisplayTitle); titles.Add(sequence.DisplayTitle);
} }
targets = ids; targets = ids;
@@ -99,7 +101,11 @@ public static class JobEndpoints
List<(string Label, string? Parameters)> queue = [(label, request.ParametersJson)]; List<(string Label, string? Parameters)> queue = [(label, request.ParametersJson)];
if (kind == JobKind.Render) if (kind == JobKind.Render)
{ {
if (ParseRender(request.ParametersJson) is not { } parsed) return ApiErrors.BadRequest(context, "invalid_parameters", "parametersJson"); if (ParseRender(request.ParametersJson) is not { } given) return ApiErrors.BadRequest(context, "invalid_parameters", "parametersJson");
// A client's export folder means nothing to the server, and on a shared desktop library it would be anywhere the
// desktop's user may write (owner review 5, #67): a render always goes to the sequence's exports.
var parsed = WithoutExportFolder(given);
if (!ReferenceEquals(parsed, given)) request = request with { ParametersJson = JsonSerializer.Serialize(parsed, ProtocolJson.Default.RenderJobParameters) };
// A render of a project version (owner review 2, R8): of the sequence's projects, a project alone pinned to its head. // A render of a project version (owner review 2, R8): of the sequence's projects, a project alone pinned to its head.
var (render, missing) = await ProjectRenderAsync(db, archives, targets[0], parsed, ct); var (render, missing) = await ProjectRenderAsync(db, archives, targets[0], parsed, ct);
if (missing is not null) return ApiErrors.NotFound(context, missing); if (missing is not null) return ApiErrors.NotFound(context, missing);
@@ -221,7 +227,9 @@ public static class JobEndpoints
private static async Task<IResult> ActAsync(HttpContext context, Caller caller, Guid id, ChronosDatabase db, JobState[] allowed, Func<Job, CancellationToken, Task> action) private static async Task<IResult> ActAsync(HttpContext context, Caller caller, Guid id, ChronosDatabase db, JobState[] allowed, Func<Job, CancellationToken, Task> action)
{ {
var ct = context.RequestAborted; var ct = context.RequestAborted;
if (await db.Jobs.GetAsync(id, ct) is not { } job) return ApiErrors.NotFound(context, "job"); // A shared desktop library's own jobs (workspace, sync, downloads) are not the server's (owner review 5, #67).
if (await db.Jobs.GetAsync(id, ct) is not { } job || !context.RequestServices.GetRequiredService<JobEngineHost>().Exposes(job.Kind))
return ApiErrors.NotFound(context, "job");
if (job.CreatedBy != caller.Id && !caller.Has(Permissions.ManageArchive)) return ApiErrors.Forbidden(context); if (job.CreatedBy != caller.Id && !caller.Has(Permissions.ManageArchive)) return ApiErrors.Forbidden(context);
if (!allowed.Contains(job.State)) return ApiErrors.Conflict(context, "invalid_state", JobWire.State(job.State)); if (!allowed.Contains(job.State)) return ApiErrors.Conflict(context, "invalid_state", JobWire.State(job.State));
await action(job, ct); await action(job, ct);
@@ -230,6 +238,20 @@ public static class JobEndpoints
} }
/// <summary>Render parameters, or null when they are missing or incomplete.</summary> /// <summary>Render parameters, or null when they are missing or incomplete.</summary>
/// <summary>
/// <paramref name="parameters"/> without the export folder its preset names (key <c>folder</c>, any case), or the same
/// instance when it names none (owner review 5, #67).
/// </summary>
public static RenderJobParameters WithoutExportFolder(RenderJobParameters parameters)
{
ArgumentNullException.ThrowIfNull(parameters);
if (System.Text.Json.Nodes.JsonNode.Parse(parameters.PresetJson) is not System.Text.Json.Nodes.JsonObject preset) return parameters;
var folders = preset.Select(p => p.Key).Where(k => k.Equals("folder", StringComparison.OrdinalIgnoreCase)).ToList();
if (folders.Count == 0) return parameters;
foreach (var key in folders) preset.Remove(key);
return parameters with { PresetJson = preset.ToJsonString() };
}
public static RenderJobParameters? ParseRender(string? json) public static RenderJobParameters? ParseRender(string? json)
{ {
if (string.IsNullOrWhiteSpace(json)) return null; if (string.IsNullOrWhiteSpace(json)) return null;
+4 -2
View File
@@ -219,7 +219,8 @@ public static class LibraryEndpoints
var allowed = new List<Sequence>(); var allowed = new List<Sequence>();
foreach (var id in ids) foreach (var id in ids)
{ {
if (await db.Sequences.GetAsync(id, ct) is not { } sequence) items[id] = Skip(context, id, "not_found"); if (await db.Sequences.GetAsync(id, ct) is not { } sequence || !context.RequestServices.GetRequiredService<ServerArchive>().Owns(sequence))
items[id] = Skip(context, id, "not_found");
else if (!caller.IsAdmin && sequence.OwnerUserId != caller.Id) items[id] = Skip(context, id, "forbidden"); else if (!caller.IsAdmin && sequence.OwnerUserId != caller.Id) items[id] = Skip(context, id, "forbidden");
else allowed.Add(sequence); else allowed.Add(sequence);
} }
@@ -337,7 +338,8 @@ public static class LibraryEndpoints
{ {
for (var attempt = 0; attempt < 3; attempt++) for (var attempt = 0; attempt < 3; attempt++)
{ {
if (await db.Sequences.GetAsync(id, ct) is not { } sequence) return Skip(context, id, "not_found"); if (await db.Sequences.GetAsync(id, ct) is not { } sequence || !context.RequestServices.GetRequiredService<ServerArchive>().Owns(sequence))
return Skip(context, id, "not_found");
var tags = sequence.Tags.Where(t => !remove.Contains(t, StringComparer.OrdinalIgnoreCase)).ToList(); var tags = sequence.Tags.Where(t => !remove.Contains(t, StringComparer.OrdinalIgnoreCase)).ToList();
tags.AddRange(add.Where(t => !tags.Contains(t, StringComparer.OrdinalIgnoreCase))); tags.AddRange(add.Where(t => !tags.Contains(t, StringComparer.OrdinalIgnoreCase)));
if (tags.Count > SequenceEndpoints.MaxTags) return Skip(context, id, "bad_request"); if (tags.Count > SequenceEndpoints.MaxTags) return Skip(context, id, "bad_request");
+90
View File
@@ -0,0 +1,90 @@
using Microsoft.AspNetCore.Routing.Patterns;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Server.Storage;
namespace Chronos.Server.Api;
/// <summary>
/// The served archive's items alone (owner review 5, #67): an index may hold several archives (Chronos Desktop's, which
/// shares one of them, also keeps the archives of other servers' originals), and a sequence, frame, render or video of
/// another one answers 404 as an unknown id would, on every route that names one and in every body that lists them.
/// The rule holds on a server of its own too, whose index holds one archive.
/// </summary>
public static class ServedItems
{
/// <summary>What the id in a route names, by the route's prefix and the id's name.</summary>
private static readonly (string Prefix, string Value, ItemKind Kind)[] Routes =
[
("/api/v1/sequences/{id", "id", ItemKind.Sequence),
("/api/v1/sequences/{sid", "sid", ItemKind.Sequence),
("/api/v1/frames/{id", "id", ItemKind.Frame),
("/api/v1/renders/{id", "id", ItemKind.Render),
("/api/v1/videos/{id", "id", ItemKind.Render),
];
private enum ItemKind
{
Sequence,
Frame,
Render,
}
/// <summary>The endpoint filter of the API group: an id of another archive's item answers 404 before the endpoint runs.</summary>
public static async ValueTask<object?> FilterAsync(EndpointFilterInvocationContext invocation, EndpointFilterDelegate next)
{
ArgumentNullException.ThrowIfNull(invocation);
ArgumentNullException.ThrowIfNull(next);
var context = invocation.HttpContext;
if (context.GetEndpoint() is RouteEndpoint { RoutePattern: { } pattern } && Named(pattern, context) is var (kind, id))
{
var db = context.RequestServices.GetRequiredService<ChronosDatabase>();
var archive = context.RequestServices.GetRequiredService<ServerArchive>();
if (await ArchiveOfAsync(db, kind, id, context.RequestAborted).ConfigureAwait(false) is { } owner && owner != archive.Id)
return ApiErrors.NotFound(context, kind == ItemKind.Render ? "render" : kind.ToString().ToLowerInvariant());
}
return await next(invocation).ConfigureAwait(false);
}
/// <summary>The sequence <paramref name="id"/> when it belongs to the served archive; null for another archive's or an unknown one.</summary>
public static async Task<Sequence?> SequenceAsync(ChronosDatabase db, ServerArchive archive, Guid id, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(db);
ArgumentNullException.ThrowIfNull(archive);
return await db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } sequence && archive.Owns(sequence) ? sequence : null;
}
/// <summary>The render <paramref name="id"/> when its sequence belongs to the served archive; null otherwise.</summary>
public static async Task<Render?> RenderAsync(ChronosDatabase db, ServerArchive archive, Guid id, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(db);
ArgumentNullException.ThrowIfNull(archive);
return await db.Renders.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } render
&& await SequenceAsync(db, archive, render.SequenceId, cancellationToken).ConfigureAwait(false) is not null
? render
: null;
}
private static (ItemKind Kind, Guid Id)? Named(RoutePattern pattern, HttpContext context)
{
if (pattern.RawText is not { } text) return null;
foreach (var (prefix, value, kind) in Routes)
{
if (text.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) && context.Request.RouteValues.TryGetValue(value, out var raw)
&& Guid.TryParse(raw?.ToString(), out var id))
return (kind, id);
}
return null;
}
private static async Task<Guid?> ArchiveOfAsync(ChronosDatabase db, ItemKind kind, Guid id, CancellationToken cancellationToken)
{
var sequenceId = kind switch
{
ItemKind.Sequence => id,
ItemKind.Frame => (await db.Frames.GetAsync(id, cancellationToken).ConfigureAwait(false))?.SequenceId,
_ => (await db.Renders.GetAsync(id, cancellationToken).ConfigureAwait(false))?.SequenceId,
};
return sequenceId is { } sid ? (await db.Sequences.GetAsync(sid, cancellationToken).ConfigureAwait(false))?.ArchiveId : null;
}
}
+8 -1
View File
@@ -49,7 +49,8 @@ public static class SystemEndpoints
["jpeg", "png", "tiff", "dng", "cr2", "cr3", "nef", "arw", "raf", "orf", "rw2", "pef", "heic", "webp"], ["jpeg", "png", "tiff", "dng", "cr2", "cr3", "nef", "arw", "raf", "orf", "rw2", "pef", "heic", "webp"],
new ServerLimits(options.MaxUploadBytes, options.ChunkSizeBytes, PasswordHasher.MinimumLength), new ServerLimits(options.MaxUploadBytes, options.ChunkSizeBytes, PasswordHasher.MinimumLength),
PhotoExtensions, PhotoExtensions,
ProjectSettings.CurrentVersion), ProtocolJson.Default.ServerInfo)).AllowAnonymousCaller(); ProjectSettings.CurrentVersion,
state.ServerId), ProtocolJson.Default.ServerInfo)).AllowAnonymousCaller();
api.MapGet("/i18n/{culture}", (string culture) => api.MapGet("/i18n/{culture}", (string culture) =>
{ {
@@ -114,6 +115,12 @@ public sealed class ServerState
{ {
public string? TlsFingerprint { get; init; } public string? TlsFingerprint { get; init; }
/// <summary>
/// The server's stable id (<see cref="ServerInfo.ServerId"/>), kept in its database's settings
/// (<see cref="Hosting.ServerHost.ServerIdKey"/>); null only where a host built the state without a database.
/// </summary>
public Guid? ServerId { get; init; }
/// <summary>Engine and version of the database ("PostgreSQL 17.2", "SQLite 3.45.1").</summary> /// <summary>Engine and version of the database ("PostgreSQL 17.2", "SQLite 3.45.1").</summary>
public string Database { get; init; } = string.Empty; public string Database { get; init; } = string.Empty;
+20 -1
View File
@@ -100,6 +100,7 @@ public static class VideoEndpoints
[FromServices] ArchiveService? archives, [FromServices] IVideoLibrary? videos, AuditLog audit, EventHub events, IHostApplicationLifetime lifetime) [FromServices] ArchiveService? archives, [FromServices] IVideoLibrary? videos, AuditLog audit, EventHub events, IHostApplicationLifetime lifetime)
{ {
if (Ids(request.Ids) is not { } ids) return ApiErrors.BadRequest(context, "bad_request", "ids"); if (Ids(request.Ids) is not { } ids) return ApiErrors.BadRequest(context, "bad_request", "ids");
ids = await ServedAsync(context, db, ids);
var library = Library(videos, archives, db); var library = Library(videos, archives, db);
if (!library.IsAvailable) return Unavailable(context); if (!library.IsAvailable) return Unavailable(context);
try try
@@ -166,7 +167,8 @@ public static class VideoEndpoints
var renders = new List<Render>(ids.Count); var renders = new List<Render>(ids.Count);
foreach (var id in ids) foreach (var id in ids)
{ {
if (await db.Renders.GetAsync(id, ct) is not { } render) return ApiErrors.NotFound(context, "render"); if (await ServedItems.RenderAsync(db, context.RequestServices.GetRequiredService<ServerArchive>(), id, ct) is not { } render)
return ApiErrors.NotFound(context, "render");
renders.Add(render); renders.Add(render);
} }
if (!library.IsAvailable || !host.CanRun(JobKind.VideoCopy)) return Unavailable(context); if (!library.IsAvailable || !host.CanRun(JobKind.VideoCopy)) return Unavailable(context);
@@ -200,6 +202,23 @@ public static class VideoEndpoints
private static IResult Unavailable(HttpContext context) => ApiErrors.Conflict(context, "job_unavailable", JobWire.Kind(JobKind.VideoCopy)); private static IResult Unavailable(HttpContext context) => ApiErrors.Conflict(context, "job_unavailable", JobWire.Kind(JobKind.VideoCopy));
/// <summary>The ids of a request, each once in order; null when there are none, too many, or an empty one.</summary> /// <summary>The ids of a request, each once in order; null when there are none, too many, or an empty one.</summary>
/// <summary>
/// <paramref name="ids"/> without the renders of another archive of the index (owner review 5, #67): they are left out as
/// ids the server does not know. Unknown ids stay, for the library to report.
/// </summary>
private static async Task<List<Guid>> ServedAsync(HttpContext context, ChronosDatabase db, List<Guid> ids)
{
var archive = context.RequestServices.GetRequiredService<ServerArchive>();
var served = new List<Guid>(ids.Count);
foreach (var id in ids)
{
if (await db.Renders.GetAsync(id, context.RequestAborted) is not { } render
|| archive.Owns(await db.Sequences.GetAsync(render.SequenceId, context.RequestAborted)))
served.Add(id);
}
return served;
}
private static List<Guid>? Ids(IReadOnlyList<Guid>? ids) private static List<Guid>? Ids(IReadOnlyList<Guid>? ids)
{ {
if (ids is null || ids.Count is 0 or > MaxIds || ids.Contains(Guid.Empty)) return null; if (ids is null || ids.Count is 0 or > MaxIds || ids.Contains(Guid.Empty)) return null;
+3 -3
View File
@@ -1,12 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk.Web"> <Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup> <PropertyGroup>
<!-- A library (owner review 5, #67): Chronos.Server.Host is the console program, and Chronos Desktop hosts the same
server in-process when it shares its library. -->
<OutputType>Library</OutputType>
<TargetFramework>net10.0</TargetFramework> <TargetFramework>net10.0</TargetFramework>
<RootNamespace>Chronos.Server</RootNamespace> <RootNamespace>Chronos.Server</RootNamespace>
<AssemblyName>Chronos.Server</AssemblyName> <AssemblyName>Chronos.Server</AssemblyName>
<ApplicationIcon Condition="Exists('$(ChronosIconDir)chronos-server.ico')">$(ChronosIconDir)chronos-server.ico</ApplicationIcon>
<ServerGarbageCollection>true</ServerGarbageCollection>
<InvariantGlobalization>false</InvariantGlobalization> <InvariantGlobalization>false</InvariantGlobalization>
<UserSecretsId />
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Chronos.Core\Chronos.Core.csproj" /> <ProjectReference Include="..\Chronos.Core\Chronos.Core.csproj" />
@@ -369,6 +369,121 @@ public sealed class ServerOptions
return options; return options;
} }
/// <summary>What <see cref="LockedBy"/> names for a setting Chronos Desktop owns while it shares its library (owner review 5, #67).</summary>
public const string DesktopLock = "desktop";
/// <summary>
/// The server Chronos Desktop hosts in-process to share this PC's library (owner review 5, #67): its index, archive service,
/// engine and scheduler are the desktop's (<see cref="HostedEngine"/>), its own state is in the desktop's data folder.
/// </summary>
[JsonIgnore]
public bool Hosted { get; private set; }
/// <summary>
/// The options of the server Chronos Desktop hosts (owner review 5, #67): <paramref name="dataPath"/>'s <c>server.json</c>
/// (what the admin panel saved: token lifetime, uploads, sign-in limits, render nodes, audit retention), then the values
/// the desktop owns, locked there with <see cref="DesktopLock"/> (its name, ports, discovery, archive, videos folder, jobs,
/// language and logs). No environment variable is read: a <c>CHRONOS_*</c> variable set for a server never reaches the
/// desktop. The index is the desktop's (SQLite), the certificate a self-signed one.
/// </summary>
public static ServerOptions ForHosted(string dataPath, HostedSettings desktop)
{
ArgumentException.ThrowIfNullOrWhiteSpace(dataPath);
ArgumentNullException.ThrowIfNull(desktop);
var options = new ServerOptions();
var file = Path.Combine(dataPath, "server.json");
if (File.Exists(file))
{
try
{
options = JsonSerializer.Deserialize(DataFolderAccess.ReadTrustedText(file), ServerOptionsJson.Default.ServerOptions) ?? options;
}
catch (JsonException ex)
{
throw new InvalidOperationException($"{file} is not valid JSON: {ex.Message}", ex);
}
}
options.Hosted = true;
options.DataPath = dataPath;
options.InContainer = false;
options.AdminUser = null;
options.AdminPassword = null;
options.DbConnectionString = null;
options.Database = DatabaseKind.Sqlite;
options.TlsMode = TlsMode.Auto;
options.TlsCert = null;
options.TlsKey = null;
options.TrustedProxies = DefaultTrustedProxies;
options.SpacePath = null;
options.ApplyDesktop(desktop);
options.Locked = HostedLocks;
options.LockedBy = HostedLocks.ToDictionary(s => s, _ => DesktopLock, StringComparer.Ordinal);
options.ValidateHosted();
return options;
}
/// <summary>The settings Chronos Desktop owns while it shares its library: the admin panel shows them locked.</summary>
public static IReadOnlyList<string> HostedLocks { get; } =
[
nameof(ServerName), nameof(HttpPort), nameof(HttpsPort), nameof(PublicHttpPort), nameof(PublicHttpsPort), nameof(Discovery), nameof(ArchivePath),
nameof(VideosPath), nameof(Parallelism), nameof(PriorityQueue), nameof(JobPriorities), nameof(Language), nameof(LogLevel), nameof(ConsoleLogLevel),
nameof(LogRetentionDays), nameof(LogMaxFileMb), nameof(LogMaxTotalMb), nameof(LogRotation), nameof(DiagnosticsLogMb), nameof(TlsMode),
nameof(Database), nameof(JobHistoryDays),
];
/// <summary>
/// Puts the values of Chronos Desktop's settings into these options (owner review 5, #67): when the share starts and
/// whenever the desktop saves its settings, so the parallelism, the priority queue, the language and the logs follow at
/// once; a change of name, port or discovery restarts the share.
/// </summary>
public void ApplyDesktop(HostedSettings desktop)
{
ArgumentNullException.ThrowIfNull(desktop);
ServerName = string.IsNullOrWhiteSpace(desktop.ServerName) ? Environment.MachineName : desktop.ServerName.Trim();
HttpPort = desktop.HttpPort;
HttpsPort = desktop.HttpsPort;
PublicHttpPort = desktop.PublicHttpPort;
PublicHttpsPort = desktop.PublicHttpsPort;
Discovery = desktop.Discovery;
ArchivePath = desktop.ArchivePath;
VideosPath = string.IsNullOrWhiteSpace(desktop.VideosPath) ? null : desktop.VideosPath.Trim();
Parallelism = Math.Clamp(desktop.Parallelism, 1, MaxParallelism);
PriorityQueue = desktop.PriorityQueue;
JobPriorities = new Dictionary<string, string>(desktop.JobPriorities, StringComparer.Ordinal);
Language = string.IsNullOrWhiteSpace(desktop.Language) ? "en" : desktop.Language;
LogLevel = MsLevel(desktop.LogLevel);
// Nobody reads the console of a desktop program.
ConsoleLogLevel = LogLevel.None;
LogRetentionDays = desktop.LogRetentionDays;
LogMaxFileMb = desktop.LogMaxFileMb;
LogMaxTotalMb = desktop.LogMaxTotalMb;
LogRotation = desktop.LogRotation;
DiagnosticsLogMb = desktop.DiagnosticsLogMb;
JobHistoryDays = Chronos.Data.Housekeeping.CleanupSteps.DefaultHistoryDays;
}
private static LogLevel MsLevel(Chronos.Core.Diagnostics.LogLevel level) => level switch
{
Chronos.Core.Diagnostics.LogLevel.Trace => LogLevel.Trace,
Chronos.Core.Diagnostics.LogLevel.Debug => LogLevel.Debug,
Chronos.Core.Diagnostics.LogLevel.Info => LogLevel.Information,
Chronos.Core.Diagnostics.LogLevel.Warning => LogLevel.Warning,
_ => LogLevel.Error,
};
/// <summary><see cref="Validate"/> for <see cref="ForHosted"/>: no platform check, as the index is the desktop's.</summary>
private void ValidateHosted()
{
if (HttpPort is < 0 or > 65535 || HttpsPort is < 0 or > 65535 || PublicHttpPort is < 1 or > 65535 || PublicHttpsPort is < 1 or > 65535)
throw new InvalidOperationException("The ports must be between 1 and 65535.");
if (ChunkSizeBytes is < 64 * 1024 or > 64 * 1024 * 1024)
throw new InvalidOperationException("The chunk size must be between 64 KiB and 64 MiB.");
if (MaxUploadBytes < 1 || TokenLifetimeDays < 1 || JobHistoryDays < 1 || UploadRetentionHours < 1)
throw new InvalidOperationException("Upload size, token lifetime, job history and upload retention must be positive.");
if (ServerLogging.Problem(LogRetentionDays, LogMaxFileMb, LogMaxTotalMb, AuditRetentionDays, DiagnosticsLogMb) is { } log)
throw new InvalidOperationException($"{log} is out of range: {ServerLogging.Ranges}.");
}
/// <summary>The database to open: <see cref="DbConnectionString"/>, the SQLite file in the data folder, or PostgreSQL from the parts.</summary> /// <summary>The database to open: <see cref="DbConnectionString"/>, the SQLite file in the data folder, or PostgreSQL from the parts.</summary>
public DatabaseOptions ToDatabaseOptions() public DatabaseOptions ToDatabaseOptions()
{ {
@@ -457,6 +572,31 @@ public sealed class ServerOptions
} }
} }
/// <summary>
/// What Chronos Desktop decides for the server it hosts when it shares this PC's library (owner review 5, #67): Settings ›
/// Server (name, ports, discovery), the current archive, Settings › Videos, Settings › Rendering (parallelism, priority
/// queue), the language and Settings › Advanced › Logs. <see cref="ServerOptions.ForHosted"/> locks them in the admin panel.
/// </summary>
public sealed record HostedSettings(
string? ServerName,
int HttpPort,
int HttpsPort,
int? PublicHttpPort,
int? PublicHttpsPort,
bool Discovery,
string ArchivePath,
string? VideosPath,
int Parallelism,
bool PriorityQueue,
IReadOnlyDictionary<string, string> JobPriorities,
string? Language,
Chronos.Core.Diagnostics.LogLevel LogLevel,
int LogRetentionDays,
int LogMaxFileMb,
int LogMaxTotalMb,
LogRotation LogRotation,
int DiagnosticsLogMb);
[JsonSourceGenerationOptions(WriteIndented = true, UseStringEnumConverter = true, PropertyNameCaseInsensitive = true)] [JsonSourceGenerationOptions(WriteIndented = true, UseStringEnumConverter = true, PropertyNameCaseInsensitive = true)]
[JsonSerializable(typeof(ServerOptions))] [JsonSerializable(typeof(ServerOptions))]
internal sealed partial class ServerOptionsJson : JsonSerializerContext; internal sealed partial class ServerOptionsJson : JsonSerializerContext;
+1 -1
View File
@@ -3,7 +3,7 @@ using Chronos.Server.Configuration;
namespace Chronos.Server.Hosting; namespace Chronos.Server.Hosting;
/// <summary> /// <summary>
/// <c>Chronos.Server --healthcheck</c>: probes the local /health endpoint and exits 0/1, so the container /// <c>Chronos.Server.Host --healthcheck</c>: probes the local /health endpoint and exits 0/1, so the container
/// HEALTHCHECK needs no curl/wget in the image. /// HEALTHCHECK needs no curl/wget in the image.
/// </summary> /// </summary>
public static class HealthProbe public static class HealthProbe
+168
View File
@@ -0,0 +1,168 @@
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Housekeeping;
using Chronos.Data.Jobs;
using Chronos.Data.Processing;
using Chronos.Data.Projects;
using Chronos.Data.Scheduling;
using Chronos.Server.Api;
using Chronos.Server.Configuration;
using Chronos.Server.Events;
using Chronos.Server.Jobs;
using Chronos.Server.Security;
using Chronos.Server.Storage;
namespace Chronos.Server.Hosting;
/// <summary>
/// What Chronos Desktop lends the server it hosts to share this PC's library (owner review 5, #67): its index, archive and
/// processing services, job engine and running scheduler, and the archive it serves. The server uses them and never
/// creates, starts, stops, replaces or disposes any of them.
/// </summary>
public sealed record HostedEngine(ChronosDatabase Database, ArchiveService Archives, ProcessingService Processing, JobEngine Engine, Scheduler Scheduler,
Archive Archive);
/// <summary>
/// The server Chronos Desktop runs in its own process while it shares this PC's library (owner review 5, #67), built by
/// <see cref="ServerHost.BuildHosted"/>: start, stop, and what the desktop shows of it (fingerprint, id, ports, the clients
/// of the last minutes, the first administrator's temporary password); and the way the desktop's own engines tell its
/// clients of what they change (<see cref="SequenceChangedAsync"/>, <see cref="ProjectsChangedAsync"/>).
/// </summary>
public sealed class HostedServer : IAsyncDisposable
{
private readonly WebApplication _app;
private readonly ServerLogging _logging;
private int _started;
private int _disposed;
internal HostedServer(WebApplication app, ServerOptions options, ServerState state, ServerLogging logging)
{
_app = app;
_logging = logging;
Options = options;
State = state;
var jobs = app.Services.GetRequiredService<JobEngineHost>();
jobs.ChangedOutside += job => JobChangedOutside?.Invoke(job);
}
public ServerOptions Options { get; }
internal ServerState State { get; }
public IServiceProvider Services => _app.Services;
/// <summary>SHA-256 fingerprint of the certificate, colon hex, as clients see it the first time they connect.</summary>
public string? Fingerprint => State.TlsFingerprint;
/// <summary>The server's stable id (<see cref="Protocol.ServerInfo.ServerId"/>), kept in the desktop's index.</summary>
public Guid? ServerId => State.ServerId;
/// <summary>The events connected clients receive.</summary>
public EventHub Events => _app.Services.GetRequiredService<EventHub>();
/// <summary>The programs that used the server in the last minutes.</summary>
public ClientActivity Clients => _app.Services.GetRequiredService<ClientActivity>();
/// <summary>A render node changed a job's state, outside the desktop's engine.</summary>
public event Action<Job>? JobChangedOutside;
/// <summary>The port the HTTP listener got (the configured one, or the system's choice for 0); 0 before the start.</summary>
public int HttpPort { get; private set; }
/// <summary>The port the HTTPS listener got; 0 before the start or without a certificate.</summary>
public int HttpsPort { get; private set; }
/// <summary>The file that holds the first administrator's temporary password until it is changed.</summary>
public string AdminPasswordFile => Path.Combine(Options.DataPath, AdminBootstrap.PasswordFileName);
/// <summary>The first administrator's temporary password while its file exists; null once an administrator set their own.</summary>
public string? AdminPassword()
{
try
{
return File.Exists(AdminPasswordFile) ? File.ReadAllText(AdminPasswordFile).Trim() : null;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return null;
}
}
/// <summary>Listens and starts the server's own services; a port in use throws (<see cref="IOException"/>).</summary>
public async Task StartAsync(CancellationToken cancellationToken = default)
{
if (Interlocked.Exchange(ref _started, 1) == 1) return;
await _app.StartAsync(cancellationToken).ConfigureAwait(false);
foreach (var address in _app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()?.Addresses ?? [])
{
if (!Uri.TryCreate(address.Replace("[::]", "localhost", StringComparison.Ordinal).Replace("0.0.0.0", "localhost", StringComparison.Ordinal),
UriKind.Absolute, out var uri))
continue;
if (uri.Scheme == Uri.UriSchemeHttps) HttpsPort = uri.Port;
else if (uri.Scheme == Uri.UriSchemeHttp) HttpPort = uri.Port;
}
}
/// <summary>Stops listening and the server's own services; the desktop's engines run on.</summary>
public async Task StopAsync(CancellationToken cancellationToken = default)
{
if (Volatile.Read(ref _started) == 0) return;
await _app.StopAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>The desktop saved its settings: the parallelism, the priority queue, the language and the logs apply at once.</summary>
public void ApplyDesktop(HostedSettings desktop)
{
Options.ApplyDesktop(desktop);
_logging.Apply(Options);
}
/// <summary>The desktop's archive or processing service changed or made sequence <paramref name="id"/>: clients are told.</summary>
public Task SequenceChangedAsync(Guid id, string change, CancellationToken cancellationToken) =>
ServerEventBridge.SequenceChangedAsync(Services.GetRequiredService<ChronosDatabase>(), Events, Services.GetService<ProjectCatchUp>(), id, change,
cancellationToken);
/// <summary>The desktop's archive service changed a sequence's projects: clients are told.</summary>
public Task ProjectsChangedAsync(ProjectChangeSet changed, CancellationToken cancellationToken) =>
ServerEventBridge.ProjectsChangedAsync(Services.GetRequiredService<ChronosDatabase>(), Events, changed, cancellationToken);
/// <summary>The <c>uploads</c> clean-up step of the server: abandoned uploads and old upload records (the upload-cleanup schedule).</summary>
public Task<string> SweepUploadsAsync(CleanupContext context, CleanupParameters parameters) =>
Services.GetRequiredService<UploadCleanupStep>().RunAsync(context, parameters);
/// <summary>The render nodes online now, by name.</summary>
public async Task<IReadOnlyList<string>> RenderNodesAsync(CancellationToken cancellationToken)
{
var since = DateTimeOffset.UtcNow - TimeSpan.FromSeconds(Options.NodeTimeoutSeconds);
var nodes = await Services.GetRequiredService<ChronosDatabase>().RenderNodes.ListOnlineAsync(since, cancellationToken).ConfigureAwait(false);
return [.. nodes.Select(n => n.ClientName)];
}
public async ValueTask DisposeAsync()
{
if (Interlocked.Exchange(ref _disposed, 1) == 1) return;
try
{
await StopAsync(CancellationToken.None).ConfigureAwait(false);
}
finally
{
await _app.DisposeAsync().ConfigureAwait(false);
}
}
}
/// <summary>
/// The lifetime of the server Chronos Desktop hosts (owner review 5, #67): the desktop starts and stops it, so nothing hooks
/// Ctrl+C, the process's exit or a termination signal, as the console lifetime would.
/// </summary>
internal sealed class DesktopHostLifetime : IHostLifetime
{
public Task WaitForStartAsync(CancellationToken cancellationToken) => Task.CompletedTask;
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
@@ -1,17 +1,11 @@
namespace Chronos.Server.Hosting; namespace Chronos.Server.Hosting;
/// <summary>What <c>Chronos.Server</c> was asked to do.</summary> /// <summary>What <c>Chronos.Server.Host</c> was asked to do.</summary>
public enum ServerCommand public enum ServerCommand
{ {
/// <summary>Run in the console (Docker, Linux, development).</summary> /// <summary>Run in the console (Docker, Linux, development).</summary>
Run, Run,
/// <summary>Run under the Windows Service Control Manager (the command line the installed service uses).</summary>
Service,
InstallService,
UninstallService,
/// <summary>Probe <c>/health</c> of the local server and exit 0/1 (container health check).</summary> /// <summary>Probe <c>/health</c> of the local server and exit 0/1 (container health check).</summary>
HealthCheck, HealthCheck,
@@ -24,12 +18,9 @@ public sealed record ServerCommandLine(ServerCommand Command, IReadOnlyList<stri
public const string Usage = """ public const string Usage = """
Chronos Server — time-lapse archive, uploads, jobs and rendering. Chronos Server — time-lapse archive, uploads, jobs and rendering.
Usage: Chronos.Server [--service | --install-service | --uninstall-service | --healthcheck | --help] Usage: Chronos.Server.Host [--healthcheck | --help]
(no switch) run in the console until Ctrl+C (no switch) run in the console until Ctrl+C
--service run under the Windows Service Control Manager
--install-service register the "ChronosServer" Windows service (automatic start, LocalSystem)
--uninstall-service stop and remove the Windows service
--healthcheck exit 0 when the local server answers /health, 1 otherwise --healthcheck exit 0 when the local server answers /health, 1 otherwise
Configuration: /data/server.json (CHRONOS_DATA_PATH) overridden by environment variables: Configuration: /data/server.json (CHRONOS_DATA_PATH) overridden by environment variables:
@@ -72,9 +63,6 @@ public sealed record ServerCommandLine(ServerCommand Command, IReadOnlyList<stri
{ {
ServerCommand? parsed = arg switch ServerCommand? parsed = arg switch
{ {
"--service" => ServerCommand.Service,
"--install-service" => ServerCommand.InstallService,
"--uninstall-service" => ServerCommand.UninstallService,
"--healthcheck" => ServerCommand.HealthCheck, "--healthcheck" => ServerCommand.HealthCheck,
"--help" or "-h" or "-?" or "/?" => ServerCommand.Help, "--help" or "-h" or "-?" or "/?" => ServerCommand.Help,
_ => null, _ => null,
+140 -22
View File
@@ -16,12 +16,13 @@ using Chronos.Server.Storage;
namespace Chronos.Server.Hosting; namespace Chronos.Server.Hosting;
/// <summary> /// <summary>
/// Builds the Chronos Server web application from <see cref="ServerOptions"/> (used by Program, the Windows service /// Builds the Chronos Server web application from <see cref="ServerOptions"/> (used by Chronos.Server.Host's Program and
/// host and tests). The archive module plugs in through the <c>configureServices</c> callback of <see cref="Build"/>, /// tests). The archive module plugs in through the <c>configureServices</c> callback of <see cref="Build"/>,
/// which runs before the server's own registrations: it must register <see cref="IArchiveIngest"/> and /// which runs before the server's own registrations: it must register <see cref="IArchiveIngest"/> and
/// <see cref="IFrameAssetLocator"/> (the server refuses to start without them), may add /// <see cref="IFrameAssetLocator"/> (the server refuses to start without them), may add
/// <see cref="Chronos.Data.Jobs.IJobHandler"/>s, and may resolve <see cref="ChronosDatabase"/>, <see cref="ServerArchive"/> /// <see cref="Chronos.Data.Jobs.IJobHandler"/>s, and may resolve <see cref="ChronosDatabase"/>, <see cref="ServerArchive"/>
/// and <see cref="ServerOptions"/> from DI in its factories. /// and <see cref="ServerOptions"/> from DI in its factories. <see cref="BuildHosted"/> builds the same server over the index,
/// engines and scheduler of Chronos Desktop, which shares its library with it (owner review 5, #67).
/// </summary> /// </summary>
public static class ServerHost public static class ServerHost
{ {
@@ -58,21 +59,10 @@ public static class ServerHost
{ {
TlsFingerprint = certificate is null ? null : CertificateStore.Fingerprint(certificate), TlsFingerprint = certificate is null ? null : CertificateStore.Fingerprint(certificate),
Database = ServerDatabase.DescribeAsync(database, CancellationToken.None).GetAwaiter().GetResult(), Database = ServerDatabase.DescribeAsync(database, CancellationToken.None).GetAwaiter().GetResult(),
ServerId = ServerIdAsync(database, bootLogger, CancellationToken.None).GetAwaiter().GetResult(),
}; };
builder.WebHost.ConfigureKestrel(k => ConfigureKestrel(builder, options, certificate);
{
k.AddServerHeader = false;
k.Limits.MaxRequestBodySize = JsonBodyLimit;
k.Limits.RequestHeadersTimeout = TimeSpan.FromSeconds(30);
k.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(2);
k.ListenAnyIP(options.HttpPort);
if (certificate is not null) k.ListenAnyIP(options.HttpsPort, l =>
{
l.Protocols = HttpProtocols.Http1AndHttp2;
l.UseHttps(certificate);
});
});
ConfigureServices(builder.Services, options, state, database, archive); ConfigureServices(builder.Services, options, state, database, archive);
var app = builder.Build(); var app = builder.Build();
@@ -117,8 +107,110 @@ public static class ServerHost
} }
} }
/// <summary>The single composition root of the server's services.</summary> /// <summary>
public static void ConfigureServices(IServiceCollection services, ServerOptions options, ServerState state, ChronosDatabase database, ServerArchive archive) /// The server Chronos Desktop runs in its own process to share this PC's library (owner review 5, #67): the same API, admin
/// panel, accounts, TLS, discovery, uploads, sync, events and render nodes as a server of its own, over the desktop's
/// index, archive service, processing service, job engine and scheduler (<paramref name="engine"/>), which it never
/// creates, starts, stops or disposes. Its own state is in <see cref="ServerOptions.DataPath"/> (made private first);
/// the first administrator is made there as on a new server. It sets no process-wide log sink or level and hooks no
/// console signal: the desktop's stay. Runs synchronously: call it off the UI thread.
/// </summary>
public static HostedServer BuildHosted(ServerOptions options, HostedEngine engine)
{
ArgumentNullException.ThrowIfNull(options);
ArgumentNullException.ThrowIfNull(engine);
if (!options.Hosted) throw new ArgumentException("The options are not those of a hosted server (ServerOptions.ForHosted).", nameof(options));
DataFolderAccess.Restrict(options.DataPath);
Directory.CreateDirectory(options.LogPath);
Directory.CreateDirectory(options.UploadsPath);
// The desktop's command line and environment are not the server's.
var builder = WebApplication.CreateSlimBuilder(new WebApplicationOptions { Args = [], ContentRootPath = AppContext.BaseDirectory });
var logging = new ServerLogging(options, setsEngineLevel: false);
logging.AddTo(builder.Logging);
builder.Services.AddSingleton(logging);
var bootLogger = new FileLoggerProvider(logging).CreateLogger("Chronos.Server");
var certificate = CertificateStore.Load(options, bootLogger);
AdminBootstrap.RunAsync(engine.Database, options, TimeProvider.System, bootLogger, CancellationToken.None).GetAwaiter().GetResult();
var state = new ServerState
{
TlsFingerprint = certificate is null ? null : CertificateStore.Fingerprint(certificate),
Database = ServerDatabase.DescribeAsync(engine.Database, CancellationToken.None).GetAwaiter().GetResult(),
ServerId = ServerIdAsync(engine.Database, bootLogger, CancellationToken.None).GetAwaiter().GetResult(),
};
var archive = ServerArchive.ForArchive(engine.Archive);
ConfigureKestrel(builder, options, certificate);
ConfigureServices(builder.Services, options, state, engine.Database, archive, engine);
var app = builder.Build();
ConfigurePipeline(app, options);
app.Logger.LogInformation("Chronos Server {Version} in Chronos Desktop · archive {Archive} · data {Data} · TLS {Tls}{Fingerprint}",
SystemEndpoints.Version, archive.Root, options.DataPath, options.TlsMode,
state.TlsFingerprint is null ? string.Empty : " · SHA-256 " + state.TlsFingerprint);
if (archive.Structure is { IsComplete: false } structure)
app.Logger.LogWarning("The archive's folders are incomplete: {Problem} {Detail}", structure.Message, structure.Detail ?? string.Empty);
return new HostedServer(app, options, state, logging);
}
/// <summary>Kestrel on every interface: the HTTP port, and the HTTPS port with HTTP/2 when there is a certificate.</summary>
private static void ConfigureKestrel(WebApplicationBuilder builder, ServerOptions options, System.Security.Cryptography.X509Certificates.X509Certificate2? certificate) =>
builder.WebHost.ConfigureKestrel(k =>
{
k.AddServerHeader = false;
k.Limits.MaxRequestBodySize = JsonBodyLimit;
k.Limits.RequestHeadersTimeout = TimeSpan.FromSeconds(30);
k.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(2);
k.ListenAnyIP(options.HttpPort);
if (certificate is not null) k.ListenAnyIP(options.HttpsPort, l =>
{
l.Protocols = HttpProtocols.Http1AndHttp2;
l.UseHttps(certificate);
});
});
/// <summary>The app setting that holds the server's stable id (<see cref="ServerInfo.ServerId"/>).</summary>
public const string ServerIdKey = "server.id";
/// <summary>
/// The server's stable id (owner review 5, #66): read from its database's app settings (<see cref="ServerIdKey"/>), or made
/// once (a version 7 UUID) and stored there at the first start. It lives in the database, so a restore keeps it and the
/// server keeps its id whatever address, port or name it is reached by. A value that does not read as an id is kept aside
/// in the log and replaced.
/// </summary>
public static async Task<Guid> ServerIdAsync(ChronosDatabase database, ILogger? logger, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(database);
var json = await database.Settings.GetJsonAsync(Data.Repositories.SettingScope.App, null, ServerIdKey, cancellationToken).ConfigureAwait(false);
if (json is not null)
{
try
{
using var stored = System.Text.Json.JsonDocument.Parse(json);
if (stored.RootElement.ValueKind == System.Text.Json.JsonValueKind.String && Guid.TryParse(stored.RootElement.GetString(), out var known)
&& known != Guid.Empty)
return known;
}
catch (System.Text.Json.JsonException)
{
// Replaced below; the old value is logged.
}
logger?.LogWarning("The server id stored in the database ({Value}) is not an id; a new one is made", json);
}
var id = Guid.CreateVersion7();
await database.Settings.SetJsonAsync(Data.Repositories.SettingScope.App, null, ServerIdKey, "\"" + id.ToString("D") + "\"", cancellationToken)
.ConfigureAwait(false);
logger?.LogInformation("Server id {Id} made", id);
return id;
}
/// <summary>
/// The single composition root of the server's services; with <paramref name="hosted"/>, those of the library Chronos
/// Desktop shares, whose engines, engine and scheduler are the desktop's (owner review 5, #67).
/// </summary>
public static void ConfigureServices(IServiceCollection services, ServerOptions options, ServerState state, ChronosDatabase database, ServerArchive archive,
HostedEngine? hosted = null)
{ {
services.AddSingleton(options); services.AddSingleton(options);
services.AddSingleton(state); services.AddSingleton(state);
@@ -129,7 +221,9 @@ public static class ServerHost
services.TryAddSingleton<VolumeSpace>(); services.TryAddSingleton<VolumeSpace>();
services.ConfigureHttpJsonOptions(j => j.SerializerOptions.TypeInfoResolverChain.Insert(0, ProtocolJson.Default)); services.ConfigureHttpJsonOptions(j => j.SerializerOptions.TypeInfoResolverChain.Insert(0, ProtocolJson.Default));
services.Configure<RouteHandlerOptions>(o => o.ThrowOnBadRequest = true); services.Configure<RouteHandlerOptions>(o => o.ThrowOnBadRequest = true);
services.Configure<HostOptions>(o => o.ShutdownTimeout = TimeSpan.FromSeconds(30)); // The desktop's exit waits for everything it runs: the server it hosts stops within a few seconds.
services.Configure<HostOptions>(o => o.ShutdownTimeout = TimeSpan.FromSeconds(hosted is null ? 30 : 5));
if (hosted is not null) RegisterHosted(services, hosted);
if (options.TlsMode == TlsMode.Proxy) if (options.TlsMode == TlsMode.Proxy)
{ {
// Only the configured proxies may say who the client is: a client that reaches the HTTP port directly would // Only the configured proxies may say who the client is: a client that reaches the HTTP port directly would
@@ -156,18 +250,24 @@ public static class ServerHost
services.AddSingleton<SequenceJobs>(); services.AddSingleton<SequenceJobs>();
services.AddSingleton<PlanCache>(); services.AddSingleton<PlanCache>();
services.AddSingleton<RenderNodeService>(); services.AddSingleton<RenderNodeService>();
services.AddSingleton<JobEngineHost>(); services.AddSingleton<ClientActivity>();
if (hosted is null) services.AddSingleton<JobEngineHost>();
else services.AddSingleton(sp => new JobEngineHost(hosted.Engine, sp.GetRequiredService<EventHub>(), sp.GetRequiredService<TimeProvider>()));
services.AddHostedService(sp => sp.GetRequiredService<JobEngineHost>()); services.AddHostedService(sp => sp.GetRequiredService<JobEngineHost>());
// After the engine's host: the scheduler queues on its engine, starts after it and stops before it (owner review 2, R10). // After the engine's host: the scheduler queues on its engine, starts after it and stops before it (owner review 2, R10).
services.AddSingleton<ServerScheduleHost>(); services.AddSingleton<ServerScheduleHost>();
services.AddSingleton<SchedulerHost>(); if (hosted is null) services.AddSingleton<SchedulerHost>();
else services.AddSingleton(sp => new SchedulerHost(database, hosted.Scheduler, sp.GetRequiredService<ServerScheduleHost>(), options,
sp.GetRequiredService<EventHub>(), sp.GetRequiredService<TimeProvider>(), sp.GetRequiredService<ILogger<SchedulerHost>>()));
services.AddHostedService(sp => sp.GetRequiredService<SchedulerHost>()); services.AddHostedService(sp => sp.GetRequiredService<SchedulerHost>());
services.AddSingleton<RenderNodeMonitor>(); services.AddSingleton<RenderNodeMonitor>();
services.AddHostedService(sp => sp.GetRequiredService<RenderNodeMonitor>()); services.AddHostedService(sp => sp.GetRequiredService<RenderNodeMonitor>());
// Recovers interrupted commits at start; its sweep is the clean-up step of the upload-cleanup schedule. // Recovers interrupted commits at start; its sweep is the clean-up step of the upload-cleanup schedule.
services.AddSingleton<UploadMaintenance>(); services.AddSingleton<UploadMaintenance>();
services.AddHostedService(sp => sp.GetRequiredService<UploadMaintenance>()); services.AddHostedService(sp => sp.GetRequiredService<UploadMaintenance>());
services.AddSingleton<ICleanupStep, UploadCleanupStep>(); // The desktop's archive service holds a step of its own that runs this one while it shares its library.
services.AddSingleton<UploadCleanupStep>();
services.AddSingleton<ICleanupStep>(sp => sp.GetRequiredService<UploadCleanupStep>());
// Main takes settings written outside the projects soon after they are (owner review 2, R8). // Main takes settings written outside the projects soon after they are (owner review 2, R8).
services.AddSingleton<ProjectCatchUp>(); services.AddSingleton<ProjectCatchUp>();
services.AddHostedService(sp => sp.GetRequiredService<ProjectCatchUp>()); services.AddHostedService(sp => sp.GetRequiredService<ProjectCatchUp>());
@@ -175,6 +275,22 @@ public static class ServerHost
services.AddHostedService(sp => sp.GetRequiredService<DiscoveryBeaconService>()); services.AddHostedService(sp => sp.GetRequiredService<DiscoveryBeaconService>());
} }
/// <summary>
/// The desktop's engines as the archive and processing modules would register them, and a lifetime that hooks no console
/// signal of the desktop's process (owner review 5, #67).
/// </summary>
private static void RegisterHosted(IServiceCollection services, HostedEngine hosted)
{
services.AddSingleton(hosted);
services.AddSingleton(hosted.Archives);
services.AddSingleton<IArchiveIngest>(hosted.Archives.Ingest);
services.AddSingleton<Chronos.Data.Videos.IVideoLibrary>(hosted.Archives.Videos);
services.AddSingleton<IFrameAssetLocator, ArchiveAssetLocator>();
services.AddSingleton(hosted.Processing);
services.AddSingleton<RenderNodeAvailability>();
services.AddSingleton<IHostLifetime, DesktopHostLifetime>();
}
private static void ConfigurePipeline(WebApplication app, ServerOptions options) private static void ConfigurePipeline(WebApplication app, ServerOptions options)
{ {
if (options.TlsMode == TlsMode.Proxy) app.UseForwardedHeaders(); if (options.TlsMode == TlsMode.Proxy) app.UseForwardedHeaders();
@@ -185,6 +301,8 @@ public static class ServerHost
AdminPanel.Map(app, options); AdminPanel.Map(app, options);
var api = app.MapGroup("/api/v1"); var api = app.MapGroup("/api/v1");
// A sequence, frame, render or video of another archive of the index answers as an unknown id (owner review 5, #67).
api.AddEndpointFilter(ServedItems.FilterAsync);
SystemEndpoints.Map(app, api); SystemEndpoints.Map(app, api);
AuthEndpoints.Map(api); AuthEndpoints.Map(api);
UserEndpoints.Map(api); UserEndpoints.Map(api);
+11 -2
View File
@@ -33,12 +33,21 @@ public sealed class ServerLogging
private volatile MsLogLevel _console; private volatile MsLogLevel _console;
/// <summary>Opens the log files of <paramref name="options"/> and applies its levels (call once the data folder is prepared).</summary> /// <summary>Opens the log files of <paramref name="options"/> and applies its levels (call once the data folder is prepared).</summary>
public ServerLogging(ServerOptions options) /// <param name="options">The server's settings.</param>
/// <param name="setsEngineLevel">
/// Whether the levels also set the engine's <see cref="Log.MinimumLevel"/>: false when Chronos Desktop hosts the server
/// (owner review 5, #67), whose own log settings keep it.
/// </param>
public ServerLogging(ServerOptions options, bool setsEngineLevel = true)
{ {
SetsEngineLevel = setsEngineLevel;
Sink = new FileLogSink(options.LogPath, "server", FileOptions(options)); Sink = new FileLogSink(options.LogPath, "server", FileOptions(options));
Apply(options); Apply(options);
} }
/// <summary>The levels set the process's <see cref="Log.MinimumLevel"/> too (a server of its own, not one Chronos Desktop hosts).</summary>
public bool SetsEngineLevel { get; }
public FileLogSink Sink { get; } public FileLogSink Sink { get; }
public MsLogLevel FileLevel => _file; public MsLogLevel FileLevel => _file;
@@ -63,7 +72,7 @@ public sealed class ServerLogging
_file = options.LogLevel; _file = options.LogLevel;
_console = options.ConsoleLogLevel; _console = options.ConsoleLogLevel;
Sink.Configure(FileOptions(options)); Sink.Configure(FileOptions(options));
Log.MinimumLevel = Core(options.LogLevel < options.ConsoleLogLevel ? options.LogLevel : options.ConsoleLogLevel); if (SetsEngineLevel) Log.MinimumLevel = Core(options.LogLevel < options.ConsoleLogLevel ? options.LogLevel : options.ConsoleLogLevel);
} }
public static LogFileOptions FileOptions(ServerOptions options) => new() public static LogFileOptions FileOptions(ServerOptions options) => new()
@@ -1,58 +0,0 @@
using System.Runtime.Versioning;
using static Chronos.Server.Hosting.Windows.ServiceNative;
namespace Chronos.Server.Hosting.Windows;
/// <summary>
/// Errors of the Windows service in the Application event log (source <c>ChronosServer</c>). A service has no console,
/// and a start-up failure comes before the server's log file exists (the data folder that holds it may be the very
/// thing refused), so Event Viewer is where an operator finds why the service stopped. The source is not registered
/// with a message file: Event Viewer says it found no description for the event, then shows the text whole.
/// </summary>
internal static unsafe class ServiceEventLog
{
public const uint StartFailed = 1;
public const uint StopFailed = 2;
/// <summary>ReportEvent takes at most 31,839 characters per string.</summary>
public const int MaxLength = 31_839;
/// <summary>
/// The event text: <paramref name="what"/> and the reason the server gave (the entry to check, for a refused data
/// folder), then the exception for a bug report; cut to <see cref="MaxLength"/>.
/// </summary>
public static string Describe(string what, Exception exception)
{
var text = $"{what} {exception.Message}{Environment.NewLine}{Environment.NewLine}{exception}";
if (text.Length <= MaxLength) return text;
var cut = MaxLength - 1;
// Never half a surrogate pair.
if (char.IsHighSurrogate(text[cut - 1])) cut--;
return string.Concat(text.AsSpan(0, cut), "…");
}
/// <summary>Writes an error event; false when the event log could not be written (the console still gets it).</summary>
[SupportedOSPlatform("windows")]
public static bool Error(uint eventId, string text) => Error(WindowsServiceHost.ServiceName, eventId, text);
/// <summary><see cref="Error(uint, string)"/> as <paramref name="sourceName"/> (tests write as their own source).</summary>
[SupportedOSPlatform("windows")]
internal static bool Error(string sourceName, uint eventId, string text)
{
var source = RegisterEventSourceW(null, sourceName);
if (source == 0) return false;
try
{
fixed (char* chars = text.Length <= MaxLength ? text : text[..MaxLength])
{
var strings = stackalloc char*[1];
strings[0] = chars;
return ReportEventW(source, EventLogErrorType, 0, eventId, 0, 1, 0, strings, null);
}
}
finally
{
DeregisterEventSource(source);
}
}
}
@@ -1,160 +0,0 @@
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Principal;
using Chronos.Core.Localization;
using static Chronos.Server.Hosting.Windows.ServiceNative;
namespace Chronos.Server.Hosting.Windows;
/// <summary>
/// <c>--install-service</c> / <c>--uninstall-service</c>: registers the server with the Service Control Manager
/// (automatic start, LocalSystem, command line <c>"…\Chronos.Server.exe" --service</c>) or stops and removes it.
/// Both need an elevated prompt; failures surface as <see cref="Win32Exception"/>. A LocalSystem service runs whatever
/// sits at its image path, so it is registered only from a copy under Program Files that nobody but SYSTEM,
/// Administrators and TrustedInstaller can change: a per-user install or a zip unpacked elsewhere would hand SYSTEM to
/// any program of that user. Otherwise <see cref="Install"/> refuses with <see cref="InvalidOperationException"/>.
/// </summary>
[SupportedOSPlatform("windows")]
public static unsafe class ServiceInstaller
{
private const string DisplayName = "Chronos Server";
/// <summary>TrustedInstaller, the owner of Windows' own files under Program Files.</summary>
private static readonly SecurityIdentifier TrustedInstaller = new("S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464");
/// <exception cref="InvalidOperationException">This copy is not in a folder that only administrators can change.</exception>
public static void Install()
{
if (UnsafeLocation() is { } problem) throw new InvalidOperationException(problem);
var manager = OpenSCManagerW(null, null, ScManagerConnect | ScManagerCreateService);
if (manager == 0) throw new Win32Exception(Marshal.GetLastPInvokeError());
try
{
var service = CreateServiceW(manager, WindowsServiceHost.ServiceName, DisplayName, ServiceAllAccess, ServiceWin32OwnProcess, ServiceAutoStart,
ServiceErrorNormal, CommandLine(), null, 0, null, null, null);
if (service == 0) throw new Win32Exception(Marshal.GetLastPInvokeError());
try
{
fixed (char* text = Loc.L("Server.Service.Description"))
{
var description = new ServiceDescription { Description = text };
ChangeServiceConfig2W(service, ServiceConfigDescription, &description);
}
}
finally
{
CloseServiceHandle(service);
}
}
finally
{
CloseServiceHandle(manager);
}
}
public static void Uninstall()
{
var manager = OpenSCManagerW(null, null, ScManagerConnect);
if (manager == 0) throw new Win32Exception(Marshal.GetLastPInvokeError());
try
{
var service = OpenServiceW(manager, WindowsServiceHost.ServiceName, Delete | ServiceStop | ServiceQueryStatus);
if (service == 0) throw new Win32Exception(Marshal.GetLastPInvokeError());
try
{
ServiceStatus status;
if (!ControlService(service, ControlStop, &status) && Marshal.GetLastPInvokeError() is var stopError && stopError != ErrorServiceNotActive)
throw new Win32Exception(stopError);
if (!DeleteService(service) && Marshal.GetLastPInvokeError() is var deleteError && deleteError != ErrorServiceMarkedForDelete)
throw new Win32Exception(deleteError);
}
finally
{
CloseServiceHandle(service);
}
}
finally
{
CloseServiceHandle(manager);
}
}
/// <summary>
/// Why this copy may not be registered, as a localized sentence, or null when it may: the program folder (and, when
/// run by <c>dotnet</c>, the host's folder) must be inside Program Files and changeable only by administrators.
/// </summary>
internal static string? UnsafeLocation()
{
var program = Path.TrimEndingDirectorySeparator(AppContext.BaseDirectory);
if (!IsUnderProgramFiles(program)) return Loc.L("Server.Service.NotProgramFiles", program);
if (FindChangeable(new DirectoryInfo(program), recursive: true) is { } open) return Loc.L("Server.Service.Writable", open);
// Under dotnet the host runs as SYSTEM too; its folder is checked without the thousands of framework files below it.
if (Environment.ProcessPath is { } process && Path.GetDirectoryName(process) is { } host
&& !string.Equals(Path.TrimEndingDirectorySeparator(host), program, StringComparison.OrdinalIgnoreCase))
{
if (!IsUnderProgramFiles(host)) return Loc.L("Server.Service.NotProgramFiles", host);
if (FindChangeable(new DirectoryInfo(host), recursive: false) is { } hostOpen) return Loc.L("Server.Service.Writable", hostOpen);
}
return null;
}
/// <summary>True for a path inside <c>%ProgramFiles%</c> or <c>%ProgramFiles(x86)%</c> (not the folder itself).</summary>
internal static bool IsUnderProgramFiles(string path)
{
var full = Path.GetFullPath(path);
foreach (var folder in new[] { Environment.SpecialFolder.ProgramFiles, Environment.SpecialFolder.ProgramFilesX86 })
{
var root = Environment.GetFolderPath(folder);
if (root.Length > 0 && full.StartsWith(Path.TrimEndingDirectorySeparator(root) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
/// <summary>
/// The first of the folder, its files and (when recursive) its subfolders whose ACL lets an account other than
/// SYSTEM, Administrators, TrustedInstaller or the registering administrator change it; null when there is none.
/// </summary>
internal static string? FindChangeable(DirectoryInfo folder, bool recursive) => FindChangeable(folder, recursive, TrustedAccounts());
private static string? FindChangeable(DirectoryInfo folder, bool recursive, HashSet<SecurityIdentifier> trusted)
{
if (DataFolderAccess.IsChangeableByOthers(folder.GetAccessControl(), trusted, checkOwner: false)) return folder.FullName;
foreach (var file in folder.EnumerateFiles())
{
if (DataFolderAccess.IsChangeableByOthers(file.GetAccessControl(), trusted, checkOwner: false)) return file.FullName;
}
if (!recursive) return null;
foreach (var child in folder.EnumerateDirectories())
{
if (FindChangeable(child, recursive: true, trusted) is { } path) return path;
}
return null;
}
private static HashSet<SecurityIdentifier> TrustedAccounts()
{
var trusted = new HashSet<SecurityIdentifier>
{
new(WellKnownSidType.LocalSystemSid, null),
new(WellKnownSidType.BuiltinAdministratorsSid, null),
TrustedInstaller,
};
// Registering needs an elevated prompt, so the account doing it is an administrator; setups often name it.
using var identity = WindowsIdentity.GetCurrent();
if (identity.User is { } user && new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator)) trusted.Add(user);
return trusted;
}
/// <summary>The service's command line: this executable (or <c>dotnet</c> plus this assembly) with <c>--service</c>.</summary>
private static string CommandLine()
{
var process = Environment.ProcessPath ?? throw new InvalidOperationException("The executable path is unknown.");
// Assembly.Location is empty in a single-file app; under dotnet the entry assembly sits in the base directory.
var assembly = Path.Combine(AppContext.BaseDirectory, typeof(ServiceInstaller).Assembly.GetName().Name + ".dll");
return Path.GetFileNameWithoutExtension(process).Equals("dotnet", StringComparison.OrdinalIgnoreCase)
? $"\"{process}\" \"{assembly}\" --service"
: $"\"{process}\" --service";
}
}
@@ -1,107 +0,0 @@
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
namespace Chronos.Server.Hosting.Windows;
/// <summary>Service Control Manager and event log functions of advapi32 (no Windows-only package needed).</summary>
[SupportedOSPlatform("windows")]
internal static unsafe partial class ServiceNative
{
public const uint ServiceWin32OwnProcess = 0x10;
public const uint ServiceAutoStart = 2;
public const uint ServiceErrorNormal = 1;
public const uint ScManagerConnect = 0x1;
public const uint ScManagerCreateService = 0x2;
public const uint ServiceAllAccess = 0xF01FF;
public const uint ServiceQueryStatus = 0x4;
public const uint ServiceStop = 0x20;
public const uint Delete = 0x10000;
public const uint ServiceConfigDescription = 1;
public const uint ControlStop = 1;
public const uint ControlInterrogate = 4;
public const uint ControlShutdown = 5;
public const int ErrorFailedServiceControllerConnect = 1063;
public const int ErrorServiceNotActive = 1062;
public const int ErrorServiceMarkedForDelete = 1072;
public const uint NoError = 0;
public const uint ErrorCallNotImplemented = 120;
public const uint ErrorExceptionInService = 1064;
public const ushort EventLogErrorType = 0x1;
[StructLayout(LayoutKind.Sequential)]
public struct ServiceStatus
{
public uint ServiceType;
public uint CurrentState;
public uint ControlsAccepted;
public uint Win32ExitCode;
public uint ServiceSpecificExitCode;
public uint CheckPoint;
public uint WaitHint;
}
[StructLayout(LayoutKind.Sequential)]
public struct ServiceTableEntry
{
public char* ServiceName;
public delegate* unmanaged[Stdcall]<uint, char**, void> ServiceProc;
}
[StructLayout(LayoutKind.Sequential)]
public struct ServiceDescription
{
public char* Description;
}
[LibraryImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool StartServiceCtrlDispatcherW(ServiceTableEntry* table);
[LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
public static partial nint RegisterServiceCtrlHandlerExW(string serviceName, delegate* unmanaged[Stdcall]<uint, uint, nint, nint, uint> handler, nint context);
[LibraryImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool SetServiceStatus(nint statusHandle, ServiceStatus* status);
[LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
public static partial nint OpenSCManagerW(string? machineName, string? databaseName, uint desiredAccess);
[LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
public static partial nint CreateServiceW(nint manager, string serviceName, string displayName, uint desiredAccess, uint serviceType, uint startType,
uint errorControl, string binaryPathName, string? loadOrderGroup, nint tagId, string? dependencies, string? serviceStartName, string? password);
[LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
public static partial nint OpenServiceW(nint manager, string serviceName, uint desiredAccess);
[LibraryImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool ChangeServiceConfig2W(nint service, uint infoLevel, void* info);
[LibraryImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool ControlService(nint service, uint control, ServiceStatus* status);
[LibraryImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool DeleteService(nint service);
[LibraryImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool CloseServiceHandle(nint handle);
[LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
public static partial nint RegisterEventSourceW(string? uncServerName, string sourceName);
[LibraryImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool ReportEventW(nint eventLog, ushort type, ushort category, uint eventId, nint userSid, ushort stringCount, uint dataSize,
char** strings, void* rawData);
[LibraryImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool DeregisterEventSource(nint eventLog);
}
@@ -1,68 +0,0 @@
namespace Chronos.Server.Hosting.Windows;
/// <summary>SERVICE_STATUS.dwCurrentState values the server reports.</summary>
public enum ServiceState : uint
{
Stopped = 1,
StartPending = 2,
StopPending = 3,
Running = 4,
}
/// <summary>One status report for <c>SetServiceStatus</c>.</summary>
public readonly record struct ServiceStatusReport(ServiceState State, uint ControlsAccepted, uint CheckPoint, uint WaitHintMilliseconds, uint ExitCode);
/// <summary>
/// The service's state machine and the rules of SERVICE_STATUS: no controls are accepted while pending, the check point
/// grows with every pending report and is zero otherwise, a stopped service carries its exit code.
/// </summary>
public sealed class ServiceStatusTracker
{
public const uint AcceptStop = 0x1;
public const uint AcceptShutdown = 0x4;
private readonly Lock _gate = new();
private uint _checkPoint;
public ServiceStatusReport Current { get; private set; } = new(ServiceState.Stopped, 0, 0, 0, 0);
public ServiceStatusReport StartPending(uint waitHintMilliseconds) => Pending(ServiceState.StartPending, waitHintMilliseconds, ServiceState.Stopped, ServiceState.StartPending);
public ServiceStatusReport Running()
{
lock (_gate)
{
Require(ServiceState.StartPending);
_checkPoint = 0;
return Current = new ServiceStatusReport(ServiceState.Running, AcceptStop | AcceptShutdown, 0, 0, 0);
}
}
/// <summary>Stopping from start-up or from running; repeating it reports progress (a higher check point).</summary>
public ServiceStatusReport StopPending(uint waitHintMilliseconds) =>
Pending(ServiceState.StopPending, waitHintMilliseconds, ServiceState.StartPending, ServiceState.Running, ServiceState.StopPending);
public ServiceStatusReport Stopped(uint exitCode)
{
lock (_gate)
{
_checkPoint = 0;
return Current = new ServiceStatusReport(ServiceState.Stopped, 0, 0, 0, exitCode);
}
}
private ServiceStatusReport Pending(ServiceState state, uint waitHintMilliseconds, params ServiceState[] from)
{
lock (_gate)
{
Require(from);
_checkPoint = Current.State == state ? _checkPoint + 1 : 1;
return Current = new ServiceStatusReport(state, 0, _checkPoint, waitHintMilliseconds, 0);
}
}
private void Require(params ServiceState[] allowed)
{
if (!allowed.Contains(Current.State)) throw new InvalidOperationException($"A service cannot go from {Current.State} to that state.");
}
}
@@ -1,121 +0,0 @@
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using static Chronos.Server.Hosting.Windows.ServiceNative;
namespace Chronos.Server.Hosting.Windows;
/// <summary>
/// Runs the server as a Windows service with the SCM API directly (StartServiceCtrlDispatcherW,
/// RegisterServiceCtrlHandlerExW, SetServiceStatus). Stop and shutdown requests stop the web host gracefully: running
/// jobs keep their checkpoints and resume at the next start. A failure to start or stop goes to the Application event
/// log (<see cref="ServiceEventLog"/>), since a service has no console.
/// </summary>
[SupportedOSPlatform("windows")]
public static class WindowsServiceHost
{
public const string ServiceName = "ChronosServer";
private const uint StartWaitHint = 60_000;
private const uint StopWaitHint = 35_000;
private static readonly ServiceStatusTracker Status = new();
private static Func<WebApplication>? _build;
private static WebApplication? _app;
private static nint _statusHandle;
/// <summary>
/// Hands the process to the Service Control Manager and returns when the service has stopped. False when the
/// process was not started by the SCM (for example from a console).
/// </summary>
public static unsafe bool Run(Func<WebApplication> build)
{
_build = build;
fixed (char* name = ServiceName)
{
var table = stackalloc ServiceTableEntry[2];
table[0] = new ServiceTableEntry { ServiceName = name, ServiceProc = &ServiceMain };
table[1] = default;
if (StartServiceCtrlDispatcherW(table)) return true;
}
var error = Marshal.GetLastPInvokeError();
if (error == ErrorFailedServiceControllerConnect) return false;
throw new Win32Exception(error);
}
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvStdcall)])]
private static unsafe void ServiceMain(uint argc, char** argv)
{
_statusHandle = RegisterServiceCtrlHandlerExW(ServiceName, &Handler, 0);
if (_statusHandle == 0) return;
Report(Status.StartPending(StartWaitHint));
try
{
_app = _build!();
_app.StartAsync().GetAwaiter().GetResult();
Report(Status.Running());
}
catch (Exception ex)
{
// A refused data folder or server.json says which entry to check; the SCM itself records only error 1064.
Console.Error.WriteLine(ex);
ServiceEventLog.Error(ServiceEventLog.StartFailed, ServiceEventLog.Describe("Chronos Server did not start:", ex));
Report(Status.Stopped(ErrorExceptionInService));
}
}
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvStdcall)])]
private static unsafe uint Handler(uint control, uint eventType, nint eventData, nint context)
{
switch (control)
{
case ControlStop or ControlShutdown:
if (Status.Current.State is ServiceState.Running or ServiceState.StartPending)
{
Report(Status.StopPending(StopWaitHint));
// The handler must return at once; the host stops on the thread pool.
_ = Task.Run(StopAsync);
}
return NoError;
case ControlInterrogate:
Report(Status.Current);
return NoError;
default:
return ErrorCallNotImplemented;
}
}
private static async Task StopAsync()
{
uint exitCode = 0;
try
{
if (_app is { } app)
{
await app.StopAsync();
await app.DisposeAsync();
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex);
ServiceEventLog.Error(ServiceEventLog.StopFailed, ServiceEventLog.Describe("Chronos Server did not stop cleanly:", ex));
exitCode = ErrorExceptionInService;
}
Report(Status.Stopped(exitCode));
}
private static unsafe void Report(ServiceStatusReport report)
{
var status = new ServiceStatus
{
ServiceType = ServiceWin32OwnProcess,
CurrentState = (uint)report.State,
ControlsAccepted = report.ControlsAccepted,
Win32ExitCode = report.ExitCode,
CheckPoint = report.CheckPoint,
WaitHint = report.WaitHintMilliseconds,
};
SetServiceStatus(_statusHandle, &status);
}
}
+69 -8
View File
@@ -15,18 +15,21 @@ namespace Chronos.Server.Jobs;
/// running one, in the order of the priority queue of the settings (owner review 1). Render jobs run here only when the registered render /// running one, in the order of the priority queue of the settings (owner review 1). Render jobs run here only when the registered render
/// handler accepts them (<see cref="ISelectiveJobHandler"/>: managed formats, and MP4 jobs no render node can take); /// handler accepts them (<see cref="ISelectiveJobHandler"/>: managed formats, and MP4 jobs no render node can take);
/// render nodes claim the others (BRIEF §14.5, §14.7). On shutdown running jobs stay marked running and are requeued from their checkpoints at the next start. /// render nodes claim the others (BRIEF §14.5, §14.7). On shutdown running jobs stay marked running and are requeued from their checkpoints at the next start.
/// When Chronos Desktop shares its library (owner review 5, #67) the engine is the desktop's own: this host relays it while the
/// server runs, never starts, stops or disposes it, and the jobs API shows only the kinds a server runs (<see cref="Exposes"/>):
/// the desktop's workspace, sync and download jobs stay its own.
/// Progress goes out through the <see cref="Gate"/> render nodes share, with what each job does now (owner review 5, #65). /// Progress goes out through the <see cref="Gate"/> render nodes share, with what each job does now (owner review 5, #65).
/// </summary> /// </summary>
public sealed class JobEngineHost : IHostedService public sealed class JobEngineHost : IHostedService
{ {
private readonly ChronosDatabase _db;
private readonly EventHub _events; private readonly EventHub _events;
private readonly HashSet<JobKind> _kinds; private readonly HashSet<JobKind> _kinds;
private readonly bool _ownsEngine = true;
private int _subscribed;
public JobEngineHost(ChronosDatabase db, IEnumerable<IJobHandler> handlers, IEnumerable<IJobHandlerProvider> providers, ServerOptions options, public JobEngineHost(ChronosDatabase db, IEnumerable<IJobHandler> handlers, IEnumerable<IJobHandlerProvider> providers, ServerOptions options,
EventHub events, TimeProvider time) EventHub events, TimeProvider time)
{ {
_db = db;
_events = events; _events = events;
Gate = new ProgressGate(time); Gate = new ProgressGate(time);
// A render handler must be selective: a plain one would take the jobs that need a render node's encoder. // A render handler must be selective: a plain one would take the jobs that need a render node's encoder.
@@ -39,8 +42,21 @@ public sealed class JobEngineHost : IHostedService
Kinds = _kinds, Kinds = _kinds,
PriorityQueue = () => ServerSettingsStore.PriorityQueue(options), PriorityQueue = () => ServerSettingsStore.PriorityQueue(options),
}); });
Engine.JobChanged += OnJobChanged; Subscribe();
Engine.Progress += OnProgress; }
/// <summary>
/// Relays <paramref name="engine"/>, an engine Chronos Desktop runs (owner review 5, #67), from <see cref="StartAsync"/> to
/// <see cref="StopAsync"/>; the engine stays the desktop's.
/// </summary>
public JobEngineHost(JobEngine engine, EventHub events, TimeProvider time)
{
ArgumentNullException.ThrowIfNull(engine);
_events = events;
Gate = new ProgressGate(time);
_ownsEngine = false;
_kinds = [];
Engine = engine;
} }
/// <summary>Node id stamped on jobs this server runs.</summary> /// <summary>Node id stamped on jobs this server runs.</summary>
@@ -51,15 +67,60 @@ public sealed class JobEngineHost : IHostedService
/// <summary>The pace of every job's progress events, the server's own jobs and render nodes' alike.</summary> /// <summary>The pace of every job's progress events, the server's own jobs and render nodes' alike.</summary>
public ProgressGate Gate { get; } public ProgressGate Gate { get; }
/// <summary>The engine is the one Chronos Desktop runs, which shares its library (owner review 5, #67).</summary>
public bool Hosted => !_ownsEngine;
/// <summary>True when a job of <paramref name="kind"/> has somewhere to run: a local handler, or render nodes for renders.</summary> /// <summary>True when a job of <paramref name="kind"/> has somewhere to run: a local handler, or render nodes for renders.</summary>
public bool CanRun(JobKind kind) => kind == JobKind.Render || _kinds.Contains(kind); public bool CanRun(JobKind kind) => kind == JobKind.Render || (_ownsEngine ? _kinds.Contains(kind) : Engine.CanRun(kind) && Exposes(kind));
public Task StartAsync(CancellationToken cancellationToken) => Engine.StartAsync(cancellationToken); /// <summary>
/// Whether the jobs API lists, shows and acts on jobs of <paramref name="kind"/>: every kind on a server of its own; on a
/// shared desktop library only the kinds a server runs (<see cref="ServerSettingsStore.Kinds"/>), so a client never sees or
/// cancels the desktop's own workspace, sync and download jobs (owner review 5, #67).
/// </summary>
public bool Exposes(JobKind kind) => _ownsEngine || ServerSettingsStore.Kinds.Contains(kind);
public async Task StopAsync(CancellationToken cancellationToken) => await Engine.DisposeAsync(); public Task StartAsync(CancellationToken cancellationToken)
{
if (_ownsEngine) return Engine.StartAsync(cancellationToken);
Subscribe();
return Task.CompletedTask;
}
public async Task StopAsync(CancellationToken cancellationToken)
{
if (_ownsEngine)
{
await Engine.DisposeAsync();
return;
}
// The desktop's engine runs on: only this server stops following it.
if (Interlocked.Exchange(ref _subscribed, 0) == 1)
{
Engine.JobChanged -= OnJobChanged;
Engine.Progress -= OnProgress;
}
}
private void Subscribe()
{
if (Interlocked.Exchange(ref _subscribed, 1) == 1) return;
Engine.JobChanged += OnJobChanged;
Engine.Progress += OnProgress;
}
/// <summary>
/// A job's state changed outside the engine (render nodes, cancellation of node jobs): Chronos Desktop's Jobs section
/// follows these as it follows its engine's own changes while it shares its library (owner review 5, #67).
/// </summary>
public event Action<Job>? ChangedOutside;
/// <summary>Publishes a state change made outside the engine (render nodes, cancellation of node jobs).</summary> /// <summary>Publishes a state change made outside the engine (render nodes, cancellation of node jobs).</summary>
public void Publish(Job job) => OnJobChanged(job); public void Publish(Job job)
{
OnJobChanged(job);
ChangedOutside?.Invoke(job);
}
private void OnJobChanged(Job job) private void OnJobChanged(Job job)
{ {
+57 -7
View File
@@ -19,7 +19,10 @@ namespace Chronos.Server.Jobs;
/// retention in force is the audit clean-up schedule's age limit, 0 while it is off or without its audit step: /// retention in force is the audit clean-up schedule's age limit, 0 while it is off or without its audit step:
/// Settings › Logs shows it (<see cref="AuditRetentionAsync"/>) and sets it (<see cref="ApplyAuditRetentionAsync"/>); /// Settings › Logs shows it (<see cref="AuditRetentionAsync"/>) and sets it (<see cref="ApplyAuditRetentionAsync"/>);
/// <see cref="ServerOptions.AuditRetentionDays"/> is only what the schedule is seeded and reset with, or what an environment /// <see cref="ServerOptions.AuditRetentionDays"/> is only what the schedule is seeded and reset with, or what an environment
/// variable fixes. Every schedule change and run goes out as a <see cref="ScheduleChangedEvent"/>. /// variable fixes. Every schedule change and run goes out as a <see cref="ScheduleChangedEvent"/>. On the library Chronos
/// Desktop shares (owner review 5, #67) the scheduler is the desktop's, already running: this host follows it while the
/// server runs, adds the server's own system schedules to it (<see cref="ServerScheduleHost.ShareSchedules"/>) and never
/// starts, seeds the desktop's schedules for or disposes it.
/// </summary> /// </summary>
public sealed class SchedulerHost : IHostedService public sealed class SchedulerHost : IHostedService
{ {
@@ -29,6 +32,10 @@ public sealed class SchedulerHost : IHostedService
private readonly CancellationTokenSource _stopping = new(); private readonly CancellationTokenSource _stopping = new();
private Task _startScan = Task.CompletedTask; private Task _startScan = Task.CompletedTask;
private Task _refresh = Task.CompletedTask; private Task _refresh = Task.CompletedTask;
private readonly bool _ownsScheduler = true;
private readonly Action<ScheduleDto> _changed;
private readonly Action<Guid> _deleted;
private readonly int _auditRetentionDays;
private int _stopped; private int _stopped;
public SchedulerHost(ChronosDatabase db, JobEngineHost jobs, ServerScheduleHost host, EventHub events, TimeProvider time, ILogger<SchedulerHost> logger) public SchedulerHost(ChronosDatabase db, JobEngineHost jobs, ServerScheduleHost host, EventHub events, TimeProvider time, ILogger<SchedulerHost> logger)
@@ -41,8 +48,31 @@ public sealed class SchedulerHost : IHostedService
Host = host; Host = host;
Scheduler = new Scheduler(db, jobs.Engine, new SchedulerOptions { Time = time }); Scheduler = new Scheduler(db, jobs.Engine, new SchedulerOptions { Time = time });
// The Scheduled tab of the admin panel follows them, the runs that queue no job included. // The Scheduled tab of the admin panel follows them, the runs that queue no job included.
Scheduler.ScheduleChanged += schedule => events.Publish(new ScheduleChangedEvent(schedule.Id, Deleted: false)); _changed = schedule => events.Publish(new ScheduleChangedEvent(schedule.Id, Deleted: false));
Scheduler.ScheduleDeleted += id => events.Publish(new ScheduleChangedEvent(id, Deleted: true)); _deleted = id => events.Publish(new ScheduleChangedEvent(id, Deleted: true));
Scheduler.ScheduleChanged += _changed;
Scheduler.ScheduleDeleted += _deleted;
}
/// <summary>
/// Follows <paramref name="scheduler"/>, the running scheduler of Chronos Desktop (owner review 5, #67), from
/// <see cref="StartAsync"/> to <see cref="StopAsync"/>.
/// </summary>
public SchedulerHost(ChronosDatabase db, Scheduler scheduler, ServerScheduleHost host, ServerOptions options, EventHub events, TimeProvider time,
ILogger<SchedulerHost> logger)
{
ArgumentNullException.ThrowIfNull(scheduler);
ArgumentNullException.ThrowIfNull(options);
ArgumentNullException.ThrowIfNull(events);
_db = db;
_time = time;
_logger = logger;
_ownsScheduler = false;
_auditRetentionDays = options.AuditRetentionDays;
Host = host;
Scheduler = scheduler;
_changed = schedule => events.Publish(new ScheduleChangedEvent(schedule.Id, Deleted: false));
_deleted = id => events.Publish(new ScheduleChangedEvent(id, Deleted: true));
} }
public Scheduler Scheduler { get; } public Scheduler Scheduler { get; }
@@ -51,10 +81,21 @@ public sealed class SchedulerHost : IHostedService
public async Task StartAsync(CancellationToken cancellationToken) public async Task StartAsync(CancellationToken cancellationToken)
{ {
var started = Scheduler.Options.Time.GetUtcNow();
await Scheduler.StartAsync(Host, ApplyLockedAgesAsync, cancellationToken);
var stopping = _stopping.Token; var stopping = _stopping.Token;
_startScan = Task.Run(() => ScanAtStartAsync(started, stopping), CancellationToken.None); if (!_ownsScheduler)
{
Scheduler.ScheduleChanged += _changed;
Scheduler.ScheduleDeleted += _deleted;
// The desktop seeds its own system schedules; the server's state brings two more (never overwritten once there).
if (await _db.Schedules.EnsureSystemAsync(ServerScheduleHost.ShareSchedules(_auditRetentionDays), _time.GetUtcNow(), cancellationToken) > 0)
Scheduler.Wake();
}
else
{
var started = Scheduler.Options.Time.GetUtcNow();
await Scheduler.StartAsync(Host, ApplyLockedAgesAsync, cancellationToken);
_startScan = Task.Run(() => ScanAtStartAsync(started, stopping), CancellationToken.None);
}
// Created here, so its first period counts from the start. // Created here, so its first period counts from the start.
var timer = new PeriodicTimer(TimeSpan.FromMinutes(ServerScheduleHost.ScanMinutes), _time); var timer = new PeriodicTimer(TimeSpan.FromMinutes(ServerScheduleHost.ScanMinutes), _time);
_refresh = Task.Run(() => RefreshArchiveAsync(timer, stopping), CancellationToken.None); _refresh = Task.Run(() => RefreshArchiveAsync(timer, stopping), CancellationToken.None);
@@ -66,7 +107,16 @@ public sealed class SchedulerHost : IHostedService
await _stopping.CancelAsync(); await _stopping.CancelAsync();
await _startScan; await _startScan;
await _refresh; await _refresh;
await Scheduler.DisposeAsync(); if (_ownsScheduler)
{
await Scheduler.DisposeAsync();
}
else
{
// The desktop's scheduler runs on: only this server stops following it.
Scheduler.ScheduleChanged -= _changed;
Scheduler.ScheduleDeleted -= _deleted;
}
_stopping.Dispose(); _stopping.Dispose();
} }
+17 -6
View File
@@ -66,13 +66,13 @@ public sealed class ServerScheduleHost : IScheduleHost
{ {
get get
{ {
var nightly = (Backup: new TimeOnly(3, 0), History: new TimeOnly(4, 0), Audit: new TimeOnly(4, 30)); var nightly = (Backup: new TimeOnly(3, 0), History: new TimeOnly(4, 0));
var share = ShareSchedules(_options.AuditRetentionDays);
var list = new List<SystemSchedule> var list = new List<SystemSchedule>
{ {
// A missed scan is not caught up: the next one comes within minutes and SchedulerHost scans once at start. // A missed scan is not caught up: the next one comes within minutes and SchedulerHost scans once at start.
new(ArchiveScan, "Archive scan", ScheduleActions.Scan, ScheduleRecurrence.Interval(ScanMinutes, RecurrenceUnit.Minutes), CatchUp: false), new(ArchiveScan, "Archive scan", ScheduleActions.Scan, ScheduleRecurrence.Interval(ScanMinutes, RecurrenceUnit.Minutes), CatchUp: false),
new(UploadCleanup, "Upload clean-up", ScheduleActions.Cleanup, ScheduleRecurrence.Interval(UploadSweepHours, RecurrenceUnit.Hours), share[0],
new ScheduleParametersDto(OlderThanDays: UploadMaintenance.FinishedRetentionDays, Steps: [UploadCleanupStep.StepName])),
}; };
// PostgreSQL is backed up with its own tools (BRIEF §6.2): no schedule that could never run. Seeded due at once // PostgreSQL is backed up with its own tools (BRIEF §6.2): no schedule that could never run. Seeded due at once
// when the newest copy is a day old, as the daily loop it replaced made one at start. // when the newest copy is a day old, as the daily loop it replaced made one at start.
@@ -83,13 +83,24 @@ public sealed class ServerScheduleHost : IScheduleHost
} }
list.Add(new(Housekeeping, "Housekeeping", ScheduleActions.Cleanup, ScheduleRecurrence.DailyAt(nightly.History), list.Add(new(Housekeeping, "Housekeeping", ScheduleActions.Cleanup, ScheduleRecurrence.DailyAt(nightly.History),
new ScheduleParametersDto(OlderThanDays: _options.JobHistoryDays, Steps: [Chronos.Data.Housekeeping.CleanupSteps.JobHistory]))); new ScheduleParametersDto(OlderThanDays: _options.JobHistoryDays, Steps: [Chronos.Data.Housekeeping.CleanupSteps.JobHistory])));
var audit = _options.AuditRetentionDays; list.Add(share[1]);
list.Add(new(AuditCleanup, "Audit log clean-up", ScheduleActions.Cleanup, ScheduleRecurrence.DailyAt(nightly.Audit),
new ScheduleParametersDto(OlderThanDays: audit, Steps: [Chronos.Data.Housekeeping.CleanupSteps.Audit]), Enabled: audit > 0));
return list; return list;
} }
} }
/// <summary>
/// The system schedules of a server's own state, which Chronos Desktop adds to its own while it shares its library
/// (owner review 5, #67), the archive scan, the index backup and the housekeeping being the desktop's: the uploads sweep
/// every <see cref="UploadSweepHours"/> hours and the audit log clean-up, nightly at 04:30, off at 0 days.
/// </summary>
public static IReadOnlyList<SystemSchedule> ShareSchedules(int auditRetentionDays) =>
[
new(UploadCleanup, "Upload clean-up", ScheduleActions.Cleanup, ScheduleRecurrence.Interval(UploadSweepHours, RecurrenceUnit.Hours),
new ScheduleParametersDto(OlderThanDays: UploadMaintenance.FinishedRetentionDays, Steps: [UploadCleanupStep.StepName])),
new(AuditCleanup, "Audit log clean-up", ScheduleActions.Cleanup, ScheduleRecurrence.DailyAt(new TimeOnly(4, 30)),
new ScheduleParametersDto(OlderThanDays: auditRetentionDays, Steps: [Chronos.Data.Housekeeping.CleanupSteps.Audit]), Enabled: auditRetentionDays > 0),
];
/// <summary> /// <summary>
/// The served archive, after taking the settings another writer sharing it (a desktop) put into its archive.json, as /// The served archive, after taking the settings another writer sharing it (a desktop) put into its archive.json, as
/// the former polling did; while it is offline, or the file cannot be read, as the index has it. /// the former polling did; while it is offline, or the file cannot be read, as the index has it.
-62
View File
@@ -1,62 +0,0 @@
using System.ComponentModel;
using Chronos.Server.Configuration;
using Chronos.Server.Hosting;
using Chronos.Server.Hosting.Windows;
using Chronos.Server.Storage;
var command = ServerCommandLine.Parse(args);
if (command.Error is not null)
{
await Console.Error.WriteLineAsync(command.Error);
return 2;
}
switch (command.Command)
{
case ServerCommand.Help:
Console.WriteLine(ServerCommandLine.Usage);
return 0;
case ServerCommand.HealthCheck:
return await HealthProbe.RunAsync();
case ServerCommand.Service or ServerCommand.InstallService or ServerCommand.UninstallService when !OperatingSystem.IsWindows():
await Console.Error.WriteLineAsync("Windows services are available on Windows only.");
return 2;
case ServerCommand.InstallService when OperatingSystem.IsWindows():
return ServiceAction(ServiceInstaller.Install, $"Installed the {WindowsServiceHost.ServiceName} service.");
case ServerCommand.UninstallService when OperatingSystem.IsWindows():
return ServiceAction(ServiceInstaller.Uninstall, $"Removed the {WindowsServiceHost.ServiceName} service.");
case ServerCommand.Service when OperatingSystem.IsWindows():
if (WindowsServiceHost.Run(() => ServerHost.Build(ServerOptions.Load(), [.. command.HostArguments], RegisterModules))) return 0;
await Console.Error.WriteLineAsync("--service is used by the Service Control Manager; start the service with 'sc start ChronosServer'.");
return 1;
default:
var app = ServerHost.Build(ServerOptions.Load(), [.. command.HostArguments], RegisterModules);
await app.RunAsync();
return 0;
}
// The archive engine, then analysis and managed rendering over it.
static void RegisterModules(IServiceCollection services)
{
ArchiveModule.Register(services);
ProcessingModule.Register(services);
}
static int ServiceAction(Action action, string done)
{
try
{
action();
Console.WriteLine(done);
return 0;
}
catch (Exception ex) when (ex is Win32Exception or InvalidOperationException)
{
// Win32: the Service Control Manager's reason; InvalidOperation: a folder the service must not run from.
Console.Error.WriteLine(ex.Message);
return 1;
}
}
/// <summary>Entry point type, visible to the in-process test host.</summary>
public partial class Program;
@@ -16,7 +16,8 @@ namespace Chronos.Server.Security;
public static class AdminBootstrap public static class AdminBootstrap
{ {
public const string DefaultUsername = "admin"; public const string DefaultUsername = "admin";
private const string PasswordFileName = "initial-admin-password.txt"; /// <summary>The file in the data folder that holds a generated temporary password until an administrator sets their own.</summary>
public const string PasswordFileName = "initial-admin-password.txt";
public static async Task RunAsync(ChronosDatabase db, ServerOptions options, TimeProvider time, ILogger logger, CancellationToken cancellationToken) public static async Task RunAsync(ChronosDatabase db, ServerOptions options, TimeProvider time, ILogger logger, CancellationToken cancellationToken)
{ {
@@ -6,12 +6,15 @@ namespace Chronos.Server.Security;
/// <summary> /// <summary>
/// Resolves the caller of every <c>/api</c> request (bearer token or admin cookie) and enforces the endpoint's /// Resolves the caller of every <c>/api</c> request (bearer token or admin cookie) and enforces the endpoint's
/// <see cref="AccessRule"/>: 401 without a valid token, 403 for a missing permission, a missing CSRF header on a /// <see cref="AccessRule"/>: 401 without a valid token, 403 for a missing permission, a missing CSRF header on a
/// cookie request, or a pending password change. Runs after routing, so the endpoint's metadata is known. /// cookie request, or a pending password change. Runs after routing, so the endpoint's metadata is known. Every request it
/// lets through is noted in <see cref="ClientActivity"/> (owner review 5, #67).
/// </summary> /// </summary>
public sealed class AuthenticationMiddleware(RequestDelegate next, TokenService tokens) public sealed class AuthenticationMiddleware(RequestDelegate next, TokenService tokens)
{ {
public async Task InvokeAsync(HttpContext context) public async Task InvokeAsync(HttpContext context, ClientActivity activity)
{ {
ArgumentNullException.ThrowIfNull(context);
ArgumentNullException.ThrowIfNull(activity);
var rule = context.GetEndpoint()?.Metadata.GetMetadata<AccessRule>(); var rule = context.GetEndpoint()?.Metadata.GetMetadata<AccessRule>();
if (rule is null && !context.Request.Path.StartsWithSegments("/api")) if (rule is null && !context.Request.Path.StartsWithSegments("/api"))
{ {
@@ -48,6 +51,8 @@ public sealed class AuthenticationMiddleware(RequestDelegate next, TokenService
return; return;
} }
context.Features.Set(caller); context.Features.Set(caller);
var address = context.Connection.RemoteIpAddress;
activity.Record(caller, (address is { IsIPv4MappedToIPv6: true } ? address.MapToIPv4() : address)?.ToString());
await next(context); await next(context);
} }
@@ -0,0 +1,42 @@
using System.Collections.Concurrent;
namespace Chronos.Server.Security;
/// <summary>A program that used the server lately: its account, its name (the token's client), its address and when.</summary>
public sealed record ClientSeen(string User, string Client, string Address, DateTimeOffset LastSeen);
/// <summary>
/// The programs that used the server in the last <see cref="Window"/> (owner review 5, #67): Chronos Desktop shows them in
/// its Server section while it shares its library, and asks before it stops sharing while there are any. Kept in memory
/// only; <see cref="AuthenticationMiddleware"/> records every signed-in request.
/// </summary>
public sealed class ClientActivity(TimeProvider time)
{
/// <summary>How long a program counts as active after its last request.</summary>
public static TimeSpan Window { get; } = TimeSpan.FromMinutes(5);
/// <summary>What a request signed in through the admin panel's cookie shows as its program.</summary>
public const string AdminPanel = "Admin panel";
private readonly ConcurrentDictionary<(Guid User, string Client, string Address), ClientSeen> _seen = new();
/// <summary>A signed-in request of <paramref name="caller"/> from <paramref name="address"/>.</summary>
public void Record(Caller caller, string? address)
{
ArgumentNullException.ThrowIfNull(caller);
var client = caller.Source == CredentialSource.Cookie ? AdminPanel : string.IsNullOrWhiteSpace(caller.ClientName) ? "?" : caller.ClientName.Trim();
var from = string.IsNullOrEmpty(address) ? "?" : address;
_seen[(caller.Id, client, from)] = new ClientSeen(caller.User.Username, client, from, time.GetUtcNow());
}
/// <summary>The programs seen in the last <see cref="Window"/>, the latest first; older entries are dropped.</summary>
public IReadOnlyList<ClientSeen> Recent()
{
var since = time.GetUtcNow() - Window;
foreach (var (key, seen) in _seen)
{
if (seen.LastSeen < since) _seen.TryRemove(new KeyValuePair<(Guid, string, string), ClientSeen>(key, seen));
}
return [.. _seen.Values.Where(s => s.LastSeen >= since).OrderByDescending(s => s.LastSeen)];
}
}
+4 -20
View File
@@ -23,8 +23,6 @@ namespace Chronos.Server.Storage;
/// </summary> /// </summary>
public static class ArchiveModule public static class ArchiveModule
{ {
/// <summary>The change a conversion's Replace tells about a sequence (<c>sequenceChanged</c>).</summary>
private const string ConvertedChange = "converted";
/// <summary>Name the server writes into the archive's lease files.</summary> /// <summary>Name the server writes into the archive's lease files.</summary>
public static string Owner { get; } = "server@" + Environment.MachineName; public static string Owner { get; } = "server@" + Environment.MachineName;
@@ -40,24 +38,10 @@ public static class ArchiveModule
// Photos the running job processes at once: the settings' value as it is when each sequence starts (owner review 1). // Photos the running job processes at once: the settings' value as it is when each sequence starts (owner review 1).
var service = new ArchiveService(db, new ArchiveServiceOptions var service = new ArchiveService(db, new ArchiveServiceOptions
{ {
// A Reorganize or a conversion tells connected clients of every sequence it changed or made (BRIEF §14.3). // A Reorganize or a conversion tells connected clients of every sequence it changed or made (BRIEF §14.3), and
SequenceChanged = async (id, change, ct) => // every change of a sequence's projects reaches them too (owner review 2, R8).
{ SequenceChanged = (id, change, ct) => ServerEventBridge.SequenceChangedAsync(db, events, sp.GetService<ProjectCatchUp>(), id, change, ct),
if (await db.Sequences.GetAsync(id, ct) is { } sequence) ProjectsChanged = (changed, ct) => ServerEventBridge.ProjectsChangedAsync(db, events, changed, ct),
events.Publish(new SequenceChangedEvent(id, change, sequence.FramesVersion, sequence.SettingsVersion));
// A conversion may leave settings Main has not taken yet (owner review 2, R8).
if (change == ConvertedChange) sp.GetService<ProjectCatchUp>()?.Touch(id);
},
// Every change of a sequence's projects reaches connected clients (owner review 2, R8): a workspace with that
// project checked out knows its home moved, the admin panel lists the projects again. Main's head written into the
// sequence's settings is a settings change for the clients that read those (an older client, a desktop's sync).
ProjectsChanged = async (changed, ct) =>
{
foreach (var change in changed.Changes)
events.Publish(new ProjectChangedEvent(changed.SequenceId, change.ProjectId, change.Change, change.HeadNumber, change.HeadVersionId));
if (changed.SettingsChanged && await db.Sequences.GetAsync(changed.SequenceId, ct) is { } sequence)
events.Publish(new SequenceChangedEvent(sequence.Id, "settings", sequence.FramesVersion, sequence.SettingsVersion));
},
Decoder = DecoderFactory.CreateServer(), Decoder = DecoderFactory.CreateServer(),
// Where a conversion writes (owner review 2, R7): the tighter of what the panel shows as the archive's free space // Where a conversion writes (owner review 2, R7): the tighter of what the panel shows as the archive's free space
// (R2: the space path's volume) and the volume the archive's folders are on, which takes every byte it stages // (R2: the space path's volume) and the volume the archive's folders are on, which takes every byte it stages
@@ -45,13 +45,8 @@ public static class ProcessingModule
Host = EncoderHost.Server, Host = EncoderHost.Server,
AwaitsRenderNode = sp.GetRequiredService<RenderNodeAvailability>().AwaitsNodeAsync, AwaitsRenderNode = sp.GetRequiredService<RenderNodeAvailability>().AwaitsNodeAsync,
ProducedBy = options.ServerName, ProducedBy = options.ServerName,
SequenceChanged = async (id, change, ct) => // Auto values an analysis wrote into the settings become Main's next version now (owner review 2, R8).
{ SequenceChanged = (id, change, ct) => ServerEventBridge.SequenceChangedAsync(db, events, sp.GetService<ProjectCatchUp>(), id, change, ct),
if (await db.Sequences.GetAsync(id, ct) is { } sequence)
events.Publish(new SequenceChangedEvent(id, change, sequence.FramesVersion, sequence.SettingsVersion));
// Auto values an analysis wrote into the settings become Main's next version now (owner review 2, R8).
if (change == ProcessingOptions.SettingsChange) sp.GetService<ProjectCatchUp>()?.Touch(id);
},
}); });
}); });
services.AddSingleton<IJobHandlerProvider>(sp => sp.GetRequiredService<ProcessingService>()); services.AddSingleton<IJobHandlerProvider>(sp => sp.GetRequiredService<ProcessingService>());
Loaded 100 of 127 files, more files were not shown because too many files have changed in this diff. Show more