using System.IO; using System.Net.Http; using Chronos.Core.Diagnostics; using Chronos.Core.Updates; using Chronos.Ui.Mvvm; namespace Chronos.Ui.Updates; /// Where the update notice stands. public enum UpdateState { Unknown, Checking, UpToDate, Available, Failed, Downloading, Downloaded, DownloadFailed, NotVerified, } /// What needs from the application: the running version, the mode, the network and the shell. public sealed record UpdateHost( Version Running, bool IsCapture, bool IsPortable, Func> CheckAsync, Func?, CancellationToken, Task> DownloadAsync, Action OpenUrl, Action Reveal) { /// The running build is a pre-release ("0.1.0-rc.1"): the final release of the same version is newer. public bool RunningIsPrerelease { get; init; } } /// /// The update notice of Settings › Updates (BRIEF §18): checks the latest release, downloads and verifies the /// package that upgrades this copy (: 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 SHA256SUMS 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. /// 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); } /// Raised after every change of state, release, progress or downloaded file. public event Action? Changed; public UpdateState State { get; private set; } = UpdateState.Unknown; /// The newer release, or null when there is none (or no check has succeeded yet). public ReleaseInfo? Release { get; private set; } /// Fraction of the package downloaded so far. public double Downloaded { get; private set; } /// The verified package; null until a download succeeded. public string? PackagePath { get; private set; } public bool IsPortable => _host.IsPortable; public AsyncRelayCommand Check { get; } public AsyncRelayCommand Download { get; } /// Download is offered: a newer release exists and no verified package is waiting (a failed download can be retried). public bool IsDownloadOffered => Release is not null && State is UpdateState.Available or UpdateState.DownloadFailed or UpdateState.NotVerified; /// The package Download fetches; null when Download opens the release page instead. public ReleaseAsset? Package => Release is { } release && UpdateDownload.CanDownload(release, _host.IsPortable) ? UpdateDownload.Package(release, _host.IsPortable) : null; /// Stops a download in progress; its partial file is kept and the next Download resumes it. public void CancelDownload() => Download.Cancel(); /// The start-up check (BRIEF §18): only when the user left it on and never in a capture run. public Task CheckOnStartAsync(bool enabled) => enabled ? CheckAsync(CancellationToken.None) : Task.FromResult(null); /// Asks for the latest release and returns it when it is newer than the running version. public async Task 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; } /// Sets a check result without the network (capture, tests). A package already verified for the same release stays offered. 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(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(); } }