From 3f61040840e60346af133fe957c5436132136365 Mon Sep 17 00:00:00 2001 From: Patricio <12850986+PAumedes@users.noreply.github.com> Date: Wed, 14 Oct 2026 00:10:45 -0300 Subject: [PATCH 1/4] feat: update Queueify from inside the app At start (unless turned off) and from About, the app asks GitHub for the latest release. Update and restart downloads its exe next to the user's, checks it against GitHub's SHA-256, swaps the two and restarts through it. A folder it can't write to gets the release page instead (ADR-0009). --- Queueify.Core/Services/Strings.En.cs | 22 ++ Queueify.Core/Services/Strings.Es.cs | 22 ++ Queueify.Core/Services/UiState.cs | 3 + Queueify.Core/Services/Updater.cs | 231 +++++++++++ Queueify.Tests/AppDataTests.cs | 17 +- Queueify.Tests/UpdaterTests.cs | 381 +++++++++++++++++++ Queueify/MainWindow.xaml | 30 ++ Queueify/MainWindow.xaml.cs | 104 +++++ README.md | 7 +- SECURITY.md | 3 +- docs/ARCHITECTURE.md | 2 + docs/RELEASING.md | 4 + docs/TESTING.md | 2 + docs/adr/0009-update-from-github-releases.md | 45 +++ docs/adr/README.md | 1 + tests/ui/Queueify.UpdateUiTests.ps1 | 168 ++++++++ 16 files changed, 1037 insertions(+), 5 deletions(-) create mode 100644 Queueify.Core/Services/Updater.cs create mode 100644 Queueify.Tests/UpdaterTests.cs create mode 100644 docs/adr/0009-update-from-github-releases.md create mode 100644 tests/ui/Queueify.UpdateUiTests.ps1 diff --git a/Queueify.Core/Services/Strings.En.cs b/Queueify.Core/Services/Strings.En.cs index 093b7f3..346f8b6 100644 --- a/Queueify.Core/Services/Strings.En.cs +++ b/Queueify.Core/Services/Strings.En.cs @@ -251,6 +251,9 @@ public static partial class Loc ["settings.layout.reset"] = "Reset layout", ["settings.layout.done"] = "Layout reset: the panel, the list view, the order and the window are back as they started.", ["settings.sync.open"] = "Open sync", + ["settings.updates"] = "Updates", + ["settings.updates.auto"] = "Check for updates when Queueify starts", + ["settings.updates.auto.text"] = "Asks GitHub for the number of the latest version; nothing about you or your queue is sent. Updating always waits for your click.", ["service.logo"] = "{0} logo", ["service.id"] = "Client ID", ["service.secret"] = "Client secret", @@ -291,6 +294,7 @@ public static partial class Loc ["help.trouble.2"] = "• An album isn't found: use fewer words (artist + main title), check the spelling, or add it without a link.", ["help.trouble.3"] = "• Text on a photo is read wrong: use good light and shoot the page straight on. Install Spanish text recognition from the Magazine photo page for accents and ñ.", ["help.trouble.4"] = "• Sync shows a warning: point at the Sync icon for the reason. Usually it's no internet, or the security rules weren't published in Firebase.", + ["help.trouble.5"] = "• An update fails: open the release page, download the new exe and put it in place of yours, with the same name.", ["help.about"] = "About Queueify", ["help.data"] = "Open data folder", ["help.data.tip"] = "Your queue, settings and layout live here. To carry them on a USB stick, put them in a Data folder next to the Queueify exe.", @@ -301,6 +305,24 @@ public static partial class Loc ["about.credit.sync"] = "Sync between PCs: Google Firebase (Cloud Firestore), in your own project.", ["about.credit.logos"] = "Spotify and Tidal logos: Simple Icons (CC0). They belong to their owners.", ["about.credit.built"] = "Built with WinUI 3, the Windows App SDK and .NET.", + ["update.available"] = "Queueify {0} is available.", + ["update.install"] = "Update and restart", + ["update.whats_new"] = "What's new", + ["update.page"] = "Release page", + ["update.downloading"] = "Downloading Queueify {0}…", + ["update.check"] = "Check for updates", + ["update.checking"] = "Checking for updates…", + ["update.latest"] = "You have the latest version.", + ["update.manual"] = "This copy wasn't started from the Queueify exe, so it can't update itself. Get the new version from the release page.", + ["update.unreachable"] = "Couldn't reach GitHub ({0}). Check the internet connection.", + ["update.timeout"] = "GitHub didn't answer in time. Try again later.", + ["update.http"] = "GitHub answered {0}. Try again later.", + ["update.unreadable"] = "GitHub's answer about the latest version couldn't be read.", + ["update.damaged"] = "The download doesn't match the release, so it was thrown away. Nothing changed.", + ["update.too_big"] = "The download is far bigger than Queueify, so it was refused. Nothing changed.", + ["update.no_write"] = "Queueify can't write next to its exe ({0}). Download the new version from the release page instead.", + ["update.locked"] = "The exe couldn't be replaced ({0}). Nothing changed; try again in a moment.", + ["update.halfway"] = "The update stopped halfway. To start Queueify again, rename {0} back to {1} in its folder.", ["keys.enter"] = "In the search box: search, then press again to add the highlighted album", ["keys.arrows"] = "Choose another search result", ["keys.esc"] = "Clear the search box", diff --git a/Queueify.Core/Services/Strings.Es.cs b/Queueify.Core/Services/Strings.Es.cs index 371900f..b21f1b7 100644 --- a/Queueify.Core/Services/Strings.Es.cs +++ b/Queueify.Core/Services/Strings.Es.cs @@ -252,6 +252,9 @@ public static partial class Loc ["settings.layout.reset"] = "Restablecer diseño", ["settings.layout.done"] = "Diseño restablecido: el panel, la vista de lista, el orden y la ventana quedaron como al principio.", ["settings.sync.open"] = "Abrir sincronización", + ["settings.updates"] = "Actualizaciones", + ["settings.updates.auto"] = "Buscar actualizaciones al abrir Queueify", + ["settings.updates.auto.text"] = "Le pregunta a GitHub el número de la última versión; no se envía nada sobre vos ni tu lista. Actualizar siempre espera tu clic.", ["service.logo"] = "Logo de {0}", ["service.id"] = "Client ID", ["service.secret"] = "Client secret", @@ -292,6 +295,7 @@ public static partial class Loc ["help.trouble.2"] = "• No aparece un álbum: usá menos palabras (artista + título principal), revisá cómo está escrito o agregalo sin enlace.", ["help.trouble.3"] = "• El texto de una foto se lee mal: usá buena luz y sacá la página de frente. Instalá el reconocimiento de texto en español desde Foto de revista para los acentos y la ñ.", ["help.trouble.4"] = "• Sincronizar muestra una advertencia: pasá el mouse por el ícono para ver el motivo. Casi siempre es falta de internet, o que no se publicaron las reglas de seguridad en Firebase.", + ["help.trouble.5"] = "• Una actualización falla: abrí la página de la versión, descargá el exe nuevo y ponelo en lugar del tuyo, con el mismo nombre.", ["help.about"] = "Acerca de Queueify", ["help.data"] = "Abrir la carpeta de datos", ["help.data.tip"] = "Acá viven tu lista, la configuración y el diseño. Para llevarlos en un pendrive, ponelos en una carpeta Data al lado del exe de Queueify.", @@ -302,6 +306,24 @@ public static partial class Loc ["about.credit.sync"] = "Sincronización entre PC: Google Firebase (Cloud Firestore), en tu propio proyecto.", ["about.credit.logos"] = "Logos de Spotify y Tidal: Simple Icons (CC0). Pertenecen a sus dueños.", ["about.credit.built"] = "Hecho con WinUI 3, el Windows App SDK y .NET.", + ["update.available"] = "Está disponible Queueify {0}.", + ["update.install"] = "Actualizar y reiniciar", + ["update.whats_new"] = "Novedades", + ["update.page"] = "Página de la versión", + ["update.downloading"] = "Descargando Queueify {0}…", + ["update.check"] = "Buscar actualizaciones", + ["update.checking"] = "Buscando actualizaciones…", + ["update.latest"] = "Tenés la última versión.", + ["update.manual"] = "Esta copia no se abrió desde el exe de Queueify, así que no puede actualizarse sola. Bajá la versión nueva desde la página de la versión.", + ["update.unreachable"] = "No se pudo llegar a GitHub ({0}). Revisá la conexión a internet.", + ["update.timeout"] = "GitHub no respondió a tiempo. Probá más tarde.", + ["update.http"] = "GitHub respondió {0}. Probá más tarde.", + ["update.unreadable"] = "No se pudo leer la respuesta de GitHub sobre la última versión.", + ["update.damaged"] = "La descarga no coincide con la versión publicada, así que se descartó. No cambió nada.", + ["update.too_big"] = "La descarga es muchísimo más grande que Queueify, así que se rechazó. No cambió nada.", + ["update.no_write"] = "Queueify no puede escribir junto a su exe ({0}). Bajá la versión nueva desde la página de la versión.", + ["update.locked"] = "No se pudo reemplazar el exe ({0}). No cambió nada; probá de nuevo en un momento.", + ["update.halfway"] = "La actualización quedó a medias. Para volver a abrir Queueify, renombrá {0} a {1} en su carpeta.", ["keys.enter"] = "En el cuadro de búsqueda: buscar, y con otro Enter agregar el álbum resaltado", ["keys.arrows"] = "Elegir otro resultado de búsqueda", ["keys.esc"] = "Borrar el cuadro de búsqueda", diff --git a/Queueify.Core/Services/UiState.cs b/Queueify.Core/Services/UiState.cs index d623eec..0079642 100644 --- a/Queueify.Core/Services/UiState.cs +++ b/Queueify.Core/Services/UiState.cs @@ -34,6 +34,9 @@ public sealed class UiState /// "Don't show this again" on the Photo page's offer to install Spanish text recognition. public bool OcrHintDismissed { get; set; } + /// Ask GitHub for a newer version at each start (Settings → Updates). + public bool CheckForUpdates { get; set; } = true; + /// Back to the original layout (panel, list view, order, window size); the tour isn't repeated. public void ResetLayout() { diff --git a/Queueify.Core/Services/Updater.cs b/Queueify.Core/Services/Updater.cs new file mode 100644 index 0000000..287ef69 --- /dev/null +++ b/Queueify.Core/Services/Updater.cs @@ -0,0 +1,231 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Security.Cryptography; +using System.Text.Json; + +namespace Queueify.Services; + +/// A release Queueify can update to: its exe and the SHA-256 GitHub lists for it. +public sealed record AppRelease(string Version, Uri Download, string Sha256, Uri Page); + +/// An update check or download that failed, with a message for the user. +public sealed class UpdateException(string message, Exception? inner = null) : Exception(message, inner); + +/// Where the latest release is described, and where its download may come from. +public sealed record UpdateSource(Uri Latest, string DownloadPrefix) +{ + public static UpdateSource GitHub { get; } = new( + new Uri("https://api.github.com/repos/PAumedes/Queueify/releases/latest"), + "https://github.com/PAumedes/Queueify/releases/download/"); + + /// The releases page, for when the app can't update itself. + public static Uri Releases { get; } = new("https://github.com/PAumedes/Queueify/releases/latest"); + + /// + /// GitHub, unless QUEUEIFY_UPDATE_SERVER names a server on this PC: the UI tests serve a release from + /// one. Anything else is ignored, so the variable can't point updates elsewhere. + /// + public static UpdateSource For(string? testServer) + { + if (!Uri.TryCreate(testServer, UriKind.Absolute, out var server) || server.Scheme != Uri.UriSchemeHttp || !server.IsLoopback) + return GitHub; + var root = new Uri(server.GetLeftPart(UriPartial.Authority) + "/"); + return new UpdateSource(new Uri(root, "latest"), root.AbsoluteUri); + } +} + +/// +/// Updates the download's exe from the latest release: checks the version, downloads the new exe next to +/// the old one, checks its SHA-256 and swaps the two. The exe isn't in use while the app runs (the starter +/// has finished by then), so it can be replaced. +/// +public sealed class Updater(HttpClient http, UpdateSource source) +{ + /// Several times Queueify's size: anything bigger isn't a Queueify release. + private const long MaxDownload = 256L << 20; + + /// The release in GitHub's answer, or null when it isn't one Queueify can install. + public AppRelease? Parse(string json) + { + try + { + using var doc = JsonDocument.Parse(json); + var root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object + || root.TryGetProperty("draft", out var draft) && draft.ValueKind != JsonValueKind.False + || root.TryGetProperty("prerelease", out var pre) && pre.ValueKind != JsonValueKind.False + || !root.TryGetProperty("tag_name", out var tag) || tag.ValueKind != JsonValueKind.String + || !root.TryGetProperty("assets", out var assets) || assets.ValueKind != JsonValueKind.Array) + return null; + + var version = tag.GetString()!.TrimStart('v'); + if (!System.Version.TryParse(version, out _)) return null; + var page = root.TryGetProperty("html_url", out var html) && html.ValueKind == JsonValueKind.String + && Uri.TryCreate(html.GetString(), UriKind.Absolute, out var p) && p.Scheme == Uri.UriSchemeHttps + ? p : UpdateSource.Releases; + + var exeName = $"Queueify-{version}-win-x64.exe"; + foreach (var asset in assets.EnumerateArray()) + { + if (asset.ValueKind != JsonValueKind.Object || Text(asset, "name") != exeName) continue; + var url = Text(asset, "browser_download_url"); + var digest = Text(asset, "digest"); + if (url == null || !url.StartsWith(source.DownloadPrefix, StringComparison.Ordinal) + || !Uri.TryCreate(url, UriKind.Absolute, out var download) + || digest is not { Length: 71 } || !digest.StartsWith("sha256:", StringComparison.Ordinal) + || !digest[7..].All(char.IsAsciiHexDigit)) + return null; + return new AppRelease(version, download, digest[7..].ToLowerInvariant(), page); + } + return null; + } + catch (JsonException) + { + return null; + } + } + + private static string? Text(JsonElement e, string name) => + e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() : null; + + public static bool IsNewer(string candidate, string current) => + System.Version.TryParse(candidate, out var c) && System.Version.TryParse(current, out var v) && c > v; + + /// The latest release when it's newer than this version; null when this is the latest. + public async Task CheckAsync(string currentVersion, CancellationToken ct) + { + using var request = new HttpRequestMessage(HttpMethod.Get, source.Latest); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github+json")); + string json; + try + { + using var response = await http.SendAsync(request, ct); + if (!response.IsSuccessStatusCode) + throw new UpdateException(Loc.F("update.http", $"{(int)response.StatusCode} {response.ReasonPhrase}".Trim())); + json = await response.Content.ReadAsStringAsync(ct); + } + catch (Exception ex) when (Failed(ex, ct) is { } message) + { + throw new UpdateException(message, ex); + } + + var release = Parse(json) ?? throw new UpdateException(Loc.T("update.unreadable")); + return IsNewer(release.Version, currentVersion) ? release : null; + } + + /// + /// Downloads the release's exe next to and returns its path once its SHA-256 + /// matches; anything else leaves no file behind. + /// + public async Task DownloadAsync(AppRelease release, string exe, IProgress? progress, CancellationToken ct) + { + var path = exe + ".download"; + try + { + using var response = await http.GetAsync(release.Download, HttpCompletionOption.ResponseHeadersRead, ct); + if (!response.IsSuccessStatusCode) + throw new UpdateException(Loc.F("update.http", $"{(int)response.StatusCode} {response.ReasonPhrase}".Trim())); + var length = response.Content.Headers.ContentLength; + if (length > MaxDownload) throw new UpdateException(Loc.T("update.too_big")); + + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + await using (var body = await response.Content.ReadAsStreamAsync(ct)) + await using (var file = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None)) + { + var buffer = new byte[1 << 16]; + long received = 0; + while (await ReadAsync(body, buffer, ct) is var n and > 0) + { + received += n; + if (received > MaxDownload) throw new UpdateException(Loc.T("update.too_big")); + hash.AppendData(buffer, 0, n); + await file.WriteAsync(buffer.AsMemory(0, n), ct); + if (length > 0) progress?.Report(Math.Min(1.0, (double)received / length.Value)); + } + } + if (Convert.ToHexStringLower(hash.GetHashAndReset()) != release.Sha256) + throw new UpdateException(Loc.T("update.damaged")); + progress?.Report(1.0); + return path; + } + catch (Exception ex) + { + TryDelete(path); + if (ex is UpdateException) throw; + // Reading the download fails as an UpdateException (see ReadAsync); what's left is the file. + if (ex is IOException or UnauthorizedAccessException) + throw new UpdateException(Loc.F("update.no_write", Path.GetDirectoryName(exe)), ex); + if (Failed(ex, ct) is { } message) throw new UpdateException(message, ex); + throw; + } + } + + /// + /// Puts the downloaded exe in place of the old one, which stays as "<exe>.old" until + /// . If the new one can't be moved in, the old one goes back. + /// + public static void Replace(string exe, string downloaded) + { + var old = exe + ".old"; + try + { + File.Move(exe, old, overwrite: true); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + TryDelete(downloaded); + throw new UpdateException(Loc.F("update.locked", ex.Message), ex); + } + try + { + File.Move(downloaded, exe); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + TryDelete(downloaded); + try + { + File.Move(old, exe); + } + catch (Exception back) when (back is IOException or UnauthorizedAccessException) + { + throw new UpdateException(Loc.F("update.halfway", Path.GetFileName(old), Path.GetFileName(exe)), back); + } + throw new UpdateException(Loc.F("update.locked", ex.Message), ex); + } + } + + private static async Task ReadAsync(Stream body, byte[] buffer, CancellationToken ct) + { + try + { + return await body.ReadAsync(buffer, ct); + } + catch (IOException ex) + { + throw new UpdateException(Loc.F("update.unreachable", ex.Message), ex); + } + } + + /// Removes the exe an update replaced and a download that never finished; in use, they wait. + public static void RemoveLeftovers(string exe) + { + TryDelete(exe + ".old"); + TryDelete(exe + ".download"); + } + + private static void TryDelete(string path) + { + try { File.Delete(path); } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { } + } + + /// The message for a network failure; null for the caller's own cancellation and anything else. + private static string? Failed(Exception ex, CancellationToken ct) => ex switch + { + OperationCanceledException when ct.IsCancellationRequested => null, + OperationCanceledException => Loc.T("update.timeout"), + HttpRequestException => Loc.F("update.unreachable", ex.Message), + _ => null, + }; +} diff --git a/Queueify.Tests/AppDataTests.cs b/Queueify.Tests/AppDataTests.cs index ee10abf..85a5766 100644 --- a/Queueify.Tests/AppDataTests.cs +++ b/Queueify.Tests/AppDataTests.cs @@ -177,15 +177,26 @@ public void Layout_survives_a_save_and_load() { PaneWidth = 512, PaneVisible = false, CoverView = true, Sort = "artist", WindowBounds = [10, 20, 1300, 900], Maximized = true, TourSeen = true, - Theme = "dark", Language = "es", OcrLanguage = "en-US", OcrHintDismissed = true, + Theme = "dark", Language = "es", OcrLanguage = "en-US", OcrHintDismissed = true, CheckForUpdates = false, }; saved.Save(path); var loaded = UiState.Load(path); Assert.Equal( - (saved.PaneWidth, saved.PaneVisible, saved.CoverView, saved.Sort, saved.Maximized, saved.TourSeen, saved.Theme, saved.Language, saved.OcrLanguage, saved.OcrHintDismissed), - (loaded.PaneWidth, loaded.PaneVisible, loaded.CoverView, loaded.Sort, loaded.Maximized, loaded.TourSeen, loaded.Theme, loaded.Language, loaded.OcrLanguage, loaded.OcrHintDismissed)); + (saved.PaneWidth, saved.PaneVisible, saved.CoverView, saved.Sort, saved.Maximized, saved.TourSeen, saved.Theme, saved.Language, saved.OcrLanguage, saved.OcrHintDismissed, saved.CheckForUpdates), + (loaded.PaneWidth, loaded.PaneVisible, loaded.CoverView, loaded.Sort, loaded.Maximized, loaded.TourSeen, loaded.Theme, loaded.Language, loaded.OcrLanguage, loaded.OcrHintDismissed, loaded.CheckForUpdates)); Assert.Equal(saved.WindowBounds, loaded.WindowBounds); } + + [Fact] + public void Updates_are_checked_unless_turned_off() + { + // ui.json from earlier versions has no such setting. + var path = Path.Combine(_dir, "ui.json"); + Directory.CreateDirectory(_dir); + File.WriteAllText(path, """{ "Theme": "dark" }"""); + + Assert.True(UiState.Load(path).CheckForUpdates); + } } diff --git a/Queueify.Tests/UpdaterTests.cs b/Queueify.Tests/UpdaterTests.cs new file mode 100644 index 0000000..7d4196d --- /dev/null +++ b/Queueify.Tests/UpdaterTests.cs @@ -0,0 +1,381 @@ +using System.Net; +using System.Security.Cryptography; +using System.Text; +using Queueify.Services; + +namespace Queueify.Tests; + +// Updates come from the latest GitHub release: its exe replaces the one the user started, after its +// SHA-256 matches the one GitHub lists for it. +public sealed class UpdaterTests : IDisposable +{ + private readonly string _dir = Path.Combine(Path.GetTempPath(), "queueify-tests", Guid.NewGuid().ToString("N")); + + public UpdaterTests() => Directory.CreateDirectory(_dir); + + public void Dispose() + { + if (Directory.Exists(_dir)) Directory.Delete(_dir, recursive: true); + } + + private static readonly byte[] NewExe = Encoding.ASCII.GetBytes("MZ the new Queueify"); + private static string Sha256Of(byte[] data) => Convert.ToHexStringLower(SHA256.HashData(data)); + + private static string LatestJson(string tag = "v1.4.0", string? digest = null, string? url = null, string? name = null, + bool draft = false, bool prerelease = false) + { + var version = tag.TrimStart('v'); + name ??= $"Queueify-{version}-win-x64.exe"; + url ??= $"https://github.com/PAumedes/Queueify/releases/download/{tag}/{name}"; + digest ??= "sha256:" + Sha256Of(NewExe); + return $$""" + { + "tag_name": "{{tag}}", + "name": "Queueify {{tag}}", + "html_url": "https://github.com/PAumedes/Queueify/releases/tag/{{tag}}", + "draft": {{(draft ? "true" : "false")}}, + "prerelease": {{(prerelease ? "true" : "false")}}, + "assets": [ + { "name": "notes.txt", "digest": "sha256:{{new string('0', 64)}}", + "browser_download_url": "https://github.com/PAumedes/Queueify/releases/download/{{tag}}/notes.txt" }, + { "name": "{{name}}", "size": {{NewExe.Length}}, "digest": "{{digest}}", + "browser_download_url": "{{url}}" } + ] + } + """; + } + + private static Updater GitHub(HttpMessageHandler? api = null) => + new(new HttpClient(api ?? new FakeGitHub(HttpStatusCode.OK, LatestJson())), UpdateSource.GitHub); + + // ── What the latest release offers ── + + [Fact] + public void A_release_gives_its_version_download_hash_and_page() + { + var release = GitHub().Parse(LatestJson()); + + Assert.NotNull(release); + Assert.Equal("1.4.0", release.Version); + Assert.Equal("https://github.com/PAumedes/Queueify/releases/download/v1.4.0/Queueify-1.4.0-win-x64.exe", release.Download.AbsoluteUri); + Assert.Equal(Sha256Of(NewExe), release.Sha256); + Assert.Equal("https://github.com/PAumedes/Queueify/releases/tag/v1.4.0", release.Page.AbsoluteUri); + } + + [Theory] + [InlineData(true, false)] + [InlineData(false, true)] + public void Drafts_and_previews_are_not_offered(bool draft, bool prerelease) + { + Assert.Null(GitHub().Parse(LatestJson(draft: draft, prerelease: prerelease))); + } + + [Theory] + [InlineData("")] + [InlineData("md5:0123456789abcdef0123456789abcdef")] + [InlineData("sha256:not-a-hash")] + [InlineData("sha256:0123")] + public void A_release_without_a_usable_hash_is_not_offered(string digest) + { + Assert.Null(GitHub().Parse(LatestJson(digest: digest))); + } + + [Theory] + [InlineData("https://example.com/Queueify-1.4.0-win-x64.exe")] + [InlineData("http://github.com/PAumedes/Queueify/releases/download/v1.4.0/Queueify-1.4.0-win-x64.exe")] + [InlineData("https://github.com/someone/Queueify/releases/download/v1.4.0/Queueify-1.4.0-win-x64.exe")] + public void A_download_from_anywhere_but_Queueifys_releases_is_not_offered(string url) + { + Assert.Null(GitHub().Parse(LatestJson(url: url))); + } + + [Theory] + [InlineData("Queueify-1.3.0-win-x64.exe")] // another version's exe + [InlineData("Queueify-1.4.0-win-x64.zip")] + [InlineData("Queueify-1.4.0-win-arm64.exe")] + public void Only_that_versions_exe_is_offered(string name) + { + Assert.Null(GitHub().Parse(LatestJson(name: name))); + } + + [Theory] + [InlineData("not json")] + [InlineData("[]")] + [InlineData("""{"tag_name": 14}""")] + [InlineData("""{"tag_name": "v1.4.0", "assets": "none"}""")] + [InlineData("""{"tag_name": "latest", "assets": []}""")] + public void An_answer_that_isnt_a_release_offers_nothing(string json) + { + Assert.Null(GitHub().Parse(json)); + } + + [Theory] + [InlineData("1.4.0", "1.3.0", true)] + [InlineData("1.10.0", "1.9.0", true)] + [InlineData("2.0.0", "1.99.99", true)] + [InlineData("1.3.0", "1.3.0", false)] + [InlineData("1.2.9", "1.3.0", false)] + [InlineData("soon", "1.3.0", false)] + public void Only_a_newer_version_is_an_update(string candidate, string current, bool newer) + { + Assert.Equal(newer, Updater.IsNewer(candidate, current)); + } + + // ── Asking GitHub ── + + [Fact] + public async Task A_newer_release_is_offered() + { + var release = await GitHub().CheckAsync("1.3.0", CancellationToken.None); + + Assert.Equal("1.4.0", release?.Version); + } + + [Fact] + public async Task The_same_version_is_no_update() + { + Assert.Null(await GitHub().CheckAsync("1.4.0", CancellationToken.None)); + } + + [Fact] + public async Task GitHub_asks_who_is_asking_and_gets_its_json() + { + var api = new FakeGitHub(HttpStatusCode.OK, LatestJson()); + + await GitHub(api).CheckAsync("1.3.0", CancellationToken.None); + + Assert.Equal("https://api.github.com/repos/PAumedes/Queueify/releases/latest", api.Requests.Single().RequestUri!.AbsoluteUri); + Assert.Contains("application/vnd.github+json", api.Requests.Single().Headers.Accept.ToString()); + } + + [Theory] + [InlineData(HttpStatusCode.Forbidden)] // GitHub's limit of 60 questions an hour + [InlineData(HttpStatusCode.NotFound)] + [InlineData(HttpStatusCode.InternalServerError)] + public async Task A_failed_check_says_so(HttpStatusCode status) + { + await Assert.ThrowsAsync(() => GitHub(new FakeGitHub(status, "{}")).CheckAsync("1.3.0", CancellationToken.None)); + } + + [Fact] + public async Task No_connection_says_so() + { + await Assert.ThrowsAsync(() => GitHub(new FakeGitHub(new HttpRequestException("No such host"))).CheckAsync("1.3.0", CancellationToken.None)); + } + + [Fact] + public async Task A_release_that_cant_be_offered_says_so() + { + // Better than "you have the latest version" when GitHub has a newer one without a hash. + var api = new FakeGitHub(HttpStatusCode.OK, LatestJson(digest: "")); + + await Assert.ThrowsAsync(() => GitHub(api).CheckAsync("1.3.0", CancellationToken.None)); + } + + // ── Downloading ── + + private string Exe() + { + var exe = Path.Combine(_dir, "Queueify (1).exe"); + File.WriteAllText(exe, "MZ the old Queueify"); + return exe; + } + + private static AppRelease Release(string? sha256 = null) => new("1.4.0", + new Uri("https://github.com/PAumedes/Queueify/releases/download/v1.4.0/Queueify-1.4.0-win-x64.exe"), + sha256 ?? Sha256Of(NewExe), new Uri("https://github.com/PAumedes/Queueify/releases/tag/v1.4.0")); + + [Fact] + public async Task The_new_exe_is_downloaded_next_to_the_old_one() + { + var exe = Exe(); + var progress = new List(); + + var downloaded = await GitHub(new FakeGitHub(HttpStatusCode.OK, NewExe)).DownloadAsync(Release(), exe, new SyncProgress(progress.Add), CancellationToken.None); + + Assert.Equal(_dir, Path.GetDirectoryName(downloaded)); + Assert.Equal(NewExe, File.ReadAllBytes(downloaded)); + Assert.Equal("MZ the old Queueify", File.ReadAllText(exe)); + Assert.Equal(1.0, progress.Last()); + } + + [Fact] + public async Task A_download_that_doesnt_match_the_release_is_thrown_away() + { + var exe = Exe(); + var tampered = Encoding.ASCII.GetBytes("MZ something else"); + + await Assert.ThrowsAsync(() => + GitHub(new FakeGitHub(HttpStatusCode.OK, tampered)).DownloadAsync(Release(), exe, null, CancellationToken.None)); + + Assert.Equal([exe], Directory.GetFiles(_dir)); + } + + [Fact] + public async Task A_download_far_bigger_than_Queueify_is_refused() + { + var exe = Exe(); + var api = new FakeGitHub(HttpStatusCode.OK, NewExe) { ClaimedLength = 2L << 30 }; + + await Assert.ThrowsAsync(() => GitHub(api).DownloadAsync(Release(), exe, null, CancellationToken.None)); + + Assert.Equal([exe], Directory.GetFiles(_dir)); + } + + [Fact] + public async Task A_failed_download_leaves_nothing_behind() + { + var exe = Exe(); + + await Assert.ThrowsAsync(() => + GitHub(new FakeGitHub(HttpStatusCode.NotFound, "{}")).DownloadAsync(Release(), exe, null, CancellationToken.None)); + + Assert.Equal([exe], Directory.GetFiles(_dir)); + } + + [Fact] + public async Task A_folder_Queueify_cant_write_to_says_so() + { + var exe = Path.Combine(_dir, "gone", "Queueify.exe"); + + await Assert.ThrowsAsync(() => + GitHub(new FakeGitHub(HttpStatusCode.OK, NewExe)).DownloadAsync(Release(), exe, null, CancellationToken.None)); + } + + // ── Swapping ── + + private string Downloaded() + { + var path = Path.Combine(_dir, "Queueify (1).exe.download"); + File.WriteAllBytes(path, NewExe); + return path; + } + + [Fact] + public void The_new_exe_takes_the_old_ones_name() + { + var exe = Exe(); + + Updater.Replace(exe, Downloaded()); + + Assert.Equal(NewExe, File.ReadAllBytes(exe)); + Assert.Equal("MZ the old Queueify", File.ReadAllText(exe + ".old")); + Assert.False(File.Exists(exe + ".download")); + } + + [Fact] + public void An_old_exe_left_from_the_last_update_is_replaced() + { + var exe = Exe(); + File.WriteAllText(exe + ".old", "MZ an even older Queueify"); + + Updater.Replace(exe, Downloaded()); + + Assert.Equal("MZ the old Queueify", File.ReadAllText(exe + ".old")); + } + + [Fact] + public void When_the_new_exe_cant_be_moved_in_the_old_one_stays() + { + var exe = Exe(); + var downloaded = Downloaded(); + // An antivirus still scanning it, say. + using var scanning = File.Open(downloaded, FileMode.Open, FileAccess.Read, FileShare.Read); + + Assert.Throws(() => Updater.Replace(exe, downloaded)); + + Assert.Equal("MZ the old Queueify", File.ReadAllText(exe)); + Assert.False(File.Exists(exe + ".old")); + } + + [Fact] + public void When_the_old_exe_cant_be_moved_nothing_changes() + { + var exe = Exe(); + var downloaded = Downloaded(); + using var held = File.Open(exe, FileMode.Open, FileAccess.Read, FileShare.Read); + + Assert.Throws(() => Updater.Replace(exe, downloaded)); + + Assert.Equal("MZ the old Queueify", File.ReadAllText(exe)); + } + + [Fact] + public void The_old_exe_and_a_stray_download_are_removed_next_time() + { + var exe = Exe(); + File.WriteAllText(exe + ".old", "old"); + File.WriteAllText(exe + ".download", "half"); + + Updater.RemoveLeftovers(exe); + + Assert.Equal([exe], Directory.GetFiles(_dir)); + } + + [Fact] + public void A_leftover_still_in_use_waits_for_another_time() + { + var exe = Exe(); + File.WriteAllText(exe + ".old", "old"); + using var held = File.Open(exe + ".old", FileMode.Open, FileAccess.Read, FileShare.Read); + + Updater.RemoveLeftovers(exe); + + Assert.True(File.Exists(exe + ".old")); + } + + // ── Where updates come from ── + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("https://example.com/")] // only a server on this PC, for the UI tests + [InlineData("http://192.168.1.20:8123/")] + [InlineData("file:///C:/releases/")] + [InlineData("not a url")] + public void Updates_come_from_GitHub(string? testServer) + { + Assert.Equal(UpdateSource.GitHub, UpdateSource.For(testServer)); + } + + [Theory] + [InlineData("http://127.0.0.1:8123/")] + [InlineData("http://127.0.0.1:8123")] + [InlineData("http://localhost:8123/")] + public void The_UI_tests_can_serve_updates_from_this_PC(string testServer) + { + var source = UpdateSource.For(testServer); + + Assert.Equal(new Uri(new Uri(testServer), "latest"), source.Latest); + var release = new Updater(new HttpClient(), source).Parse(LatestJson(url: new Uri(new Uri(testServer), "Queueify-1.4.0-win-x64.exe").AbsoluteUri)); + Assert.NotNull(release); + } + + private sealed class SyncProgress(Action report) : IProgress + { + public void Report(double value) => report(value); + } + + private sealed class FakeGitHub : HttpMessageHandler + { + private readonly HttpStatusCode _status; + private readonly byte[] _body = []; + private readonly Exception? _failure; + + public FakeGitHub(HttpStatusCode status, string body) : this(status, Encoding.UTF8.GetBytes(body)) { } + public FakeGitHub(HttpStatusCode status, byte[] body) { _status = status; _body = body; } + public FakeGitHub(Exception failure) => _failure = failure; + + public List Requests { get; } = []; + public long? ClaimedLength { get; init; } + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct) + { + Requests.Add(request); + if (_failure != null) throw _failure; + var content = new ByteArrayContent(_body); + if (ClaimedLength is { } length) content.Headers.ContentLength = length; + return Task.FromResult(new HttpResponseMessage(_status) { Content = content }); + } + } +} diff --git a/Queueify/MainWindow.xaml b/Queueify/MainWindow.xaml index fdfdcce..945f009 100644 --- a/Queueify/MainWindow.xaml +++ b/Queueify/MainWindow.xaml @@ -498,6 +498,9 @@ Style="{StaticResource CaptionTextBlockStyle}" Foreground="{ThemeResource TextFillColorSecondaryBrush}" /> + + @@ -642,6 +645,7 @@ + @@ -665,9 +669,13 @@ +