fix(app): resumable, cancellable update download; portable copies get the portable zip

- UpdateFlow owns the update notice (check, download, cancel) as a plain class;
  AboutViewModel only maps it to text and commands.
- A portable copy downloads and verifies Titano-win-x64-portable-<v>.zip instead
  of the setup; a release without the package or SHA256SUMS opens its page.
- The download fails after 60 s without data instead of after 30 minutes,
  keeps its .part file and resumes it with a range request; Cancel stops it.
- Older release folders under %TEMP%\Titano\updates are removed after a
  verified download; an unexpected exception never leaves "Downloading".
- Tooltips show the package size; stale machine translations of the three
  rewritten tooltips are removed so they fall back to English.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-03 10:00:54 +00:00
1 parent aac2539276
commit ffa05d9f69
36 files changed
+828 -298

No files matched your search

+133 -47
View File
@@ -1,5 +1,7 @@
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;
@@ -10,31 +12,47 @@ namespace Titano.App.About;
public sealed class UpdateVerificationException(string message) : Exception(message);
/// <summary>
/// "Download" of the update notice (BRIEF §18, P1): fetches the desktop setup of the latest release 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 Titano may perform, so callers show the verified file in
/// Explorer and the user runs it.
/// "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 Titano 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 desktop setup ("Titano-Setup-1.2.3.exe"), not the Uploader's.</summary>
public static ReleaseAsset? Installer(ReleaseInfo release) =>
release.Assets.FirstOrDefault(a => a.Name.StartsWith("Titano-Setup-", StringComparison.OrdinalIgnoreCase)
&& a.Name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)
&& a.Name == Path.GetFileName(a.Name));
/// <summary>
/// The file that upgrades this copy: the desktop setup ("Titano-Setup-1.2.3.exe", not the Uploader's) or, for a
/// portable copy, the portable zip ("Titano-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 ? ("Titano-win-x64-portable-", ".zip") : ("Titano-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 a setup and <c>SHA256SUMS</c>; otherwise only its page can be opened.</summary>
public static bool CanDownload(ReleaseInfo release) => Installer(release) is not null && Checksums(release) is not null;
/// <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%\Titano\updates\&lt;tag&gt;</c> under <paramref name="tempRoot"/>.</summary>
public static string Folder(string tempRoot, ReleaseInfo release) =>
Path.Combine(tempRoot, "Titano", "updates", string.Concat(release.Tag.Select(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '-' ? c : '_')));
/// <summary><c>%TEMP%\Titano\updates</c>: one folder per release below it, all owned by Titano.</summary>
public static string Root(string tempPath) => Path.Combine(tempPath, "Titano", "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
@@ -55,80 +73,134 @@ public static class UpdateDownload
}
/// <summary>
/// Downloads the setup of <paramref name="release"/> into <paramref name="folder"/>, verifies it against
/// <c>SHA256SUMS</c> and returns its path. A verified copy already there is reused; a partial or mismatching
/// download is deleted.
/// 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>
public static async Task<string> DownloadAsync(HttpClient http, ReleaseInfo release, string folder, string userAgentVersion, IProgress<double>? progress,
CancellationToken ct)
/// <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 installer = Installer(release) ?? throw new UpdateVerificationException($"Release {release.Tag} has no Titano setup.");
var package = Package(release, portable)
?? throw new UpdateVerificationException($"Release {release.Tag} has no {(portable ? "portable zip" : "Titano setup")}.");
var checksums = Checksums(release) ?? throw new UpdateVerificationException($"Release {release.Tag} has no {ChecksumsName}.");
var expected = ParseChecksums(await ReadChecksumsAsync(http, checksums, userAgentVersion, ct).ConfigureAwait(false)).GetValueOrDefault(installer.Name)
?? throw new UpdateVerificationException($"{ChecksumsName} of {release.Tag} has no line for {installer.Name}.");
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, installer.Name);
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 + ".part";
try
{
var actual = await DownloadToAsync(http, installer, part, userAgentVersion, progress, ct).ConfigureAwait(false);
if (actual != expected) throw new UpdateVerificationException($"{installer.Name}: SHA-256 {actual} does not match {expected} in {ChecksumsName}.");
File.Move(part, target, overwrite: true);
return target;
}
finally
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, ct).ConfigureAwait(false);
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"/>, hashing as it goes; refuses more bytes than the release announced.</summary>
/// <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,
CancellationToken ct)
CancellationTokenSource idle, TimeSpan idleTimeout)
{
using var response = await SendAsync(http, asset, userAgentVersion, ct).ConfigureAwait(false);
var length = asset.Size > 0 ? asset.Size : response.Content.Headers.ContentLength ?? -1;
await using var input = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false);
await using var output = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 16, FileOptions.Asynchronous);
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) throw new UpdateVerificationException($"{asset.Name} is larger than the release announced.");
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 (length > 0) progress?.Report(Math.Min(1.0, (double)total / length));
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, CancellationToken ct)
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("Titano", 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
{
@@ -142,18 +214,32 @@ public static class UpdateDownload
}
}
/// <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 (IOException)
{
// A scanner may hold the partial file; %TEMP% cleanup removes it later.
}
catch (UnauthorizedAccessException)
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// A scanner may hold the file; the next download overwrites it.
}
}
+177
View File
@@ -0,0 +1,177 @@
using System.IO;
using System.Net.Http;
using Titano.Core.Diagnostics;
using Titano.Ui.Mvvm;
namespace Titano.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 update notice of About and 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 Titano 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) ? 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();
}
}
+5 -4
View File
@@ -39,8 +39,8 @@ public sealed class AppServices : IAsyncDisposable
private static readonly Lazy<HttpClient> Http = new(() => new HttpClient { Timeout = TimeSpan.FromSeconds(20) });
/// <summary>Setups are large: the download is bounded by the caller's cancellation, not a short timeout.</summary>
private static readonly Lazy<HttpClient> DownloadHttp = new(() => new HttpClient { Timeout = TimeSpan.FromMinutes(30) });
/// <summary>Update packages are large: their download fails when it stalls (<see cref="UpdateDownload.IdleTimeout"/>), never after a fixed total time.</summary>
private static readonly Lazy<HttpClient> DownloadHttp = new(() => new HttpClient { Timeout = Timeout.InfiniteTimeSpan });
private readonly CancellationTokenSource _stopping = new();
private readonly Dictionary<Guid, Guid> _scans = [];
private Task _polling = Task.CompletedTask;
@@ -59,7 +59,8 @@ public sealed class AppServices : IAsyncDisposable
Encoders = new MediaFoundationInventory();
CheckForUpdateAsync = ct => UpdateCheck.FetchAsync(Http.Value, ProductLinks.LatestReleaseApi, VersionText, ct);
DownloadUpdateAsync = (release, progress, ct) =>
UpdateDownload.DownloadAsync(DownloadHttp.Value, release, UpdateDownload.Folder(Path.GetTempPath(), release), VersionText, progress, ct);
UpdateDownload.DownloadAsync(DownloadHttp.Value, release, environment.IsPortable, UpdateDownload.Root(Path.GetTempPath()), VersionText, progress,
UpdateDownload.IdleTimeout, ct);
}
public AppEnvironment Environment { get; }
@@ -94,7 +95,7 @@ public sealed class AppServices : IAsyncDisposable
/// <summary>Latest public release (GitHub Releases API of the releases repository, BRIEF §18).</summary>
public Func<CancellationToken, Task<ReleaseInfo?>> CheckForUpdateAsync { get; set; }
/// <summary>Downloads and verifies the setup of a release (BRIEF §18 P1) and returns its path.</summary>
/// <summary>Downloads and verifies the package of a release for this copy (setup, or portable zip; BRIEF §18 P1) and returns its path.</summary>
public Func<ReleaseInfo, IProgress<double>?, CancellationToken, Task<string>> DownloadUpdateAsync { get; set; }
/// <summary>The index; null until <see cref="OpenAsync"/> succeeded.</summary>
+7 -4
View File
@@ -55,11 +55,14 @@
<ui:StatusGlyph Kind="{Binding UpdateKind}" Text="{Binding UpdateText}" FontSize="13" VerticalAlignment="Center"
Visibility="{Binding HasUpdateText, Converter={StaticResource BoolToVisibility}}" />
<Button Style="{StaticResource Button.Link}" FontSize="13" Margin="12,0,0,0" VerticalAlignment="Center" Content="{l:Loc About.Update.Download}"
Command="{Binding DownloadCommand}" ToolTip="{l:Loc Tooltips.About.Download}"
Command="{Binding DownloadCommand}" ToolTip="{Binding DownloadToolTip}"
Visibility="{Binding IsUpdateAvailable, Converter={StaticResource BoolToVisibility}}" />
<Button Style="{StaticResource Button.Link}" FontSize="13" Margin="12,0,0,0" VerticalAlignment="Center" Content="{l:Loc About.Update.ShowSetup}"
Command="{Binding ShowSetupCommand}" ToolTip="{l:Loc Tooltips.About.ShowSetup}"
Visibility="{Binding IsSetupReady, Converter={StaticResource BoolToVisibility}}" />
<Button Style="{StaticResource Button.Link}" FontSize="13" Margin="12,0,0,0" VerticalAlignment="Center" Content="{l:Loc About.Update.Cancel}"
Command="{Binding CancelDownloadCommand}" ToolTip="{l:Loc Tooltips.About.CancelDownload}"
Visibility="{Binding IsDownloading, Converter={StaticResource BoolToVisibility}}" />
<Button Style="{StaticResource Button.Link}" FontSize="13" Margin="12,0,0,0" VerticalAlignment="Center" Content="{l:Loc About.Update.ShowFile}"
Command="{Binding ShowPackageCommand}" ToolTip="{Binding ShowPackageToolTip}"
Visibility="{Binding IsPackageReady, Converter={StaticResource BoolToVisibility}}" />
</StackPanel>
</Grid>
+43 -113
View File
@@ -1,12 +1,10 @@
using System.IO;
using System.Net.Http;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Input;
using Titano.App.About;
using Titano.App.Infrastructure;
using Titano.App.Shell;
using Titano.Core.Diagnostics;
using Titano.Core.Localization;
using Titano.Ui.Controls;
using Titano.Ui.Mvvm;
@@ -15,27 +13,26 @@ namespace Titano.App.Sections;
/// <summary>
/// About (BRIEF §12.9): version and build, licence link, third-party notice (none), translation notice,
/// diagnostics bundle and the update check against the public releases repository (BRIEF §18). Download fetches the
/// setup and verifies it against the release's SHA256SUMS, then shows it in Explorer: BRIEF §8.6 does not allow Titano
/// to start an installer, so the user runs it.
/// diagnostics bundle and the update notice of <see cref="UpdateFlow"/> (BRIEF §18), which Settings › Updates shows too.
/// </summary>
public sealed class AboutViewModel : SectionViewModel
{
private ReleaseInfo? _release;
private UpdateState _state = UpdateState.Unknown;
private double _downloaded;
private string? _setupPath;
private readonly UpdateFlow _update;
public AboutViewModel(ShellViewModel shell)
: base(SectionKey.About, "Icon.About")
{
Shell = shell;
CheckCommand = new AsyncRelayCommand(() => CheckAsync(notify: false), () => _state is not (UpdateState.Checking or UpdateState.Downloading));
DownloadCommand = new AsyncRelayCommand(DownloadAsync, () => _release is not null && _state != UpdateState.Downloading);
ShowSetupCommand = new RelayCommand(() =>
var environment = shell.Services.Environment;
_update = new UpdateFlow(new UpdateHost(UpdateCheck.RunningVersion(Version), environment.IsCapture, environment.IsPortable,
ct => Shell.Services.CheckForUpdateAsync(ct), (release, progress, ct) => Shell.Services.DownloadUpdateAsync(release, progress, ct),
ShellActions.OpenUrl, ShellActions.Reveal));
_update.Changed += RaiseUpdate;
ShowPackageCommand = new RelayCommand(() =>
{
if (_setupPath is { } path) ShellActions.Reveal(path);
}, () => _setupPath is not null);
if (_update.PackagePath is { } path) ShellActions.Reveal(path);
}, () => _update.PackagePath is not null);
CancelDownloadCommand = new RelayCommand(_update.CancelDownload, () => IsDownloading);
OpenReleasesCommand = new RelayCommand(() => ShellActions.OpenUrl(ProductLinks.Releases));
OpenLicenceCommand = new RelayCommand(() => ShellActions.OpenUrl(ProductLinks.Licence));
ReviewTranslationCommand = new RelayCommand(() => ShellActions.OpenUrl(ProductLinks.Issues));
@@ -43,19 +40,6 @@ public sealed class AboutViewModel : SectionViewModel
DiagnosticsCommand = new AsyncRelayCommand(DiagnosticsAsync);
}
private enum UpdateState
{
Unknown,
Checking,
UpToDate,
Available,
Failed,
Downloading,
Downloaded,
DownloadFailed,
NotVerified,
}
public ShellViewModel Shell { get; }
public string Version => AppServices.VersionText;
@@ -73,9 +57,10 @@ public sealed class AboutViewModel : SectionViewModel
/// <summary>Every language but English is machine-translated and open to review (BRIEF §16).</summary>
public bool IsTranslated => !Loc.Culture.TwoLetterISOLanguageName.Equals("en", StringComparison.OrdinalIgnoreCase);
public ICommand CheckCommand { get; }
public ICommand DownloadCommand { get; }
public ICommand ShowSetupCommand { get; }
public ICommand CheckCommand => _update.Check;
public ICommand DownloadCommand => _update.Download;
public ICommand ShowPackageCommand { get; }
public ICommand CancelDownloadCommand { get; }
public ICommand OpenReleasesCommand { get; }
public ICommand OpenLicenceCommand { get; }
public ICommand ReviewTranslationCommand { get; }
@@ -83,20 +68,20 @@ public sealed class AboutViewModel : SectionViewModel
public ICommand DiagnosticsCommand { get; }
/// <summary>"Up to date", "Titano 0.2.0 available", …; null before the first check.</summary>
public string? UpdateText => _state switch
public string? UpdateText => _update.State switch
{
UpdateState.Checking => Loc.L("About.Update.Checking"),
UpdateState.UpToDate => Loc.L("About.Update.Current"),
UpdateState.Available when _release is { } r => Loc.L("About.Update.Available", UpdateCheck.Display(r.Version)),
UpdateState.Available when _update.Release is { } r => Loc.L("About.Update.Available", UpdateCheck.Display(r.Version)),
UpdateState.Failed => Loc.L("About.Update.Failed"),
UpdateState.Downloading => Loc.L("About.Update.Downloading", _downloaded),
UpdateState.Downloaded when _release is { } r => Loc.L("About.Update.Ready", UpdateCheck.Display(r.Version)),
UpdateState.Downloading => Loc.L("About.Update.Downloading", _update.Downloaded),
UpdateState.Downloaded when _update.Release is { } r => Loc.L("About.Update.Ready", UpdateCheck.Display(r.Version)),
UpdateState.DownloadFailed => Loc.L("About.Update.DownloadFailed"),
UpdateState.NotVerified => Loc.L("About.Update.NotVerified"),
_ => null,
};
public StatusKind UpdateKind => _state switch
public StatusKind UpdateKind => _update.State switch
{
UpdateState.Checking or UpdateState.Downloading => StatusKind.Running,
UpdateState.UpToDate or UpdateState.Downloaded => StatusKind.Done,
@@ -106,89 +91,32 @@ public sealed class AboutViewModel : SectionViewModel
public bool HasUpdateText => UpdateText is not null;
/// <summary>Download is offered: a newer release exists and no verified setup is waiting (a failed download can be retried).</summary>
public bool IsUpdateAvailable => _state is UpdateState.Available or UpdateState.DownloadFailed or UpdateState.NotVerified;
/// <summary>Download is offered: a newer release exists and no verified package is waiting (a failed download can be retried).</summary>
public bool IsUpdateAvailable => _update.IsDownloadOffered;
/// <summary>The verified setup is in the temporary folder.</summary>
public bool IsSetupReady => _state == UpdateState.Downloaded;
/// <summary>The verified setup or portable zip is in the temporary folder.</summary>
public bool IsPackageReady => _update.State == UpdateState.Downloaded;
/// <summary>Starts the update check on start when allowed (opt-out, BRIEF §18).</summary>
public void Attach()
{
if (Shell.Services.Settings.CheckForUpdates && !Shell.Services.Environment.IsCapture) _ = CheckAsync(notify: true);
}
public bool IsDownloading => _update.State == UpdateState.Downloading;
/// <summary>What Download does here: fetch and verify the setup or the portable zip (with its size), or open the release page.</summary>
public string DownloadToolTip => _update.Package is { } package
? Loc.L(_update.IsPortable ? "Tooltips.About.DownloadPortable" : "Tooltips.About.Download", Formatting.Bytes(package.Size))
: Loc.L("Tooltips.About.DownloadPage");
public string ShowPackageToolTip => Loc.L(_update.IsPortable ? "Tooltips.About.ShowPortable" : "Tooltips.About.ShowSetup");
/// <summary>Starts the update check on start when allowed (opt-out, BRIEF §18); never in a capture run.</summary>
public void Attach() => _ = NotifyAsync();
/// <summary>Sets a result without the network (capture, tests).</summary>
internal void SetResult(ReleaseInfo? release, bool failed = false)
{
_release = release is not null && UpdateCheck.IsNewer(release, UpdateCheck.RunningVersion(Version)) ? release : null;
_state = failed ? UpdateState.Failed : _release is null ? UpdateState.UpToDate : UpdateState.Available;
_setupPath = null;
RaiseUpdate();
}
internal void SetResult(ReleaseInfo? release, bool failed = false) => _update.SetResult(release, failed);
private async Task CheckAsync(bool notify)
private async Task NotifyAsync()
{
_state = UpdateState.Checking;
RaiseUpdate();
try
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var release = await Shell.Services.CheckForUpdateAsync(timeout.Token);
SetResult(release);
if (notify && _release is { } newer)
{
Shell.Notify(Loc.L("About.Update.Available", UpdateCheck.Display(newer.Version)), actionText: Loc.L("About.Update.Download"),
actionToolTip: Loc.L("Tooltips.About.Download"), action: () => DownloadCommand.Execute(null));
}
}
catch (Exception ex) when (ex is HttpRequestException or OperationCanceledException or IOException)
{
Log.Info("update", "Update check failed: " + ex.Message);
SetResult(null, failed: true);
}
}
/// <summary>
/// Downloads and verifies the setup, then shows it in Explorer. A release without a setup or SHA256SUMS only opens
/// the release page; a capture run never touches the network.
/// </summary>
private async Task DownloadAsync()
{
if (_release is not { } release || Shell.Services.Environment.IsCapture) return;
if (!UpdateDownload.CanDownload(release))
{
ShellActions.OpenUrl(release.PageUrl);
return;
}
_state = UpdateState.Downloading;
_downloaded = 0;
RaiseUpdate();
var progress = new Progress<double>(fraction =>
{
if (_state != UpdateState.Downloading || fraction - _downloaded < 0.01) return;
_downloaded = fraction;
OnPropertyChanged(nameof(UpdateText));
});
try
{
using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(30));
_setupPath = await Shell.Services.DownloadUpdateAsync(release, progress, timeout.Token);
_state = UpdateState.Downloaded;
Log.Info("update", $"Setup of {release.Tag} downloaded and verified: {_setupPath}");
ShellActions.Reveal(_setupPath);
}
catch (UpdateVerificationException ex)
{
Log.Warning("update", "Update download refused: " + ex.Message);
_state = UpdateState.NotVerified;
}
catch (Exception ex) when (ex is HttpRequestException or OperationCanceledException or IOException or UnauthorizedAccessException)
{
Log.Warning("update", "Update download failed: " + ex.Message);
_state = UpdateState.DownloadFailed;
}
RaiseUpdate();
if (await _update.CheckOnStartAsync(Shell.Services.Settings.CheckForUpdates) is not { } newer) return;
Shell.Notify(Loc.L("About.Update.Available", UpdateCheck.Display(newer.Version)), actionText: Loc.L("About.Update.Download"),
actionToolTip: DownloadToolTip, action: () => DownloadCommand.Execute(null));
}
private async Task DiagnosticsAsync()
@@ -212,7 +140,9 @@ public sealed class AboutViewModel : SectionViewModel
OnPropertyChanged(nameof(UpdateKind));
OnPropertyChanged(nameof(HasUpdateText));
OnPropertyChanged(nameof(IsUpdateAvailable));
OnPropertyChanged(nameof(IsSetupReady));
OnPropertyChanged(nameof(IsPackageReady));
OnPropertyChanged(nameof(IsDownloading));
OnPropertyChanged(nameof(DownloadToolTip));
CommandManager.InvalidateRequerySuggested();
}
}
+6 -3
View File
@@ -291,12 +291,15 @@
<Button Content="{l:Loc About.Update.Check}" Command="{Binding Shell.About.CheckCommand}" ToolTip="{l:Loc Tooltips.About.Check}" />
<ui:StatusGlyph Kind="{Binding Shell.About.UpdateKind}" Text="{Binding Shell.About.UpdateText}" FontSize="13" VerticalAlignment="Center" Margin="12,0,0,0"
Visibility="{Binding Shell.About.HasUpdateText, Converter={StaticResource BoolToVisibility}}" />
<Button Style="{StaticResource Button.Link}" Content="{l:Loc About.Update.Download}" Command="{Binding Shell.About.DownloadCommand}" ToolTip="{l:Loc Tooltips.About.Download}"
<Button Style="{StaticResource Button.Link}" Content="{l:Loc About.Update.Download}" Command="{Binding Shell.About.DownloadCommand}" ToolTip="{Binding Shell.About.DownloadToolTip}"
VerticalAlignment="Center" Margin="12,0,0,0" FontSize="13"
Visibility="{Binding Shell.About.IsUpdateAvailable, Converter={StaticResource BoolToVisibility}}" />
<Button Style="{StaticResource Button.Link}" Content="{l:Loc About.Update.ShowSetup}" Command="{Binding Shell.About.ShowSetupCommand}" ToolTip="{l:Loc Tooltips.About.ShowSetup}"
<Button Style="{StaticResource Button.Link}" Content="{l:Loc About.Update.Cancel}" Command="{Binding Shell.About.CancelDownloadCommand}" ToolTip="{l:Loc Tooltips.About.CancelDownload}"
VerticalAlignment="Center" Margin="12,0,0,0" FontSize="13"
Visibility="{Binding Shell.About.IsSetupReady, Converter={StaticResource BoolToVisibility}}" />
Visibility="{Binding Shell.About.IsDownloading, Converter={StaticResource BoolToVisibility}}" />
<Button Style="{StaticResource Button.Link}" Content="{l:Loc About.Update.ShowFile}" Command="{Binding Shell.About.ShowPackageCommand}" ToolTip="{Binding Shell.About.ShowPackageToolTip}"
VerticalAlignment="Center" Margin="12,0,0,0" FontSize="13"
Visibility="{Binding Shell.About.IsPackageReady, Converter={StaticResource BoolToVisibility}}" />
</WrapPanel>
</HeaderedContentControl>
</StackPanel>