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

Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #68.
This commit is contained in:
Alby96 authored and Alby96 committed 2026-11-15 18:11:43 +01:00
1 parent 988068ee8e
commit 20d64af4a4
793 files changed
+23882 -2096

No files matched your search

+23 -6
View File
@@ -17,9 +17,16 @@ public sealed record SequenceOrphans(string Folder, IReadOnlyList<string> Uninde
public static class SequenceAdopter
{
/// <summary>A new sidecar for a folder without one. A folder outside the layout (no <c>originals/</c>) is titled by its name.</summary>
public static SequenceManifest Build(Guid id, SequencePaths sequence, string? createdBy, CancellationToken cancellationToken = default)
public static SequenceManifest Build(Guid id, SequencePaths sequence, string? createdBy, CancellationToken cancellationToken = default) =>
Build(id, sequence, createdBy, null, cancellationToken);
/// <summary>
/// A new sidecar for a folder without one, telling <paramref name="photoRead"/> after each photo it read (photo done of
/// total), so a scan can show how far it is inside a large folder.
/// </summary>
public static SequenceManifest Build(Guid id, SequencePaths sequence, string? createdBy, Action<int, int>? photoRead, CancellationToken cancellationToken = default)
{
var (frames, first) = ReadFrames(sequence, ArchiveScanner.ListPhotos(sequence), cancellationToken);
var (frames, first) = ReadFrames(sequence, ArchiveScanner.ListPhotos(sequence), photoRead, cancellationToken);
var now = DateTimeOffset.UtcNow;
var inLayout = Directory.Exists(sequence.Originals);
var manifest = new SequenceManifest
@@ -48,7 +55,14 @@ public static class SequenceAdopter
/// Brings a sidecar in line with its folder: unindexed photos are added (in capture order), frames whose file is
/// gone get <see cref="FrameFlags.Missing"/> and frames whose file came back lose it. Null when nothing changed.
/// </summary>
public static SequenceManifest? Reconcile(SequencePaths sequence, SequenceManifest manifest, CancellationToken cancellationToken = default)
public static SequenceManifest? Reconcile(SequencePaths sequence, SequenceManifest manifest, CancellationToken cancellationToken = default) =>
Reconcile(sequence, manifest, null, cancellationToken);
/// <summary>
/// <see cref="Reconcile(SequencePaths, SequenceManifest, CancellationToken)"/>, telling <paramref name="photoRead"/> after
/// each unindexed photo it read (photo done of total).
/// </summary>
public static SequenceManifest? Reconcile(SequencePaths sequence, SequenceManifest manifest, Action<int, int>? photoRead, CancellationToken cancellationToken = default)
{
var orphans = FindOrphans(sequence, manifest);
var missing = orphans.MissingFiles.Select(f => f.Id).ToHashSet();
@@ -61,7 +75,7 @@ public static class SequenceAdopter
}
if (flagChanges.Count == 0 && orphans.UnindexedFiles.Count == 0) return null;
var updated = flagChanges.Count == 0 ? manifest : SequenceFrames.Update(manifest, flagChanges);
var (added, first) = ReadFrames(sequence, orphans.UnindexedFiles, cancellationToken);
var (added, first) = ReadFrames(sequence, orphans.UnindexedFiles, photoRead, cancellationToken);
// Photos that cannot be read yet (held open by another program, no read permission, a placeholder not downloaded)
// stay unindexed: with nothing else changed, nothing changed.
if (added.Count == 0 && flagChanges.Count == 0) return null;
@@ -70,13 +84,15 @@ public static class SequenceAdopter
return SequenceFrames.Insert(updated, added);
}
private static (List<SidecarFrame> Frames, FrameMetadata? First) ReadFrames(SequencePaths sequence, IReadOnlyList<string> files, CancellationToken cancellationToken)
private static (List<SidecarFrame> Frames, FrameMetadata? First) ReadFrames(SequencePaths sequence, IReadOnlyList<string> files, Action<int, int>? photoRead,
CancellationToken cancellationToken)
{
var frames = new List<SidecarFrame>(files.Count);
FrameMetadata? first = null;
foreach (var file in files)
for (var i = 0; i < files.Count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
var file = files[i];
var path = sequence.File(file);
try
{
@@ -88,6 +104,7 @@ public static class SequenceAdopter
{
Log.Warning("archive", $"Skipped unreadable photo {sequence.ArchiveRelative(file)}", ex);
}
photoRead?.Invoke(i + 1, files.Count);
}
return (frames, first);
}
+178
View File
@@ -0,0 +1,178 @@
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
namespace Chronos.Core.IO;
/// <summary>
/// The folders each home of the desktop keeps apart (owner review 5, #66): this PC's archive is the home <see cref="Local"/>,
/// and every Chronos Server is a home of its own under <see cref="Servers"/>, named by the server's stable id
/// (<c>servers\&lt;id:N&gt;</c>), or, for a server that announces none (an older server), by a hash of its address key
/// (<c>servers\addr-&lt;16 hex&gt;</c>: the hash the 1.0 proxy cache named its folders by, so moving them is a rename).
/// The same names are used in the workspace (<c>&lt;workspace&gt;\local</c>, <c>&lt;workspace&gt;\servers\&lt;folder&gt;</c>)
/// and in the cache (<c>&lt;cache&gt;\servers\&lt;folder&gt;\{proxies,render-node,import}</c>). A folder name is never renamed
/// after the server: its name lives in <see cref="ServerFile"/> beside it.
/// </summary>
public static class HomeFolders
{
/// <summary>The folder of this PC's archive's home.</summary>
public const string Local = "local";
/// <summary>The folder that holds one folder per server home.</summary>
public const string Servers = "servers";
/// <summary>What a server home's folder says about its server (id, name, last address), for someone browsing it.</summary>
public const string ServerFile = "server.json";
/// <summary>A server home's proxies of its sequences, in the cache.</summary>
public const string Proxies = "proxies";
/// <summary>A server home's render-node downloads, in the cache.</summary>
public const string RenderNode = "render-node";
/// <summary>A server home's staged card imports, in the cache.</summary>
public const string Import = "import";
/// <summary>The start of a server key made from the server's announced id (<c>id:&lt;32 hex&gt;</c>).</summary>
public const string IdKeyPrefix = "id:";
/// <summary>The start of the folder of a server known by its address only.</summary>
public const string AddressPrefix = "addr-";
/// <summary>Hex digits of the address hash in a folder name (as the 1.0 proxy cache used).</summary>
public const int HashLength = 16;
/// <summary>
/// The folder of a server home: the 32 hex digits of the id of an id key (<c>id:&lt;N&gt;</c>), else <c>addr-</c> and the
/// first 16 hex digits of the SHA-256 of the key (an address key, as <c>SyncService.ServerKey</c> makes it).
/// </summary>
public static string ServerFolder(string serverKey)
{
ArgumentException.ThrowIfNullOrWhiteSpace(serverKey);
return IdOfKey(serverKey) is { } id ? id.ToString("N") : AddressPrefix + AddressHash(serverKey);
}
/// <summary>The 16 hex digits the 1.0 proxy cache named a server's folder by: the start of the SHA-256 of its key.</summary>
public static string AddressHash(string serverKey)
{
ArgumentNullException.ThrowIfNull(serverKey);
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(serverKey)))[..HashLength];
}
/// <summary>The id an id key names (<c>id:&lt;N&gt;</c>); null for an address key.</summary>
public static Guid? IdOfKey(string? serverKey) =>
serverKey is { Length: > 0 } key && key.StartsWith(IdKeyPrefix, StringComparison.OrdinalIgnoreCase)
&& Guid.TryParseExact(key.AsSpan(IdKeyPrefix.Length), "N", out var id) && id != Guid.Empty
? id
: null;
/// <summary>The key of a server known by its announced id.</summary>
public static string IdKey(Guid serverId)
{
if (serverId == Guid.Empty) throw new ArgumentException("A server id is never empty.", nameof(serverId));
return IdKeyPrefix + serverId.ToString("N");
}
/// <summary>
/// A name a server home's folder can have: 32 lower-case hex digits (an id) or <c>addr-</c> with 16 lower-case hex
/// digits. Anything else under <see cref="Servers"/> is not a home (left alone).
/// </summary>
public static bool IsServerFolder(string? name) => name is { Length: > 0 } && (IdOfFolder(name) is not null || IsAddressFolder(name));
/// <summary>The server id a folder named by one stands for; null for an address folder or another name.</summary>
public static Guid? IdOfFolder(string? name) =>
name is { Length: 32 } && IsLowerHex(name) && Guid.TryParseExact(name, "N", out var id) && id != Guid.Empty ? id : null;
/// <summary>A folder of a server known by its address only (<c>addr-</c> and 16 lower-case hex digits).</summary>
public static bool IsAddressFolder(string? name) =>
name is { Length: > 0 } && name.Length == AddressPrefix.Length + HashLength && name.StartsWith(AddressPrefix, StringComparison.Ordinal)
&& IsLowerHex(name.AsSpan(AddressPrefix.Length));
/// <summary>The folder of this PC's home under <paramref name="root"/> (a workspace or a cache folder).</summary>
public static string LocalPath(string root)
{
ArgumentException.ThrowIfNullOrWhiteSpace(root);
return Path.Combine(root, Local);
}
/// <summary>The folder of the home of <paramref name="serverKey"/> under <paramref name="root"/> (a workspace or a cache folder).</summary>
public static string ServerPath(string root, string serverKey)
{
ArgumentException.ThrowIfNullOrWhiteSpace(root);
return Path.Combine(root, Servers, ServerFolder(serverKey));
}
/// <summary>
/// Where the originals a server's sequences download go by default (owner review 5, Q1): an archive of their own beside
/// this PC's, <c>&lt;parent of the archive&gt;\&lt;archive folder name&gt; - &lt;server name&gt;</c>, for example
/// <c>D:\ChronosArchive - Studio NAS</c>. The server's name is made safe as a folder name (<see cref="SafeName"/>); a
/// folder <paramref name="taken"/> says is taken gets " (2)", " (3)"… With no archive of this PC's,
/// <paramref name="fallbackArchiveRoot"/> (where a first archive would go) stands for it.
/// </summary>
/// <param name="localArchiveRoot">The root of this PC's archive; null when there is none.</param>
/// <param name="serverName">The server's name as its <c>server/info</c> gives it.</param>
/// <param name="fallbackArchiveRoot">Where this PC's first archive would go (the desktop's default archive folder).</param>
/// <param name="taken">Whether a folder is taken (it exists, or another archive uses it); null takes an existing folder or file.</param>
public static string OriginalsArchiveRoot(string? localArchiveRoot, string serverName, string fallbackArchiveRoot, Func<string, bool>? taken = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(fallbackArchiveRoot);
var archive = Path.TrimEndingDirectorySeparator(Path.GetFullPath(string.IsNullOrWhiteSpace(localArchiveRoot) ? fallbackArchiveRoot : localArchiveRoot));
var parent = Path.GetDirectoryName(archive) ?? archive;
var name = Path.GetFileName(archive);
if (string.IsNullOrEmpty(name)) name = SafeName(Path.GetFileName(Path.TrimEndingDirectorySeparator(fallbackArchiveRoot)));
var stem = name + " - " + SafeName(serverName);
taken ??= path => Directory.Exists(path) || File.Exists(path);
for (var n = 1; ; n++)
{
var candidate = Path.Combine(parent, n == 1 ? stem : stem + " (" + n.ToString(CultureInfo.InvariantCulture) + ")");
if (!taken(candidate)) return candidate;
}
}
/// <summary>Characters no folder name may hold on Windows (and so on any PC a folder may be copied to).</summary>
private static readonly char[] Unsafe = ['<', '>', ':', '"', '/', '\\', '|', '?', '*'];
private static readonly string[] Reserved =
[
"CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5",
"LPT6", "LPT7", "LPT8", "LPT9",
];
/// <summary>The longest folder name <see cref="SafeName"/> gives.</summary>
public const int MaxNameLength = 60;
/// <summary>
/// <paramref name="name"/> as a folder name every Windows file system takes: characters it refuses and control characters
/// become spaces, runs of spaces one, leading and trailing spaces and dots go, a device name (CON, NUL, COM1…) gets an
/// underscore, and it is cut to <see cref="MaxNameLength"/>. "Server" when nothing is left.
/// </summary>
public static string SafeName(string? name)
{
var text = new StringBuilder(name?.Length ?? 0);
foreach (var c in name ?? string.Empty)
{
var bad = char.IsControl(c) || Array.IndexOf(Unsafe, c) >= 0;
var space = bad || char.IsWhiteSpace(c);
if (space)
{
if (text.Length > 0 && text[^1] != ' ') text.Append(' ');
continue;
}
text.Append(c);
}
var safe = text.ToString().Trim(' ', '.');
if (safe.Length > MaxNameLength) safe = safe[..MaxNameLength].TrimEnd(' ', '.');
if (safe.Length == 0) return "Server";
var stem = safe.Split('.')[0];
return Reserved.Contains(stem, StringComparer.OrdinalIgnoreCase) ? safe + "_" : safe;
}
private static bool IsLowerHex(ReadOnlySpan<char> text)
{
foreach (var c in text)
{
if (c is not ((>= '0' and <= '9') or (>= 'a' and <= 'f'))) return false;
}
return true;
}
}
+6
View File
@@ -393,6 +393,12 @@ public sealed record Job
/// <summary>The schedule that queued this job; null for jobs queued by a user or by other jobs (owner review 2, R10).</summary>
public Guid? ScheduleId { get; init; }
/// <summary>
/// What the job did when its progress was last saved (step, item, photo x of y, part n of m); null when its handler
/// reports none or the job never ran. Kept when the job stops, so a paused or failed one tells where it stopped.
/// </summary>
public JobDetail? Detail { get; init; }
}
/// <summary>
+79
View File
@@ -0,0 +1,79 @@
namespace Chronos.Core.Model;
/// <summary>
/// What a running job does now (<see cref="JobDetail.Step"/>). Values are appended only, never reordered or renamed: they
/// are stored and sent by their kebab-case name (<c>copy-photo</c>), and a name a build does not know reads as
/// <see cref="None"/>. Each client words a step in its own language; a handler never sends progress text.
/// </summary>
public enum JobStep
{
None,
List,
Check,
Index,
Verify,
Thumbs,
Proxies,
Analyse,
Convert,
Replace,
Reorganize,
CopyPhoto,
CopyProxy,
CopyOriginal,
CopyVideo,
Encode,
Upload,
Download,
Erase,
Backup,
Cleanup,
Maintenance,
FollowUps,
Process,
}
/// <summary>
/// What a job counts its parts in (<see cref="JobDetail.Parts"/>: sequence 12 of 340). Appended only and stored by name,
/// as <see cref="JobStep"/>.
/// </summary>
public enum JobPartUnit
{
None,
Sequence,
Folder,
Render,
Entry,
Step,
}
/// <summary>
/// The detail of a running job's progress beside its overall done and total, which alone drive the bar, the rate and the
/// time left: the step, the item it works on, how far it is inside that item (photo x of y) and which part of the job that
/// item is (sequence n of m). Data, never wording: clients localize the step and the unit.
/// </summary>
/// <param name="Step">What the job does now.</param>
/// <param name="Item">
/// The sequence title, folder, file name, or the key of a sub-step (clean-up, maintenance) it works on; null for none. Cut
/// to <see cref="MaxItemLength"/> characters.
/// </param>
/// <param name="ItemDone">Photos (frames, files) done inside the item; 0 of 0 when not counted.</param>
/// <param name="ItemTotal">Photos (frames, files) of the item; 0 when not counted.</param>
/// <param name="Part">The 1-based part of <paramref name="Parts"/> the item is; 0 of 0 for a job of one part.</param>
/// <param name="Parts">The parts of the job, counted in <paramref name="PartUnit"/>.</param>
/// <param name="PartUnit">What a part is.</param>
public sealed record JobDetail(JobStep Step, string? Item = null, long ItemDone = 0, long ItemTotal = 0, int Part = 0, int Parts = 0,
JobPartUnit PartUnit = JobPartUnit.None)
{
/// <summary>The longest <see cref="Item"/> kept; a longer one is cut (never inside a surrogate pair).</summary>
public const int MaxItemLength = 160;
public string? Item { get; init => field = Cut(value); } = Cut(Item);
private static string? Cut(string? item)
{
if (item is not { Length: > MaxItemLength }) return item;
var length = char.IsHighSurrogate(item[MaxItemLength - 1]) ? MaxItemLength - 1 : MaxItemLength;
return item[..length];
}
}
+4 -1
View File
@@ -23,7 +23,10 @@ public sealed record BundleSequence(Guid Id, string Folder, string? Title, int F
/// <summary>
/// Where a workspace project's versions live (owner review 2, R8): this PC's archive (<see cref="ArchiveKind"/>, with the
/// archive's id) or a server (<see cref="ServerKind"/>, with its address), and the sequence there.
/// archive's id) or a server (<see cref="ServerKind"/>, with its key), and the sequence there. A server's key is its id key
/// (<c>id:&lt;N&gt;</c>, <see cref="IO.HomeFolders.IdKey"/>) once the server announced its stable id (owner review 5, #66),
/// else the address it was reached at (<c>https://nas.local:8443</c>, the 1.0 key, which an id-keyed server keeps as an
/// alias); the format does not change.
/// </summary>
public sealed record BundleHome(string Kind, Guid SequenceId, Guid? ArchiveId = null, string? Server = null)
{
+51
View File
@@ -0,0 +1,51 @@
using System.Reflection;
namespace Chronos.Core.Updates;
/// <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&amp;pre-release=false&amp;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;
}
}
+154
View File
@@ -0,0 +1,154 @@
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
namespace Chronos.Core.Updates;
/// <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/&lt;tag&gt;</c>, <c>/releases/download/&lt;tag&gt;/&lt;name&gt;</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));
}
+251
View File
@@ -0,0 +1,251 @@
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.Core.Updates;
/// <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));
}
}