refactor: share the update check; owner review 5 request

Move UpdateCheck, UpdateDownload and ProductLinks to Chronos.Core/Updates and
UpdateFlow to Chronos.Ui/Updates, so the Uploader can reuse the update check
(#64) and the check and download tests run on Linux in Core.Tests. No
behaviour change: only namespaces and usings moved. Record owner review 5
(request, interpretation R1-R5, answers Q1-Q3, the v1.1.0 phase).

Refs #64

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-15 12:29:46 +01:00
1 parent 988068ee8e
commit 58ed737310
11 files changed
+53 -12

No files matched your search

+2
View File
@@ -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;
-154
View File
@@ -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/&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
@@ -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));
}
}
-181
View File
@@ -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();
}
}
+1 -1
View File
@@ -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;
@@ -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;
@@ -16,6 +15,7 @@ using Chronos.Core.Export;
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;
@@ -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&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;
}
}