feat(uploader): check for updates and fetch the single setup
The Uploader had no update check, so an Uploader-only install never heard of a new version. Its settings panel gains an Updates row driven by the shared UpdateFlow: Check on start (opt-out, on for 1.0 settings files), Check now, Download (the single Chronos setup, or the portable zip of a portable copy, verified against the release's SHA256SUMS) and Show setup (reveals the verified file in Explorer; the user runs it). The start-up check is skipped when Chronos.exe sits beside the Uploader, because the desktop's own notice covers the same setup; Check now still works there. A newer release found on start is offered in a toast with Download as its action. The capture scene shows the notice with a sample release. Refs #64 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
58ed737310
commit
7181589590
16 files changed
+661
-8
No files matched your search
@@ -82,6 +82,7 @@ public partial class App : Application
|
||||
UpdateTray();
|
||||
UpdateDiscovery();
|
||||
if (command.Paths.Count > 0) _ = _vm.EnqueueAsync(command.Paths);
|
||||
_ = _vm.Updates.CheckOnStartAsync(_environment.HasDesktopBeside);
|
||||
|
||||
if (command.StartInTray && _settings.MinimizeToTray) return;
|
||||
if (command.StartInTray) _window!.WindowState = WindowState.Minimized;
|
||||
@@ -122,7 +123,10 @@ public partial class App : Application
|
||||
var startup = new RunKeyStartupRegistration();
|
||||
startup.Refresh();
|
||||
var dialogs = new UploaderDialogs();
|
||||
_vm = new MainViewModel(new UploaderServices(settings, SaveSettings, _session, _queue, _engine, startup, dialogs, _watch, _memory, environment.LogDirectory));
|
||||
_vm = new MainViewModel(new UploaderServices(settings, SaveSettings, _session, _queue, _engine, startup, dialogs, _watch, _memory, environment.LogDirectory)
|
||||
{
|
||||
Updates = UploaderUpdates.Host(environment.IsPortable),
|
||||
});
|
||||
_window = new Shell.MainWindow(_vm, settings);
|
||||
dialogs.Owner = _window;
|
||||
MainWindow = _window;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.ComponentModel;
|
||||
using System.Globalization;
|
||||
using System.Runtime.CompilerServices;
|
||||
using Chronos.Core.Updates;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Uploader.Infrastructure;
|
||||
using Chronos.Uploader.Server;
|
||||
@@ -19,6 +20,7 @@ public sealed class SampleData
|
||||
{
|
||||
private const int FileCount = 4_812;
|
||||
private const long FileSize = 20_000_000;
|
||||
private const string RunningVersion = "1.0.0";
|
||||
|
||||
/// <summary>The sample's "now" (when the failed file failed): fixed, so the screenshots are the same on any day.</summary>
|
||||
private static readonly DateTime Now = new(2026, 9, 28, 19, 2, 0, DateTimeKind.Utc);
|
||||
@@ -51,7 +53,11 @@ public sealed class SampleData
|
||||
_session.BandwidthLimit = Settings.BandwidthLimit;
|
||||
_vm = new MainViewModel(new UploaderServices(
|
||||
Settings, () => { }, _session, _queue, new SampleEngine(_queue), startup ?? new SampleStartup(), new UploaderDialogs(),
|
||||
new WatchFolderService(memory, _queue.ContainsPath), memory, string.Empty));
|
||||
new WatchFolderService(memory, _queue.ContainsPath), memory, string.Empty)
|
||||
{
|
||||
// A fixed running version, so the update notice reads the same whatever this build's version is.
|
||||
Updates = UploaderUpdates.Offline(RunningVersion),
|
||||
});
|
||||
foreach (var w in _vm.WatchFolders) w.IsAvailable = true;
|
||||
// A disconnected drive: its chip shows the hollow ring and wraps to a second line.
|
||||
_vm.WatchFolders[^1].IsAvailable = false;
|
||||
@@ -79,6 +85,20 @@ public sealed class SampleData
|
||||
_vm.RefreshQueue();
|
||||
}
|
||||
|
||||
/// <summary>The settings panel's update notice: a newer release with its setup and checksums, so Download is offered.</summary>
|
||||
public void ShowUpdate()
|
||||
{
|
||||
const string Base = "https://gitea.example/BalboSoft/Chronos/releases/download/v1.1.0/";
|
||||
_vm!.Updates.SetResult(new ReleaseInfo(new Version(1, 1, 0), "v1.1.0", "https://gitea.example/BalboSoft/Chronos/releases/tag/v1.1.0")
|
||||
{
|
||||
Assets =
|
||||
[
|
||||
new ReleaseAsset("Chronos-Setup-1.1.0.exe", Base + "Chronos-Setup-1.1.0.exe", 92_400_000),
|
||||
new ReleaseAsset(UpdateDownload.ChecksumsName, Base + UpdateDownload.ChecksumsName, 300),
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
private void FillQueue()
|
||||
{
|
||||
var batch = new UploadBatch { Id = Guid.CreateVersion7(), Mode = UploadTargetMode.Sessions };
|
||||
|
||||
@@ -9,9 +9,14 @@ namespace Chronos.Uploader.Infrastructure;
|
||||
/// </summary>
|
||||
public sealed class UploaderEnvironment
|
||||
{
|
||||
private UploaderEnvironment(string dataDirectory)
|
||||
/// <summary>The desktop program's file name; the single setup installs it in the Uploader's own folder.</summary>
|
||||
public const string DesktopExecutable = "Chronos.exe";
|
||||
|
||||
private UploaderEnvironment(string dataDirectory, bool isPortable, bool hasDesktopBeside)
|
||||
{
|
||||
DataDirectory = dataDirectory;
|
||||
IsPortable = isPortable;
|
||||
HasDesktopBeside = hasDesktopBeside;
|
||||
Directory.CreateDirectory(DataDirectory);
|
||||
Directory.CreateDirectory(LogDirectory);
|
||||
}
|
||||
@@ -19,6 +24,15 @@ public sealed class UploaderEnvironment
|
||||
public string DataDirectory { get; }
|
||||
public string LogDirectory => Path.Combine(DataDirectory, "logs");
|
||||
|
||||
/// <summary>A portable copy (<c>portable.txt</c> beside the executable): its update is the portable zip, not the setup.</summary>
|
||||
public bool IsPortable { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Chronos Desktop sits in the same folder: its own update notice covers the same setup, so the Uploader skips its
|
||||
/// start-up check (Check now still works).
|
||||
/// </summary>
|
||||
public bool HasDesktopBeside { get; }
|
||||
|
||||
/// <summary>Settings, DPAPI-protected token and trusted certificate fingerprints.</summary>
|
||||
public string SettingsPath => Path.Combine(DataDirectory, "uploader.json");
|
||||
|
||||
@@ -31,8 +45,12 @@ public sealed class UploaderEnvironment
|
||||
public static UploaderEnvironment Detect()
|
||||
{
|
||||
var exeDir = AppContext.BaseDirectory;
|
||||
if (File.Exists(Path.Combine(exeDir, "portable.txt"))) return new UploaderEnvironment(Path.Combine(exeDir, "data"));
|
||||
var desktop = IsDesktopBeside(exeDir);
|
||||
if (File.Exists(Path.Combine(exeDir, "portable.txt"))) return new UploaderEnvironment(Path.Combine(exeDir, "data"), isPortable: true, desktop);
|
||||
var local = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
|
||||
return new UploaderEnvironment(Path.Combine(local, "Chronos"));
|
||||
return new UploaderEnvironment(Path.Combine(local, "Chronos"), isPortable: false, desktop);
|
||||
}
|
||||
|
||||
/// <summary>True when <see cref="DesktopExecutable"/> is in <paramref name="folder"/>.</summary>
|
||||
public static bool IsDesktopBeside(string folder) => File.Exists(Path.Combine(folder, DesktopExecutable));
|
||||
}
|
||||
@@ -27,6 +27,10 @@ public sealed class UploaderSettings
|
||||
public int BandwidthLimit { get; set; }
|
||||
|
||||
public bool MinimizeToTray { get; set; } = true;
|
||||
|
||||
/// <summary>Look for a newer Chronos release on start (opt-out, BRIEF §18); a 1.0 file without the key keeps it on.</summary>
|
||||
public bool CheckForUpdates { get; set; } = true;
|
||||
|
||||
public bool DeleteAfterUpload { get; set; }
|
||||
public UploadTargetMode Target { get; set; } = UploadTargetMode.Sessions;
|
||||
public Guid? TargetSequenceId { get; set; }
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Reflection;
|
||||
using Chronos.Core.Updates;
|
||||
using Chronos.Ui.Updates;
|
||||
using Chronos.Uploader.Interop;
|
||||
|
||||
namespace Chronos.Uploader.Infrastructure;
|
||||
|
||||
/// <summary>
|
||||
/// The Uploader's side of the shared update notice (BRIEF §18, owner review 5): the same releases feed, the same single
|
||||
/// setup (or the portable zip of a portable copy) and the same <c>%TEMP%\Chronos\updates</c> folder as the desktop.
|
||||
/// </summary>
|
||||
public static class UploaderUpdates
|
||||
{
|
||||
private static readonly Lazy<HttpClient> Http = new(() => new HttpClient { Timeout = TimeSpan.FromSeconds(20) });
|
||||
|
||||
/// <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 });
|
||||
|
||||
/// <summary>The informational version of this build, such as "1.1.0" or "1.1.0-rc.1".</summary>
|
||||
public static string VersionText { get; } =
|
||||
typeof(UploaderUpdates).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "0.0.0";
|
||||
|
||||
/// <summary>The live host: the public releases repository, the shell's browser and Explorer.</summary>
|
||||
public static UpdateHost Host(bool portable) =>
|
||||
Host(Http.Value, DownloadHttp.Value, ProductLinks.Repository, VersionText, portable, UpdateDownload.Root(Path.GetTempPath()), ShellActions.OpenUrl,
|
||||
ShellActions.Reveal);
|
||||
|
||||
/// <summary>A host over the given clients and releases repository ("https://host/owner/name"); tests pass a fake transport.</summary>
|
||||
public static UpdateHost Host(HttpClient http, HttpClient downloadHttp, string repository, string versionText, bool portable, string downloadRoot,
|
||||
Action<string> openUrl, Action<string> reveal) =>
|
||||
new(UpdateCheck.RunningVersion(versionText), IsCapture: false, portable,
|
||||
ct => UpdateCheck.FetchAsync(http, ProductLinks.StableReleasesApiOf(repository), repository, versionText, ct),
|
||||
(release, progress, ct) => UpdateDownload.DownloadAsync(downloadHttp, release, portable, downloadRoot, versionText, progress, UpdateDownload.IdleTimeout, ct),
|
||||
openUrl, reveal)
|
||||
{
|
||||
RunningIsPrerelease = UpdateCheck.IsPrerelease(versionText),
|
||||
};
|
||||
|
||||
/// <summary>A host that never touches the network or the shell (<c>--capture</c>, design time).</summary>
|
||||
public static UpdateHost Offline(string versionText) =>
|
||||
new(UpdateCheck.RunningVersion(versionText), IsCapture: true, IsPortable: false,
|
||||
_ => Task.FromResult<ReleaseInfo?>(null), (_, _, _) => Task.FromException<string>(new InvalidOperationException("No download in a capture run.")),
|
||||
_ => { }, _ => { });
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using Chronos.Core.Diagnostics;
|
||||
|
||||
namespace Chronos.Uploader.Interop;
|
||||
|
||||
/// <summary>
|
||||
/// The two shell actions of the update notice (BRIEF §8.6): open an https link in the browser and show a file selected
|
||||
/// in Explorer. Nothing else is started; the verified setup is run by the user.
|
||||
/// </summary>
|
||||
public static partial class ShellActions
|
||||
{
|
||||
/// <summary>Opens an absolute https link with the shell's "open" verb; anything else is ignored.</summary>
|
||||
public static void OpenUrl(string url)
|
||||
{
|
||||
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttps) return;
|
||||
try
|
||||
{
|
||||
using var _ = Process.Start(new ProcessStartInfo(uri.AbsoluteUri) { UseShellExecute = true, Verb = "open" });
|
||||
}
|
||||
catch (Exception ex) when (ex is Win32Exception or InvalidOperationException)
|
||||
{
|
||||
Log.Warning("shell", $"The shell could not open {uri.AbsoluteUri}", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Shows the file selected in its Explorer folder (SHOpenFolderAndSelectItems); a missing file is ignored.</summary>
|
||||
public static void Reveal(string path)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path) || !File.Exists(path)) return;
|
||||
var full = Path.GetFullPath(path);
|
||||
if (SHParseDisplayName(full, 0, out var itemList, 0, out _) < 0)
|
||||
{
|
||||
Log.Warning("shell", $"Explorer could not show {full}");
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
// With no child items the absolute ID list names the item to select; Explorer opens its parent.
|
||||
if (SHOpenFolderAndSelectItems(itemList, 0, 0, 0) < 0) Log.Warning("shell", $"Explorer could not show {full}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Marshal.FreeCoTaskMem(itemList);
|
||||
}
|
||||
}
|
||||
|
||||
[LibraryImport("shell32.dll", StringMarshalling = StringMarshalling.Utf16)]
|
||||
private static partial int SHParseDisplayName(string name, nint bindContext, out nint itemIdList, uint attributesIn, out uint attributesOut);
|
||||
|
||||
[LibraryImport("shell32.dll")]
|
||||
private static partial int SHOpenFolderAndSelectItems(nint folder, uint count, nint items, uint flags);
|
||||
}
|
||||
@@ -7,8 +7,10 @@ using System.Windows.Input;
|
||||
using System.Windows.Threading;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Updates;
|
||||
using Chronos.Ui.Controls;
|
||||
using Chronos.Ui.Mvvm;
|
||||
using Chronos.Ui.Updates;
|
||||
using Chronos.Uploader.Infrastructure;
|
||||
using Chronos.Uploader.Server;
|
||||
using Chronos.Uploader.Sources;
|
||||
@@ -32,7 +34,11 @@ public sealed record UploaderServices(
|
||||
IUploaderDialogs Dialogs,
|
||||
WatchFolderService Watch,
|
||||
ProcessedFileMemory Memory,
|
||||
string LogDirectory);
|
||||
string LogDirectory)
|
||||
{
|
||||
/// <summary>The update notice's network and shell; null never touches either (capture, tests).</summary>
|
||||
public UpdateHost? Updates { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>State of the uploader window (BRIEF §15, mockup Uploader.html).</summary>
|
||||
public sealed class MainViewModel : LocalizedViewModel
|
||||
@@ -65,6 +71,8 @@ public sealed class MainViewModel : LocalizedViewModel
|
||||
if (e.PropertyName == nameof(ConnectViewModel.IsSigningIn)) OnPropertyChanged(nameof(IsConnectVisible));
|
||||
};
|
||||
foreach (var w in services.Settings.WatchFolders) WatchFolders.Add(NewWatchFolder(w.Path, w.IntervalSeconds));
|
||||
Updates = new UpdatesViewModel(services.Updates ?? UploaderUpdates.Offline(UploaderUpdates.VersionText), services.Settings, services.SaveSettings);
|
||||
Updates.Found += OnUpdateFound;
|
||||
|
||||
OpenSettingsCommand = new RelayCommand(() => IsSettingsOpen = true);
|
||||
CloseSettingsCommand = new RelayCommand(() => IsSettingsOpen = false);
|
||||
@@ -105,6 +113,9 @@ public sealed class MainViewModel : LocalizedViewModel
|
||||
|
||||
public ConnectViewModel Connect { get; }
|
||||
|
||||
/// <summary>The Updates row of the settings panel.</summary>
|
||||
public UpdatesViewModel Updates { get; }
|
||||
|
||||
/// <summary>In-window notifications; the window forwards them to its <see cref="ToastHost"/>.</summary>
|
||||
public ObservableCollection<Toast> PendingToasts { get; } = [];
|
||||
|
||||
@@ -416,6 +427,8 @@ public sealed class MainViewModel : LocalizedViewModel
|
||||
_s.Session.PropertyChanged -= OnSessionChanged;
|
||||
_s.Session.SessionEnded -= OnSessionEnded;
|
||||
_s.Engine.Drained -= OnDrained;
|
||||
Updates.Found -= OnUpdateFound;
|
||||
Updates.Dispose();
|
||||
base.Dispose();
|
||||
}
|
||||
|
||||
@@ -592,6 +605,11 @@ public sealed class MainViewModel : LocalizedViewModel
|
||||
if (confirmed > 0) UploadsCompleted?.Invoke(confirmed);
|
||||
}
|
||||
|
||||
/// <summary>The start-up check found a newer release: one sentence, and Download as its action.</summary>
|
||||
private void OnUpdateFound(ReleaseInfo release) =>
|
||||
ShowToast(Loc.L("Uploader.Updates.Available", UpdateCheck.Display(release.Version)), Loc.L("Uploader.Updates.Download"),
|
||||
Updates.DownloadToolTip, Updates.DownloadCommand);
|
||||
|
||||
/// <summary>One sentence and at most one action; <paramref name="isError"/> marks a failure or refusal, which screen readers say at once.</summary>
|
||||
private void ShowToast(string title, string? actionText = null, string? actionToolTip = null, ICommand? action = null, bool isError = false) =>
|
||||
PendingToasts.Add(new Toast { Title = title, ActionText = actionText, ActionToolTip = actionToolTip, ActionCommand = action, IsError = isError });
|
||||
|
||||
@@ -471,6 +471,8 @@
|
||||
<RowDefinition Height="Auto" MinHeight="36" />
|
||||
<RowDefinition Height="Auto" MinHeight="36" />
|
||||
<RowDefinition Height="Auto" MinHeight="36" />
|
||||
<RowDefinition Height="Auto" MinHeight="44" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<TextBlock Text="{l:Loc Uploader.Settings.Server}" Style="{StaticResource Text.PanelLabel}" />
|
||||
@@ -501,6 +503,26 @@
|
||||
ToolTip="{l:Loc Tooltips.Uploader.DeleteSource}" VerticalAlignment="Center">
|
||||
<TextBlock Text="{l:Loc Uploader.Options.DeleteSource}" TextWrapping="Wrap" />
|
||||
</CheckBox>
|
||||
|
||||
<!-- Updates: the desktop's notice (BRIEF §18); Download verifies the setup, Show setup reveals it. -->
|
||||
<TextBlock Grid.Row="7" Text="{l:Loc Uploader.Updates.Title}" Style="{StaticResource Text.PanelLabel}" Margin="0,8,12,0" />
|
||||
<CheckBox Grid.Row="7" Grid.Column="1" DataContext="{Binding Updates}" IsChecked="{Binding CheckOnStart}" ToolTip="{l:Loc Tooltips.Uploader.Updates.CheckOnStart}"
|
||||
VerticalAlignment="Center" Margin="0,8,0,0">
|
||||
<TextBlock Text="{l:Loc Uploader.Updates.CheckOnStart}" TextWrapping="Wrap" />
|
||||
</CheckBox>
|
||||
<WrapPanel Grid.Row="8" Grid.Column="1" DataContext="{Binding Updates}" Margin="0,4,0,0">
|
||||
<Button x:Name="CheckUpdatesButton" Content="{l:Loc Uploader.Updates.CheckNow}" Command="{Binding CheckCommand}" ToolTip="{l:Loc Tooltips.Uploader.Updates.CheckNow}"
|
||||
Margin="0,0,12,6" />
|
||||
<ui:StatusGlyph x:Name="UpdateStatus" Kind="{Binding StatusKind}" Text="{Binding StatusText}" ToolTip="{Binding StatusToolTip}" FontSize="{StaticResource Size.Body}"
|
||||
VerticalAlignment="Center" Margin="0,0,12,6" AutomationProperties.Name="{Binding StatusAnnouncement}" AutomationProperties.LiveSetting="Polite"
|
||||
Visibility="{Binding HasStatus, Converter={StaticResource BoolToVisibility}}" />
|
||||
<Button Style="{StaticResource Button.Link}" Content="{l:Loc Uploader.Updates.Download}" Command="{Binding DownloadCommand}" ToolTip="{Binding DownloadToolTip}"
|
||||
VerticalAlignment="Center" Margin="0,0,12,6" Visibility="{Binding IsDownloadOffered, Converter={StaticResource BoolToVisibility}}" />
|
||||
<Button Style="{StaticResource Button.Link}" Content="{l:Loc Uploader.Updates.Cancel}" Command="{Binding CancelCommand}" ToolTip="{l:Loc Tooltips.Uploader.Updates.Cancel}"
|
||||
VerticalAlignment="Center" Margin="0,0,12,6" Visibility="{Binding IsDownloading, Converter={StaticResource BoolToVisibility}}" />
|
||||
<Button Style="{StaticResource Button.Link}" Content="{l:Loc Uploader.Updates.ShowSetup}" Command="{Binding ShowSetupCommand}" ToolTip="{Binding ShowSetupToolTip}"
|
||||
VerticalAlignment="Center" Margin="0,0,12,6" Visibility="{Binding IsReady, Converter={StaticResource BoolToVisibility}}" />
|
||||
</WrapPanel>
|
||||
</Grid>
|
||||
</DockPanel>
|
||||
</Border>
|
||||
|
||||
@@ -35,6 +35,11 @@ public sealed partial class MainWindow : ChronosWindow
|
||||
vm.PendingToasts.CollectionChanged += OnToastRequested;
|
||||
vm.PropertyChanged += OnViewModelChanged;
|
||||
vm.Connect.PropertyChanged += OnConnectChanged;
|
||||
// Each new update state is announced once, not each percent of a download.
|
||||
vm.Updates.PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.PropertyName == nameof(UpdatesViewModel.State)) Dispatcher.BeginInvoke(DispatcherPriority.Background, () => Announce(UpdateStatus));
|
||||
};
|
||||
vm.SignInRequested += (_, _) => FocusLater(Password);
|
||||
PreviewKeyDown += OnPreviewKeyDown;
|
||||
Loaded += (_, _) => FocusStart();
|
||||
|
||||
@@ -78,6 +78,7 @@ public static class ScreenCapture
|
||||
Save(window, Path.Combine(directory, $"uploader-connect{suffix}.png"));
|
||||
sample.ShowQueue();
|
||||
Save(window, Path.Combine(directory, $"uploader-queue{suffix}.png"));
|
||||
sample.ShowUpdate();
|
||||
vm.IsSettingsOpen = true;
|
||||
Save(window, Path.Combine(directory, $"uploader-settings{suffix}.png"));
|
||||
vm.IsSettingsOpen = false;
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
using System.Windows.Input;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Updates;
|
||||
using Chronos.Ui.Controls;
|
||||
using Chronos.Ui.Mvvm;
|
||||
using Chronos.Ui.Updates;
|
||||
using Chronos.Uploader.Infrastructure;
|
||||
using Chronos.Uploader.Text;
|
||||
|
||||
namespace Chronos.Uploader.Shell;
|
||||
|
||||
/// <summary>
|
||||
/// The Updates row of the Uploader's settings panel (BRIEF §18, owner review 5): Check on start (opt-out), Check now,
|
||||
/// then Download, which fetches the single setup (the portable zip for a portable copy), verifies it against the
|
||||
/// release's <c>SHA256SUMS</c> and shows it in Explorer, and Show setup. The work is the desktop's <see cref="UpdateFlow"/>.
|
||||
/// The start-up check is skipped when Chronos Desktop sits beside the Uploader: its own notice covers the same setup.
|
||||
/// </summary>
|
||||
public sealed class UpdatesViewModel : LocalizedViewModel
|
||||
{
|
||||
private readonly UpdateFlow _flow;
|
||||
private readonly UploaderSettings _settings;
|
||||
private readonly Action _saveSettings;
|
||||
private UpdateState _shown;
|
||||
|
||||
public UpdatesViewModel(UpdateHost host, UploaderSettings settings, Action saveSettings)
|
||||
{
|
||||
_flow = new UpdateFlow(host);
|
||||
_settings = settings;
|
||||
_saveSettings = saveSettings;
|
||||
_flow.Changed += RaiseState;
|
||||
CancelCommand = new RelayCommand(_flow.CancelDownload, () => IsDownloading);
|
||||
ShowSetupCommand = new RelayCommand(() =>
|
||||
{
|
||||
if (_flow.PackagePath is { } path) host.Reveal(path);
|
||||
}, () => _flow.PackagePath is not null);
|
||||
}
|
||||
|
||||
/// <summary>The start-up check found a newer release; the window offers it in a toast.</summary>
|
||||
public event Action<ReleaseInfo>? Found;
|
||||
|
||||
public UpdateState State => _flow.State;
|
||||
|
||||
public bool CheckOnStart
|
||||
{
|
||||
get => _settings.CheckForUpdates;
|
||||
set
|
||||
{
|
||||
if (_settings.CheckForUpdates == value) return;
|
||||
_settings.CheckForUpdates = value;
|
||||
_saveSettings();
|
||||
Log.Info("settings", "Check for updates on start " + (value ? "on" : "off"));
|
||||
OnPropertyChanged();
|
||||
}
|
||||
}
|
||||
|
||||
public ICommand CheckCommand => _flow.Check;
|
||||
public ICommand DownloadCommand => _flow.Download;
|
||||
public ICommand CancelCommand { get; }
|
||||
public ICommand ShowSetupCommand { get; }
|
||||
|
||||
/// <summary>"Up to date", "Version 1.1.0 available", "Check failed", …; null before the first check.</summary>
|
||||
public string? StatusText => _flow.State switch
|
||||
{
|
||||
UpdateState.Checking => Loc.L("Uploader.Updates.Checking"),
|
||||
UpdateState.UpToDate => Loc.L("Uploader.Updates.UpToDate"),
|
||||
UpdateState.Available when _flow.Release is { } r => Loc.L("Uploader.Updates.Available", UpdateCheck.Display(r.Version)),
|
||||
UpdateState.Failed => Loc.L("Uploader.Updates.Failed"),
|
||||
UpdateState.Downloading => Loc.L("Uploader.Updates.Downloading", _flow.Downloaded),
|
||||
UpdateState.Downloaded when _flow.Release is { } r => Loc.L("Uploader.Updates.Ready", UpdateCheck.Display(r.Version)),
|
||||
UpdateState.DownloadFailed => Loc.L("Uploader.Updates.DownloadFailed"),
|
||||
UpdateState.NotVerified => Loc.L("Uploader.Updates.NotVerified"),
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <summary>What screen readers announce: each new state, not each percent of a download.</summary>
|
||||
public string? StatusAnnouncement => _flow.State == UpdateState.Downloading ? Loc.L("Uploader.Updates.InProgress") : StatusText;
|
||||
|
||||
/// <summary>What a state means and what to do next; null where the text says it all.</summary>
|
||||
public string? StatusToolTip => _flow.State switch
|
||||
{
|
||||
UpdateState.UpToDate => Loc.L("Tooltips.Uploader.Updates.UpToDate"),
|
||||
UpdateState.Available => Loc.L("Tooltips.Uploader.Updates.Available"),
|
||||
UpdateState.Failed => Loc.L("Tooltips.Uploader.Updates.Failed"),
|
||||
_ => null,
|
||||
};
|
||||
|
||||
public StatusKind StatusKind => _flow.State switch
|
||||
{
|
||||
UpdateState.Checking or UpdateState.Downloading => StatusKind.Running,
|
||||
UpdateState.UpToDate or UpdateState.Downloaded => StatusKind.Done,
|
||||
UpdateState.Available => StatusKind.Warning,
|
||||
_ => StatusKind.Error,
|
||||
};
|
||||
|
||||
public bool HasStatus => StatusText is not null;
|
||||
|
||||
/// <summary>Download is offered: a newer release exists and no verified package is waiting (a failed download can be retried).</summary>
|
||||
public bool IsDownloadOffered => _flow.IsDownloadOffered;
|
||||
|
||||
public bool IsDownloading => _flow.State == UpdateState.Downloading;
|
||||
|
||||
/// <summary>The verified setup or portable zip is in the temporary folder.</summary>
|
||||
public bool IsReady => _flow.State == UpdateState.Downloaded;
|
||||
|
||||
/// <summary>The verified package; null until a download succeeded.</summary>
|
||||
public string? PackagePath => _flow.PackagePath;
|
||||
|
||||
/// <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 => _flow.Package is { } package
|
||||
? Loc.L(_flow.IsPortable ? "Tooltips.Uploader.Updates.DownloadPortable" : "Tooltips.Uploader.Updates.Download", UploaderText.Bytes(package.Size, Loc.Culture))
|
||||
: Loc.L("Tooltips.Uploader.Updates.DownloadPage");
|
||||
|
||||
public string ShowSetupToolTip => Loc.L(_flow.IsPortable ? "Tooltips.Uploader.Updates.ShowPortable" : "Tooltips.Uploader.Updates.ShowSetup");
|
||||
|
||||
/// <summary>The start-up check runs when the user left it on and Chronos Desktop is not installed beside the Uploader.</summary>
|
||||
public static bool ChecksOnStart(bool enabled, bool desktopBeside) => enabled && !desktopBeside;
|
||||
|
||||
/// <summary>
|
||||
/// The start-up check (never in a capture run): raises <see cref="Found"/> when a newer release exists. Skipped when
|
||||
/// the user turned it off or Chronos Desktop is beside the Uploader.
|
||||
/// </summary>
|
||||
public async Task CheckOnStartAsync(bool desktopBeside)
|
||||
{
|
||||
if (!ChecksOnStart(CheckOnStart, desktopBeside))
|
||||
{
|
||||
Log.Info("update", desktopBeside ? "Start-up update check left to Chronos Desktop" : "Start-up update check off");
|
||||
return;
|
||||
}
|
||||
if (await _flow.CheckOnStartAsync(enabled: true) is { } newer) Found?.Invoke(newer);
|
||||
}
|
||||
|
||||
/// <summary>Sets a check result without the network (capture, tests).</summary>
|
||||
public void SetResult(ReleaseInfo? release, bool failed = false) => _flow.SetResult(release, failed);
|
||||
|
||||
private void RaiseState()
|
||||
{
|
||||
// The flow reports each percent of a download too; State changes only with the state, so the view announces it once.
|
||||
if (_shown != _flow.State)
|
||||
{
|
||||
_shown = _flow.State;
|
||||
OnPropertyChanged(nameof(State));
|
||||
}
|
||||
OnPropertyChanged(nameof(StatusText));
|
||||
OnPropertyChanged(nameof(StatusAnnouncement));
|
||||
OnPropertyChanged(nameof(StatusToolTip));
|
||||
OnPropertyChanged(nameof(StatusKind));
|
||||
OnPropertyChanged(nameof(HasStatus));
|
||||
OnPropertyChanged(nameof(IsDownloadOffered));
|
||||
OnPropertyChanged(nameof(IsDownloading));
|
||||
OnPropertyChanged(nameof(IsReady));
|
||||
OnPropertyChanged(nameof(PackagePath));
|
||||
OnPropertyChanged(nameof(DownloadToolTip));
|
||||
OnPropertyChanged(nameof(ShowSetupToolTip));
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user