diff --git a/Queueify.Core/Services/Strings.En.cs b/Queueify.Core/Services/Strings.En.cs index 093b7f3..69e2c30 100644 --- a/Queueify.Core/Services/Strings.En.cs +++ b/Queueify.Core/Services/Strings.En.cs @@ -15,14 +15,14 @@ public static partial class Loc ["nav.help.tip"] = "Help, shortcuts and about (F1)", ["nav.sync"] = "Sync", ["nav.settings"] = "Settings", - ["nav.settings.tip"] = "Settings: Tidal and Spotify, country, theme, language, layout", + ["nav.settings.tip"] = "Settings: Tidal and Spotify, country, theme, language, layout, updates", ["badge.waiting"] = "{0}, {1} waiting", ["badge.listened"] = "{0}, {1} listened", ["badge.waiting.one"] = "{0}, {1} waiting", ["badge.listened.one"] = "{0}, {1} listened", ["page.photo.summary"] = "Drop a photo of a page, then click the artist and the album on it.", ["page.help.summary"] = "{0} {1} · how everything works", - ["page.settings.summary"] = "Music services, country, theme, language and layout. Changes are saved right away.", + ["page.settings.summary"] = "Music services, country, theme, language, layout and updates. Changes are saved right away.", // ── Add albums panel ── ["pane.title"] = "Add albums", @@ -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. Nothing is installed until you 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: click “Try again” in the bar (or Check for updates in About), or download the new exe from github.com/PAumedes/Queueify/releases 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,28 @@ 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"] = "A new version is out: Queueify {0}.", + ["update.retry"] = "Try again", + ["update.cancel"] = "Cancel", + ["update.restarting"] = "Starting Queueify {0}…", + ["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. Download the new version from its page on GitHub.", + ["update.unreachable"] = "Couldn't reach GitHub. Check the internet connection.", + ["update.failed"] = "The update didn't work ({0}). Nothing changed.", + ["update.restart_failed"] = "Queueify {0} is in place. Close Queueify and open it again to use it.", + ["update.timeout"] = "GitHub didn't answer in time. Try again later.", + ["update.http"] = "GitHub answered with an error ({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 its page on GitHub instead.", + ["update.locked"] = "Queueify's exe is in use right now. Nothing changed; try again in a moment.", ["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..8868b5b 100644 --- a/Queueify.Core/Services/Strings.Es.cs +++ b/Queueify.Core/Services/Strings.Es.cs @@ -16,14 +16,14 @@ public static partial class Loc ["nav.help.tip"] = "Ayuda, atajos y acerca de (F1)", ["nav.sync"] = "Sincronizar", ["nav.settings"] = "Configuración", - ["nav.settings.tip"] = "Configuración: Tidal y Spotify, país, tema, idioma, diseño", + ["nav.settings.tip"] = "Configuración: Tidal y Spotify, país, tema, idioma, diseño, actualizaciones", ["badge.waiting"] = "{0}, {1} esperando", ["badge.listened"] = "{0}, {1} escuchados", ["badge.waiting.one"] = "{0}, {1} esperando", ["badge.listened.one"] = "{0}, {1} escuchado", ["page.photo.summary"] = "Soltá una foto de una página y después hacé clic en el artista y el álbum.", ["page.help.summary"] = "{0} {1} · cómo funciona todo", - ["page.settings.summary"] = "Servicios de música, país, tema, idioma y diseño. Los cambios se guardan al instante.", + ["page.settings.summary"] = "Servicios de música, país, tema, idioma, diseño y actualizaciones. Los cambios se guardan al instante.", // ── Panel Agregar álbumes ── ["pane.title"] = "Agregar álbumes", @@ -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. Nunca se instala nada sin que hagas 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: hacé clic en “Probar de nuevo” en la barra (o en Buscar actualizaciones, en Acerca de), o descargá el exe nuevo de github.com/PAumedes/Queueify/releases 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,28 @@ 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"] = "Hay una versión nueva: Queueify {0}.", + ["update.retry"] = "Probar de nuevo", + ["update.cancel"] = "Cancelar", + ["update.restarting"] = "Abriendo 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. Descargá la versión nueva desde su página en GitHub.", + ["update.unreachable"] = "No se pudo llegar a GitHub. Revisá la conexión a internet.", + ["update.failed"] = "La actualización no funcionó ({0}). No cambió nada.", + ["update.restart_failed"] = "Queueify {0} ya está en su lugar. Cerrá Queueify y volvé a abrirlo para usarlo.", + ["update.timeout"] = "GitHub no respondió a tiempo. Probá más tarde.", + ["update.http"] = "GitHub respondió con un error ({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}). Descargá la versión nueva desde su página en GitHub.", + ["update.locked"] = "El exe de Queueify está en uso en este momento. No cambió nada; probá de nuevo en un rato.", ["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..e951f76 --- /dev/null +++ b/Queueify.Core/Services/Updater.cs @@ -0,0 +1,262 @@ +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, TimeSpan? stallTimeout = null) +{ + private readonly TimeSpan _stallTimeout = stallTimeout ?? TimeSpan.FromSeconds(30); + + /// 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; + + // Three parts, as AppInfo.Version shows it: anything else would be offered again after updating. + var version = tag.GetString()!.TrimStart('v'); + if (!System.Version.TryParse(version, out var parsed) || parsed.Build < 0 || parsed.Revision >= 0) 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"); + // Checked once read as an address, after "..", "%2e" and "\" are resolved. + if (!Uri.TryCreate(url, UriKind.Absolute, out var download) + || !download.AbsoluteUri.StartsWith(source.DownloadPrefix, StringComparison.Ordinal) + || 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)); + // GitHub's JSON is UTF-8 whatever a proxy on the way says it is. + json = System.Text.Encoding.UTF8.GetString(await response.Content.ReadAsByteArrayAsync(ct)); + } + catch (Exception ex) when (ex is not UpdateException && 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. Only the caller's own cancellation comes out as + /// something other than an . + /// + 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)); + var length = response.Content.Headers.ContentLength; + if (length > MaxDownload) throw new UpdateException(Loc.T("update.too_big")); + + // Always a file of its own: one already there (or a link) may belong to someone else who can + // write the folder, and would keep their rights to the new exe. If it can't go, no update. + TryDelete(path); + FileStream file; + try + { + file = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // Still there: another Queueify window is downloading, or someone else's file won't go. + throw new UpdateException(File.Exists(path) + ? Loc.T("update.locked") + : Loc.F("update.no_write", Path.GetDirectoryName(exe)), ex); + } + + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + await using (file) + await using (var body = await response.Content.ReadAsStreamAsync(ct)) + { + 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)); + } + } + // Cancel pressed after the last read still counts: nothing is put in place. + ct.ThrowIfCancellationRequested(); + 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 writing 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; + } + } + + /// + /// One read of the download. A connection that sends nothing for a while gives up; a slow one that keeps + /// sending doesn't (HttpClient's own timeout stops at the headers). + /// + private async Task ReadAsync(Stream body, byte[] buffer, CancellationToken ct) + { + using var stalled = CancellationTokenSource.CreateLinkedTokenSource(ct); + stalled.CancelAfter(_stallTimeout); + try + { + return await body.ReadAsync(buffer, stalled.Token); + } + catch (Exception ex) when (!ct.IsCancellationRequested) + { + throw new UpdateException(Failed(ex, ct)!, ex); + } + } + /// + /// Puts the downloaded exe in place of the old one, in one step: the name is never free, not even for a + /// moment, so a file someone else drops in the folder can't take it, and no other name next to the exe + /// is ever written (one could be a link to the user's own files). If it fails, the exe is as it was. + /// + public static void Replace(string exe, string downloaded) + { + var readOnly = File.Exists(exe) && File.GetAttributes(exe).HasFlag(FileAttributes.ReadOnly); + try + { + // A read-only exe (copied from a CD or a locked-down share) couldn't be replaced. + ClearReadOnly(exe); + File.Move(downloaded, exe, overwrite: true); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + if (readOnly) TrySetReadOnly(exe); + TryDelete(downloaded); + throw new UpdateException(Loc.T("update.locked"), ex); + } + } + private static void TrySetReadOnly(string path) + { + try { File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.ReadOnly); } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { } + } + /// Removes a download that never finished; one in use (another window downloading) waits. + public static void RemoveLeftovers(string exe) => TryDelete(exe + ".download"); + + private static void TryDelete(string path) + { + try + { + ClearReadOnly(path); + File.Delete(path); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { } + } + + /// Only on the file itself: a link left in its place is never followed. + private static void ClearReadOnly(string path) + { + if (!File.Exists(path)) return; + var attributes = File.GetAttributes(path); + if (attributes.HasFlag(FileAttributes.ReadOnly) && !attributes.HasFlag(FileAttributes.ReparsePoint)) + File.SetAttributes(path, attributes & ~FileAttributes.ReadOnly); + } + + // Plain words for the user: the system's own messages are English and technical. Only an unexpected + // failure (a bug) shows it, as a clue. + /// The message for a failure; null only for the caller's own cancellation, which goes on as it is. + private static string? Failed(Exception ex, CancellationToken ct) => ex switch + { + OperationCanceledException when ct.IsCancellationRequested => null, + OperationCanceledException => Loc.T("update.timeout"), + HttpRequestException or IOException => Loc.T("update.unreachable"), + _ => Loc.F("update.failed", ex.Message), + }; +} 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..e865a69 --- /dev/null +++ b/Queueify.Tests/UpdaterTests.cs @@ -0,0 +1,585 @@ +using System.Net; +using System.Runtime.InteropServices; +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, TimeSpan? stall = null) => + new(new HttpClient(api ?? new FakeGitHub(HttpStatusCode.OK, LatestJson())), UpdateSource.GitHub, stall); + + // ── 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")] + // Dot segments that would lead out of Queueify's releases once the address is read + [InlineData("https://github.com/PAumedes/Queueify/releases/download/../../../../evil/repo/releases/download/v1.4.0/Queueify-1.4.0-win-x64.exe")] + [InlineData("https://github.com/PAumedes/Queueify/releases/download/%2e%2e/%2e%2e/%2e%2e/%2e%2e/evil/Queueify-1.4.0-win-x64.exe")] + [InlineData("https://github.com/PAumedes/Queueify/releases/download/..\\..\\..\\..\\evil\\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("v1.4.0.1")] // Queueify shows three parts: a fourth would be offered again after updating + [InlineData("v1.4")] + public void Only_three_part_versions_are_offered(string tag) + { + Assert.Null(GitHub().Parse(LatestJson(tag: tag))); + } + + [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 An_answer_in_a_character_set_NET_doesnt_know_still_reads() + { + // GitHub sends UTF-8; a proxy may label it oddly. + var api = new FakeGitHub(HttpStatusCode.OK, LatestJson()) { ContentType = "application/json; charset=utf8" }; + + Assert.Equal("1.4.0", (await GitHub(api).CheckAsync("1.3.0", CancellationToken.None))?.Version); + } + + [Fact] + public async Task Any_other_failure_while_checking_says_so() + { + var api = new FakeGitHub(new InvalidOperationException("Something unexpected")); + + await Assert.ThrowsAsync(() => GitHub(api).CheckAsync("1.3.0", CancellationToken.None)); + } + + [Fact] + public async Task No_answer_in_time_says_so() + { + // HttpClient's own timeout, not the caller cancelling. + var api = new FakeGitHub(new TaskCanceledException("The request was canceled due to the configured HttpClient.Timeout")); + + var ex = await Assert.ThrowsAsync(() => GitHub(api).CheckAsync("1.3.0", CancellationToken.None)); + Assert.Equal(Loc.T("update.timeout"), ex.Message); + } + + [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_file_already_named_like_the_download_is_never_written_into() + { + // In a folder others can add files to, someone could leave one there that they can still change. + var exe = Exe(); + var planted = new FileInfo(exe + ".download"); + File.WriteAllText(planted.FullName, "planted"); + var acl = planted.GetAccessControl(); + var everyone = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null); + acl.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(everyone, System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow)); + planted.SetAccessControl(acl); + + var downloaded = await GitHub(new FakeGitHub(HttpStatusCode.OK, NewExe)).DownloadAsync(Release(), exe, null, CancellationToken.None); + + var rules = new FileInfo(downloaded).GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier)); + Assert.DoesNotContain(rules.Cast(), r => r.IdentityReference == everyone && !r.IsInherited); + Assert.Equal(NewExe, File.ReadAllBytes(downloaded)); + } + + [Theory] + [InlineData("io")] + [InlineData("other")] + public async Task A_download_breaking_off_says_so_and_leaves_nothing(string how) + { + var exe = Exe(); + Exception failure = how == "io" ? new IOException("The connection was reset") : new InvalidOperationException("Something unexpected"); + var api = new FakeGitHub(HttpStatusCode.OK, NewExe) { Body = () => new BrokenStream(NewExe[..5], failure) }; + + await Assert.ThrowsAsync(() => GitHub(api).DownloadAsync(Release(), exe, null, CancellationToken.None)); + + Assert.Equal([exe], Directory.GetFiles(_dir)); + } + + [Fact] + public async Task A_download_that_stops_coming_gives_up() + { + var exe = Exe(); + var api = new FakeGitHub(HttpStatusCode.OK, NewExe) { Body = () => new BrokenStream(NewExe[..5], null) }; + + var ex = await Assert.ThrowsAsync(() => + GitHub(api, stall: TimeSpan.FromMilliseconds(200)).DownloadAsync(Release(), exe, null, CancellationToken.None)); + + Assert.Equal(Loc.T("update.timeout"), ex.Message); + Assert.Equal([exe], Directory.GetFiles(_dir)); + } + + [Fact] + public async Task Cancelling_a_download_is_passed_on_and_leaves_nothing() + { + var exe = Exe(); + var api = new FakeGitHub(HttpStatusCode.OK, NewExe) { Body = () => new BrokenStream(NewExe[..5], null) }; + using var cancel = new CancellationTokenSource(TimeSpan.FromMilliseconds(200)); + + await Assert.ThrowsAnyAsync(() => GitHub(api).DownloadAsync(Release(), exe, null, cancel.Token)); + + Assert.Equal([exe], Directory.GetFiles(_dir)); + } + + [Fact] + public async Task A_download_already_running_in_another_window_isnt_called_a_folder_problem() + { + var exe = Exe(); + using var other = File.Open(exe + ".download", FileMode.CreateNew, FileAccess.Write, FileShare.None); + + var ex = await Assert.ThrowsAsync(() => + GitHub(new FakeGitHub(HttpStatusCode.OK, NewExe)).DownloadAsync(Release(), exe, null, CancellationToken.None)); + + Assert.Equal(Loc.T("update.locked"), ex.Message); + } + + [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([exe], Directory.GetFiles(_dir)); + } + [Fact] + public void The_exe_name_is_never_free_during_an_update() + { + // In a folder others can add files to, a moment without Queueify.exe would let theirs take the name. + // Someone tries to, nonstop, through many updates. + var exe = Exe(); + var stop = false; + var taken = 0; + var squatter = new Thread(() => + { + while (!Volatile.Read(ref stop)) + { + try { using var planted = new FileStream(exe, FileMode.CreateNew); taken++; } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { } + } + }); + squatter.Start(); + try + { + for (int i = 0; i < 200 && taken == 0; i++) + { + if (!File.Exists(exe)) break; + Updater.Replace(exe, Downloaded()); + } + } + catch (UpdateException) + { + // The old code's rollback failing is the same story. + } + finally + { + Volatile.Write(ref stop, true); + squatter.Join(); + } + + Assert.Equal(0, taken); + Assert.Equal(NewExe, File.ReadAllBytes(exe)); + } + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern bool CreateHardLink(string link, string existing, IntPtr security); + + [Fact] + public void A_file_left_next_to_the_exe_is_never_written_into() + { + // In a folder others can add files to, a name like Queueify.exe.old could be a link to one of the + // user's own files: nothing writes through such a name. + var exe = Exe(); + var victim = Path.Combine(_dir, "queueify.db"); + File.WriteAllText(victim, "keep"); + Assert.True(CreateHardLink(exe + ".old", victim, IntPtr.Zero)); + + Updater.Replace(exe, Downloaded()); + Updater.RemoveLeftovers(exe); + + Assert.Equal("keep", File.ReadAllText(victim)); + Assert.False(File.GetAttributes(victim).HasFlag(FileAttributes.ReadOnly)); + } + + [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)); + } + + [Fact] + public void When_the_old_exe_is_in_use_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)); + Assert.False(File.Exists(downloaded)); + } + + [Fact] + public void A_read_only_exe_is_updated_and_stays_read_only_if_it_cant_be() + { + var exe = Exe(); + File.SetAttributes(exe, FileAttributes.ReadOnly); + + Updater.Replace(exe, Downloaded()); + Assert.Equal(NewExe, File.ReadAllBytes(exe)); + + File.SetAttributes(exe, FileAttributes.ReadOnly); + var downloaded = Downloaded(); + using (File.Open(downloaded, FileMode.Open, FileAccess.Read, FileShare.Read)) + Assert.Throws(() => Updater.Replace(exe, downloaded)); + Assert.True(File.GetAttributes(exe).HasFlag(FileAttributes.ReadOnly)); + File.SetAttributes(exe, FileAttributes.Normal); + } + + [Fact] + public void A_stray_download_is_removed_next_time() + { + var exe = Exe(); + File.WriteAllText(exe + ".download", "half"); + + Updater.RemoveLeftovers(exe); + + Assert.Equal([exe], Directory.GetFiles(_dir)); + } + + [Fact] + public void A_download_still_in_use_waits_for_another_time() + { + // Another Queueify window is downloading it. + var exe = Exe(); + using var other = File.Open(exe + ".download", FileMode.CreateNew, FileAccess.Write, FileShare.None); + + Updater.RemoveLeftovers(exe); + + Assert.True(File.Exists(exe + ".download")); + } + // ── 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); + } + + /// Gives some bytes, then fails with , or never answers again when it's null. + private sealed class BrokenStream(byte[] first, Exception? failure) : Stream + { + private bool _sent; + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken ct = default) + { + if (!_sent) + { + _sent = true; + first.CopyTo(buffer); + return first.Length; + } + if (failure != null) throw failure; + await Task.Delay(Timeout.Infinite, ct); + return 0; + } + + public override int Read(byte[] buffer, int offset, int count) => ReadAsync(buffer.AsMemory(offset, count)).AsTask().GetAwaiter().GetResult(); + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => throw new NotSupportedException(); + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + public override void Flush() { } + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } + + 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; } + public string? ContentType { get; init; } + public Func? Body { get; init; } + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct) + { + Requests.Add(request); + if (_failure != null) throw _failure; + HttpContent content = Body != null ? new StreamContent(Body()) : new ByteArrayContent(_body); + if (ClaimedLength is { } length) content.Headers.ContentLength = length; + if (ContentType != null) content.Headers.TryAddWithoutValidation("Content-Type", ContentType); + return Task.FromResult(new HttpResponseMessage(_status) { Content = content }); + } + } +} diff --git a/Queueify/MainWindow.xaml b/Queueify/MainWindow.xaml index fdfdcce..89f3633 100644 --- a/Queueify/MainWindow.xaml +++ b/Queueify/MainWindow.xaml @@ -489,6 +489,10 @@ + + + + @@ -498,6 +502,10 @@ Style="{StaticResource CaptionTextBlockStyle}" Foreground="{ThemeResource TextFillColorSecondaryBrush}" /> + + @@ -642,6 +650,7 @@ + @@ -665,9 +674,13 @@ +