feat: single setup, mass-pass progress, per-server homes, Desktop shares its library (owner review 5, v1.1.0) (#68)
CI / Build and test (push) Successful in 11m36s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 12s
Release / Build, test and publish (push) Successful in 14m56s
CI / PostgreSQL 16 integration (push) Successful in 10m11s
CI / PostgreSQL 17 integration (push) Successful in 10m15s
CI / Docker image (push) Successful in 45s
Release / Server image (push) Successful in 4m55s
CI / Build and test (push) Successful in 11m36s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 12s
Release / Build, test and publish (push) Successful in 14m56s
CI / PostgreSQL 16 integration (push) Successful in 10m11s
CI / PostgreSQL 17 integration (push) Successful in 10m15s
CI / Docker image (push) Successful in 45s
Release / Server image (push) Successful in 4m55s
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #68.
This commit is contained in:
1 parent
988068ee8e
commit
20d64af4a4
793 files changed
+23882
-2096
No files matched your search
@@ -4,8 +4,10 @@ using System.Windows.Input;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Shell;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Updates;
|
||||
using Chronos.Ui.Controls;
|
||||
using Chronos.Ui.Mvvm;
|
||||
using Chronos.Ui.Updates;
|
||||
|
||||
namespace Chronos.App.About;
|
||||
|
||||
|
||||
@@ -1,154 +0,0 @@
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Chronos.App.About;
|
||||
|
||||
/// <summary>The newest public release (BRIEF §18) with its downloadable files.</summary>
|
||||
public sealed record ReleaseInfo(Version Version, string Tag, string PageUrl)
|
||||
{
|
||||
public IReadOnlyList<ReleaseAsset> Assets { get; init; } = [];
|
||||
}
|
||||
|
||||
/// <summary>One file attached to a release.</summary>
|
||||
public sealed record ReleaseAsset(string Name, string DownloadUrl, long Size);
|
||||
|
||||
/// <summary>
|
||||
/// Update check against the Gitea releases API of the releases repository (BRIEF §18, §19.4, amended 2026-10-23, R2):
|
||||
/// reads the published stable releases, takes the highest version (Gitea's own "latest" is the most recently created
|
||||
/// one, which a re-published older tag or a backport would become), and compares it with the running version. The
|
||||
/// release page and download links are built from the repository address the build names (ChronosReleasesUrl), not
|
||||
/// taken from the answer: Gitea writes its links with its ROOT_URL, which may be an address clients cannot reach
|
||||
/// (the owner's is a plain-http LAN address).
|
||||
/// </summary>
|
||||
public static class UpdateCheck
|
||||
{
|
||||
/// <summary>"v1.2.3", "1.2.3", "v1.2.3-beta.1" → 1.2.3; null for anything else.</summary>
|
||||
public static Version? ParseVersion(string? tag)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(tag)) return null;
|
||||
var text = tag.Trim();
|
||||
if (text.StartsWith('v') || text.StartsWith('V')) text = text[1..];
|
||||
var end = text.IndexOfAny(['-', '+', ' ']);
|
||||
if (end >= 0) text = text[..end];
|
||||
if (!Version.TryParse(text, out var version)) return null;
|
||||
// Normalise to three parts so 1.2 equals 1.2.0.
|
||||
return new Version(version.Major, version.Minor, Math.Max(0, version.Build));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The newest release of a releases-list response (an array: the highest version wins) or of one release object;
|
||||
/// null when there is none. With <paramref name="repository"/> ("https://host/owner/name"), the release page and
|
||||
/// the download links are that repository's (<c>/releases/tag/<tag></c>, <c>/releases/download/<tag>/<name></c>);
|
||||
/// without it, the ones in the answer. Drafts, pre-releases, unparsable tags and pages without an https link are
|
||||
/// skipped, and so are assets without an https download link.
|
||||
/// </summary>
|
||||
public static ReleaseInfo? Parse(string json, string? repository = null)
|
||||
{
|
||||
var baseUrl = repository?.Trim().TrimEnd('/');
|
||||
using var document = JsonDocument.Parse(json);
|
||||
var root = document.RootElement;
|
||||
return root.ValueKind switch
|
||||
{
|
||||
JsonValueKind.Array => root.EnumerateArray().Select(r => ParseRelease(r, baseUrl)).OfType<ReleaseInfo>().MaxBy(r => r.Version),
|
||||
JsonValueKind.Object => ParseRelease(root, baseUrl),
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
private static ReleaseInfo? ParseRelease(JsonElement root, string? repository)
|
||||
{
|
||||
if (root.ValueKind != JsonValueKind.Object) return null;
|
||||
if (Flag(root, "draft") || Flag(root, "prerelease")) return null;
|
||||
var tag = root.TryGetProperty("tag_name", out var t) && t.ValueKind == JsonValueKind.String ? t.GetString() : null;
|
||||
var version = ParseVersion(tag);
|
||||
if (version is null || tag is null) return null;
|
||||
var url = repository is not null
|
||||
? $"{repository}/releases/tag/{Uri.EscapeDataString(tag)}"
|
||||
: root.TryGetProperty("html_url", out var u) && u.ValueKind == JsonValueKind.String ? u.GetString() : null;
|
||||
if (url is null || !url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) return null;
|
||||
return new ReleaseInfo(version, tag, url) { Assets = ParseAssets(root, repository, tag) };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when <paramref name="release"/> is newer than <paramref name="running"/> (build/revision ignored). A
|
||||
/// pre-release build (<paramref name="runningIsPrerelease"/>, "0.1.0-rc.1") is older than the release of its own
|
||||
/// version: only stable releases are read, so the equal version is the final one.
|
||||
/// </summary>
|
||||
public static bool IsNewer(ReleaseInfo release, Version running, bool runningIsPrerelease = false)
|
||||
{
|
||||
var current = new Version(running.Major, running.Minor, Math.Max(0, running.Build));
|
||||
return release.Version > current || (runningIsPrerelease && release.Version == current);
|
||||
}
|
||||
|
||||
/// <summary>"0.1.0-rc.1" and "v0.1.0-beta" are pre-releases; "0.1.0" and "0.1.0+abc" (build metadata) are not.</summary>
|
||||
public static bool IsPrerelease(string? informationalVersion)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(informationalVersion)) return false;
|
||||
var text = informationalVersion.Trim();
|
||||
var plus = text.IndexOf('+');
|
||||
if (plus >= 0) text = text[..plus];
|
||||
return text.Contains('-');
|
||||
}
|
||||
|
||||
/// <summary>The running version from an informational version such as "0.1.0" or "0.1.0+abc".</summary>
|
||||
public static Version RunningVersion(string informationalVersion) => ParseVersion(informationalVersion) ?? new Version(0, 0, 0);
|
||||
|
||||
/// <summary>
|
||||
/// Asks the releases API for the newest stable release; null when the repository has none or the answer cannot be
|
||||
/// read. A 404 means the repository itself cannot be seen (Gitea answers so for a private or missing repository):
|
||||
/// that is a failed check, never "up to date".
|
||||
/// </summary>
|
||||
/// <exception cref="HttpRequestException">The request failed, or the repository was not found.</exception>
|
||||
public static Task<ReleaseInfo?> FetchAsync(HttpClient http, string apiUrl, string userAgentVersion, CancellationToken ct) =>
|
||||
FetchAsync(http, apiUrl, null, userAgentVersion, ct);
|
||||
|
||||
/// <summary>
|
||||
/// As <see cref="FetchAsync(HttpClient, string, string, CancellationToken)"/>, with the release page and download
|
||||
/// links built from <paramref name="repository"/> (see <see cref="Parse"/>).
|
||||
/// </summary>
|
||||
/// <exception cref="HttpRequestException">The request failed, or the repository was not found.</exception>
|
||||
public static async Task<ReleaseInfo?> FetchAsync(HttpClient http, string apiUrl, string? repository, string userAgentVersion, CancellationToken ct)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, apiUrl);
|
||||
request.Headers.UserAgent.Add(new ProductInfoHeaderValue("Chronos", userAgentVersion));
|
||||
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
using var response = await http.SendAsync(request, ct).ConfigureAwait(false);
|
||||
if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
|
||||
throw new HttpRequestException($"The releases repository was not found or is not public: {apiUrl}", null, response.StatusCode);
|
||||
response.EnsureSuccessStatusCode();
|
||||
var json = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
return Parse(json, repository);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static List<ReleaseAsset> ParseAssets(JsonElement root, string? repository, string tag)
|
||||
{
|
||||
var assets = new List<ReleaseAsset>();
|
||||
if (!root.TryGetProperty("assets", out var list) || list.ValueKind != JsonValueKind.Array) return assets;
|
||||
foreach (var a in list.EnumerateArray())
|
||||
{
|
||||
if (a.ValueKind != JsonValueKind.Object) continue;
|
||||
var name = a.TryGetProperty("name", out var n) && n.ValueKind == JsonValueKind.String ? n.GetString() : null;
|
||||
var link = repository is not null && !string.IsNullOrEmpty(name)
|
||||
? $"{repository}/releases/download/{Uri.EscapeDataString(tag)}/{Uri.EscapeDataString(name)}"
|
||||
: a.TryGetProperty("browser_download_url", out var d) && d.ValueKind == JsonValueKind.String ? d.GetString() : null;
|
||||
var size = a.TryGetProperty("size", out var z) && z.ValueKind == JsonValueKind.Number && z.TryGetInt64(out var bytes) ? bytes : -1;
|
||||
if (string.IsNullOrEmpty(name) || link is null || !link.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) continue;
|
||||
assets.Add(new ReleaseAsset(name, link, size));
|
||||
}
|
||||
return assets;
|
||||
}
|
||||
|
||||
private static bool Flag(JsonElement root, string name) =>
|
||||
root.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.True;
|
||||
|
||||
/// <summary>"0.2.0" for display.</summary>
|
||||
public static string Display(Version version) => version.ToString(Math.Clamp(version.Build < 0 ? 2 : 3, 2, 3));
|
||||
}
|
||||
@@ -1,251 +0,0 @@
|
||||
using System.Buffers;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace Chronos.App.About;
|
||||
|
||||
/// <summary>A downloaded update was refused: the release lacks a setup or checksum line, or the bytes do not match.</summary>
|
||||
public sealed class UpdateVerificationException(string message) : Exception(message);
|
||||
|
||||
/// <summary>
|
||||
/// "Download" of the update notice (BRIEF §18, P1): fetches the package of the latest release that upgrades this copy
|
||||
/// (the setup, or the portable zip for a portable copy) into a temporary folder and keeps it only when its SHA-256
|
||||
/// equals the line for it in the release's <c>SHA256SUMS</c>. BRIEF §8.6 does not list starting an installer among the
|
||||
/// OS actions Chronos may perform, so callers show the verified file in Explorer and the user runs or unpacks it. An
|
||||
/// interrupted download resumes from its partial file; a transfer that stalls fails after <see cref="IdleTimeout"/>
|
||||
/// instead of hanging.
|
||||
/// </summary>
|
||||
public static class UpdateDownload
|
||||
{
|
||||
public const string ChecksumsName = "SHA256SUMS";
|
||||
|
||||
/// <summary>A transfer that delivers no byte for this long fails (and can be resumed).</summary>
|
||||
public static readonly TimeSpan IdleTimeout = TimeSpan.FromSeconds(60);
|
||||
|
||||
private const string PartSuffix = ".part";
|
||||
private const int MaxChecksumsBytes = 64 * 1024;
|
||||
private static readonly SearchValues<char> Hex = SearchValues.Create("0123456789abcdefABCDEF");
|
||||
|
||||
/// <summary>
|
||||
/// The file that upgrades this copy: the desktop setup ("Chronos-Setup-1.2.3.exe", not the Uploader's) or, for a
|
||||
/// portable copy, the portable zip ("Chronos-win-x64-portable-1.2.3.zip"); null when the release has none.
|
||||
/// </summary>
|
||||
public static ReleaseAsset? Package(ReleaseInfo release, bool portable)
|
||||
{
|
||||
var (prefix, extension) = portable ? ("Chronos-win-x64-portable-", ".zip") : ("Chronos-Setup-", ".exe");
|
||||
return release.Assets.FirstOrDefault(a => a.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)
|
||||
&& a.Name.EndsWith(extension, StringComparison.OrdinalIgnoreCase)
|
||||
&& a.Name == Path.GetFileName(a.Name));
|
||||
}
|
||||
|
||||
public static ReleaseAsset? Checksums(ReleaseInfo release) => release.Assets.FirstOrDefault(a => a.Name == ChecksumsName);
|
||||
|
||||
/// <summary>The release carries both the package for this copy and <c>SHA256SUMS</c>; otherwise only its page can be opened.</summary>
|
||||
public static bool CanDownload(ReleaseInfo release, bool portable) => Package(release, portable) is not null && Checksums(release) is not null;
|
||||
|
||||
/// <summary><c>%TEMP%\Chronos\updates</c>: one folder per release below it, all owned by Chronos.</summary>
|
||||
public static string Root(string tempPath) => Path.Combine(tempPath, "Chronos", "updates");
|
||||
|
||||
/// <summary>The folder of one release below <paramref name="root"/>, named after its tag.</summary>
|
||||
public static string Folder(string root, ReleaseInfo release) =>
|
||||
Path.Combine(root, string.Concat(release.Tag.Select(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '-' ? c : '_')));
|
||||
|
||||
/// <summary>
|
||||
/// File name → lower-case hex SHA-256 from <c>sha256sum</c> output (<c>hash name</c> or <c>hash *name</c>); lines
|
||||
/// that are not a 64-digit hash followed by a name are ignored.
|
||||
/// </summary>
|
||||
public static Dictionary<string, string> ParseChecksums(string text)
|
||||
{
|
||||
var sums = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var raw in text.Split('\n'))
|
||||
{
|
||||
var line = raw.TrimEnd('\r');
|
||||
if (line.Length < 66 || line[64] != ' ' || line.AsSpan(0, 64).ContainsAnyExcept(Hex)) continue;
|
||||
var name = line[65..];
|
||||
if (name.StartsWith(' ') || name.StartsWith('*')) name = name[1..];
|
||||
if (name.Length > 0) sums[name] = line[..64].ToLowerInvariant();
|
||||
}
|
||||
return sums;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Downloads the <see cref="Package"/> of <paramref name="release"/> for this copy into its <see cref="Folder"/> under
|
||||
/// <paramref name="root"/>, verifies it against <c>SHA256SUMS</c> and returns its path. A verified copy already there
|
||||
/// is reused; an interrupted or cancelled transfer keeps its partial file for the next attempt; bytes that do not
|
||||
/// verify are deleted. After a verified download the folders of other releases under <paramref name="root"/> are removed.
|
||||
/// </summary>
|
||||
/// <exception cref="UpdateVerificationException">The release cannot be verified or the bytes do not match.</exception>
|
||||
/// <exception cref="HttpRequestException">A request failed.</exception>
|
||||
/// <exception cref="TimeoutException">No byte arrived for <paramref name="idleTimeout"/>.</exception>
|
||||
/// <exception cref="IOException">The transfer ended early or the file could not be written.</exception>
|
||||
public static async Task<string> DownloadAsync(HttpClient http, ReleaseInfo release, bool portable, string root, string userAgentVersion,
|
||||
IProgress<double>? progress, TimeSpan idleTimeout, CancellationToken ct)
|
||||
{
|
||||
var package = Package(release, portable)
|
||||
?? throw new UpdateVerificationException($"Release {release.Tag} has no {(portable ? "portable zip" : "Chronos setup")}.");
|
||||
var checksums = Checksums(release) ?? throw new UpdateVerificationException($"Release {release.Tag} has no {ChecksumsName}.");
|
||||
var text = await WhileReceivingAsync(idle => ReadChecksumsAsync(http, checksums, userAgentVersion, idle.Token), idleTimeout, ct).ConfigureAwait(false);
|
||||
var expected = ParseChecksums(text).GetValueOrDefault(package.Name)
|
||||
?? throw new UpdateVerificationException($"{ChecksumsName} of {release.Tag} has no line for {package.Name}.");
|
||||
|
||||
var folder = Folder(root, release);
|
||||
Directory.CreateDirectory(folder);
|
||||
var target = Path.Combine(folder, package.Name);
|
||||
if (File.Exists(target) && await HashFileAsync(target, ct).ConfigureAwait(false) == expected)
|
||||
{
|
||||
progress?.Report(1);
|
||||
return target;
|
||||
}
|
||||
|
||||
var part = target + PartSuffix;
|
||||
var actual = await WhileReceivingAsync(idle => DownloadToAsync(http, package, part, userAgentVersion, progress, idle, idleTimeout), idleTimeout, ct)
|
||||
.ConfigureAwait(false);
|
||||
if (actual != expected)
|
||||
{
|
||||
DeleteQuietly(part);
|
||||
throw new UpdateVerificationException($"{package.Name}: SHA-256 {actual} does not match {expected} in {ChecksumsName}.");
|
||||
}
|
||||
File.Move(part, target, overwrite: true);
|
||||
RemoveOtherReleases(root, folder);
|
||||
return target;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs one network phase under a token that fires when nothing arrives for <paramref name="idleTimeout"/> (the phase
|
||||
/// re-arms it on every read) and reports that as a <see cref="TimeoutException"/>; the caller's cancellation stays a cancellation.
|
||||
/// </summary>
|
||||
private static async Task<T> WhileReceivingAsync<T>(Func<CancellationTokenSource, Task<T>> phase, TimeSpan idleTimeout, CancellationToken ct)
|
||||
{
|
||||
using var idle = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
idle.CancelAfter(idleTimeout);
|
||||
try
|
||||
{
|
||||
return await phase(idle).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (idle.IsCancellationRequested && !ct.IsCancellationRequested)
|
||||
{
|
||||
throw new TimeoutException(string.Create(CultureInfo.InvariantCulture, $"No data received for {idleTimeout.TotalSeconds:0} s."));
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<string> ReadChecksumsAsync(HttpClient http, ReleaseAsset asset, string userAgentVersion, CancellationToken ct)
|
||||
{
|
||||
using var response = await SendAsync(http, asset, userAgentVersion, 0, ct).ConfigureAwait(false);
|
||||
if (response.Content.Headers.ContentLength > MaxChecksumsBytes) throw new UpdateVerificationException($"{ChecksumsName} is too large.");
|
||||
var bytes = await response.Content.ReadAsByteArrayAsync(ct).ConfigureAwait(false);
|
||||
if (bytes.Length > MaxChecksumsBytes) throw new UpdateVerificationException($"{ChecksumsName} is too large.");
|
||||
return System.Text.Encoding.UTF8.GetString(bytes);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Streams the asset into <paramref name="path"/>, continuing an existing partial file when the server honours the
|
||||
/// range request, and returns the SHA-256 of the whole file. Refuses more bytes than the release announced and
|
||||
/// fails with an <see cref="IOException"/> (partial file kept) when the transfer ends before the announced size.
|
||||
/// </summary>
|
||||
private static async Task<string> DownloadToAsync(HttpClient http, ReleaseAsset asset, string path, string userAgentVersion, IProgress<double>? progress,
|
||||
CancellationTokenSource idle, TimeSpan idleTimeout)
|
||||
{
|
||||
var ct = idle.Token;
|
||||
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
|
||||
var buffer = new byte[1 << 16];
|
||||
|
||||
// Resume only with a known size: a partial file of an unknown total cannot be checked against it.
|
||||
var offset = File.Exists(path) ? new FileInfo(path).Length : 0;
|
||||
if (asset.Size <= 0 || offset > asset.Size) offset = 0;
|
||||
if (offset > 0 && offset == asset.Size) return await HashFileAsync(path, ct).ConfigureAwait(false);
|
||||
|
||||
using var response = await SendAsync(http, asset, userAgentVersion, offset, ct).ConfigureAwait(false);
|
||||
var resumed = offset > 0 && response.StatusCode == HttpStatusCode.PartialContent && response.Content.Headers.ContentRange?.From == offset;
|
||||
await using var output = new FileStream(path, resumed ? FileMode.Open : FileMode.Create, FileAccess.ReadWrite, FileShare.None, 1 << 16, FileOptions.Asynchronous);
|
||||
long total = 0;
|
||||
if (resumed)
|
||||
{
|
||||
int kept;
|
||||
while (total < offset && (kept = await output.ReadAsync(buffer.AsMemory(0, (int)Math.Min(buffer.Length, offset - total)), ct).ConfigureAwait(false)) > 0)
|
||||
{
|
||||
hash.AppendData(buffer, 0, kept);
|
||||
total += kept;
|
||||
}
|
||||
output.SetLength(total);
|
||||
}
|
||||
|
||||
await using var input = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false);
|
||||
int read;
|
||||
while ((read = await input.ReadAsync(buffer, ct).ConfigureAwait(false)) > 0)
|
||||
{
|
||||
idle.CancelAfter(idleTimeout);
|
||||
total += read;
|
||||
if (asset.Size > 0 && total > asset.Size)
|
||||
{
|
||||
await output.DisposeAsync().ConfigureAwait(false);
|
||||
DeleteQuietly(path);
|
||||
throw new UpdateVerificationException($"{asset.Name} is larger than the release announced.");
|
||||
}
|
||||
hash.AppendData(buffer, 0, read);
|
||||
await output.WriteAsync(buffer.AsMemory(0, read), ct).ConfigureAwait(false);
|
||||
if (asset.Size > 0) progress?.Report((double)total / asset.Size);
|
||||
}
|
||||
await output.FlushAsync(ct).ConfigureAwait(false);
|
||||
if (asset.Size > 0 && total < asset.Size)
|
||||
throw new IOException(string.Create(CultureInfo.InvariantCulture, $"{asset.Name}: the transfer ended after {total} of {asset.Size} bytes."));
|
||||
return Convert.ToHexStringLower(hash.GetHashAndReset());
|
||||
}
|
||||
|
||||
private static async Task<HttpResponseMessage> SendAsync(HttpClient http, ReleaseAsset asset, string userAgentVersion, long offset, CancellationToken ct)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, asset.DownloadUrl);
|
||||
request.Headers.UserAgent.Add(new ProductInfoHeaderValue("Chronos", userAgentVersion));
|
||||
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));
|
||||
if (offset > 0) request.Headers.Range = new RangeHeaderValue(offset, null);
|
||||
var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
response.EnsureSuccessStatusCode();
|
||||
return response;
|
||||
}
|
||||
catch
|
||||
{
|
||||
response.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Drops the folders of other (older) releases: only the verified setup is worth keeping.</summary>
|
||||
private static void RemoveOtherReleases(string root, string keep)
|
||||
{
|
||||
foreach (var folder in Directory.EnumerateDirectories(root))
|
||||
{
|
||||
if (string.Equals(Path.GetFullPath(folder), Path.GetFullPath(keep), StringComparison.OrdinalIgnoreCase)) continue;
|
||||
try
|
||||
{
|
||||
Directory.Delete(folder, recursive: true);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// A setup still open (running, scanned) stays until the next verified download.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void DeleteQuietly(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// A scanner may hold the file; the next download overwrites it.
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<string> HashFileAsync(string path, CancellationToken ct)
|
||||
{
|
||||
await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 16, FileOptions.Asynchronous | FileOptions.SequentialScan);
|
||||
return Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, ct).ConfigureAwait(false));
|
||||
}
|
||||
}
|
||||
@@ -1,181 +0,0 @@
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.About;
|
||||
|
||||
/// <summary>Where the update notice stands.</summary>
|
||||
public enum UpdateState
|
||||
{
|
||||
Unknown,
|
||||
Checking,
|
||||
UpToDate,
|
||||
Available,
|
||||
Failed,
|
||||
Downloading,
|
||||
Downloaded,
|
||||
DownloadFailed,
|
||||
NotVerified,
|
||||
}
|
||||
|
||||
/// <summary>What <see cref="UpdateFlow"/> needs from the application: the running version, the mode, the network and the shell.</summary>
|
||||
public sealed record UpdateHost(
|
||||
Version Running,
|
||||
bool IsCapture,
|
||||
bool IsPortable,
|
||||
Func<CancellationToken, Task<ReleaseInfo?>> CheckAsync,
|
||||
Func<ReleaseInfo, IProgress<double>?, CancellationToken, Task<string>> DownloadAsync,
|
||||
Action<string> OpenUrl,
|
||||
Action<string> Reveal)
|
||||
{
|
||||
/// <summary>The running build is a pre-release ("0.1.0-rc.1"): the final release of the same version is newer.</summary>
|
||||
public bool RunningIsPrerelease { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The update notice of Settings › Updates (BRIEF §18): checks the latest release, downloads and verifies the
|
||||
/// package that upgrades this copy (<see cref="UpdateDownload"/>: the setup, or the portable zip for a portable copy)
|
||||
/// and shows it in Explorer. Running it is left to the user because BRIEF §8.6 lets Chronos only open links and show
|
||||
/// files. A release without that package or without <c>SHA256SUMS</c> only opens its page; a capture run never touches
|
||||
/// the network. The flow owns its two commands so that their can-execute state follows every change.
|
||||
/// </summary>
|
||||
public sealed class UpdateFlow
|
||||
{
|
||||
private static readonly TimeSpan CheckTimeout = TimeSpan.FromSeconds(30);
|
||||
|
||||
private readonly UpdateHost _host;
|
||||
|
||||
public UpdateFlow(UpdateHost host)
|
||||
{
|
||||
_host = host;
|
||||
Check = new AsyncRelayCommand((_, ct) => CheckAsync(ct), _ => State is not (UpdateState.Checking or UpdateState.Downloading));
|
||||
Download = new AsyncRelayCommand((_, ct) => DownloadAsync(ct), _ => IsDownloadOffered);
|
||||
}
|
||||
|
||||
/// <summary>Raised after every change of state, release, progress or downloaded file.</summary>
|
||||
public event Action? Changed;
|
||||
|
||||
public UpdateState State { get; private set; } = UpdateState.Unknown;
|
||||
|
||||
/// <summary>The newer release, or null when there is none (or no check has succeeded yet).</summary>
|
||||
public ReleaseInfo? Release { get; private set; }
|
||||
|
||||
/// <summary>Fraction of the package downloaded so far.</summary>
|
||||
public double Downloaded { get; private set; }
|
||||
|
||||
/// <summary>The verified package; null until a download succeeded.</summary>
|
||||
public string? PackagePath { get; private set; }
|
||||
|
||||
public bool IsPortable => _host.IsPortable;
|
||||
|
||||
public AsyncRelayCommand Check { get; }
|
||||
|
||||
public AsyncRelayCommand Download { get; }
|
||||
|
||||
/// <summary>Download is offered: a newer release exists and no verified package is waiting (a failed download can be retried).</summary>
|
||||
public bool IsDownloadOffered =>
|
||||
Release is not null && State is UpdateState.Available or UpdateState.DownloadFailed or UpdateState.NotVerified;
|
||||
|
||||
/// <summary>The package Download fetches; null when Download opens the release page instead.</summary>
|
||||
public ReleaseAsset? Package =>
|
||||
Release is { } release && UpdateDownload.CanDownload(release, _host.IsPortable) ? UpdateDownload.Package(release, _host.IsPortable) : null;
|
||||
|
||||
/// <summary>Stops a download in progress; its partial file is kept and the next Download resumes it.</summary>
|
||||
public void CancelDownload() => Download.Cancel();
|
||||
|
||||
/// <summary>The start-up check (BRIEF §18): only when the user left it on and never in a capture run.</summary>
|
||||
public Task<ReleaseInfo?> CheckOnStartAsync(bool enabled) => enabled ? CheckAsync(CancellationToken.None) : Task.FromResult<ReleaseInfo?>(null);
|
||||
|
||||
/// <summary>Asks for the latest release and returns it when it is newer than the running version.</summary>
|
||||
public async Task<ReleaseInfo?> CheckAsync(CancellationToken ct)
|
||||
{
|
||||
if (_host.IsCapture || State is UpdateState.Checking or UpdateState.Downloading) return null;
|
||||
SetState(UpdateState.Checking);
|
||||
ReleaseInfo? latest = null;
|
||||
var failed = true;
|
||||
try
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(CheckTimeout);
|
||||
latest = await _host.CheckAsync(timeout.Token);
|
||||
failed = false;
|
||||
}
|
||||
catch (Exception ex) when (ex is HttpRequestException or OperationCanceledException or IOException)
|
||||
{
|
||||
Log.Info("update", "Update check failed: " + ex.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
SetResult(latest, failed);
|
||||
}
|
||||
return Release;
|
||||
}
|
||||
|
||||
/// <summary>Sets a check result without the network (capture, tests). A package already verified for the same release stays offered.</summary>
|
||||
public void SetResult(ReleaseInfo? release, bool failed = false)
|
||||
{
|
||||
var newer = !failed && release is not null && UpdateCheck.IsNewer(release, _host.Running, _host.RunningIsPrerelease) ? release : null;
|
||||
var keepPackage = newer is not null && PackagePath is not null && newer.Tag == Release?.Tag && File.Exists(PackagePath);
|
||||
Release = newer;
|
||||
if (!keepPackage) PackagePath = null;
|
||||
SetState(failed ? UpdateState.Failed
|
||||
: newer is null ? UpdateState.UpToDate
|
||||
: keepPackage ? UpdateState.Downloaded
|
||||
: UpdateState.Available);
|
||||
}
|
||||
|
||||
private async Task DownloadAsync(CancellationToken ct)
|
||||
{
|
||||
if (Release is not { } release || _host.IsCapture) return;
|
||||
if (Package is null)
|
||||
{
|
||||
_host.OpenUrl(release.PageUrl);
|
||||
return;
|
||||
}
|
||||
Downloaded = 0;
|
||||
SetState(UpdateState.Downloading);
|
||||
var progress = new Progress<double>(fraction =>
|
||||
{
|
||||
if (State != UpdateState.Downloading || fraction - Downloaded < 0.01) return;
|
||||
Downloaded = fraction;
|
||||
Changed?.Invoke();
|
||||
});
|
||||
try
|
||||
{
|
||||
var path = await _host.DownloadAsync(release, progress, ct);
|
||||
PackagePath = path;
|
||||
Log.Info("update", $"{Path.GetFileName(path)} of {release.Tag} downloaded and verified: {path}");
|
||||
SetState(UpdateState.Downloaded);
|
||||
_host.Reveal(path);
|
||||
}
|
||||
catch (UpdateVerificationException ex)
|
||||
{
|
||||
Log.Warning("update", "Update download refused: " + ex.Message);
|
||||
SetState(UpdateState.NotVerified);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
Log.Info("update", $"Download of {release.Tag} cancelled; the next one resumes it.");
|
||||
SetState(UpdateState.Available);
|
||||
}
|
||||
catch (Exception ex) when (ex is HttpRequestException or TimeoutException or OperationCanceledException or IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("update", "Update download failed: " + ex.Message);
|
||||
SetState(UpdateState.DownloadFailed);
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Anything unexpected still reaches the command's error report; the notice must not stay "Downloading".
|
||||
if (State == UpdateState.Downloading) SetState(UpdateState.DownloadFailed);
|
||||
}
|
||||
}
|
||||
|
||||
private void SetState(UpdateState state)
|
||||
{
|
||||
State = state;
|
||||
Changed?.Invoke();
|
||||
Check.RaiseCanExecuteChanged();
|
||||
Download.RaiseCanExecuteChanged();
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,7 @@ public partial class App : Application
|
||||
private readonly TaskCompletionSource _started = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private FileLogSink? _log;
|
||||
private SingleInstance? _instance;
|
||||
private ShellTray? _tray;
|
||||
private bool _windowClosed;
|
||||
|
||||
public AppEnvironment Environment { get; private set; } = null!;
|
||||
@@ -113,7 +114,10 @@ public partial class App : Application
|
||||
_windowClosed = true;
|
||||
_instance?.StopListening();
|
||||
};
|
||||
window.Show();
|
||||
// While sharing: closing hides the window to the tray, and a start at sign-in waits there (owner review 5, #67).
|
||||
_tray = new ShellTray(window, shell);
|
||||
_tray.Update();
|
||||
if (ShareLifetime.Start(Shell.MainWindow.StartsMinimized(e.Args), Settings.Share.Enabled) != StartWindow.Tray) window.Show();
|
||||
_instance?.Receive(args => Dispatcher.BeginInvoke(() => OnHandOver(shell, args)));
|
||||
_ = StartAsync(shell, projectFile);
|
||||
}
|
||||
@@ -197,6 +201,8 @@ public partial class App : Application
|
||||
}
|
||||
// Every settings change passes here, Settings › Advanced › Logs, its Reset and an imported file included.
|
||||
ApplyLogSettings();
|
||||
// Sharing turned on or off, or a new name: the tray icon follows.
|
||||
_tray?.Update();
|
||||
}
|
||||
|
||||
/// <summary>Settings › Advanced › Logs to the log files, from the next line on (owner review 2, R11).</summary>
|
||||
@@ -209,6 +215,7 @@ public partial class App : Application
|
||||
{
|
||||
// The mutex stays until the services have stopped, so a launch now waits for this one to exit.
|
||||
_instance?.StopListening();
|
||||
_tray?.Dispose();
|
||||
SaveSettings();
|
||||
if (MainWindow?.DataContext is ShellViewModel shell) shell.Dispose();
|
||||
try
|
||||
|
||||
@@ -3,6 +3,7 @@ using Chronos.App.Jobs;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Repositories;
|
||||
using Chronos.Ui.Controls;
|
||||
|
||||
@@ -30,9 +31,15 @@ public enum OrphanKind
|
||||
/// <summary>One line of the orphans report and the target of its fix.</summary>
|
||||
public sealed record OrphanRow(OrphanKind Kind, string Title, string Detail, Guid? SequenceId);
|
||||
|
||||
/// <summary>A line of "Recent maintenance": date, operation and outcome.</summary>
|
||||
public sealed record MaintenanceRow(Guid JobId, string DateText, string Text, string StateText, JobState State)
|
||||
/// <summary>
|
||||
/// A line of "Recent maintenance": date, operation and outcome; <paramref name="Detail"/>, the muted second line of a running
|
||||
/// job (what it does now) or of a paused or failed one (where it stopped), owner review 5, #65; empty otherwise, with
|
||||
/// <paramref name="DetailToolTip"/> the line whole plus the speed and time left.
|
||||
/// </summary>
|
||||
public sealed record MaintenanceRow(Guid JobId, string DateText, string Text, string StateText, JobState State, string Detail = "", string DetailToolTip = "")
|
||||
{
|
||||
public bool HasDetail => Detail.Length > 0;
|
||||
|
||||
/// <summary>The outcome's glyph and colour, as on the Jobs screen (paired with the word, never colour alone).</summary>
|
||||
public StatusKind StateKind => State switch
|
||||
{
|
||||
@@ -102,18 +109,36 @@ public static class MaintenanceReports
|
||||
return rows;
|
||||
}
|
||||
|
||||
public static IReadOnlyList<MaintenanceRow> Recent(IEnumerable<Job> jobs, int count) =>
|
||||
/// <summary>
|
||||
/// <paramref name="jobs"/> with <paramref name="changed"/> in place of its earlier state, or added when it is a maintenance
|
||||
/// job of <paramref name="archiveId"/> not among them yet (queued or started while the screen is shown, owner review 5,
|
||||
/// #65); <paramref name="jobs"/> itself for any other job.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<Job> Track(IReadOnlyList<Job> jobs, Job changed, Guid archiveId)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(jobs);
|
||||
ArgumentNullException.ThrowIfNull(changed);
|
||||
if (!MaintenanceKinds.Contains(changed.Kind) || !changed.TargetIds.Contains(archiveId)) return jobs;
|
||||
return [changed, .. jobs.Where(j => j.Id != changed.Id)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The latest <paramref name="count"/> jobs as "Recent maintenance" lines; a running one shows its percentage and what it
|
||||
/// does now from its <paramref name="live"/> progress when there is some (owner review 5, #65), else from its stored snapshot.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<MaintenanceRow> Recent(IEnumerable<Job> jobs, int count, IReadOnlyDictionary<Guid, JobProgressInfo>? live = null) =>
|
||||
[
|
||||
.. jobs.OrderByDescending(j => j.Finished ?? j.Started ?? j.Created).Take(count).Select(j =>
|
||||
{
|
||||
var when = j.Finished ?? j.Started ?? j.Created;
|
||||
var text = string.IsNullOrWhiteSpace(j.TargetLabel) ? JobText.Kind(j.Kind) : Loc.L("Archive.Recent.Line", JobText.Kind(j.Kind), j.TargetLabel);
|
||||
var entry = new JobEntry(j) { Live = j.State == JobState.Running ? live?.GetValueOrDefault(j.Id) : null };
|
||||
var state = j.State switch
|
||||
{
|
||||
JobState.Running when j.ProgressTotal > 0 => Formatting.Percent(j.ProgressDone / (double)j.ProgressTotal),
|
||||
JobState.Running when entry.Fraction is { } fraction => Formatting.Percent(fraction),
|
||||
_ => Loc.L("Jobs.State." + j.State),
|
||||
};
|
||||
return new MaintenanceRow(j.Id, Formatting.Date(when), text, state, j.State);
|
||||
return new MaintenanceRow(j.Id, Formatting.Date(when), text, state, j.State, JobText.RowStatus(entry), JobText.RowStatusToolTip(entry));
|
||||
}),
|
||||
];
|
||||
}
|
||||
@@ -13,8 +13,13 @@
|
||||
<ProjectReference Include="..\Chronos.Core.Windows\Chronos.Core.Windows.csproj" />
|
||||
<ProjectReference Include="..\Chronos.Data\Chronos.Data.csproj" />
|
||||
<ProjectReference Include="..\Chronos.Protocol\Chronos.Protocol.csproj" />
|
||||
<ProjectReference Include="..\Chronos.Server\Chronos.Server.csproj" />
|
||||
<ProjectReference Include="..\Chronos.Ui\Chronos.Ui.csproj" />
|
||||
</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>
|
||||
<InternalsVisibleTo Include="Chronos.App.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using Chronos.App.About;
|
||||
using Chronos.App.Editor;
|
||||
using Chronos.App.Import;
|
||||
using Chronos.App.Infrastructure;
|
||||
@@ -21,6 +20,7 @@ using Chronos.Core.Localization;
|
||||
using Chronos.Core.Metadata;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Updates;
|
||||
using Chronos.Core.Video;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
@@ -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>
|
||||
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>
|
||||
public static SampleData Configure(AppServices services)
|
||||
{
|
||||
@@ -84,7 +114,7 @@ public sealed class SampleData
|
||||
services.CheckForUpdateAsync = _ => Task.FromResult<ReleaseInfo?>(null);
|
||||
services.Devices.Dispose();
|
||||
services.Devices = new SampleDeviceMonitor();
|
||||
services.Sync.RemoteFactory = (_, _, _) => sample._remote;
|
||||
services.Sync.RemoteFactory = (_, _, _, _) => sample._remote;
|
||||
services.Sync.EditorFactory = (_, _, _) => sample._remote;
|
||||
// The schedules keep the sample's moment: nothing becomes due while the screenshots are taken.
|
||||
services.SchedulerTime = new FixedTime(Now);
|
||||
@@ -121,7 +151,7 @@ public sealed class SampleData
|
||||
await db.Sequences.SetTagsAsync(sequences[9].Sequence.Id, ["holy grail"]);
|
||||
|
||||
_scanSchedule = (await db.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.ArchiveScan))?.Id;
|
||||
var jobs = Jobs(sequences.Select(s => s.Sequence).ToList(), archive.Id).ToList();
|
||||
var jobs = Jobs(sequences.Select(s => s.Sequence).ToList(), archive.Id).Select(SampleJobDetails.Apply).ToList();
|
||||
foreach (var job in jobs) await db.Jobs.EnqueueAsync(job);
|
||||
await FillSchedulesAsync(db, jobs);
|
||||
await FillServerAsync(db, sequences.Select(s => s.Sequence).ToList());
|
||||
@@ -134,6 +164,16 @@ public sealed class SampleData
|
||||
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.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;
|
||||
// The jobs sample shows a deep analysis that yielded to the render (owner review 1).
|
||||
settings.PriorityQueue = true;
|
||||
@@ -232,10 +272,10 @@ public sealed class SampleData
|
||||
var originals = $$"""{"server":"{{ServerAddress}}","mode":"Originals"}""";
|
||||
var comet = await LocalAsync("Comet");
|
||||
var fog = await LocalAsync("Fog lifting");
|
||||
await db.Jobs.EnqueueAsync(Transfer(JobKind.UploadCommit, comet.Id, comet.DisplayTitle, upload, JobState.Running, 462, 1_005));
|
||||
await db.Jobs.EnqueueAsync(Transfer(JobKind.UploadCommit, fog.Id, fog.DisplayTitle, upload, JobState.Queued, 0, 0));
|
||||
await db.Jobs.EnqueueAsync(Transfer(JobKind.Download, _sunrise, "Sunrise over Superga", originals, JobState.Queued, 1_210, 2_880));
|
||||
await db.Jobs.EnqueueAsync(Transfer(JobKind.Download, _lakeComo, "Lake Como storm", originals, JobState.Paused, 300, 1_450));
|
||||
await db.Jobs.EnqueueAsync(SampleJobDetails.Apply(Transfer(JobKind.UploadCommit, comet.Id, comet.DisplayTitle, upload, JobState.Running, 462, 1_005)));
|
||||
await db.Jobs.EnqueueAsync(SampleJobDetails.Apply(Transfer(JobKind.UploadCommit, fog.Id, fog.DisplayTitle, upload, JobState.Queued, 0, 0)));
|
||||
await db.Jobs.EnqueueAsync(SampleJobDetails.Apply(Transfer(JobKind.Download, _sunrise, "Sunrise over Superga", originals, JobState.Queued, 1_210, 2_880)));
|
||||
await db.Jobs.EnqueueAsync(SampleJobDetails.Apply(Transfer(JobKind.Download, _lakeComo, "Lake Como storm", originals, JobState.Paused, 300, 1_450)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
using Chronos.Core.Model;
|
||||
|
||||
namespace Chronos.App.DesignTime;
|
||||
|
||||
/// <summary>
|
||||
/// What the sample's running and paused jobs do now (owner review 5, #65), for the design view, the screenshots and the
|
||||
/// visual tests: a pass over many photos says which photo of which sequence; a job of another kind, or one that is queued or
|
||||
/// finished, is left as it is.
|
||||
/// </summary>
|
||||
public static class SampleJobDetails
|
||||
{
|
||||
/// <summary><paramref name="job"/> with the sample detail of its kind while it runs or is paused; unchanged otherwise.</summary>
|
||||
public static Job Apply(Job job)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(job);
|
||||
if (job.State is not (JobState.Running or JobState.Paused) || job.Detail is not null) return job;
|
||||
var title = string.IsNullOrWhiteSpace(job.TargetLabel) ? null : job.TargetLabel;
|
||||
JobDetail? detail = job.Kind switch
|
||||
{
|
||||
JobKind.Scan or JobKind.Rebuild => new JobDetail(JobStep.Index, "2024/2024-09-27 Harbour sunset", 1_240, 3_600, 12, 340, JobPartUnit.Folder),
|
||||
JobKind.Verify => new JobDetail(JobStep.Verify, "Harbour sunset", 812, 2_400, 3, 41, JobPartUnit.Sequence),
|
||||
JobKind.Thumbs => new JobDetail(JobStep.Thumbs, title, 1_240, 3_600, 2, 7, JobPartUnit.Sequence),
|
||||
JobKind.Proxies => new JobDetail(JobStep.Proxies, title, 1_240, 3_600, 2, 7, JobPartUnit.Sequence),
|
||||
JobKind.LightAnalyse => new JobDetail(JobStep.Analyse, title, Part: 120, Parts: 4_812, PartUnit: JobPartUnit.Sequence),
|
||||
JobKind.DeepAnalyse => new JobDetail(JobStep.Analyse, title, job.ProgressDone, job.ProgressTotal),
|
||||
JobKind.Render or JobKind.WorkspaceRender => new JobDetail(JobStep.Encode, null, job.ProgressDone, job.ProgressTotal),
|
||||
JobKind.Convert => new JobDetail(JobStep.Convert, title, 412, 1_200, 4, 9, JobPartUnit.Sequence),
|
||||
JobKind.Import => new JobDetail(JobStep.CopyPhoto, "IMG_4812.CR3", 1_240, 4_812),
|
||||
JobKind.UploadCommit => new JobDetail(JobStep.Upload, title, job.ProgressDone, job.ProgressTotal),
|
||||
JobKind.Download => new JobDetail(JobStep.Download, title, job.ProgressDone, job.ProgressTotal),
|
||||
JobKind.Maintenance => new JobDetail(JobStep.Maintenance, "packs", Part: 3, Parts: 5, PartUnit: JobPartUnit.Step),
|
||||
_ => null,
|
||||
};
|
||||
return detail is null ? job : job with { Detail = detail };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using Chronos.App.Server;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Protocol;
|
||||
|
||||
namespace Chronos.App.DesignTime;
|
||||
|
||||
/// <summary>
|
||||
/// The sample server's jobs for the Server section's job list (owner review 5, #65), for the screenshots: empty until
|
||||
/// <see cref="Fill"/>, then a verification and a thumbnail pass running with what each does now, and a proxy pass paused.
|
||||
/// Pause, resume and cancel change the list; no event ever comes. Thread-safe; disposing it does nothing, so it can be reused.
|
||||
/// </summary>
|
||||
public sealed class SampleServerJobs : IServerJobsApi
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private List<JobDto> _jobs = [];
|
||||
|
||||
/// <summary>The sample's running and paused jobs.</summary>
|
||||
public void Fill()
|
||||
{
|
||||
var now = SampleData.Now;
|
||||
lock (_gate)
|
||||
{
|
||||
_jobs =
|
||||
[
|
||||
Job(JobKind.Verify, "Harbour sunset", JobState.Running, 812, 2_400, 38.5, 41, now.AddMinutes(-6),
|
||||
new JobDetail(JobStep.Verify, "Harbour sunset", 812, 2_400, 3, 41, JobPartUnit.Sequence)),
|
||||
Job(JobKind.Thumbs, "Sunrise over Superga", JobState.Running, 1_240, 3_600, 52.0, 45, now.AddMinutes(-3),
|
||||
new JobDetail(JobStep.Thumbs, "Sunrise over Superga", 1_240, 3_600, 2, 7, JobPartUnit.Sequence)),
|
||||
Job(JobKind.Proxies, "Alpine lake, winter", JobState.Paused, 300, 1_800, null, null, now.AddMinutes(-40),
|
||||
new JobDetail(JobStep.Proxies, "Alpine lake, winter", 300, 1_800, 1, 2, JobPartUnit.Sequence)),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Nothing runs on the server again.</summary>
|
||||
public void Clear()
|
||||
{
|
||||
lock (_gate) _jobs = [];
|
||||
}
|
||||
|
||||
public Task<Page<JobDto>> ListJobsAsync(string state, string? cursor, CancellationToken cancellationToken)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
var items = _jobs.Where(j => j.State == state).ToList();
|
||||
return Task.FromResult(new Page<JobDto>(items, null, items.Count));
|
||||
}
|
||||
}
|
||||
|
||||
public Task<JobDto> GetJobAsync(Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
lock (_gate) return Task.FromResult(_jobs.Single(j => j.Id == id));
|
||||
}
|
||||
|
||||
public Task<JobDto> PauseJobAsync(Guid id, CancellationToken cancellationToken) => SetState(id, JobState.Paused);
|
||||
|
||||
public Task<JobDto> ResumeJobAsync(Guid id, CancellationToken cancellationToken) => SetState(id, JobState.Running);
|
||||
|
||||
public Task<JobDto> CancelJobAsync(Guid id, CancellationToken cancellationToken) => SetState(id, JobState.Cancelled);
|
||||
|
||||
public async IAsyncEnumerable<ServerEvent> EventsAsync([EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
{
|
||||
await Task.Delay(Timeout.Infinite, cancellationToken).ConfigureAwait(false);
|
||||
yield break;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
|
||||
private Task<JobDto> SetState(Guid id, JobState state)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
var index = _jobs.FindIndex(j => j.Id == id);
|
||||
var job = _jobs[index] with { State = JobWire.State(state) };
|
||||
if (state is JobState.Running or JobState.Paused) _jobs[index] = job;
|
||||
else _jobs.RemoveAt(index);
|
||||
return Task.FromResult(job);
|
||||
}
|
||||
}
|
||||
|
||||
private static JobDto Job(JobKind kind, string target, JobState state, long done, long total, double? rate, double? eta, DateTimeOffset started,
|
||||
JobDetail detail) =>
|
||||
new(Guid.NewGuid(), JobWire.Kind(kind), [Guid.NewGuid()], target, JobWire.State(state), JobWire.Priority(JobPriority.Background), done, total,
|
||||
rate, eta, null, null, 1, null, started, started, null, null, JobWire.Detail(detail));
|
||||
}
|
||||
@@ -44,7 +44,10 @@ public static class EditorText
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>"Render running on Studio NAS · 1,240 / 3,600 · 11.3 fps · 3 min left"; "Render waiting on Studio NAS".</summary>
|
||||
/// <summary>
|
||||
/// "Render running on Studio NAS · 1,240 / 3,600 · 11.3 fps · 3 min left"; with what the job does now in place of the
|
||||
/// counter ("… · Encoding frame 1,240 of 3,600 · 11.3 fps · 3 min left", owner review 5, #65); "Render waiting on Studio NAS".
|
||||
/// </summary>
|
||||
public static string ServerJobDetail(Job job, string server)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(job);
|
||||
@@ -55,7 +58,8 @@ public static class EditorText
|
||||
_ => "Tooltips.Editor.ServerJob",
|
||||
};
|
||||
var parts = new List<string> { Loc.L(key, JobText.Kind(job.Kind), server) };
|
||||
if (JobText.Counter(job.ProgressDone, job.ProgressTotal) is { Length: > 0 } counter) parts.Add(counter);
|
||||
if (job.State == JobState.Running && JobText.Status(job.Detail) is { Length: > 0 } status) parts.Add(status);
|
||||
else if (JobText.Counter(job.Kind, job.ProgressDone, job.ProgressTotal) is { Length: > 0 } counter) parts.Add(counter);
|
||||
if (JobText.Speed(job.Kind, job.ItemsPerSecond) is { Length: > 0 } speed) parts.Add(speed);
|
||||
if (job.Eta is { } eta) parts.Add(Loc.L("Editor.ServerJob.Left", Formatting.Duration(eta)));
|
||||
return string.Join(Separator, parts);
|
||||
|
||||
@@ -74,7 +74,7 @@ public sealed class ProjectFiles(ShellViewModel shell)
|
||||
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.
|
||||
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);
|
||||
await shell.Sequence.ShowAsync(sequence.Id, new ProjectRequest(sequence.Id, workspace.ProjectId), own ? null : editor => Apply(editor, bundle));
|
||||
return;
|
||||
|
||||
@@ -180,6 +180,8 @@ internal sealed class ServerJobs : IAsyncDisposable
|
||||
ProgressTotal = progress.Total,
|
||||
ItemsPerSecond = progress.ItemsPerSecond,
|
||||
Eta = JobEta.FromSeconds(progress.EtaSeconds),
|
||||
// What it does now (owner review 5, #65); an older server sends none, and the last one stays.
|
||||
Detail = JobWire.FromDto(progress.Detail) ?? job.Detail,
|
||||
});
|
||||
break;
|
||||
case JobProgressEvent:
|
||||
|
||||
@@ -84,6 +84,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders,
|
||||
private readonly ImageDecoder _decoder;
|
||||
private readonly JobEngine? _engine;
|
||||
private readonly WorkspaceServerHome? _server;
|
||||
private readonly IDisposable? _hold;
|
||||
private readonly Lock _gate = new();
|
||||
private readonly List<IRenderFrameSource> _retired = [];
|
||||
private IRenderFrameSource? _frames;
|
||||
@@ -104,7 +105,9 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders,
|
||||
private int _disposed;
|
||||
|
||||
/// <param name="server">The server the project's home is (phase 5b); null for a project of this PC's archive.</param>
|
||||
public WorkspaceSequenceSource(WorkspaceSync sync, Guid projectId, ChronosDatabase db, ImageDecoder decoder, JobEngine? engine, WorkspaceServerHome? server = null)
|
||||
/// <param name="hold">Released when the source is disposed: what marks the project open in the editor (<see cref="Chronos.App.Workspace.WorkspaceHost.HoldInEditor"/>).</param>
|
||||
public WorkspaceSequenceSource(WorkspaceSync sync, Guid projectId, ChronosDatabase db, ImageDecoder decoder, JobEngine? engine, WorkspaceServerHome? server = null,
|
||||
IDisposable? hold = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sync);
|
||||
ArgumentNullException.ThrowIfNull(db);
|
||||
@@ -114,6 +117,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders,
|
||||
_decoder = decoder;
|
||||
_engine = engine;
|
||||
_server = server;
|
||||
_hold = hold;
|
||||
ProjectId = projectId;
|
||||
// This PC's engine runs the copies of the media (Update media), whatever the home.
|
||||
if (engine is not null) engine.JobChanged += OnJobChanged;
|
||||
@@ -729,6 +733,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders,
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) == 1) return;
|
||||
_hold?.Dispose();
|
||||
if (_engine is not null) _engine.JobChanged -= OnJobChanged;
|
||||
List<IRenderFrameSource> sources;
|
||||
ServerJobs? jobs;
|
||||
|
||||
@@ -44,6 +44,16 @@ public sealed class AppEnvironment
|
||||
public string LogDirectory => Path.Combine(DataDirectory, "logs");
|
||||
public string CacheDirectory => Path.Combine(DataDirectory, "cache");
|
||||
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 SettingsPath => Path.Combine(DataDirectory, AppPaths.SettingsFileName);
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@ using System.ComponentModel;
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Reflection;
|
||||
using Chronos.App.About;
|
||||
using Chronos.App.Archiving;
|
||||
using Chronos.App.Import;
|
||||
using Chronos.App.Jobs;
|
||||
@@ -13,14 +12,17 @@ using Chronos.App.Workspace;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Imaging.Decoders;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Updates;
|
||||
using Chronos.Core.Video.Managed;
|
||||
using Chronos.Core.Windows.MediaFoundation;
|
||||
using Chronos.Core.Windows.Wic;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Homes;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Processing;
|
||||
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).
|
||||
Chronos.App.Editor.EditorSettings.Groups.Bind(settings.EditorGroups, saveSettings);
|
||||
_renderNode = new RenderNodeHost(StartRenderNode);
|
||||
Share = new LibraryShare(this);
|
||||
ArchiveSetup = new EngineArchiveSetup(this);
|
||||
Sync = new SyncHost(this);
|
||||
ScheduleHost = new DesktopScheduleHost(settings, () => Database, () => Archives);
|
||||
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).
|
||||
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;
|
||||
Server = new ServerSession(settings, saveSettings, new ChronosServerApiFactory(), new DpapiTokenProtector());
|
||||
Encoders = new MediaFoundationInventory();
|
||||
@@ -110,6 +115,7 @@ public sealed class AppServices : IAsyncDisposable
|
||||
{
|
||||
if (_server is not null) _server.PropertyChanged -= OnServerChanged;
|
||||
_server = value;
|
||||
_server.IsOwnLibrary = Share.IsOwn;
|
||||
_server.PropertyChanged += OnServerChanged;
|
||||
UpdateRenderNode();
|
||||
Sync.Update();
|
||||
@@ -119,6 +125,9 @@ public sealed class AppServices : IAsyncDisposable
|
||||
/// <summary>Sync with the signed-in server: engine, job connection, background comparison.</summary>
|
||||
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>
|
||||
/// 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.
|
||||
@@ -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>
|
||||
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>
|
||||
public IDeviceMonitor Devices { get; set; } = new WindowsDeviceMonitor();
|
||||
|
||||
@@ -201,7 +216,8 @@ public sealed class AppServices : IAsyncDisposable
|
||||
new(services.Processing?.Options ?? WorkspaceJobOptions.For(archives).Processing,
|
||||
() => services.Settings.PauseUploadsOnMetered && MeteredNetwork.IsMetered(),
|
||||
services.Workspace.MovedAsync,
|
||||
() => services.Workspace.Root);
|
||||
() => services.Workspace.Root,
|
||||
services.Workspace.SameServer);
|
||||
|
||||
/// <summary>
|
||||
/// 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();
|
||||
UpdateRenderNode();
|
||||
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>
|
||||
@@ -284,6 +301,8 @@ public sealed class AppServices : IAsyncDisposable
|
||||
_schedulerReady.TrySetResult(false);
|
||||
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
|
||||
{
|
||||
await StartJobsAsync(Database, startEngine: true, ct);
|
||||
@@ -316,6 +335,8 @@ public sealed class AppServices : IAsyncDisposable
|
||||
{
|
||||
await _stopping.CancelAsync().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);
|
||||
if (Scheduler is not null) await Scheduler.DisposeAsync().ConfigureAwait(false);
|
||||
_stopping.Dispose();
|
||||
@@ -348,6 +369,7 @@ public sealed class AppServices : IAsyncDisposable
|
||||
await StartSchedulerAsync(ct).ConfigureAwait(false);
|
||||
if (reopen is null)
|
||||
{
|
||||
await Share.StartAsync(ct).ConfigureAwait(false);
|
||||
await ScanNowAsync(started, ct).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
@@ -356,6 +378,7 @@ public sealed class AppServices : IAsyncDisposable
|
||||
{
|
||||
if (!string.Equals(reopen, Settings.LastArchivePath, StringComparison.OrdinalIgnoreCase)) return;
|
||||
if (!await ReopenAsync(reopen, ct).ConfigureAwait(false)) continue;
|
||||
await Share.StartAsync(ct).ConfigureAwait(false);
|
||||
await ScanNowAsync(null, ct).ConfigureAwait(false);
|
||||
Scheduler?.Wake();
|
||||
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)
|
||||
{
|
||||
_wic = new WicDecoderProvider();
|
||||
@@ -486,19 +569,24 @@ public sealed class AppServices : IAsyncDisposable
|
||||
MemoryBudget = () => ProcessingTuning.MemoryBudget(Settings, GC.GetGCMemoryInfo().TotalAvailableMemoryBytes),
|
||||
// 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 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)),
|
||||
new WorkspaceCleanStep(() => Workspace), new WorkspaceTrashStep(() => Workspace)],
|
||||
new WorkspaceCleanStep(() => Workspace), new WorkspaceTrashStep(() => Workspace), new ShareUploadsStep(() => Share)],
|
||||
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.
|
||||
SequenceChanged = (id, _, _) =>
|
||||
// While the library is shared, its clients see thumbnails and proxies of what a scan finds, as a server's do.
|
||||
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);
|
||||
return Task.CompletedTask;
|
||||
return Share.SequenceChangedAsync(id, change, token);
|
||||
},
|
||||
ProjectsChanged = (changed, token) => Share.ProjectsChangedAsync(changed, token),
|
||||
};
|
||||
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).
|
||||
Archives.Videos.ProtectedFolders = () => [Workspace.Root];
|
||||
Archives.Videos.ProtectedFolders = () => [Workspace.Root, Share.Folder];
|
||||
Archives.Videos.Servers = Sync;
|
||||
Processing = new ProcessingService(database, ProcessingOptions(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 });
|
||||
// The workspace's size limit runs after each copy of media into it (phase 5c).
|
||||
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.Update();
|
||||
// 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),
|
||||
Host = EncoderHost.Client,
|
||||
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,
|
||||
CacheStore.Folder(Environment, Settings)),
|
||||
};
|
||||
@@ -554,7 +645,8 @@ public sealed class AppServices : IAsyncDisposable
|
||||
var node = new RenderNodeClient(client, processing.Options, new RenderNodeOptions
|
||||
{
|
||||
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),
|
||||
});
|
||||
node.Start();
|
||||
|
||||
@@ -10,6 +10,7 @@ using Chronos.Core.Naming;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Repositories;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Ui.Theming;
|
||||
|
||||
namespace Chronos.App.Infrastructure;
|
||||
@@ -66,6 +67,61 @@ public sealed class TrustedCertificate
|
||||
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\<id></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>
|
||||
/// 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
|
||||
@@ -257,6 +313,22 @@ public sealed class AppSettings
|
||||
public List<TrustedCertificate> TrustedCertificates { 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>
|
||||
public bool RenderNodeOptIn { get; set; }
|
||||
|
||||
@@ -377,6 +449,7 @@ public sealed class AppSettings
|
||||
ProtectedToken = ProtectedToken,
|
||||
TrustedCertificates = TrustedCertificates,
|
||||
RecentServers = RecentServers,
|
||||
KnownServers = KnownServers,
|
||||
Window = Window,
|
||||
RailCollapsed = RailCollapsed,
|
||||
EditorGroups = EditorGroups,
|
||||
@@ -400,6 +473,7 @@ public sealed class AppSettings
|
||||
copy.WorkspaceFolder = null;
|
||||
copy.WorkspaceRecent = [];
|
||||
copy.WorkspaceOpened = [];
|
||||
copy.KnownServers = [];
|
||||
return copy;
|
||||
}
|
||||
|
||||
@@ -423,6 +497,7 @@ public sealed class AppSettings
|
||||
imported.WorkspaceFolder = WorkspaceFolder;
|
||||
imported.WorkspaceRecent = WorkspaceRecent;
|
||||
imported.WorkspaceOpened = WorkspaceOpened;
|
||||
imported.KnownServers = KnownServers;
|
||||
return imported;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,10 +5,12 @@ using System.Text;
|
||||
using Chronos.App.Settings;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Windows.Codecs;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Sqlite;
|
||||
using Chronos.Data.Sync;
|
||||
|
||||
namespace Chronos.App.Infrastructure;
|
||||
|
||||
@@ -34,8 +36,11 @@ public static class DiagnosticsBundle
|
||||
var settings = services.Settings.ToJson();
|
||||
var tailBytes = AppLogging.DiagnosticsTailBytes(services.Settings);
|
||||
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 () =>
|
||||
{
|
||||
report += HomesLines(workspace, cache);
|
||||
var failures = services.Database is { } db ? (await db.Jobs.ListAsync(JobState.Failed, FailedJobs, null, ct).ConfigureAwait(false)).Items : [];
|
||||
var codecs = Codecs(services.Encoders);
|
||||
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();
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
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) =>
|
||||
string.IsNullOrWhiteSpace(settings.CacheFolder) ? environment.CacheDirectory : settings.CacheFolder!;
|
||||
|
||||
/// <summary>The servers' homes in the cache (<c><cache>\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><cache>\servers\<folder></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>
|
||||
public static void Prepare(string folder)
|
||||
{
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
using System.Reflection;
|
||||
|
||||
namespace Chronos.App.Infrastructure;
|
||||
|
||||
/// <summary>
|
||||
/// Public links (BRIEF §19.4, amended 2026-10-23, R2): the Gitea repository that publishes the releases. Release
|
||||
/// builds pass the repository they publish to as the ChronosReleasesUrl property.
|
||||
/// </summary>
|
||||
public static class ProductLinks
|
||||
{
|
||||
/// <summary>The repository of local builds, as Directory.Build.props sets it.</summary>
|
||||
public const string DefaultRepository = "https://gitea.encke-hake.ts.net/BalboSoft/Chronos";
|
||||
|
||||
/// <summary>"https://host/owner/name" of the releases repository.</summary>
|
||||
public static string Repository { get; } = Normalise(
|
||||
typeof(ProductLinks).Assembly.GetCustomAttributes<AssemblyMetadataAttribute>()
|
||||
.FirstOrDefault(a => a.Key == "ChronosReleasesUrl")?.Value) ?? DefaultRepository;
|
||||
|
||||
public static string Releases => $"{Repository}/releases";
|
||||
|
||||
/// <summary>The published stable releases, from which the update check takes the newest (BRIEF §18).</summary>
|
||||
public static string StableReleasesApi => StableReleasesApiOf(Repository);
|
||||
|
||||
/// <summary>The licence (EULA) at the root of the releases repository (BRIEF §12.9).</summary>
|
||||
public static string Licence => $"{Repository}/src/branch/main/EULA.md";
|
||||
|
||||
/// <summary>Where translations are reviewed by the community (BRIEF §16).</summary>
|
||||
public static string Issues => $"{Repository}/issues";
|
||||
|
||||
/// <summary>
|
||||
/// The Gitea API address of a repository's published stable releases: "https://host[/prefix]/owner/name" →
|
||||
/// "https://host[/prefix]/api/v1/repos/owner/name/releases?draft=false&pre-release=false&limit=50" (Gitea may
|
||||
/// be served under a path prefix).
|
||||
/// </summary>
|
||||
public static string StableReleasesApiOf(string repository)
|
||||
{
|
||||
var uri = new Uri(repository, UriKind.Absolute);
|
||||
var segments = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (segments.Length < 2) throw new ArgumentException($"Not a repository address: {repository}", nameof(repository));
|
||||
var prefix = string.Concat(segments[..^2].Select(s => "/" + s));
|
||||
return $"{uri.GetLeftPart(UriPartial.Authority)}{prefix}/api/v1/repos/{segments[^2]}/{segments[^1]}/releases?draft=false&pre-release=false&limit=50";
|
||||
}
|
||||
|
||||
/// <summary>The address without surrounding spaces, trailing slashes or ".git"; null when empty.</summary>
|
||||
internal static string? Normalise(string? repository)
|
||||
{
|
||||
var text = repository?.Trim().TrimEnd('/');
|
||||
if (text is not null && text.EndsWith(".git", StringComparison.OrdinalIgnoreCase)) text = text[..^4];
|
||||
return string.IsNullOrEmpty(text) ? null : text;
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
new(WorkspaceCleanup, "Workspace clean-up", ScheduleActions.Cleanup, ScheduleRecurrence.DailyAt(WorkspaceCleanupTime),
|
||||
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() ?? [];
|
||||
@@ -84,7 +86,11 @@ public sealed class DesktopScheduleHost(AppSettings settings, Func<ChronosDataba
|
||||
public async ValueTask<Archive?> GetArchiveAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
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;
|
||||
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 ›
|
||||
/// 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
|
||||
/// 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>
|
||||
public sealed class CacheTrimStep(Func<string> folder, Func<long> limitBytes) : ICleanupStep
|
||||
{
|
||||
public const string StepName = "cache-trim";
|
||||
|
||||
/// <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;
|
||||
|
||||
|
||||
@@ -32,6 +32,12 @@ public sealed class JobEntry(Job job)
|
||||
public TimeSpan? Eta => Live?.Eta ?? Job.Eta;
|
||||
public string? Message => Live?.Message;
|
||||
|
||||
/// <summary>
|
||||
/// What the job does now (owner review 5, #65): the live detail while it runs, else the one stored with its last saved
|
||||
/// progress (where a paused or failed job stopped); null when its handler reports none.
|
||||
/// </summary>
|
||||
public JobDetail? Detail => Live?.Detail ?? Job.Detail;
|
||||
|
||||
/// <summary>0…1, or null while the total is unknown.</summary>
|
||||
public double? Fraction => Total > 0 ? Math.Clamp((double)Done / Total, 0, 1) : null;
|
||||
|
||||
|
||||
@@ -36,6 +36,17 @@ public sealed class JobRowViewModel : ObservableObject
|
||||
|
||||
public string Target => _entry.Job.TargetLabel ?? string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// What a running job does now, or where a paused or failed job stopped (owner review 5, #65), under the target; empty
|
||||
/// otherwise. Not announced: a screen reader hears state changes only (DECISIONS row 158).
|
||||
/// </summary>
|
||||
public string StatusText => JobText.RowStatus(_entry);
|
||||
|
||||
public bool HasStatus => StatusText.Length > 0;
|
||||
|
||||
/// <summary>The status line whole, then the speed and time left of a running job.</summary>
|
||||
public string StatusToolTip => JobText.RowStatusToolTip(_entry);
|
||||
|
||||
/// <summary>A schedule queued the job (owner review 2, R10): the row shows a "Scheduled" pill.</summary>
|
||||
public bool IsScheduled => _entry.Job.ScheduleId is not null;
|
||||
|
||||
@@ -136,6 +147,9 @@ public sealed class JobRowViewModel : ObservableObject
|
||||
return;
|
||||
}
|
||||
OnPropertyChanged(nameof(Progress));
|
||||
OnPropertyChanged(nameof(StatusText));
|
||||
OnPropertyChanged(nameof(HasStatus));
|
||||
OnPropertyChanged(nameof(StatusToolTip));
|
||||
OnPropertyChanged(nameof(PercentText));
|
||||
OnPropertyChanged(nameof(SpeedText));
|
||||
OnPropertyChanged(nameof(LeftText));
|
||||
|
||||
@@ -29,6 +29,141 @@ public static class JobText
|
||||
public static string Counter(long done, long total) =>
|
||||
total > 0 ? Loc.L("Jobs.Counter", Formatting.Count(done), Formatting.Count(total)) : string.Empty;
|
||||
|
||||
/// <summary>"1,240 / 3,600", or "52 GB / 1.1 TB" for a job that counts bytes; empty while the total is unknown.</summary>
|
||||
public static string Counter(JobKind kind, long done, long total) => total <= 0 ? string.Empty
|
||||
: CountsBytes(kind) ? Loc.L("Jobs.Counter", Formatting.Bytes(done), Formatting.Bytes(total))
|
||||
: Counter(done, total);
|
||||
|
||||
/// <summary>The longest status line the job bar shows (<see cref="Bar"/>); the item goes first, the full line is in the Jobs table.</summary>
|
||||
public const int BarStatusLength = 60;
|
||||
|
||||
/// <summary>
|
||||
/// What a job does now (owner review 5, #65), from its <paramref name="detail"/>: the step ("Verifying photo 812 of 2,400"),
|
||||
/// the item ("Harbour sunset", a folder kept left to right) and the part ("sequence 3 of 41"), each left out when empty;
|
||||
/// a clean-up or maintenance sub-step names itself in place of the step. A step this build does not know (a newer server)
|
||||
/// shows its counts only. Empty for no detail.
|
||||
/// </summary>
|
||||
public static string Status(JobDetail? detail) => Status(detail, int.MaxValue);
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="Status(JobDetail?)"/> in at most <paramref name="maxLength"/> characters: a longer line drops the item
|
||||
/// first, then is cut with an ellipsis.
|
||||
/// </summary>
|
||||
public static string Status(JobDetail? detail, int maxLength)
|
||||
{
|
||||
if (detail is null) return string.Empty;
|
||||
var (step, consumed) = StepPhrase(detail);
|
||||
var item = consumed ? null : ItemText(detail.Item);
|
||||
var part = PartPhrase(detail);
|
||||
var full = JoinParts(step, item, part);
|
||||
if (full.Length <= maxLength) return full;
|
||||
if (item is not null && JoinParts(step, null, part) is { Length: > 0 } shorter) full = shorter;
|
||||
return Cut(full, maxLength);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The status line of a Jobs row: what a running job does now; "Stopped at …" with where a paused or failed job stopped;
|
||||
/// empty for queued and finished jobs, and for a job whose handler reports no detail.
|
||||
/// </summary>
|
||||
public static string RowStatus(JobEntry entry)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entry);
|
||||
return entry.State switch
|
||||
{
|
||||
JobState.Running => Status(entry.Detail),
|
||||
JobState.Paused or JobState.Failed when Status(entry.Job.Detail) is { Length: > 0 } status => Loc.L("Jobs.Detail.StoppedAt", status),
|
||||
_ => string.Empty,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The tooltip of a row's status line: the line whole, then the speed and the time left while the job runs.</summary>
|
||||
public static string RowStatusToolTip(JobEntry entry)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entry);
|
||||
var parts = new List<string>(3);
|
||||
if (RowStatus(entry) is { Length: > 0 } status) parts.Add(status);
|
||||
if (entry.State == JobState.Running)
|
||||
{
|
||||
if (Speed(entry.Job.Kind, entry.ItemsPerSecond) is { Length: > 0 } speed) parts.Add(speed);
|
||||
if (entry.Eta is { } eta) parts.Add(Loc.L("Jobs.Bar.Left", Formatting.Duration(eta)));
|
||||
}
|
||||
return string.Join(Loc.Separator, parts);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The step phrase, counted when the item is ("Verifying photo 812 of 2,400"), and whether it took the item's place (the
|
||||
/// named sub-step of a clean-up or maintenance).
|
||||
/// </summary>
|
||||
private static (string? Phrase, bool ConsumedItem) StepPhrase(JobDetail detail)
|
||||
{
|
||||
var counted = detail.ItemTotal > 0;
|
||||
var done = Formatting.Count(Math.Clamp(detail.ItemDone, 0, detail.ItemTotal));
|
||||
var total = Formatting.Count(detail.ItemTotal);
|
||||
var counts = counted ? Loc.L("Jobs.Detail.Count", done, total) : null;
|
||||
// A clean-up step ("job-history") and a maintenance step ("packs") name themselves.
|
||||
var named = detail.Step switch
|
||||
{
|
||||
JobStep.Cleanup => Known("Jobs.Schedule.Step." + Pascal(detail.Item)),
|
||||
JobStep.Maintenance => Known("Jobs.Maintenance.Step." + Pascal(detail.Item)),
|
||||
_ => null,
|
||||
};
|
||||
if (named is not null) return (JoinParts(Loc.L(named), counts, null), true);
|
||||
if (detail.Step == JobStep.None) return (counts, false);
|
||||
var key = "Jobs.Step." + detail.Step;
|
||||
// The item of a clean-up or maintenance step is a key, not data: one this build does not know is never shown.
|
||||
if (detail.Step is JobStep.Cleanup or JobStep.Maintenance) return (JoinParts(Known(key) is { } step ? Loc.L(step) : null, counts, null), true);
|
||||
if (counted && Known(key + ".Count") is { } countKey) return (Loc.L(countKey, done, total), false);
|
||||
if (Known(key) is null) return (counts, false);
|
||||
return (JoinParts(Loc.L(key), counts, null), false);
|
||||
}
|
||||
|
||||
/// <summary>"sequence 3 of 41" when the job has more than one part; null otherwise.</summary>
|
||||
private static string? PartPhrase(JobDetail detail)
|
||||
{
|
||||
if (detail.Parts <= 1) return null;
|
||||
var part = Formatting.Count(Math.Clamp(detail.Part, 0, detail.Parts));
|
||||
var parts = Formatting.Count(detail.Parts);
|
||||
return detail.PartUnit != JobPartUnit.None && Known("Jobs.Part." + detail.PartUnit) is { } key
|
||||
? Loc.L(key, part, parts)
|
||||
: Loc.L("Jobs.Detail.Count", part, parts);
|
||||
}
|
||||
|
||||
/// <summary>The item as data: a folder or a path kept left to right inside right-to-left text (DECISIONS row 218).</summary>
|
||||
private static string? ItemText(string? item)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(item)) return null;
|
||||
return item.Contains('/') || item.Contains('\\') ? Formatting.LeftToRight(item) : item;
|
||||
}
|
||||
|
||||
/// <summary>"job-history" → "JobHistory"; null for a key that is not one (data from a newer peer).</summary>
|
||||
private static string? Pascal(string? key)
|
||||
{
|
||||
if (string.IsNullOrEmpty(key) || key.Length > 40 || !key.All(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_')) return null;
|
||||
return string.Concat(key.Split('-', '_', StringSplitOptions.RemoveEmptyEntries).Select(p => char.ToUpperInvariant(p[0]) + p[1..]));
|
||||
}
|
||||
|
||||
/// <summary>The key when the catalog has it (the step, unit or sub-step of a newer peer may have none); null otherwise.</summary>
|
||||
private static string? Known(string? key) => key is not null && !key.EndsWith('.') && Loc.Get(key, Loc.Culture) is not null ? key : null;
|
||||
|
||||
private static string JoinParts(string? a, string? b, string? c)
|
||||
{
|
||||
var pieces = new List<string>(3);
|
||||
if (!string.IsNullOrEmpty(a)) pieces.Add(a);
|
||||
if (!string.IsNullOrEmpty(b)) pieces.Add(b);
|
||||
if (!string.IsNullOrEmpty(c)) pieces.Add(c);
|
||||
return string.Join(Loc.Separator, pieces);
|
||||
}
|
||||
|
||||
/// <summary>Cuts <paramref name="text"/> to <paramref name="max"/> characters with an ellipsis, closing a left-to-right island it cut into.</summary>
|
||||
private static string Cut(string text, int max)
|
||||
{
|
||||
if (text.Length <= max) return text;
|
||||
var length = Math.Max(1, max - 1);
|
||||
if (char.IsHighSurrogate(text[length - 1])) length--;
|
||||
var cut = text[..length] + "…";
|
||||
return cut.Count(c => c == '') > cut.Count(c => c == '') ? cut + "" : cut;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The "Left" column: time left while running, "after n" while queued, the finish time of the history.
|
||||
/// </summary>
|
||||
@@ -71,13 +206,22 @@ public static class JobText
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Job bar line (DESIGN §4): "Render · Harbour sunset · 2,232 / 3,600 · 11.3 fps · 2 min left".
|
||||
/// Job bar line (DESIGN §4): "Render · Harbour sunset · 2,232 / 3,600 · 11.3 fps · 2 min left"; with a detail, what the
|
||||
/// job does now in place of the counter ("Scan · Archive 2024 · Indexing photo 1,240 of 3,600 · folder 12 of 340 · 41/s ·
|
||||
/// 3 min left", at most <see cref="BarStatusLength"/> characters of it); a job that counts bytes shows sizes.
|
||||
/// </summary>
|
||||
public static string Bar(JobEntry entry)
|
||||
public static string Bar(JobEntry entry) => Bar(entry, BarStatusLength);
|
||||
|
||||
/// <summary>The job bar's tooltip: its line with what the job does now whole, the item (sequence, folder) included.</summary>
|
||||
public static string BarToolTip(JobEntry entry) => Bar(entry, int.MaxValue);
|
||||
|
||||
private static string Bar(JobEntry entry, int statusLength)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entry);
|
||||
var parts = new List<string>(5) { Kind(entry.Job.Kind) };
|
||||
if (!string.IsNullOrWhiteSpace(entry.Job.TargetLabel)) parts.Add(entry.Job.TargetLabel!);
|
||||
if (Counter(entry.Done, entry.Total) is { Length: > 0 } counter) parts.Add(counter);
|
||||
if (Status(entry.Detail, statusLength) is { Length: > 0 } status) parts.Add(status);
|
||||
else if (Counter(entry.Job.Kind, entry.Done, entry.Total) is { Length: > 0 } counter) parts.Add(counter);
|
||||
if (Speed(entry.Job.Kind, entry.ItemsPerSecond) is { Length: > 0 } speed) parts.Add(speed);
|
||||
if (entry.Eta is { } eta) parts.Add(Loc.L("Jobs.Bar.Left", Formatting.Duration(eta)));
|
||||
return string.Join(Loc.Separator, parts);
|
||||
|
||||
@@ -117,11 +117,7 @@ public sealed class LibraryActions(ShellViewModel shell)
|
||||
await remote.Service.EnqueueSendExportsAsync(engine, remote.Server, selected.Sequence);
|
||||
return true;
|
||||
case SyncAction.DownloadOriginals when entry is not null:
|
||||
if ((entry.Local?.ArchiveId ?? (await Services.Sync.CurrentArchiveAsync())?.Id) is not { } archive)
|
||||
{
|
||||
shell.Notify(Loc.L("Errors.Sync.NoArchive"));
|
||||
return false;
|
||||
}
|
||||
if (await Services.Sync.OriginalsForDownloadAsync(entry.Local, (title, message, isError) => shell.Notify(title, message, isError: isError)) is not { } archive) return false;
|
||||
await remote.Service.EnqueueDownloadAsync(engine, remote.Server, entry.Id, entry.Title, SyncDownloadMode.Originals, archive);
|
||||
return true;
|
||||
case SyncAction.GetExports when entry is not null:
|
||||
|
||||
@@ -299,14 +299,20 @@
|
||||
<ItemsControl ItemsSource="{Binding Recent}" Focusable="False">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type ar:MaintenanceRow}">
|
||||
<Grid Height="28">
|
||||
<Grid MinHeight="28">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="90" />
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{Binding DateText}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" Typography.NumeralAlignment="Tabular" />
|
||||
<TextBlock Grid.Column="1" Text="{Binding Text}" Margin="12,0" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" ToolTip="{Binding Text}" />
|
||||
<!-- A running line says what its job does now under it, muted (owner review 5, #65); a paused one where it stopped. -->
|
||||
<StackPanel Grid.Column="1" Margin="12,0" VerticalAlignment="Center">
|
||||
<TextBlock Text="{Binding Text}" TextTrimming="CharacterEllipsis" ToolTip="{Binding Text}" />
|
||||
<TextBlock Text="{Binding Detail}" FontSize="{StaticResource Size.Chip}" Foreground="{DynamicResource Brush.TextMuted}" TextTrimming="CharacterEllipsis"
|
||||
Typography.NumeralAlignment="Tabular" ToolTip="{Binding DetailToolTip}" Margin="0,0,0,3"
|
||||
Visibility="{Binding HasDetail, Converter={StaticResource BoolToVisibility}}" />
|
||||
</StackPanel>
|
||||
<!-- The outcome in its state's colour and glyph (Archive.html: accent while running, green when done). -->
|
||||
<ui:StatusGlyph Grid.Column="2" Kind="{Binding StateKind}" Text="{Binding StateText}" FontSize="12" VerticalAlignment="Center"
|
||||
Typography.NumeralAlignment="Tabular" ToolTip="{Binding StateToolTip}" />
|
||||
|
||||
@@ -34,6 +34,7 @@ namespace Chronos.App.Sections;
|
||||
public sealed class ArchiveViewModel : SectionViewModel
|
||||
{
|
||||
private const int RecentCount = 6;
|
||||
private static readonly TimeSpan RecentInterval = TimeSpan.FromMilliseconds(500);
|
||||
private const int PageSize = 1000;
|
||||
private static readonly TimeSpan ReloadDelay = TimeSpan.FromSeconds(2);
|
||||
|
||||
@@ -72,6 +73,13 @@ public sealed class ArchiveViewModel : SectionViewModel
|
||||
private IReadOnlyList<ChartItem> _formats = [];
|
||||
private IReadOnlyList<HealthLineViewModel> _health = [];
|
||||
private IReadOnlyList<MaintenanceRow> _recent = [];
|
||||
|
||||
/// <summary>The jobs behind <see cref="Recent"/>, their running ones' latest progress, and the ids whose progress counts here.</summary>
|
||||
private IReadOnlyList<Job> _recentJobs = [];
|
||||
private readonly Dictionary<Guid, JobProgressInfo> _recentLive = [];
|
||||
private readonly System.Collections.Concurrent.ConcurrentDictionary<Guid, JobProgressInfo> _recentPending = new();
|
||||
private HashSet<Guid> _recentRunning = [];
|
||||
private CoalescingThrottle? _recentThrottle;
|
||||
private IReadOnlyList<DuplicateRowViewModel>? _duplicates;
|
||||
private IReadOnlyList<OrphanRowViewModel>? _orphans;
|
||||
private bool _findingDuplicates;
|
||||
@@ -524,7 +532,12 @@ public sealed class ArchiveViewModel : SectionViewModel
|
||||
{
|
||||
_reloadDelay.Stop();
|
||||
_search?.Cancel();
|
||||
if (_jobEvents && Services.Jobs is { } jobs) jobs.JobChanged -= OnJobChanged;
|
||||
if (_jobEvents && Services.Jobs is { } jobs)
|
||||
{
|
||||
jobs.JobChanged -= OnJobChanged;
|
||||
jobs.Progress -= OnProgress;
|
||||
}
|
||||
_recentThrottle?.Dispose();
|
||||
_waitingReorganize = null;
|
||||
_dialog?.Dispose();
|
||||
base.Dispose();
|
||||
@@ -663,6 +676,10 @@ public sealed class ArchiveViewModel : SectionViewModel
|
||||
foreach (var kind in MaintenanceReports.MaintenanceKinds)
|
||||
jobs.AddRange((await db.Jobs.ListAsync(null, kind, RecentCount)).Items.Where(j => j.TargetIds.Contains(archive.Id)));
|
||||
if (!IsShowing(archive)) return;
|
||||
_recentJobs = jobs;
|
||||
_recentLive.Clear();
|
||||
_recentPending.Clear();
|
||||
Volatile.Write(ref _recentRunning, [.. jobs.Where(j => j.State == JobState.Running).Select(j => j.Id)]);
|
||||
Recent = MaintenanceReports.Recent(jobs, RecentCount);
|
||||
var scan = jobs.Where(j => j.Kind == JobKind.Scan && j is { State: JobState.Done, Finished: not null, Started: not null })
|
||||
.MaxBy(j => j.Finished);
|
||||
@@ -675,15 +692,59 @@ public sealed class ArchiveViewModel : SectionViewModel
|
||||
{
|
||||
if (_jobEvents || Services.Jobs is not { } jobs) return;
|
||||
jobs.JobChanged += OnJobChanged;
|
||||
// A running Recent line follows its job (owner review 5, #65), at most twice a second.
|
||||
_recentThrottle = new CoalescingThrottle(RecentInterval, SynchronizationContext.Current, FlushRecent);
|
||||
jobs.Progress += OnProgress;
|
||||
_jobEvents = true;
|
||||
}
|
||||
|
||||
/// <summary>Progress of a running job of "Recent maintenance" (any thread): kept until the next flush.</summary>
|
||||
private void OnProgress(JobProgressInfo progress)
|
||||
{
|
||||
if (!Volatile.Read(ref _recentRunning).Contains(progress.JobId)) return;
|
||||
_recentPending[progress.JobId] = progress;
|
||||
_recentThrottle?.Signal();
|
||||
}
|
||||
|
||||
/// <summary>A maintenance job changed state: its Recent line shows it, and its progress counts while it runs (UI thread).</summary>
|
||||
private void TrackRecent(Job job)
|
||||
{
|
||||
if (_archive is not { } archive || !_loaded) return;
|
||||
var jobs = MaintenanceReports.Track(_recentJobs, job, archive.Id);
|
||||
if (ReferenceEquals(jobs, _recentJobs)) return;
|
||||
_recentJobs = jobs;
|
||||
var running = new HashSet<Guid>(Volatile.Read(ref _recentRunning));
|
||||
if (job.State == JobState.Running) running.Add(job.Id);
|
||||
else
|
||||
{
|
||||
running.Remove(job.Id);
|
||||
_recentLive.Remove(job.Id);
|
||||
}
|
||||
Volatile.Write(ref _recentRunning, running);
|
||||
Recent = MaintenanceReports.Recent(_recentJobs, RecentCount, _recentLive);
|
||||
}
|
||||
|
||||
/// <summary>The running Recent lines with their latest progress (UI thread).</summary>
|
||||
private void FlushRecent()
|
||||
{
|
||||
var changed = false;
|
||||
foreach (var id in _recentPending.Keys)
|
||||
{
|
||||
if (!_recentPending.TryRemove(id, out var progress) || !_recentRunning.Contains(id)) continue;
|
||||
_recentLive[id] = progress;
|
||||
changed = true;
|
||||
}
|
||||
if (changed) Recent = MaintenanceReports.Recent(_recentJobs, RecentCount, _recentLive);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A finished job on this archive or its sequences changes the figures: read them again once the jobs settle (a
|
||||
/// burst of analyses after an import reloads once). Jobs of other archives are none of this screen's business.
|
||||
/// A maintenance job of this archive queued, started, paused or ended: its Recent line follows it, live while it runs
|
||||
/// (owner review 5, #65). A finished job on this archive or its sequences changes the figures: read them again once the
|
||||
/// jobs settle (a burst of analyses after an import reloads once). Jobs of other archives are none of this screen's business.
|
||||
/// </summary>
|
||||
private void OnJobChanged(Job job)
|
||||
{
|
||||
if (MaintenanceReports.MaintenanceKinds.Contains(job.Kind)) System.Windows.Application.Current?.Dispatcher.BeginInvoke(() => TrackRecent(job));
|
||||
if (job.State is not (JobState.Done or JobState.Failed)) return;
|
||||
if (job.Kind is not (JobKind.Scan or JobKind.Rebuild or JobKind.Verify or JobKind.Maintenance or JobKind.Import or JobKind.Proxies or JobKind.Thumbs
|
||||
or JobKind.LightAnalyse or JobKind.DeepAnalyse or JobKind.Move or JobKind.Convert)) return;
|
||||
|
||||
@@ -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>
|
||||
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\<id>\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()
|
||||
{
|
||||
|
||||
@@ -187,13 +187,20 @@
|
||||
ui:ButtonIcon.Glyph="{StaticResource Icon.ChevronRight}" Command="{Binding ToggleLogCommand}"
|
||||
ToolTip="{Binding ToggleToolTip}" AutomationProperties.Name="{Binding ToggleName}" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Muted}" Text="{Binding Kind}" Margin="10,0,0,0" ToolTip="{Binding Kind}" />
|
||||
<!-- A job a schedule queued carries the "Scheduled" pill after its target, which gives way first. -->
|
||||
<!-- A job a schedule queued carries the "Scheduled" pill after its target, which gives way first. A running job's
|
||||
status line (what it does now; where a paused one stopped) sits under the target inside the 38 px row, muted, and is
|
||||
never announced (DECISIONS row 158). -->
|
||||
<DockPanel Grid.Column="2" Margin="10,0,0,0">
|
||||
<Border DockPanel.Dock="Right" Style="{StaticResource Pill.Auto}" Height="20" Padding="7,0" Margin="8,0,0,0" VerticalAlignment="Center"
|
||||
ToolTip="{l:Loc Tooltips.Jobs.Scheduled}" Visibility="{Binding IsScheduled, Converter={StaticResource BoolToVisibility}}">
|
||||
<TextBlock Text="{l:Loc Jobs.Scheduled}" FontSize="{StaticResource Size.Chip}" Foreground="{DynamicResource Brush.Accent}" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<TextBlock Style="{StaticResource Text.Cell}" Text="{Binding Target}" ToolTip="{Binding Target}" />
|
||||
<StackPanel VerticalAlignment="Center">
|
||||
<TextBlock Style="{StaticResource Text.Cell}" Text="{Binding Target}" ToolTip="{Binding Target}" />
|
||||
<TextBlock x:Name="Status" Style="{StaticResource Text.Cell}" Text="{Binding StatusText}" ToolTip="{Binding StatusToolTip}"
|
||||
FontSize="{StaticResource Size.Chip}" Foreground="{DynamicResource Brush.TextMuted}"
|
||||
Visibility="{Binding HasStatus, Converter={StaticResource BoolToVisibility}}" />
|
||||
</StackPanel>
|
||||
</DockPanel>
|
||||
<Grid Grid.Column="3" Margin="10,0,0,0">
|
||||
<Grid.ColumnDefinitions>
|
||||
|
||||
@@ -457,7 +457,8 @@ public sealed class JobsViewModel : SectionViewModel
|
||||
private void UpdateShell()
|
||||
{
|
||||
if (_model.Current is { } current)
|
||||
Shell.SetJob(JobText.Bar(current), current.Fraction ?? 0, indeterminate: current.Fraction is null, name: JobText.Name(current.Job));
|
||||
Shell.SetJob(JobText.Bar(current), current.Fraction ?? 0, indeterminate: current.Fraction is null, name: JobText.Name(current.Job),
|
||||
toolTip: JobText.BarToolTip(current));
|
||||
else
|
||||
Shell.SetJob(null, 0);
|
||||
// The status strip and the Running chip count the same jobs: running or paused (Jobs.html). The rail badge adds the
|
||||
|
||||
@@ -189,7 +189,7 @@ public sealed class SequencePickerViewModel : LocalizedViewModel
|
||||
{
|
||||
var generation = _generation;
|
||||
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;
|
||||
try
|
||||
|
||||
@@ -643,7 +643,8 @@ public sealed class SequenceViewModel : SectionViewModel
|
||||
{
|
||||
workspace.Remember(row.Id, 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,
|
||||
hold: workspace.HoldInEditor(entry.ProjectId)), row.DisplayTitle);
|
||||
}
|
||||
var projectId = entry?.ProjectId ?? request?.ProjectId;
|
||||
string? newName = null;
|
||||
@@ -748,9 +749,10 @@ 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:
|
||||
// made again whenever the sign-in changes, so a project opened signed out renders once signed in.
|
||||
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);
|
||||
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,
|
||||
workspace.HoldInEditor(entry.ProjectId)), entry.SequenceTitle));
|
||||
}
|
||||
// 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;
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
xmlns:l="clr-namespace:Chronos.Ui.Localization;assembly=Chronos.Ui"
|
||||
xmlns:infra="clr-namespace:Chronos.App.Infrastructure"
|
||||
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>
|
||||
<Style x:Key="Text.RowLabel" TargetType="TextBlock" BasedOn="{StaticResource Text.Label}">
|
||||
<Setter Property="MinWidth" Value="60" />
|
||||
@@ -42,14 +43,90 @@
|
||||
</Style>
|
||||
</UserControl.Resources>
|
||||
|
||||
<!-- Server.html: the connection panel, 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.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
</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}}" />
|
||||
<ui:StatusGlyph Kind="Warning" Text="{l:Loc Server.Share.LegacyService}" FontSize="12" Margin="0,8,0,0" HorizontalAlignment="Left"
|
||||
ToolTip="{l:Loc Tooltips.Server.Share.LegacyService}" Visibility="{Binding HasLegacyService, Converter={StaticResource BoolToVisibility}}" />
|
||||
<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.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
@@ -166,8 +243,11 @@
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- The server's running and paused jobs, live, while there are any (owner review 5, #65). -->
|
||||
<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. -->
|
||||
<Border Grid.Row="1" 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.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
|
||||
@@ -14,7 +14,8 @@ namespace Chronos.App.Sections;
|
||||
/// <summary>
|
||||
/// Server (BRIEF §12.7, Server.html): address with LAN-discovered servers, connect with trust-on-first-use and login,
|
||||
/// status (name, version, latency, certificate), account and quota, sign out, the options of this PC (render node,
|
||||
/// proxies kept offline, automatic project sync, uploads paused on metered networks) and the sync table (<see cref="Sync"/>).
|
||||
/// proxies kept offline, automatic project sync, uploads paused on metered networks), the server's running and paused jobs
|
||||
/// (<see cref="Jobs"/>) and the sync table (<see cref="Sync"/>).
|
||||
/// The rail badge counts the settings conflicts waiting for a choice.
|
||||
/// </summary>
|
||||
public sealed class ServerViewModel : SectionViewModel
|
||||
@@ -41,11 +42,23 @@ public sealed class ServerViewModel : SectionViewModel
|
||||
Sync = new SyncTableViewModel(shell);
|
||||
_conflicts = Sync.Chips.Single(c => c.Filter == SyncFilter.Conflicts);
|
||||
_conflicts.PropertyChanged += OnConflictsChanged;
|
||||
Jobs = new ServerJobsViewModel(() => ServerJobsViewModel.AccountOf(Session), () => JobsConnection(Session), SynchronizationContext.Current,
|
||||
(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>
|
||||
public SyncTableViewModel Sync { get; }
|
||||
|
||||
/// <summary>The server's running and paused jobs, live (owner review 5, #65).</summary>
|
||||
public ServerJobsViewModel Jobs { get; }
|
||||
|
||||
/// <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;
|
||||
|
||||
/// <summary>This PC's library shared to the LAN (owner review 5, #67).</summary>
|
||||
public SharePanelViewModel SharePanel { get; }
|
||||
|
||||
public ShellViewModel Shell { get; }
|
||||
|
||||
private ServerSession Session => _session ?? Shell.Services.Server;
|
||||
@@ -212,6 +225,7 @@ public sealed class ServerViewModel : SectionViewModel
|
||||
if (!Shell.Services.Environment.IsCapture) _session.StartDiscovery();
|
||||
Shell.Settings.Encoders.CollectionChanged += OnEncodersChanged;
|
||||
Sync.Attach();
|
||||
Jobs.Refresh();
|
||||
await _session.RestoreAsync();
|
||||
if (_session.Flow.Error is not ConnectError.None and var error && !_session.IsConnected) ErrorText = ServerSession.ErrorText(error, _session.Flow.Address);
|
||||
}
|
||||
@@ -222,6 +236,8 @@ public sealed class ServerViewModel : SectionViewModel
|
||||
if (_session is not null) _session.PropertyChanged -= OnSessionChanged;
|
||||
Shell.Settings.Encoders.CollectionChanged -= OnEncodersChanged;
|
||||
Sync.Dispose();
|
||||
Jobs.Dispose();
|
||||
SharePanel.Dispose();
|
||||
base.Dispose();
|
||||
}
|
||||
|
||||
@@ -278,6 +294,7 @@ public sealed class ServerViewModel : SectionViewModel
|
||||
{
|
||||
OnAllPropertiesChanged();
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
Jobs.Refresh();
|
||||
}
|
||||
|
||||
/// <summary>The <see cref="Core.Model.UserRole"/> name of a server role, or null for a role this build does not know.</summary>
|
||||
|
||||
@@ -563,6 +563,28 @@
|
||||
Visibility="{Binding WorkspaceRows.HasUsageText, Converter={StaticResource BoolToVisibility}}" />
|
||||
</StackPanel>
|
||||
</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}">
|
||||
<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}" />
|
||||
@@ -613,6 +635,47 @@
|
||||
|
||||
<!-- ================= 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}">
|
||||
<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}"
|
||||
@@ -648,6 +711,62 @@
|
||||
</ItemsControl>
|
||||
</Grid>
|
||||
</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>
|
||||
|
||||
<!-- ================= Updates ================= -->
|
||||
|
||||
@@ -90,8 +90,9 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
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",
|
||||
"Settings.Workspace.Sync", "Settings.Workspace.AfterSave", "Settings.Workspace.VersionOnRender", "Settings.Workspace.SaveBeforeRender",
|
||||
"Settings.Workspace.Kept", "Settings.Workspace.CleanAfter", "Settings.Workspace.OpenProject", "Settings.Workspace.Trash"]),
|
||||
new(SettingsPage.Server, ["Settings.Server.Default", "Settings.Server.RenderNode", "Settings.Server.Certificates"]),
|
||||
"Settings.Workspace.Kept", "Settings.Workspace.CleanAfter", "Settings.Workspace.OpenProject", "Settings.Workspace.Trash", "Settings.Workspace.Homes"]),
|
||||
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.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",
|
||||
@@ -177,6 +178,9 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
// Saving applies them to the log files (App.SaveSettings).
|
||||
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 ----
|
||||
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),
|
||||
@@ -272,7 +276,12 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
if (value == SettingsPage.Rendering && Encoders.Count == 0 && !_isDetecting) _ = DetectEncodersAsync();
|
||||
if (value == SettingsPage.Formats && Formats.Count == 0 && !_isDetectingFormats) _ = DetectFormatsAsync(refresh: false);
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -741,7 +750,7 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
{
|
||||
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)
|
||||
{
|
||||
@@ -793,6 +802,16 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
|
||||
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 ----------------
|
||||
|
||||
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>
|
||||
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 OpenLogsCommand { 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);
|
||||
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
|
||||
// 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;
|
||||
@@ -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()
|
||||
{
|
||||
try
|
||||
@@ -1629,6 +1674,7 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
break;
|
||||
case SettingsPage.Server:
|
||||
_s.RenderNodeOptIn = defaults.RenderNodeOptIn;
|
||||
ShareRows.Reset();
|
||||
break;
|
||||
case SettingsPage.Updates:
|
||||
_s.CheckForUpdates = defaults.CheckForUpdates;
|
||||
@@ -1736,6 +1782,7 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
foreach (var row in JobPriorities) row.Refresh();
|
||||
Logs.Refresh();
|
||||
WorkspaceRows.Refresh();
|
||||
ShareRows.Refresh();
|
||||
UpdatePreview();
|
||||
LoadCertificates();
|
||||
OnAllPropertiesChanged();
|
||||
@@ -1781,6 +1828,57 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
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()
|
||||
{
|
||||
Certificates.Clear();
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
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.Windows.Services;
|
||||
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. A
|
||||
/// warning row shows while the 1.0 Windows Server's service is installed, read at the start and at each change of state.
|
||||
/// </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 readonly Func<bool> _legacyService;
|
||||
private bool _showPassword;
|
||||
private bool _hasLegacyService;
|
||||
|
||||
/// <param name="shell">The shell whose shared library the panel shows.</param>
|
||||
/// <param name="legacyService">Whether the 1.0 Windows Server is installed; the Service Control Manager by default (never during screenshots).</param>
|
||||
public SharePanelViewModel(ShellViewModel shell, Func<bool>? legacyService = null)
|
||||
{
|
||||
_shell = shell;
|
||||
_share = shell.Services.Share;
|
||||
_legacyService = legacyService ?? (shell.Services.Environment.IsCapture ? () => false : () => ServiceProbe.IsInstalled(ServiceProbe.LegacyServer));
|
||||
_hasLegacyService = _legacyService();
|
||||
_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;
|
||||
|
||||
/// <summary>The 1.0 Windows Server's service is installed: it may hold the same ports, and the setup can remove it.</summary>
|
||||
public bool HasLegacyService => _hasLegacyService;
|
||||
|
||||
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;
|
||||
_hasLegacyService = _legacyService();
|
||||
OnAllPropertiesChanged();
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
}
|
||||
@@ -551,7 +551,7 @@ public sealed class VideosViewModel : SectionViewModel, Chronos.App.Editor.IVide
|
||||
var workspace = services.Workspace;
|
||||
if (!workspace.IsAvailable || !Directory.Exists(workspace.Root)) return [];
|
||||
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>
|
||||
|
||||
@@ -75,6 +75,9 @@ public enum ConnectError
|
||||
/// <summary>The certificate differs from the trusted one; the saved session was dropped.</summary>
|
||||
CertificateChanged,
|
||||
Failed,
|
||||
|
||||
/// <summary>The address is this PC's own shared library (owner review 5, #67), which this desktop already has open.</summary>
|
||||
OwnLibrary,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -112,6 +115,12 @@ public sealed class ConnectFlow(IServerApiFactory factory, ITrustStore trust) :
|
||||
/// <summary>Raised after every step change.</summary>
|
||||
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>
|
||||
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();
|
||||
Info = await _api.GetInfoAsync(ct);
|
||||
Latency = clock.Elapsed;
|
||||
if (IsOwnLibrary?.Invoke(Info.TlsFingerprint, Info.ServerId) == true) return Fail(ConnectError.OwnLibrary);
|
||||
return Set(ConnectStep.AwaitingCredentials, ConnectError.None);
|
||||
}
|
||||
catch (UntrustedCertificateException untrusted)
|
||||
{
|
||||
if (IsOwnLibrary?.Invoke(untrusted.Fingerprint, null) == true) return Fail(ConnectError.OwnLibrary);
|
||||
PendingFingerprint = untrusted.Fingerprint;
|
||||
return Set(ConnectStep.AwaitingTrust, ConnectError.None);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,525 @@
|
||||
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;
|
||||
|
||||
/// <summary>The server being started: its certificate and id are known before it listens and its first beacon goes out.</summary>
|
||||
private HostedServer? _starting;
|
||||
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 ((Volatile.Read(ref _server) ?? Volatile.Read(ref _starting)) 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>
|
||||
/// How many programs used the library in the last minutes plus the render nodes online, read again now; 0 while it is not
|
||||
/// served. Exit asks first when this is not 0. Never throws: a failed read counts the clients read last.
|
||||
/// </summary>
|
||||
public async Task<int> ActiveClientsAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!IsOn) return 0;
|
||||
try
|
||||
{
|
||||
await RefreshAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidOperationException or ObjectDisposedException or OperationCanceledException)
|
||||
{
|
||||
Log.Warning("share", "The clients of the shared library could not be read", ex);
|
||||
}
|
||||
return Clients.Count;
|
||||
}
|
||||
|
||||
/// <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);
|
||||
// Its first beacon goes out while it starts: LAN discovery already knows it for this PC's own (owner review 5, #67).
|
||||
Volatile.Write(ref _starting, server);
|
||||
// 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 (OperationCanceledException)
|
||||
{
|
||||
Volatile.Write(ref _starting, null);
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex) when (Failure(ex, share) is { } reason)
|
||||
{
|
||||
Volatile.Write(ref _starting, null);
|
||||
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;
|
||||
Volatile.Write(ref _starting, null);
|
||||
_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);
|
||||
}
|
||||
@@ -70,7 +70,8 @@ public sealed class DpapiTokenProtector : ITokenProtector
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// 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);
|
||||
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)
|
||||
{
|
||||
if (!_seen.Add(server.Address)) continue;
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Protocol.Client;
|
||||
|
||||
namespace Chronos.App.Server;
|
||||
|
||||
/// <summary>
|
||||
/// What the Server section's job list needs from the signed-in server (owner review 5, #65): its jobs by state, one job,
|
||||
/// pause, resume and cancel, and its events (<see cref="JobProgressEvent"/>, <see cref="JobStateEvent"/>). Owns its connection.
|
||||
/// </summary>
|
||||
public interface IServerJobsApi : IDisposable
|
||||
{
|
||||
/// <summary>A page of the server's jobs in <paramref name="state"/> (a wire name: running, paused…), newest first.</summary>
|
||||
Task<Page<JobDto>> ListJobsAsync(string state, string? cursor, CancellationToken cancellationToken);
|
||||
|
||||
Task<JobDto> GetJobAsync(Guid id, CancellationToken cancellationToken);
|
||||
|
||||
Task<JobDto> PauseJobAsync(Guid id, CancellationToken cancellationToken);
|
||||
|
||||
Task<JobDto> ResumeJobAsync(Guid id, CancellationToken cancellationToken);
|
||||
|
||||
Task<JobDto> CancelJobAsync(Guid id, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Server events until cancelled or the socket closes.</summary>
|
||||
IAsyncEnumerable<ServerEvent> EventsAsync(CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary><see cref="IServerJobsApi"/> over a signed-in <see cref="ChronosClient"/>, which it owns.</summary>
|
||||
public sealed class ChronosServerJobsApi(ChronosClient client) : IServerJobsApi
|
||||
{
|
||||
public Task<Page<JobDto>> ListJobsAsync(string state, string? cursor, CancellationToken cancellationToken) =>
|
||||
client.ListJobsAsync(state, null, cursor, cancellationToken);
|
||||
|
||||
public Task<JobDto> GetJobAsync(Guid id, CancellationToken cancellationToken) => client.GetJobAsync(id, cancellationToken);
|
||||
|
||||
public Task<JobDto> PauseJobAsync(Guid id, CancellationToken cancellationToken) => client.PauseJobAsync(id, cancellationToken);
|
||||
|
||||
public Task<JobDto> ResumeJobAsync(Guid id, CancellationToken cancellationToken) => client.ResumeJobAsync(id, cancellationToken);
|
||||
|
||||
public Task<JobDto> CancelJobAsync(Guid id, CancellationToken cancellationToken) => client.CancelJobAsync(id, cancellationToken);
|
||||
|
||||
public IAsyncEnumerable<ServerEvent> EventsAsync(CancellationToken cancellationToken) => client.EventsAsync(cancellationToken);
|
||||
|
||||
public void Dispose() => client.Dispose();
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
<UserControl x:Class="Chronos.App.Server.ServerJobsView"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ui="clr-namespace:Chronos.Ui.Controls;assembly=Chronos.Ui"
|
||||
xmlns:l="clr-namespace:Chronos.Ui.Localization;assembly=Chronos.Ui"
|
||||
xmlns:infra="clr-namespace:Chronos.App.Infrastructure"
|
||||
xmlns:j="clr-namespace:Chronos.App.Jobs"
|
||||
xmlns:srv="clr-namespace:Chronos.App.Server">
|
||||
<UserControl.Resources>
|
||||
<Style x:Key="Text.Muted" TargetType="TextBlock" BasedOn="{StaticResource Text.Cell}">
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.TextMuted}" />
|
||||
</Style>
|
||||
<!-- Numbers stay right-aligned in both reading directions; speeds and times left read in the language's direction (as on Jobs). -->
|
||||
<Style x:Key="Text.MutedNumber" TargetType="TextBlock" BasedOn="{StaticResource Text.Muted}">
|
||||
<Setter Property="TextAlignment" Value="Right" />
|
||||
<Setter Property="FlowDirection" Value="LeftToRight" />
|
||||
</Style>
|
||||
<Style x:Key="Text.MutedEnd" TargetType="TextBlock" BasedOn="{StaticResource Text.Muted}">
|
||||
<Setter Property="TextAlignment" Value="Right" />
|
||||
</Style>
|
||||
<Style x:Key="Text.HeaderEnd" TargetType="TextBlock" BasedOn="{StaticResource Text.Header}">
|
||||
<Setter Property="TextAlignment" Value="Right" />
|
||||
</Style>
|
||||
<ItemsPanelTemplate x:Key="Panel.Row">
|
||||
<StackPanel Orientation="Horizontal" />
|
||||
</ItemsPanelTemplate>
|
||||
<!-- A row reads as its job and state; Tab goes to its buttons. -->
|
||||
<Style x:Key="ListBoxItem.ServerJob" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.PlainRow}">
|
||||
<Setter Property="AutomationProperties.Name" Value="{Binding AccessibleName}" />
|
||||
<Setter Property="AutomationProperties.ItemStatus" Value="{Binding StateText}" />
|
||||
</Style>
|
||||
</UserControl.Resources>
|
||||
|
||||
<!-- The server's running and paused jobs (owner review 5, #65): the Jobs table's columns without Where; Pause, Resume and
|
||||
Cancel only for an account that manages the archive. At most four rows show; more scroll. -->
|
||||
<Border Style="{StaticResource Border.Panel}">
|
||||
<Grid Grid.IsSharedSizeScope="True">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<TextBlock Text="{l:Loc Server.Jobs.Title}" ToolTip="{Binding TitleToolTip}" FontWeight="SemiBold" Margin="14,10" HorizontalAlignment="Left" />
|
||||
|
||||
<Border Grid.Row="1" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,1,0,1" Padding="14,8,24,8">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="0.7*" MinWidth="90" MaxWidth="140" />
|
||||
<ColumnDefinition Width="1.6*" MinWidth="120" />
|
||||
<ColumnDefinition Width="*" MinWidth="104" MaxWidth="240" />
|
||||
<ColumnDefinition Width="90" />
|
||||
<ColumnDefinition Width="80" />
|
||||
<ColumnDefinition Width="0.7*" MinWidth="116" MaxWidth="170" />
|
||||
<ColumnDefinition Width="Auto" SharedSizeGroup="ServerJobActions" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.Kind}" ToolTip="{l:Loc Jobs.Column.Kind}" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.Target}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Column.Target}" />
|
||||
<TextBlock Grid.Column="2" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.Progress}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Column.Progress}" />
|
||||
<TextBlock Grid.Column="3" Style="{StaticResource Text.HeaderEnd}" Text="{l:Loc Jobs.Column.Speed}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Column.Speed}" />
|
||||
<TextBlock Grid.Column="4" Style="{StaticResource Text.HeaderEnd}" Text="{l:Loc Jobs.Column.Left}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Column.Left}" />
|
||||
<TextBlock Grid.Column="5" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.State}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Column.State}" />
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Rows: running first, then paused. The status line under the target is never announced; a new state is. -->
|
||||
<ListBox x:Name="JobList" Grid.Row="2" ItemsSource="{Binding Rows}" ItemContainerStyle="{StaticResource ListBoxItem.ServerJob}" MaxHeight="160"
|
||||
ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Visible" VirtualizingPanel.ScrollUnit="Pixel"
|
||||
KeyboardNavigation.TabNavigation="Continue" AutomationProperties.Name="{l:Loc Server.Jobs.Title}">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type srv:ServerJobRowViewModel}">
|
||||
<Border Height="38" Background="Transparent" Padding="14,0">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="0.7*" MinWidth="90" MaxWidth="140" />
|
||||
<ColumnDefinition Width="1.6*" MinWidth="120" />
|
||||
<ColumnDefinition Width="*" MinWidth="104" MaxWidth="240" />
|
||||
<ColumnDefinition Width="90" />
|
||||
<ColumnDefinition Width="80" />
|
||||
<ColumnDefinition Width="0.7*" MinWidth="116" MaxWidth="170" />
|
||||
<ColumnDefinition Width="Auto" SharedSizeGroup="ServerJobActions" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Style="{StaticResource Text.Muted}" Text="{Binding Kind}" ToolTip="{Binding Kind}" />
|
||||
<StackPanel Grid.Column="1" Margin="10,0,0,0" VerticalAlignment="Center">
|
||||
<TextBlock Style="{StaticResource Text.Cell}" Text="{Binding Target}" ToolTip="{Binding Target}" />
|
||||
<TextBlock x:Name="Status" Style="{StaticResource Text.Muted}" Text="{Binding StatusText}" ToolTip="{Binding StatusToolTip}"
|
||||
FontSize="{StaticResource Size.Chip}" Visibility="{Binding HasStatus, Converter={StaticResource BoolToVisibility}}" />
|
||||
</StackPanel>
|
||||
<Grid Grid.Column="2" Margin="10,0,0,0">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="44" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<ProgressBar Maximum="1" Value="{Binding Progress, Mode=OneWay}" IsIndeterminate="{Binding IsIndeterminate, Mode=OneWay}" VerticalAlignment="Center"
|
||||
AutomationProperties.Name="{Binding AccessibleName}" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.MutedNumber}" Text="{Binding PercentText}" />
|
||||
</Grid>
|
||||
<TextBlock Grid.Column="3" Style="{StaticResource Text.MutedEnd}" Text="{Binding SpeedText}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="4" Style="{StaticResource Text.MutedEnd}" Text="{Binding LeftText}" Margin="10,0,0,0" />
|
||||
<ui:StatusGlyph Grid.Column="5" Kind="{Binding StateKind}" Text="{Binding StateText}" ToolTip="{Binding StateToolTip}"
|
||||
FontSize="13" VerticalAlignment="Center" Margin="10,0,0,0"
|
||||
AutomationProperties.LiveSetting="Polite" infra:LiveRegion.Text="{Binding StateAnnouncement}" />
|
||||
<ItemsControl Grid.Column="6" ItemsSource="{Binding Actions}" ItemsPanel="{StaticResource Panel.Row}" Focusable="False"
|
||||
VerticalAlignment="Center" Margin="10,0,0,0">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type j:JobAction}">
|
||||
<Button Style="{StaticResource Button.Row}" Content="{Binding Text}" Command="{Binding Command}" ToolTip="{Binding ToolTip}"
|
||||
AutomationProperties.Name="{Binding AccessibleName}" />
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</Grid>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
</Grid>
|
||||
</Border>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,9 @@
|
||||
using System.Windows.Controls;
|
||||
|
||||
namespace Chronos.App.Server;
|
||||
|
||||
/// <summary>The Server section's list of the server's running and paused jobs (<see cref="ServerJobsViewModel"/>).</summary>
|
||||
public partial class ServerJobsView : UserControl
|
||||
{
|
||||
public ServerJobsView() => InitializeComponent();
|
||||
}
|
||||
@@ -0,0 +1,534 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Jobs;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Protocol.Client;
|
||||
using Chronos.Ui.Controls;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Server;
|
||||
|
||||
/// <summary>
|
||||
/// Who is signed in, as the Server section's job list sees it: <see cref="Key"/> names the session (a new sign-in is another
|
||||
/// list), <see cref="CanControl"/> whether the account may pause, resume and cancel any of the server's jobs.
|
||||
/// </summary>
|
||||
public sealed record ServerJobsAccount(string Key, bool CanControl);
|
||||
|
||||
/// <summary>
|
||||
/// The jobs running or paused on the signed-in server, live (owner review 5, #65 and the owner's answer to Q2): read from the
|
||||
/// server's jobs API, then followed through its events (<see cref="JobProgressEvent"/> with what each job does now,
|
||||
/// <see cref="JobStateEvent"/>), at most four updates a second, and read again whenever the event socket comes back after a
|
||||
/// loss (with a growing delay; nothing that fails on the way ends it). Queued jobs are the admin panel's (a busy server
|
||||
/// queues thumbnails by the thousand). Pause, Resume and Cancel are offered only to an account with the right to manage
|
||||
/// the archive, which the server requires to act on a job someone else started; otherwise the list is read-only. Empty and
|
||||
/// idle while signed out or without the right to read. UI thread, except where said.
|
||||
/// </summary>
|
||||
public sealed class ServerJobsViewModel : ObservableObject, IDisposable
|
||||
{
|
||||
private static readonly TimeSpan FlushInterval = TimeSpan.FromMilliseconds(250);
|
||||
private static readonly TimeSpan MinBackoff = TimeSpan.FromSeconds(2);
|
||||
private static readonly TimeSpan MaxBackoff = TimeSpan.FromMinutes(1);
|
||||
private static readonly string[] ListedStates = [JobWire.State(JobState.Running), JobWire.State(JobState.Paused)];
|
||||
|
||||
private readonly JobListModel _model = new();
|
||||
private readonly Updates _updates = new();
|
||||
private readonly Dictionary<Guid, ServerJobRowViewModel> _rows = [];
|
||||
private readonly Func<ServerJobsAccount?> _account;
|
||||
private readonly Func<IServerJobsApi?> _connect;
|
||||
private readonly Action<string, string>? _failed;
|
||||
private readonly CoalescingThrottle _throttle;
|
||||
private Watch? _watch;
|
||||
private bool _canControl;
|
||||
private bool _disposed;
|
||||
|
||||
/// <param name="account">The signed-in account; null while signed out or without the right to read the server's jobs.</param>
|
||||
/// <param name="connect">A connection for the signed-in session; null when there is none.</param>
|
||||
/// <param name="context">Where updates are applied (the UI); null applies them on a timer thread.</param>
|
||||
/// <param name="failed">Says that an action failed: a title and the reason.</param>
|
||||
public ServerJobsViewModel(Func<ServerJobsAccount?> account, Func<IServerJobsApi?> connect, SynchronizationContext? context, Action<string, string>? failed = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(account);
|
||||
ArgumentNullException.ThrowIfNull(connect);
|
||||
_account = account;
|
||||
_connect = connect;
|
||||
_failed = failed;
|
||||
_throttle = new CoalescingThrottle(FlushInterval, context, Flush);
|
||||
}
|
||||
|
||||
/// <summary>The account of <paramref name="session"/>: none while signed out or without the Read right; control with ManageArchive.</summary>
|
||||
public static ServerJobsAccount? AccountOf(ServerSession session)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(session);
|
||||
if (session.User is not { } user || session.Flow.Address is not { } address || session.Flow.Token is not { } token) return null;
|
||||
var permissions = (Permissions)user.Permissions;
|
||||
if (!permissions.HasFlag(Permissions.Read)) return null;
|
||||
return new ServerJobsAccount($"{ServerAddress.Display(address)}|{user.Id}|{token}", permissions.HasFlag(Permissions.ManageArchive));
|
||||
}
|
||||
|
||||
/// <summary>A connection over <see cref="ChronosClient"/> for <paramref name="session"/>, pinned to its trusted certificates; null while signed out.</summary>
|
||||
public static IServerJobsApi? ConnectionOf(ServerSession session)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(session);
|
||||
return session.IsConnected && session.Flow is { Address: { } address, Token: { } token }
|
||||
? new ChronosServerJobsApi(new ChronosClient(address, new CertificatePinning(session.Fingerprints), $"Chronos ({Environment.MachineName})") { Token = token })
|
||||
: null;
|
||||
}
|
||||
|
||||
/// <summary>Raised after the listener posted an update (any thread; tests wait on it).</summary>
|
||||
internal event Action? Posted;
|
||||
|
||||
/// <summary>The running jobs first (oldest start first), then the paused ones.</summary>
|
||||
public ObservableCollection<ServerJobRowViewModel> Rows { get; } = [];
|
||||
|
||||
/// <summary>The list shows: a session is followed and the server runs or holds something.</summary>
|
||||
public bool HasRows => Rows.Count > 0;
|
||||
|
||||
/// <summary>The account may pause, resume and cancel the server's jobs; without it the list is read-only.</summary>
|
||||
public bool CanControl => _canControl;
|
||||
|
||||
/// <summary>What the list shows, and whether the account can act on it.</summary>
|
||||
public string TitleToolTip => Loc.L(_canControl ? "Tooltips.Server.Jobs" : "Tooltips.Server.Jobs.ReadOnly");
|
||||
|
||||
/// <summary>A session is being followed.</summary>
|
||||
internal bool IsWatching => _watch is not null;
|
||||
|
||||
/// <summary>Follows the signed-in session, or stops when it ended or changed (call when the session changes).</summary>
|
||||
public void Refresh()
|
||||
{
|
||||
if (_disposed) return;
|
||||
var account = _account();
|
||||
if (account?.CanControl != _canControl)
|
||||
{
|
||||
_canControl = account?.CanControl ?? false;
|
||||
foreach (var row in _rows.Values) row.Refresh();
|
||||
OnPropertyChanged(nameof(CanControl));
|
||||
OnPropertyChanged(nameof(TitleToolTip));
|
||||
}
|
||||
if (_watch?.Key == account?.Key) return;
|
||||
Stop();
|
||||
if (account is not null && _connect() is { } api)
|
||||
{
|
||||
_watch = new Watch(account.Key, api, new CancellationTokenSource());
|
||||
var watch = _watch;
|
||||
watch.Listening = Task.Run(() => ListenAsync(watch), CancellationToken.None);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads the server's running and paused jobs again (a picture of the list as it is now).</summary>
|
||||
public async Task ReloadAsync()
|
||||
{
|
||||
if (_watch is not { } watch) return;
|
||||
await LoadAsync(watch.Api, watch, watch.Stopping.Token);
|
||||
Flush();
|
||||
}
|
||||
|
||||
/// <summary>Applies what the listener collected since the last flush (UI thread).</summary>
|
||||
internal void Flush()
|
||||
{
|
||||
var (reset, jobs, removed, progress) = _updates.Drain();
|
||||
if (reset is not null)
|
||||
{
|
||||
var listed = reset.Select(j => j.Id).ToHashSet();
|
||||
foreach (var entry in _model.Ordered().Where(e => !listed.Contains(e.Id)).ToList()) _model.Remove(entry.Id);
|
||||
foreach (var job in reset) _model.Apply(job);
|
||||
}
|
||||
foreach (var job in jobs)
|
||||
{
|
||||
if (IsListed(job.State)) _model.Apply(job);
|
||||
else _model.Remove(job.Id);
|
||||
}
|
||||
foreach (var id in removed) _model.Remove(id);
|
||||
foreach (var p in progress) _model.Apply(p);
|
||||
SyncRows();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
Stop();
|
||||
_throttle.Dispose();
|
||||
}
|
||||
|
||||
private static bool IsListed(JobState state) => state is JobState.Running or JobState.Paused;
|
||||
|
||||
private void Stop()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _watch, null) is not { } watch) return;
|
||||
watch.Stopping.Cancel();
|
||||
// The listener disposes its connection once it has stopped.
|
||||
_updates.Reset([]);
|
||||
Flush();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Lists the jobs, then follows the events until stopped; after a loss, waits with a growing delay and lists again
|
||||
/// (events missed meanwhile are in that list). Nothing that fails on the way ends it. Disposes the connection at the end.
|
||||
/// </summary>
|
||||
private async Task ListenAsync(Watch watch)
|
||||
{
|
||||
var ct = watch.Stopping.Token;
|
||||
var failures = 0;
|
||||
try
|
||||
{
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
await LoadAsync(watch.Api, watch, ct).ConfigureAwait(false);
|
||||
await foreach (var e in watch.Api.EventsAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
failures = 0;
|
||||
await OnEventAsync(watch.Api, watch, e, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
if (ct.IsCancellationRequested) return;
|
||||
Log.Info("server", $"Jobs of the server lost: {ex.Message}");
|
||||
}
|
||||
var delay = Math.Min(MaxBackoff.Ticks, MinBackoff.Ticks << Math.Min(failures++, 10));
|
||||
await Task.Delay(TimeSpan.FromTicks(delay), ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
finally
|
||||
{
|
||||
watch.Api.Dispose();
|
||||
watch.Stopping.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Every running and paused job of the server, all pages (any thread).</summary>
|
||||
private async Task LoadAsync(IServerJobsApi api, Watch watch, CancellationToken ct)
|
||||
{
|
||||
var jobs = new List<Job>();
|
||||
foreach (var state in ListedStates)
|
||||
{
|
||||
string? cursor = null;
|
||||
do
|
||||
{
|
||||
var page = await api.ListJobsAsync(state, cursor, ct).ConfigureAwait(false);
|
||||
jobs.AddRange(page.Items.Select(JobWire.FromDto).OfType<Job>().Where(j => IsListed(j.State)));
|
||||
cursor = page.NextCursor;
|
||||
}
|
||||
while (cursor is not null);
|
||||
}
|
||||
_updates.Reset(jobs);
|
||||
watch.Listed(jobs.Select(j => j.Id));
|
||||
Signal();
|
||||
}
|
||||
|
||||
private async Task OnEventAsync(IServerJobsApi api, Watch watch, ServerEvent e, CancellationToken ct)
|
||||
{
|
||||
switch (e)
|
||||
{
|
||||
case JobProgressEvent p:
|
||||
// A job that started between the list and the event socket: its running state was missed, its progress is
|
||||
// not. Read once, it joins the list (owner review 5, #65).
|
||||
if (watch.FirstUnknown(p.JobId)) await FetchAsync(api, watch, p.JobId, ct, signal: false).ConfigureAwait(false);
|
||||
// Kind and target come from the listed job; what matters here is the count, the pace and the detail.
|
||||
_updates.Post(new JobProgressInfo(p.JobId, default, null, p.Done, p.Total, p.ItemsPerSecond, JobEta.FromSeconds(p.EtaSeconds), null,
|
||||
JobWire.FromDto(p.Detail)));
|
||||
Signal();
|
||||
break;
|
||||
case JobStateEvent s when JobWire.TryParseState(s.State, out var state) && IsListed(state):
|
||||
await FetchAsync(api, watch, s.JobId, ct).ConfigureAwait(false);
|
||||
break;
|
||||
case JobStateEvent s:
|
||||
// Queued again, finished or of a state this build does not know: it leaves the list.
|
||||
watch.Know(s.JobId, false);
|
||||
_updates.Remove(s.JobId);
|
||||
Signal();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task FetchAsync(IServerJobsApi api, Watch watch, Guid jobId, CancellationToken ct, bool signal = true)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (JobWire.FromDto(await api.GetJobAsync(jobId, ct).ConfigureAwait(false)) is { } job && IsListed(job.State))
|
||||
{
|
||||
watch.Know(jobId, true);
|
||||
_updates.Post(job);
|
||||
}
|
||||
else
|
||||
{
|
||||
watch.Know(jobId, false);
|
||||
_updates.Remove(jobId);
|
||||
}
|
||||
if (signal) Signal();
|
||||
}
|
||||
catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or JsonException
|
||||
|| (ex is OperationCanceledException && !ct.IsCancellationRequested))
|
||||
{
|
||||
Log.Info("server", $"Job {jobId} of the server could not be read: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private void Signal()
|
||||
{
|
||||
_throttle.Signal();
|
||||
Posted?.Invoke();
|
||||
}
|
||||
|
||||
/// <summary>Pauses, resumes or cancels a job on the server; what the server answers shows at once (UI thread).</summary>
|
||||
internal async Task ActAsync(Guid jobId, Func<IServerJobsApi, Guid, CancellationToken, Task<JobDto>> action)
|
||||
{
|
||||
if (_watch is not { } watch || !_canControl) return;
|
||||
try
|
||||
{
|
||||
var dto = await action(watch.Api, jobId, watch.Stopping.Token);
|
||||
if (JobWire.FromDto(dto) is { } job) _updates.Post(job);
|
||||
else _updates.Remove(jobId);
|
||||
Flush();
|
||||
}
|
||||
catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or JsonException or OperationCanceledException or ObjectDisposedException)
|
||||
{
|
||||
if (watch.Stopping.IsCancellationRequested) return;
|
||||
Log.Info("server", $"Job {jobId} of the server not changed: {ex.Message}");
|
||||
// The server words its refusal in this PC's language (Accept-Language); anything else is a lost connection.
|
||||
_failed?.Invoke(Loc.L("Server.Jobs.NotChanged"),
|
||||
ex is ChronosApiException { Error.Message: { Length: > 0 } reason } ? reason : Loc.L("Server.Error.Unreachable"));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Brings <see cref="Rows"/> to the model's order with moves.</summary>
|
||||
private void SyncRows()
|
||||
{
|
||||
var ordered = _model.Ordered();
|
||||
var wanted = ordered.Select(e => e.Id).ToHashSet();
|
||||
for (var i = Rows.Count - 1; i >= 0; i--)
|
||||
{
|
||||
if (wanted.Contains(Rows[i].Id)) continue;
|
||||
_rows.Remove(Rows[i].Id);
|
||||
Rows.RemoveAt(i);
|
||||
}
|
||||
for (var i = 0; i < ordered.Count; i++)
|
||||
{
|
||||
var entry = ordered[i];
|
||||
if (!_rows.TryGetValue(entry.Id, out var row))
|
||||
{
|
||||
row = new ServerJobRowViewModel(entry, this);
|
||||
_rows[entry.Id] = row;
|
||||
}
|
||||
else
|
||||
{
|
||||
row.Update(entry);
|
||||
}
|
||||
if (i < Rows.Count && ReferenceEquals(Rows[i], row)) continue;
|
||||
var existing = Rows.IndexOf(row);
|
||||
if (existing >= 0) Rows.Move(existing, i);
|
||||
else Rows.Insert(i, row);
|
||||
}
|
||||
OnPropertyChanged(nameof(HasRows));
|
||||
}
|
||||
|
||||
/// <summary>The session followed: its key, its connection and what stops its listener.</summary>
|
||||
private sealed class Watch(string key, IServerJobsApi api, CancellationTokenSource stopping)
|
||||
{
|
||||
public string Key { get; } = key;
|
||||
public IServerJobsApi Api { get; } = api;
|
||||
public CancellationTokenSource Stopping { get; } = stopping;
|
||||
public Task? Listening { get; set; }
|
||||
|
||||
/// <summary>The jobs the list holds as the listener read them, and those read once on their progress since the last list.</summary>
|
||||
private readonly HashSet<Guid> _known = [];
|
||||
private readonly HashSet<Guid> _fetched = [];
|
||||
|
||||
/// <summary>A new list (the listener's, or a reload's): what it holds is known, and every job may be read once again.</summary>
|
||||
public void Listed(IEnumerable<Guid> ids)
|
||||
{
|
||||
lock (_known)
|
||||
{
|
||||
_known.Clear();
|
||||
_known.UnionWith(ids);
|
||||
_fetched.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
public void Know(Guid id, bool listed)
|
||||
{
|
||||
lock (_known)
|
||||
{
|
||||
if (listed) _known.Add(id);
|
||||
else _known.Remove(id);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True the first time a job the list does not hold reports progress: it is read once then.</summary>
|
||||
public bool FirstUnknown(Guid id)
|
||||
{
|
||||
lock (_known) return !_known.Contains(id) && _fetched.Add(id);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What the listener collected for the next flush (thread-safe): a new list, which drops everything collected before it;
|
||||
/// then per job its newest snapshot or its removal, and its newest progress.
|
||||
/// </summary>
|
||||
private sealed class Updates
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private IReadOnlyList<Job>? _reset;
|
||||
private Dictionary<Guid, Job> _jobs = [];
|
||||
private HashSet<Guid> _removed = [];
|
||||
private Dictionary<Guid, JobProgressInfo> _progress = [];
|
||||
|
||||
public void Reset(IReadOnlyList<Job> jobs)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_reset = jobs;
|
||||
_jobs = [];
|
||||
_removed = [];
|
||||
_progress = [];
|
||||
}
|
||||
}
|
||||
|
||||
public void Post(Job job)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_jobs[job.Id] = job;
|
||||
_removed.Remove(job.Id);
|
||||
_progress.Remove(job.Id);
|
||||
}
|
||||
}
|
||||
|
||||
public void Remove(Guid id)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_jobs.Remove(id);
|
||||
_progress.Remove(id);
|
||||
_removed.Add(id);
|
||||
}
|
||||
}
|
||||
|
||||
public void Post(JobProgressInfo progress)
|
||||
{
|
||||
lock (_gate) _progress[progress.JobId] = progress;
|
||||
}
|
||||
|
||||
public (IReadOnlyList<Job>? Reset, IReadOnlyCollection<Job> Jobs, IReadOnlyCollection<Guid> Removed, IReadOnlyCollection<JobProgressInfo> Progress) Drain()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
var drained = (_reset, (IReadOnlyCollection<Job>)_jobs.Values, (IReadOnlyCollection<Guid>)_removed, (IReadOnlyCollection<JobProgressInfo>)_progress.Values);
|
||||
_reset = null;
|
||||
_jobs = [];
|
||||
_removed = [];
|
||||
_progress = [];
|
||||
return drained;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One job of the server as the Server section lists it: kind, target with what it does now (or where a paused one stopped),
|
||||
/// progress, speed, time left, state, and Pause / Resume / Cancel when the account may.
|
||||
/// </summary>
|
||||
public sealed class ServerJobRowViewModel : ObservableObject
|
||||
{
|
||||
private readonly ServerJobsViewModel _owner;
|
||||
private JobEntry _entry;
|
||||
|
||||
internal ServerJobRowViewModel(JobEntry entry, ServerJobsViewModel owner)
|
||||
{
|
||||
_entry = entry;
|
||||
_owner = owner;
|
||||
}
|
||||
|
||||
public Guid Id => _entry.Id;
|
||||
|
||||
public JobEntry Entry => _entry;
|
||||
|
||||
public string Kind => JobText.Kind(_entry.Job.Kind);
|
||||
|
||||
public string Target => _entry.Job.TargetLabel ?? string.Empty;
|
||||
|
||||
/// <summary>"Verify · Harbour sunset": the row's name for screen readers.</summary>
|
||||
public string AccessibleName => JobText.Name(_entry.Job);
|
||||
|
||||
/// <summary>What it does now ("Verifying photo 812 of 2,400 · Harbour sunset · sequence 3 of 41"), or "Stopped at …".</summary>
|
||||
public string StatusText => JobText.RowStatus(_entry);
|
||||
|
||||
public bool HasStatus => StatusText.Length > 0;
|
||||
|
||||
public string StatusToolTip => JobText.RowStatusToolTip(_entry);
|
||||
|
||||
public double Progress => _entry.Fraction ?? 0;
|
||||
|
||||
public bool IsIndeterminate => _entry.State == JobState.Running && _entry.Fraction is null;
|
||||
|
||||
public string PercentText => _entry.Fraction is { } f ? Formatting.Percent(f) : "—";
|
||||
|
||||
public string SpeedText => _entry.State == JobState.Running ? Blank(JobText.Speed(_entry.Job.Kind, _entry.ItemsPerSecond)) : "—";
|
||||
|
||||
public string LeftText => Blank(JobText.Left(_entry, 0));
|
||||
|
||||
public string StateText => JobText.State(_entry);
|
||||
|
||||
public StatusKind StateKind => _entry.State == JobState.Paused ? StatusKind.Paused : StatusKind.Running;
|
||||
|
||||
public string StateToolTip => string.Join(Loc.Separator, StateText, Loc.L("Tooltips.Jobs.State." + _entry.State));
|
||||
|
||||
/// <summary>"Verify · Harbour sunset: running": what a screen reader announces when the state changes (not progress).</summary>
|
||||
public string StateAnnouncement => Loc.L("Jobs.Row.State", AccessibleName, StateText);
|
||||
|
||||
/// <summary>Pause and Cancel while it runs, Resume and Cancel while paused; none for a read-only account.</summary>
|
||||
public IReadOnlyList<JobAction> Actions
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!_owner.CanControl) return [];
|
||||
var id = _entry.Id;
|
||||
return _entry.State == JobState.Paused
|
||||
? [Action("Jobs.Action.Resume", "Tooltips.Jobs.Resume", (api, job, ct) => api.ResumeJobAsync(job, ct)),
|
||||
Action("Jobs.Action.Cancel", "Tooltips.Jobs.Cancel", (api, job, ct) => api.CancelJobAsync(job, ct))]
|
||||
: [Action("Jobs.Action.Pause", "Tooltips.Jobs.Pause", (api, job, ct) => api.PauseJobAsync(job, ct)),
|
||||
Action("Jobs.Action.Cancel", "Tooltips.Jobs.Cancel", (api, job, ct) => api.CancelJobAsync(job, ct))];
|
||||
|
||||
JobAction Action(string textKey, string toolTipKey, Func<IServerJobsApi, Guid, CancellationToken, Task<JobDto>> run)
|
||||
{
|
||||
var text = Loc.L(textKey);
|
||||
return new JobAction(text, Loc.L(toolTipKey), Loc.L("Jobs.ActionFor", text, AccessibleName),
|
||||
new AsyncRelayCommand(() => _owner.ActAsync(id, run)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal void Update(JobEntry entry)
|
||||
{
|
||||
var stateChanged = entry.State != _entry.State;
|
||||
_entry = entry;
|
||||
if (stateChanged)
|
||||
{
|
||||
OnAllPropertiesChanged();
|
||||
return;
|
||||
}
|
||||
OnPropertyChanged(nameof(StatusText));
|
||||
OnPropertyChanged(nameof(HasStatus));
|
||||
OnPropertyChanged(nameof(StatusToolTip));
|
||||
OnPropertyChanged(nameof(Progress));
|
||||
OnPropertyChanged(nameof(IsIndeterminate));
|
||||
OnPropertyChanged(nameof(PercentText));
|
||||
OnPropertyChanged(nameof(SpeedText));
|
||||
OnPropertyChanged(nameof(LeftText));
|
||||
}
|
||||
|
||||
internal void Refresh() => OnAllPropertiesChanged();
|
||||
|
||||
private static string Blank(string text) => text.Length == 0 ? "—" : text;
|
||||
}
|
||||
@@ -32,6 +32,13 @@ public sealed class ServerSession : ObservableObject, ITrustStore, IDisposable
|
||||
|
||||
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>
|
||||
public ObservableCollection<DiscoveredServer> Discovered { get; } = [];
|
||||
|
||||
@@ -185,6 +192,8 @@ public sealed class ServerSession : ObservableObject, ITrustStore, IDisposable
|
||||
_discovery = new DiscoveryListener();
|
||||
_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;
|
||||
Discovered.Add(server);
|
||||
};
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
using System.IO;
|
||||
using Chronos.App.Archiving;
|
||||
using Chronos.App.Editor;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Homes;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Projects;
|
||||
using Chronos.Data.Sync;
|
||||
@@ -13,8 +17,14 @@ using Chronos.Protocol.Client;
|
||||
|
||||
namespace Chronos.App.Server;
|
||||
|
||||
/// <summary>Makes the sync connection of a signed-in session.</summary>
|
||||
public delegate ISyncRemote SyncRemoteFactory(Uri address, string token, IReadOnlyCollection<string> trustedFingerprints);
|
||||
/// <summary>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, 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>
|
||||
/// 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,
|
||||
/// 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="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>
|
||||
public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDisposable
|
||||
{
|
||||
/// <summary>How long a job resumed at start waits for the saved session to be restored.</summary>
|
||||
private static readonly TimeSpan RestoreWait = TimeSpan.FromSeconds(30);
|
||||
|
||||
/// <summary>Jobs that write into the workspace or the servers' homes in the cache: the move of the folders to a server's id 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 Task _switch = Task.CompletedTask;
|
||||
private Credentials? _credentials;
|
||||
private Running? _running;
|
||||
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>
|
||||
private SharedClient? _projects;
|
||||
|
||||
/// <summary>Connections over <see cref="ChronosClient"/>; screenshots substitute a fake server.</summary>
|
||||
public SyncRemoteFactory RemoteFactory { get; set; } = (address, token, trusted) =>
|
||||
new ChronosSyncRemote(new ChronosClient(address, new CertificatePinning(trusted), $"Chronos ({Environment.MachineName})") { Token = token }, ownsClient: true);
|
||||
public SyncRemoteFactory RemoteFactory { get; set; } = (address, token, trusted, server) =>
|
||||
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>
|
||||
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>
|
||||
public ISyncRemote? Remote => Volatile.Read(ref _running)?.Remote;
|
||||
|
||||
/// <summary>Key of the signed-in server (<see cref="SyncService.ServerKey"/>); null while signed out.</summary>
|
||||
public string? Server => Volatile.Read(ref _credentials) is { } c ? SyncService.ServerKey(c.Address) : null;
|
||||
/// <summary>
|
||||
/// 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>
|
||||
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>
|
||||
/// 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
|
||||
/// 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>
|
||||
public IProjectHome? ProjectHome(BundleHome home)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(home);
|
||||
if (home.IsArchive || !HasProjects || Volatile.Read(ref _credentials) is not { } credentials
|
||||
|| !string.Equals(home.Server, SyncService.ServerKey(credentials.Address), StringComparison.OrdinalIgnoreCase))
|
||||
if (home.IsArchive || !HasProjects || Volatile.Read(ref _credentials) is not { } credentials || !Identity.Same(home.Server, credentials.Key))
|
||||
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>
|
||||
@@ -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>
|
||||
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><cache>\servers\<folder>\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)
|
||||
{
|
||||
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 =>
|
||||
{
|
||||
if (server == Server) Changed?.Invoke();
|
||||
if (Server is { } signedIn && Identity.Same(server, signedIn)) Changed?.Invoke();
|
||||
};
|
||||
return Service;
|
||||
}
|
||||
@@ -138,8 +189,9 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
|
||||
{
|
||||
var session = services.Server;
|
||||
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;
|
||||
if (wanted is { ServerId: { } serverId } && session.Flow.Info is { } info) Remember(serverId, wanted.Address, info);
|
||||
Volatile.Write(ref _credentials, wanted);
|
||||
_switch = SwitchAsync(_switch, wanted);
|
||||
if (services.Engine is not { } engine) return;
|
||||
@@ -150,6 +202,9 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
|
||||
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>
|
||||
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>
|
||||
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)
|
||||
{
|
||||
if (services.Database is not { } db) return null;
|
||||
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);
|
||||
if (archives.FirstOrDefault(a => string.Equals(Path.GetFullPath(a.RootPath).TrimEnd(Path.DirectorySeparatorChar), full, StringComparison.OrdinalIgnoreCase))
|
||||
is { } current) return current;
|
||||
var target = await OriginalsArchiveAsync(local);
|
||||
if (target.ArchiveId is null) notify(Loc.L("Errors.Sync.NoArchive"), null, true);
|
||||
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)
|
||||
@@ -187,9 +297,10 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
|
||||
var until = DateTime.UtcNow + RestoreWait;
|
||||
while (Volatile.Read(ref _credentials) is null && services.Settings.ProtectedToken is not null && DateTime.UtcNow < until)
|
||||
await Task.Delay(500, cancellationToken);
|
||||
if (Volatile.Read(ref _credentials) is not { } c || SyncService.ServerKey(c.Address) != server) return null;
|
||||
// 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));
|
||||
return RemoteFactory(c.Address, c.Token, c.Fingerprints);
|
||||
return RemoteFactory(c.Address, c.Token, c.Fingerprints, c.Key);
|
||||
}
|
||||
|
||||
/// <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);
|
||||
}
|
||||
|
||||
/// <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() =>
|
||||
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)
|
||||
{
|
||||
@@ -265,6 +379,92 @@ 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. The links move at
|
||||
/// once (<see cref="HomeLayoutMigration.RekeyLinksAsync"/>): the jobs resumed under the id key look them up by it. The
|
||||
/// folders wait while a job writes into the workspace or the cache, a project is open in the editor, or the workspace
|
||||
/// is being moved: a later sign-in moves them, 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
|
||||
{
|
||||
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.RekeyLinksAsync(id, aliases).ConfigureAwait(false);
|
||||
if (workspace.HasProjectsInEditor || await db.Jobs.HasPendingAsync(RekeyHeldBy).ConfigureAwait(false))
|
||||
{
|
||||
Log.Info("sync", $"Server {id}: its folders on this PC move from its addresses to its id at a later sign-in (jobs are under way or a project is open)");
|
||||
return;
|
||||
}
|
||||
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>
|
||||
/// 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.
|
||||
@@ -272,7 +472,8 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
|
||||
private async Task SwitchAsync(Task previous, Credentials? wanted)
|
||||
{
|
||||
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;
|
||||
var stopped = Volatile.Read(ref _running)?.Remote.Server;
|
||||
await StopAsync().ConfigureAwait(false);
|
||||
@@ -283,7 +484,8 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
|
||||
Changed?.Invoke();
|
||||
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);
|
||||
agent.Changed += () => Changed?.Invoke();
|
||||
agent.ProjectChanged += e => ProjectChanged?.Invoke(remote.Server, e);
|
||||
@@ -302,7 +504,12 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
|
||||
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>
|
||||
private sealed record SharedClient(Uri Address, string Token, ChronosClient Client);
|
||||
|
||||
@@ -316,11 +316,7 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
|
||||
await service.EnqueueSendExportsAsync(engine, server, entry.Local!);
|
||||
break;
|
||||
case SyncAction.DownloadOriginals:
|
||||
if ((entry.Local?.ArchiveId ?? (await Host.CurrentArchiveAsync())?.Id) is not { } archive)
|
||||
{
|
||||
_shell.Notify(Loc.L("Errors.Sync.NoArchive"), isError: true);
|
||||
return;
|
||||
}
|
||||
if (await Host.OriginalsForDownloadAsync(entry.Local, (title, message, isError) => _shell.Notify(title, message, isError: isError)) is not { } archive) return;
|
||||
await service.EnqueueDownloadAsync(engine, server, entry.Id, entry.Title, SyncDownloadMode.Originals, archive);
|
||||
break;
|
||||
case SyncAction.GetExports:
|
||||
|
||||
@@ -2,6 +2,7 @@ using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Jobs;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Projects;
|
||||
@@ -143,8 +144,10 @@ public static class SyncText
|
||||
{
|
||||
JobState.Paused => (StatusKind.Paused, Loc.L("Server.Sync.State.Paused"), Loc.L("Tooltips.Server.Sync.State.Paused")),
|
||||
JobState.Queued => (StatusKind.Queued, Loc.L("Server.Sync.State.Waiting"), Loc.L("Tooltips.Server.Sync.State.Waiting")),
|
||||
// What the transfer does now (owner review 5, #65: "Uploading photo 812 of 2,400") follows in the tooltip.
|
||||
_ => (StatusKind.Running, Loc.L(upload ? "Server.Sync.State.Uploading" : "Server.Sync.State.Downloading"),
|
||||
Loc.L(upload ? "Tooltips.Server.Sync.State.Uploading" : "Tooltips.Server.Sync.State.Downloading")),
|
||||
Join([Loc.L(upload ? "Tooltips.Server.Sync.State.Uploading" : "Tooltips.Server.Sync.State.Downloading"),
|
||||
.. JobText.Status(job.Detail) is { Length: > 0 } status ? [status] : Array.Empty<string>()])),
|
||||
};
|
||||
}
|
||||
if (entry.Link?.Error is { } error) return (StatusKind.Warning, Loc.L("Server.Sync.State.Failed"), Loc.L("Tooltips.Server.Sync.State.Failed", error));
|
||||
|
||||
@@ -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\<id></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));
|
||||
}
|
||||
@@ -92,7 +92,7 @@
|
||||
|
||||
<!-- Job bar (DESIGN §4): current job, progress, time left, pause; "Ready" when idle, hidden when idle in the editor.
|
||||
Screen readers hear which job starts and when the queue empties, not its progress ticks. -->
|
||||
<ui:JobBar x:Name="JobBar" Text="{Binding JobText}" Progress="{Binding JobProgress}" IsActive="{Binding IsJobActive}" IsIndeterminate="{Binding IsJobIndeterminate}"
|
||||
<ui:JobBar x:Name="JobBar" Text="{Binding JobText}" ToolTip="{Binding JobToolTip}" Progress="{Binding JobProgress}" IsActive="{Binding IsJobActive}" IsIndeterminate="{Binding IsJobIndeterminate}"
|
||||
StopCommand="{Binding StopJobCommand}" StopToolTip="{l:Loc Tooltips.Shell.PauseJob}" StopName="{l:Loc Shell.JobBar.Pause}" ActionGlyph="{StaticResource Icon.Pause}"
|
||||
Visibility="{Binding IsJobBarVisible, Converter={StaticResource BoolToVisibility}}"
|
||||
AutomationProperties.LiveSetting="Polite" infra:LiveRegion.Text="{Binding JobAnnouncement}" />
|
||||
|
||||
@@ -39,6 +39,9 @@ public partial class MainWindow : ChronosWindow
|
||||
Closed += (_, _) => _notifications.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>The Windows notifications of the toasts nobody sees (the shared library's tray icon carries them while sharing).</summary>
|
||||
internal OsNotifications Notifications => _notifications;
|
||||
|
||||
/// <summary>Started at sign-in (Settings › General › Startup): the window waits minimised on the taskbar.</summary>
|
||||
internal static bool StartsMinimized(IReadOnlyList<string> arguments) =>
|
||||
arguments.Any(a => a.Equals(RunKeyStartWithWindows.MinimizedOption, StringComparison.OrdinalIgnoreCase));
|
||||
@@ -50,6 +53,16 @@ public partial class MainWindow : ChronosWindow
|
||||
_restoreTo = maximized ? WindowState.Maximized : WindowState.Normal;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A hidden window comes back minimised on the taskbar (the tray icon went while it was hidden); its first restore
|
||||
/// brings back the state it had, maximised or not.
|
||||
/// </summary>
|
||||
internal void ShowMinimized()
|
||||
{
|
||||
if (WindowState != WindowState.Minimized) WaitMinimized(WindowState == WindowState.Maximized);
|
||||
Show();
|
||||
}
|
||||
|
||||
/// <summary>The maximised flag to save: a window started minimised and never opened keeps the state it would come back to.</summary>
|
||||
internal static bool SavesMaximized(WindowState state, WindowState? restoreTo) =>
|
||||
state == WindowState.Maximized || (state == WindowState.Minimized && restoreTo == WindowState.Maximized);
|
||||
|
||||
@@ -40,15 +40,21 @@ public sealed class OsNotifications : IDisposable
|
||||
/// <summary>The tray icon is in the notification area (tests).</summary>
|
||||
internal bool HasTrayIcon => _tray is not null;
|
||||
|
||||
/// <summary>
|
||||
/// The persistent tray icon while the library is shared (<see cref="ShellTray"/>): the balloons go there instead of a
|
||||
/// second icon of their own, and its balloon clicks come back to <see cref="OnBalloonClicked"/>. Null otherwise.
|
||||
/// </summary>
|
||||
internal TrayIcon? SharedIcon { get; set; }
|
||||
|
||||
/// <summary>Mirrors <paramref name="toast"/> as a Windows notification when nobody sees the window; true when it did.</summary>
|
||||
public bool Show(Toast toast)
|
||||
{
|
||||
// A toast raised while the app closes (the window is hidden by then) needs no icon that would outlive it.
|
||||
if (_disposed || !_enabled() || !IsUnseen(_window.WindowState, _window.IsVisible, AnyWindowActive())) return false;
|
||||
_tray ??= new TrayIcon(Loc.L("Shell.AppName"), Menu, OnMenu, Restore, OnBalloonClicked);
|
||||
var icon = SharedIcon ?? (_tray ??= new TrayIcon(Loc.L("Shell.AppName"), Menu, OnMenu, Restore, OnBalloonClicked));
|
||||
_latest = toast;
|
||||
_shown++;
|
||||
_tray.ShowBalloon(toast.Title, BalloonText(toast), toast.IsError);
|
||||
icon.ShowBalloon(toast.Title, BalloonText(toast), toast.IsError);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -112,7 +118,7 @@ public sealed class OsNotifications : IDisposable
|
||||
/// </summary>
|
||||
private void OnActivated(object? sender, EventArgs e)
|
||||
{
|
||||
if (_tray is null) return;
|
||||
if (_tray is null && _shown == 0) return;
|
||||
_window.Dispatcher.BeginInvoke(() =>
|
||||
{
|
||||
if (!IsUnseen(_window.WindowState, _window.IsVisible, AnyWindowActive())) RemoveIcon();
|
||||
|
||||
@@ -24,7 +24,7 @@ namespace Chronos.App.Shell;
|
||||
/// <summary>
|
||||
/// <c>Chronos.exe --capture <dir></c>: renders every client screen at 1440×900 in the dark and light themes to
|
||||
/// <c><screen>-<theme>.png</c> from <see cref="SampleData"/> (first run on an empty index, then a populated
|
||||
/// one, then the Videos section, then the sync table with transfers, a conflict and its confirmation, then the sequence editor on an archive
|
||||
/// one, then the Videos section, then the sync table with transfers, a conflict and its confirmation, then the server's jobs, then the sequence editor on an archive
|
||||
/// sequence and on a server sequence with proxies, its server job and a read-only account), plus the Library, the
|
||||
/// editor's Exposure tab and the import plan in Arabic (<c>*-rtl-dark.png</c>, right to left), for visual review,
|
||||
/// the pixel diff against <c>tests/visual/baselines</c> and phase reports (BRIEF §20.2), then exits. The pictures are
|
||||
@@ -53,6 +53,10 @@ public static class ScreenCapture
|
||||
window.ShowInTaskbar = false;
|
||||
window.Show();
|
||||
|
||||
// The Server section's job list reads the sample server's jobs, none until its own scene.
|
||||
var serverJobs = new SampleServerJobs();
|
||||
shell.Server.JobsConnection = _ => serverJobs;
|
||||
|
||||
// First run: empty index, nothing connected, the welcome dialog over the empty Library.
|
||||
await sample.OpenEmptyAsync();
|
||||
await shell.StartAsync();
|
||||
@@ -113,6 +117,12 @@ public static class ScreenCapture
|
||||
|
||||
shell.Navigate(SectionKey.Server);
|
||||
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).
|
||||
shell.Navigate(SectionKey.Settings);
|
||||
@@ -164,6 +174,19 @@ public static class ScreenCapture
|
||||
SelectSyncFilter(shell, SyncFilter.All);
|
||||
}
|
||||
|
||||
// The server's jobs running and paused above the sync table, with what each does now (owner review 5, #65); the
|
||||
// sample account is an editor, so the list is read-only.
|
||||
serverJobs.Fill();
|
||||
await shell.Server.Jobs.ReloadAsync();
|
||||
foreach (var theme in Themes)
|
||||
{
|
||||
ThemeManager.Apply(theme);
|
||||
shell.Navigate(SectionKey.Server);
|
||||
written += await SaveAsync(window, directory, "server-jobs", theme);
|
||||
}
|
||||
serverJobs.Clear();
|
||||
await shell.Server.Jobs.ReloadAsync();
|
||||
|
||||
written += await CaptureEditorAsync(window, shell, sample, directory);
|
||||
written += await CaptureRemoteEditorAsync(window, shell, sample, directory);
|
||||
Log.Info("capture", $"{written} screenshot(s) written to {Path.GetFullPath(directory)}");
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
using Chronos.App.Server;
|
||||
using Chronos.Core.Localization;
|
||||
|
||||
namespace Chronos.App.Shell;
|
||||
|
||||
/// <summary>How the main window appears when Chronos starts.</summary>
|
||||
public enum StartWindow
|
||||
{
|
||||
/// <summary>On screen, as the user left it.</summary>
|
||||
Shown,
|
||||
|
||||
/// <summary>Started at sign-in: minimised on the taskbar.</summary>
|
||||
Minimized,
|
||||
|
||||
/// <summary>Started at sign-in while sharing: hidden, only the tray icon shows.</summary>
|
||||
Tray,
|
||||
}
|
||||
|
||||
/// <summary>What closing the main window does.</summary>
|
||||
public enum CloseAction
|
||||
{
|
||||
/// <summary>Chronos ends (sharing, if any, stops first).</summary>
|
||||
Exit,
|
||||
|
||||
/// <summary>The window hides; Chronos keeps sharing from the tray icon.</summary>
|
||||
HideToTray,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The desktop's lifetime while it shares its library (owner review 5, #67, design §2.5): while sharing is on, or on its
|
||||
/// way, Chronos keeps running with a tray icon, closing the window hides it, Exit asks first when clients are active, and
|
||||
/// a start at sign-in waits in the tray. With sharing off nothing changes. Pure decisions, for <see cref="ShellTray"/>.
|
||||
/// </summary>
|
||||
public static class ShareLifetime
|
||||
{
|
||||
/// <summary>
|
||||
/// True while Chronos must outlive its window: the library is served or starting, or sharing is on in the settings and
|
||||
/// has not started yet (the index is opening, the archive's drive is unplugged). A share that failed to start, or one
|
||||
/// turned off and stopped, keeps nothing running.
|
||||
/// </summary>
|
||||
public static bool KeepsRunning(bool shareEnabled, ShareState state) => state switch
|
||||
{
|
||||
ShareState.On or ShareState.Starting => true,
|
||||
ShareState.Off => shareEnabled,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
/// <summary>Closing the window hides it while sharing, unless the user chose Exit (or Windows is ending the session).</summary>
|
||||
public static CloseAction OnClose(bool exiting, bool keepsRunning) => !exiting && keepsRunning ? CloseAction.HideToTray : CloseAction.Exit;
|
||||
|
||||
/// <summary>Exit asks first when programs used the shared library in the last minutes or render nodes are online.</summary>
|
||||
public static bool AsksBeforeExit(ShareState state, int activeClients) => state == ShareState.On && activeClients > 0;
|
||||
|
||||
/// <summary>A start at sign-in (<c>--minimized</c>) waits in the tray while sharing is on, else minimised on the taskbar.</summary>
|
||||
public static StartWindow Start(bool minimized, bool shareEnabled) =>
|
||||
!minimized ? StartWindow.Shown : shareEnabled ? StartWindow.Tray : StartWindow.Minimized;
|
||||
|
||||
/// <summary>The tray icon's hover text: "Chronos · sharing studio-pc" (the name clients see; empty: this PC's name).</summary>
|
||||
public static string ToolTip(string? name, string machineName) =>
|
||||
Loc.L("Shell.Tray.Sharing", string.IsNullOrWhiteSpace(name) ? machineName : name.Trim());
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
using System.ComponentModel;
|
||||
using System.Windows;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Server;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Ui.Interop;
|
||||
|
||||
namespace Chronos.App.Shell;
|
||||
|
||||
/// <summary>
|
||||
/// The desktop's tray while it shares its library (owner review 5, #67, design §2.5): while <see cref="ShareLifetime.KeepsRunning"/>
|
||||
/// a tray icon shows (Open Chronos, Exit; tooltip "Chronos · sharing name"), closing the main window hides it instead of
|
||||
/// ending Chronos (one balloon says so, the first time), and Exit asks first when clients are active, then closes the window
|
||||
/// for real: the editor stores its last edit, and the app's exit stops sharing before the other services. Without sharing
|
||||
/// nothing changes: no icon, closing ends Chronos. Create, use and dispose it on the UI thread.
|
||||
/// </summary>
|
||||
public sealed class ShellTray : IDisposable
|
||||
{
|
||||
private const int MenuOpen = 1;
|
||||
private const int MenuExit = 2;
|
||||
|
||||
private readonly MainWindow _window;
|
||||
private readonly ShellViewModel _shell;
|
||||
private readonly LibraryShare _share;
|
||||
private TrayIcon? _icon;
|
||||
private string? _toolTip;
|
||||
private bool _exiting;
|
||||
private bool _asking;
|
||||
private bool _told;
|
||||
private bool _closed;
|
||||
private bool _disposed;
|
||||
|
||||
public ShellTray(MainWindow window, ShellViewModel shell)
|
||||
{
|
||||
_window = window;
|
||||
_shell = shell;
|
||||
_share = shell.Services.Share;
|
||||
_window.Closing += OnClosing;
|
||||
_window.Closed += OnClosed;
|
||||
_share.Changed += OnShareChanged;
|
||||
if (Application.Current is { } app) app.SessionEnding += OnSessionEnding;
|
||||
}
|
||||
|
||||
/// <summary>Chronos outlives its window now: sharing is on or on its way.</summary>
|
||||
public bool KeepsRunning => ShareLifetime.KeepsRunning(_shell.Services.Settings.Share.Enabled, _share.State);
|
||||
|
||||
/// <summary>
|
||||
/// Shows or removes the icon as sharing goes on or off, and follows a new name. An icon that goes while the window is
|
||||
/// hidden brings the window back, minimised on the taskbar, so Chronos never runs out of sight. Any thread.
|
||||
/// </summary>
|
||||
public void Update()
|
||||
{
|
||||
if (!_window.Dispatcher.CheckAccess())
|
||||
{
|
||||
_window.Dispatcher.BeginInvoke(Update);
|
||||
return;
|
||||
}
|
||||
if (_disposed) return;
|
||||
if (KeepsRunning)
|
||||
{
|
||||
var text = ShareLifetime.ToolTip(_shell.Services.Settings.Share.Name, System.Environment.MachineName);
|
||||
if (_icon is null)
|
||||
{
|
||||
_icon = new TrayIcon(text, Menu, OnMenu, Open, _window.Notifications.OnBalloonClicked);
|
||||
_window.Notifications.SharedIcon = _icon;
|
||||
}
|
||||
else if (text != _toolTip)
|
||||
{
|
||||
_icon.SetToolTip(text);
|
||||
}
|
||||
_toolTip = text;
|
||||
return;
|
||||
}
|
||||
if (_icon is null) return;
|
||||
RemoveIcon();
|
||||
if (!_exiting && !_closed && !_window.IsVisible) _window.ShowMinimized();
|
||||
}
|
||||
|
||||
/// <summary>The window in front, as it was before it was hidden or minimised.</summary>
|
||||
public void Open()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_window.Show();
|
||||
if (_window.WindowState == WindowState.Minimized) _window.WindowState = WindowState.Normal;
|
||||
_window.Activate();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tray › Exit: asks first when clients are active, then ends Chronos. A window with an edit still to store comes back
|
||||
/// first, since storing it may ask; a window never shown (started in the tray) has no editor and the app shuts down.
|
||||
/// </summary>
|
||||
public async Task ExitAsync()
|
||||
{
|
||||
if (_disposed || _exiting || _asking) return;
|
||||
_asking = true;
|
||||
try
|
||||
{
|
||||
var clients = await _share.ActiveClientsAsync();
|
||||
if (ShareLifetime.AsksBeforeExit(_share.State, clients) && !_shell.Services.Dialogs.Confirm(ExitRequest(clients))) return;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_asking = false;
|
||||
}
|
||||
_exiting = true;
|
||||
if (!_window.IsLoaded)
|
||||
{
|
||||
Application.Current?.Shutdown();
|
||||
return;
|
||||
}
|
||||
if (_shell.Sequence.HasPendingSave) Open();
|
||||
_window.Close();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_window.Closing -= OnClosing;
|
||||
_window.Closed -= OnClosed;
|
||||
_share.Changed -= OnShareChanged;
|
||||
if (Application.Current is { } app) app.SessionEnding -= OnSessionEnding;
|
||||
RemoveIcon();
|
||||
}
|
||||
|
||||
/// <summary>The confirmation of Exit while clients use the library: Keep sharing is the safe, default choice.</summary>
|
||||
internal static ConfirmRequest ExitRequest(int clients) => new()
|
||||
{
|
||||
Heading = Loc.L("Shell.Exit.Heading"),
|
||||
Message = Loc.Plural("Shell.Exit.Message", clients),
|
||||
SafeText = Loc.L("Shell.Exit.Keep"),
|
||||
SafeToolTip = Loc.L("Tooltips.Shell.Exit.Keep"),
|
||||
ActionText = Loc.L("Shell.Tray.Exit"),
|
||||
ActionToolTip = Loc.L("Tooltips.Shell.Exit.Exit"),
|
||||
};
|
||||
|
||||
private IReadOnlyList<TrayMenuItem> Menu() =>
|
||||
[
|
||||
new(MenuOpen, Loc.L("Shell.Tray.Open")),
|
||||
new(0, null),
|
||||
new(MenuExit, Loc.L("Shell.Tray.Exit")),
|
||||
];
|
||||
|
||||
private void OnMenu(int id)
|
||||
{
|
||||
switch (id)
|
||||
{
|
||||
case MenuOpen:
|
||||
Open();
|
||||
break;
|
||||
case MenuExit:
|
||||
_ = RunExitAsync();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RunExitAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await ExitAsync();
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
Log.Error("app", "Chronos could not exit from the tray", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Closing hides the window while sharing; the first time, a balloon says Chronos goes on sharing.</summary>
|
||||
private void OnClosing(object? sender, CancelEventArgs e)
|
||||
{
|
||||
if (e.Cancel || ShareLifetime.OnClose(_exiting, KeepsRunning) == CloseAction.Exit) return;
|
||||
e.Cancel = true;
|
||||
// The icon exists before the window goes, whatever the last state change was.
|
||||
Update();
|
||||
_window.Hide();
|
||||
if (_told || _icon is null) return;
|
||||
_told = true;
|
||||
_icon.ShowBalloon(Loc.L("Shell.Tray.KeepsSharing"), Loc.L("Shell.Tray.KeepsSharingText"));
|
||||
}
|
||||
|
||||
private void OnShareChanged() => Update();
|
||||
|
||||
private void OnClosed(object? sender, EventArgs e) => _closed = true;
|
||||
|
||||
/// <summary>Windows is signing out or shutting down: the window closes for real (WPF closes it without waiting anyway).</summary>
|
||||
private void OnSessionEnding(object? sender, SessionEndingCancelEventArgs e) => _exiting = true;
|
||||
|
||||
private void RemoveIcon()
|
||||
{
|
||||
if (_icon is null) return;
|
||||
if (ReferenceEquals(_window.Notifications.SharedIcon, _icon)) _window.Notifications.SharedIcon = null;
|
||||
_icon.Dispose();
|
||||
_icon = null;
|
||||
_toolTip = null;
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ public sealed class ShellViewModel : LocalizedViewModel
|
||||
private bool _isRailCollapsed;
|
||||
private string? _jobText;
|
||||
private string? _jobName;
|
||||
private string? _jobToolTip;
|
||||
private double _jobProgress;
|
||||
private bool _jobActive;
|
||||
private bool _jobIndeterminate;
|
||||
@@ -227,6 +228,9 @@ public sealed class ShellViewModel : LocalizedViewModel
|
||||
? _jobText
|
||||
: _queuedCount > 0 ? Loc.Plural("Shell.JobBar.Ready", _queuedCount) : Loc.L("Shell.JobBar.Idle");
|
||||
|
||||
/// <summary>The job bar's tooltip: its line uncut, with what the job works on now (the bar cuts it at 60 characters).</summary>
|
||||
public string JobToolTip => _jobActive && _jobToolTip is not null ? _jobToolTip : JobText;
|
||||
|
||||
public double JobProgress { get => _jobProgress; private set => Set(ref _jobProgress, value); }
|
||||
public bool IsJobActive
|
||||
{
|
||||
@@ -264,16 +268,19 @@ public sealed class ShellViewModel : LocalizedViewModel
|
||||
|
||||
/// <summary>
|
||||
/// Updates the global job bar and the taskbar button. <paramref name="name"/> says which job it is without its
|
||||
/// progress ("Render: Harbour sunset"); null reads <paramref name="text"/>.
|
||||
/// progress ("Render: Harbour sunset"); null reads <paramref name="text"/>. <paramref name="toolTip"/> is the line uncut;
|
||||
/// null shows <paramref name="text"/>.
|
||||
/// </summary>
|
||||
public void SetJob(string? text, double progress, bool indeterminate = false, string? name = null)
|
||||
public void SetJob(string? text, double progress, bool indeterminate = false, string? name = null, string? toolTip = null)
|
||||
{
|
||||
_jobText = text;
|
||||
_jobToolTip = text is null ? null : toolTip ?? text;
|
||||
_jobName = text is null ? null : name ?? text;
|
||||
IsJobActive = text is not null;
|
||||
JobProgress = progress;
|
||||
IsJobIndeterminate = indeterminate;
|
||||
OnPropertyChanged(nameof(JobText));
|
||||
OnPropertyChanged(nameof(JobToolTip));
|
||||
OnPropertyChanged(nameof(JobAnnouncement));
|
||||
OnPropertyChanged(nameof(TaskbarState));
|
||||
OnPropertyChanged(nameof(TaskbarProgress));
|
||||
@@ -321,6 +328,7 @@ public sealed class ShellViewModel : LocalizedViewModel
|
||||
_queuedCount = queued;
|
||||
OnPropertyChanged(nameof(JobsText));
|
||||
OnPropertyChanged(nameof(JobText));
|
||||
OnPropertyChanged(nameof(JobToolTip));
|
||||
OnPropertyChanged(nameof(JobAnnouncement));
|
||||
}
|
||||
|
||||
|
||||
@@ -429,25 +429,37 @@ public static class VideoSources
|
||||
public static IReadOnlyList<VideoEntry> ReadWorkspace(WorkspaceStore store, IEnumerable<WorkspaceEntry> projects)
|
||||
{
|
||||
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\<id>\</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);
|
||||
var entries = new List<VideoEntry>();
|
||||
foreach (var project in projects.Where(p => p.IsReadable))
|
||||
foreach (var entry in projects.Where(p => p.IsReadable))
|
||||
{
|
||||
try
|
||||
{
|
||||
var folder = store.Project(project.ProjectId);
|
||||
var folder = project(entry.ProjectId);
|
||||
foreach (var render in folder.ReadRenders().Entries)
|
||||
{
|
||||
var path = folder.ExportFile(render.File);
|
||||
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".
|
||||
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)
|
||||
{
|
||||
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;
|
||||
|
||||
@@ -986,7 +986,7 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
|
||||
/// </summary>
|
||||
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;
|
||||
if (_context is { } context) context.Post(_ => _ = HomeChangedAsync(change), null);
|
||||
else _ = HomeChangedAsync(change);
|
||||
|
||||
@@ -36,6 +36,12 @@ public sealed record WorkspaceTrashPlan(string Folder, IReadOnlyList<WorkspaceTr
|
||||
{
|
||||
/// <summary>Nothing to erase: Empty… is disabled.</summary>
|
||||
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\<id>\</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>
|
||||
@@ -63,21 +69,28 @@ public sealed partial class WorkspaceHost
|
||||
var root = Root;
|
||||
if (!Directory.Exists(root)) return WorkspaceUsage.None;
|
||||
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();
|
||||
media += WorkspaceCleaner.Measure(Path.Combine(folder, WorkspaceProject.MediaFolder)).Bytes;
|
||||
if (!Directory.Exists(store.Root)) continue;
|
||||
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);
|
||||
return new WorkspaceUsage(media, WorkspaceCleaner.Measure(root).Bytes, trash.Bytes, trash.Entries.Count);
|
||||
var trash = Homes.Trash(cancellationToken);
|
||||
return new WorkspaceUsage(media, WorkspaceCleaner.Measure(root).Bytes, trash.Sum(t => t.Bytes), trash.Sum(t => t.Entries.Count));
|
||||
}, 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(() =>
|
||||
{
|
||||
var listing = WorkspaceTrash.List(Root, cancellationToken);
|
||||
return new WorkspaceTrashPlan(listing.Folder, [.. listing.Entries.Select(e => new WorkspaceTrashItem(e.Name, e.Bytes, e.Files, e.Trashed))], listing.Bytes,
|
||||
listing.Fingerprint);
|
||||
var listings = Homes.Trash(cancellationToken);
|
||||
var folder = listings.Count == 1 ? listings[0].Folder : WorkspaceTrash.FolderOf(Root);
|
||||
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);
|
||||
|
||||
/// <summary>
|
||||
@@ -92,11 +105,25 @@ public sealed partial class WorkspaceHost
|
||||
return Task.Run(() =>
|
||||
{
|
||||
EnsureNotMoving();
|
||||
var listing = new WorkspaceTrashListing(plan.Folder, [.. plan.Items.Select(i => new WorkspaceTrashEntry(i.Name, i.Bytes, i.Files, i.Trashed))], plan.Bytes,
|
||||
plan.Fingerprint);
|
||||
IReadOnlyList<WorkspaceTrashListing> listings = plan.Listings.Count > 0 ? plan.Listings
|
||||
: [new WorkspaceTrashListing(plan.Folder, [.. plan.Items.Select(i => new WorkspaceTrashEntry(i.Name, i.Bytes, i.Files, i.Trashed))], plan.Bytes,
|
||||
plan.Fingerprint)];
|
||||
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);
|
||||
}
|
||||
catch (WorkspaceTrashChangedException ex)
|
||||
@@ -130,7 +157,7 @@ public sealed partial class WorkspaceHost
|
||||
await _cleaning.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
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);
|
||||
}
|
||||
finally
|
||||
@@ -147,10 +174,7 @@ public sealed partial class WorkspaceHost
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(job);
|
||||
if (job is not { Kind: JobKind.WorkspaceCopy, State: JobState.Done } || _settings.WorkspaceSizeLimitGb <= 0) return;
|
||||
if (WorkspaceJobs.CopyParameters(job) is not { } copied
|
||||
|| !string.Equals(Path.TrimEndingDirectorySeparator(Path.GetFullPath(copied.WorkspaceRoot)), Path.TrimEndingDirectorySeparator(Path.GetFullPath(Root)),
|
||||
StringComparison.OrdinalIgnoreCase))
|
||||
return;
|
||||
if (WorkspaceJobs.CopyParameters(job) is not { } copied || !IsUnderRoot(copied.WorkspaceRoot)) return;
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
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\<id>\</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>
|
||||
private IReadOnlyDictionary<Guid, DateTimeOffset> OpenedSnapshot()
|
||||
{
|
||||
@@ -331,7 +365,7 @@ public sealed partial class WorkspaceHost
|
||||
if (WorkspaceJobs.SendParameters(pending)?.ProjectId == project.ProjectId) return;
|
||||
}
|
||||
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);
|
||||
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>
|
||||
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);
|
||||
// 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);
|
||||
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);
|
||||
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);
|
||||
|
||||
@@ -12,6 +12,7 @@ using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Projects;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Data.Workspaces;
|
||||
using Chronos.Protocol;
|
||||
|
||||
@@ -163,6 +164,7 @@ public sealed partial class WorkspaceHost
|
||||
private readonly Func<JobEngine?> _engine;
|
||||
private readonly Lock _gate = new();
|
||||
private readonly Dictionary<Guid, Guid> _copies = [];
|
||||
private readonly Dictionary<Guid, int> _inEditor = [];
|
||||
private OpenWorkspace? _open;
|
||||
|
||||
public WorkspaceHost(AppEnvironment environment, AppSettings settings, Action savePreferences, Func<ChronosDatabase?> db, Func<ArchiveService?> archives,
|
||||
@@ -203,27 +205,116 @@ public sealed partial class WorkspaceHost
|
||||
|
||||
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\<id></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="InvalidDataException">The folder holds another program's or a newer workspace manifest.</exception>
|
||||
public WorkspaceSync Sync
|
||||
public WorkspaceHomes Homes
|
||||
{
|
||||
get
|
||||
{
|
||||
var root = Root;
|
||||
var identity = Identity?.Invoke() ?? ServerIdentity.None;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_open is not { } open || !string.Equals(open.Root, root, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var store = new WorkspaceStore(root);
|
||||
_open = open = new OpenWorkspace(root, new WorkspaceSync(store, ClientName) { LockWait = LockWait });
|
||||
}
|
||||
return open.Sync;
|
||||
_open = open = new OpenWorkspace(root, new WorkspaceHomes(root, identity));
|
||||
open.Homes.Identity = identity;
|
||||
return open.Homes;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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>
|
||||
/// Marks <paramref name="projectId"/> open in the editor until the result is disposed. The editor keeps its project's
|
||||
/// folder for as long as it is open, so the move of a server's home to its id waits meanwhile (owner review 5, #66).
|
||||
/// </summary>
|
||||
public IDisposable HoldInEditor(Guid projectId)
|
||||
{
|
||||
lock (_inEditor) _inEditor[projectId] = _inEditor.GetValueOrDefault(projectId) + 1;
|
||||
return new EditorHold(this, projectId);
|
||||
}
|
||||
|
||||
/// <summary>A project is open in the editor (<see cref="HoldInEditor"/>).</summary>
|
||||
public bool HasProjectsInEditor
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_inEditor) return _inEditor.Count > 0;
|
||||
}
|
||||
}
|
||||
|
||||
private void ReleaseInEditor(Guid projectId)
|
||||
{
|
||||
lock (_inEditor)
|
||||
{
|
||||
if (!_inEditor.TryGetValue(projectId, out var count)) return;
|
||||
if (count <= 1) _inEditor.Remove(projectId);
|
||||
else _inEditor[projectId] = count - 1;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class EditorHold(WorkspaceHost host, Guid projectId) : IDisposable
|
||||
{
|
||||
private int _released;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _released, 1) == 0) host.ReleaseInEditor(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>
|
||||
/// The project home of a server home (phase 5b; the desktop's <c>SyncHost.ProjectHome</c>): null while this PC is not
|
||||
@@ -273,8 +364,8 @@ public sealed partial class WorkspaceHost
|
||||
BundleHome home;
|
||||
try
|
||||
{
|
||||
if (!IsAvailable || Store.Find(change.ProjectId)?.ReadBundle().Workspace?.Home is not { IsArchive: false } held || held.SequenceId != change.SequenceId
|
||||
|| !string.Equals(held.Server, server, StringComparison.OrdinalIgnoreCase))
|
||||
if (!IsAvailable || Find(change.ProjectId)?.ReadBundle().Workspace?.Home is not { IsArchive: false } held || held.SequenceId != change.SequenceId
|
||||
|| !SameServer(held.Server, server))
|
||||
return;
|
||||
home = held;
|
||||
}
|
||||
@@ -298,7 +389,7 @@ public sealed partial class WorkspaceHost
|
||||
{
|
||||
// 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");
|
||||
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)
|
||||
{
|
||||
@@ -316,7 +407,7 @@ public sealed partial class WorkspaceHost
|
||||
{
|
||||
if (!Directory.Exists(Root) && await InsideALibraryAsync(cancellationToken).ConfigureAwait(false)) return [];
|
||||
var entries = new List<WorkspaceEntry>();
|
||||
foreach (var project in Store.List())
|
||||
foreach (var project in Homes.List())
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -345,7 +436,7 @@ public sealed partial class WorkspaceHost
|
||||
{
|
||||
EnsureNotMoving();
|
||||
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);
|
||||
|
||||
/// <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 +472,7 @@ public sealed partial class WorkspaceHost
|
||||
if (plan.IsSame) return;
|
||||
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.
|
||||
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.
|
||||
_settings.WorkspaceFolder = string.Equals(plan.Folder, Path.GetFullPath(DefaultRoot(_environment)), StringComparison.OrdinalIgnoreCase) ? null : plan.Folder;
|
||||
_savePreferences();
|
||||
@@ -470,10 +561,10 @@ public sealed partial class WorkspaceHost
|
||||
: 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.
|
||||
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);
|
||||
var folder = await Sync.CheckoutAsync(reached, project.Id, media, cancellationToken).ConfigureAwait(false);
|
||||
Log.Info("workspace", $"Project {project.Id} ('{project.Name}') of sequence {sequenceId} checked out into {Store.Root}");
|
||||
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 {folder.Store.Root}");
|
||||
var title = folder.ReadBundle().Sequence.Title ?? string.Empty;
|
||||
return new WorkspaceCheckout(project, await QueueCopyCoreAsync(home, project.Id, media, title, cancellationToken).ConfigureAwait(false));
|
||||
}, cancellationToken);
|
||||
@@ -507,14 +598,14 @@ public sealed partial class WorkspaceHost
|
||||
var home = askHome ? HomeOf(named) : null;
|
||||
try
|
||||
{
|
||||
if (askHome && home is null && !named.IsArchive) return Offline(await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
|
||||
return await Sync.StatusAsync(projectId, home, cancellationToken).ConfigureAwait(false);
|
||||
if (askHome && home is null && !named.IsArchive) return Offline(await SyncOf(projectId).StatusAsync(projectId, null, 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)
|
||||
{
|
||||
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}");
|
||||
var local = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
|
||||
var local = await SyncOf(projectId).StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
|
||||
return local with
|
||||
{
|
||||
Offline = true,
|
||||
@@ -545,8 +636,8 @@ public sealed partial class WorkspaceHost
|
||||
var version = await Task.Run(async () =>
|
||||
{
|
||||
EnsureNotMoving();
|
||||
EnsureWritable(await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
|
||||
return await Sync.CommitAsync(projectId, note, null, cancellationToken).ConfigureAwait(false);
|
||||
EnsureWritable(await SyncOf(projectId).StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
|
||||
return await SyncOf(projectId).CommitAsync(projectId, note, null, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
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);
|
||||
@@ -568,8 +659,8 @@ public sealed partial class WorkspaceHost
|
||||
public Task<ProjectVersion?> CommitAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
|
||||
{
|
||||
EnsureNotMoving();
|
||||
EnsureWritable(await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
|
||||
return await Sync.CommitAsync(projectId, null, null, cancellationToken).ConfigureAwait(false);
|
||||
EnsureWritable(await SyncOf(projectId).StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
|
||||
return await SyncOf(projectId).CommitAsync(projectId, null, null, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
@@ -583,10 +674,10 @@ public sealed partial class WorkspaceHost
|
||||
{
|
||||
EnsureNotMoving();
|
||||
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.
|
||||
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);
|
||||
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]);
|
||||
@@ -609,16 +700,16 @@ public sealed partial class WorkspaceHost
|
||||
var name = SiblingName(Existing(projectId).ReadBundle().Workspace!.Name);
|
||||
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)
|
||||
{
|
||||
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
|
||||
{
|
||||
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)
|
||||
{
|
||||
@@ -628,7 +719,7 @@ public sealed partial class WorkspaceHost
|
||||
// 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;
|
||||
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)
|
||||
{
|
||||
Kept = resolved.Kept,
|
||||
@@ -652,11 +743,11 @@ public sealed partial class WorkspaceHost
|
||||
public Task<ProjectSettings> RestoreAsync(Guid projectId, Guid versionId, CancellationToken cancellationToken = default) => Task.Run(async () =>
|
||||
{
|
||||
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.MediaRemoved) throw new WorkspaceException(Loc.L("Errors.Workspace.MediaMissing"));
|
||||
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");
|
||||
return restored;
|
||||
}, cancellationToken);
|
||||
@@ -665,7 +756,7 @@ public sealed partial class WorkspaceHost
|
||||
public Task<WorkspaceHistory> HistoryAsync(Guid projectId, int limit = 50, CancellationToken cancellationToken = default) => Task.Run(async () =>
|
||||
{
|
||||
var project = Existing(projectId);
|
||||
var unsent = Sync.Unpushed(projectId);
|
||||
var unsent = SyncOf(projectId).Unpushed(projectId);
|
||||
var home = HomeOf(project.ReadBundle().Workspace!.Home);
|
||||
IReadOnlyList<ProjectVersion> stored;
|
||||
var offline = false;
|
||||
@@ -740,9 +831,9 @@ public sealed partial class WorkspaceHost
|
||||
var workspace = project.ReadBundle().Workspace!;
|
||||
if (workspace.IsMain) throw new ProjectException(ProjectError.MainCannotBeDeleted, "The Main project cannot be deleted.");
|
||||
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.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;
|
||||
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"));
|
||||
@@ -773,7 +864,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>
|
||||
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);
|
||||
var status = (await SyncAsync(projectId, cancellationToken).ConfigureAwait(false)).Status;
|
||||
if (status.State == WorkspaceState.Gone) throw new WorkspaceException(Loc.L("Errors.Workspace.DeletedAtHome"));
|
||||
@@ -837,7 +928,7 @@ public sealed partial class WorkspaceHost
|
||||
var workspace = project.ReadBundle().Workspace!;
|
||||
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.
|
||||
if (status.Ahead > 0 || status.Damaged > 0 || (status.Modified && !status.ReadOnly) || status.Conflict is not null)
|
||||
throw new WorkspaceException(Unsent(workspace.Home));
|
||||
@@ -894,8 +985,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>
|
||||
private async Task<WorkspaceSyncResult> SendAsync(Guid projectId, IProjectHome home, CancellationToken cancellationToken)
|
||||
{
|
||||
var pulled = await Sync.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);
|
||||
var pulled = await SyncOf(projectId).PullAsync(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>
|
||||
@@ -948,7 +1039,7 @@ public sealed partial class WorkspaceHost
|
||||
{ State: JobState.Queued or JobState.Running or JobState.Paused })
|
||||
await engine.CancelAsync(copy, cancellationToken).ConfigureAwait(false);
|
||||
// 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;
|
||||
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
@@ -1087,11 +1178,12 @@ public sealed partial class WorkspaceHost
|
||||
{
|
||||
var sequence = await db.Sequences.GetAsync(home.SequenceId, cancellationToken).ConfigureAwait(false)
|
||||
?? 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
|
||||
{
|
||||
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);
|
||||
}
|
||||
var job = await engine.EnqueueAsync(request, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
@@ -1108,7 +1200,7 @@ public sealed partial class WorkspaceHost
|
||||
: "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)
|
||||
{
|
||||
@@ -1206,14 +1298,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\<folder></c>, owner review 5), without making or opening it.
|
||||
/// </summary>
|
||||
private static int CountProjects(string folder)
|
||||
{
|
||||
if (!Directory.Exists(folder)) return 0;
|
||||
try
|
||||
{
|
||||
return Directory.EnumerateDirectories(folder).Count(d => Guid.TryParseExact(Path.GetFileName(d), "N", out _)
|
||||
&& File.Exists(Path.Combine(d, WorkspaceProject.BundleFile)));
|
||||
var stores = new List<string> { folder, HomeFolders.LocalPath(folder) };
|
||||
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)
|
||||
{
|
||||
@@ -1236,5 +1334,9 @@ public sealed partial class WorkspaceHost
|
||||
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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user