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 @@
+
+
@@ -871,6 +884,28 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Queueify/MainWindow.xaml.cs b/Queueify/MainWindow.xaml.cs
index af8e958..a086e01 100644
--- a/Queueify/MainWindow.xaml.cs
+++ b/Queueify/MainWindow.xaml.cs
@@ -3,6 +3,7 @@
using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Automation;
+using Microsoft.UI.Xaml.Automation.Peers;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Media;
@@ -33,6 +34,8 @@ public sealed partial class MainWindow : Window
private readonly SpotifyCatalog _spotify;
private readonly TidalCatalog _tidal;
private readonly CloudSync _cloud;
+ private readonly Updater _updater = new(Http, UpdateSource.For(Environment.GetEnvironmentVariable("QUEUEIFY_UPDATE_SERVER")));
+ private bool _updating;
private readonly DispatcherQueueTimer _searchDebounce;
private readonly DispatcherQueueTimer _toastTimer;
@@ -57,7 +60,10 @@ public MainWindow()
SetTitleBar(AppTitleBar);
AppWindow.SetIcon(Path.Combine(AppContext.BaseDirectory, "Assets", "Queueify.ico"));
if (AppData.StarterExe is { } starter)
+ {
TaskbarIdentity.PinTo(WinRT.Interop.WindowNative.GetWindowHandle(this), starter);
+ Updater.RemoveLeftovers(starter);
+ }
_ui = UiState.Load();
RestoreWindow();
@@ -112,6 +118,7 @@ public MainWindow()
{
SearchBox.Focus(FocusState.Programmatic);
_ = SyncNowAsync();
+ if (_ui.CheckForUpdates) _ = CheckForUpdatesAsync(quiet: true);
if (!_ui.TourSeen) DispatcherQueue.TryEnqueue(DispatcherQueuePriority.Low, () => ShowTourStep(0));
};
}
@@ -1076,28 +1083,67 @@ private async Task InstallOcrLanguageAsync(string tag, Action RestartApp();
+ restart.Click += (_, _) => _ = RestartAppAsync();
return restart;
}
- /// Starts a fresh copy and closes this one (which saves the window and layout as usual).
- private void RestartApp()
+ ///
+ /// Starts a fresh copy and closes this one (which saves the window and layout as usual); false when it
+ /// couldn't. Through the download's starter, this window stays until the starter has unpacked the new
+ /// copy and started it, so there's never a moment without Queueify on screen.
+ ///
+ private async Task RestartAppAsync()
{
+ // A second click while the new copy starts would start another one.
+ if (_restarting) return true;
+ _restarting = true;
// Saved first, so the new copy opens where this one was.
SaveWindow();
+ System.Diagnostics.Process? started;
+ var running = QueueifyProcesses();
try
{
// Through the download's starter when there is one, so the new copy knows it too.
- System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(AppData.StarterExe ?? Environment.ProcessPath!) { UseShellExecute = false });
+ started = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(AppData.StarterExe ?? Environment.ProcessPath!) { UseShellExecute = false });
}
catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException)
{
ShowToast(Loc.F("app.restart_failed", ex.Message), severity: InfoBarSeverity.Warning);
- return;
+ _restarting = false;
+ return false;
+ }
+ using (started)
+ {
+ if (started != null && AppData.StarterExe != null)
+ {
+ try
+ {
+ using var limit = new CancellationTokenSource(TimeSpan.FromMinutes(2));
+ await started.WaitForExitAsync(limit.Token);
+ // The starter showed its own message about what went wrong.
+ if (started.ExitCode != 0)
+ {
+ _restarting = false;
+ return false;
+ }
+ // The starter is done once the new copy runs; its window takes a moment more.
+ while (!NewQueueifyWindow(running))
+ await Task.Delay(200, limit.Token);
+ }
+ catch (OperationCanceledException)
+ {
+ // Two minutes without a new window (the starter may be showing an error): this one stays.
+ _restarting = false;
+ return false;
+ }
+ }
}
Close();
+ return true;
}
+ private bool _restarting;
+
// ───────────────────────── Sync between PCs ─────────────────────────
private void ScheduleSync()
@@ -1459,6 +1505,178 @@ private void FillHelp()
AboutDataPath.Text = AppData.Folder;
}
+ // ───────────────────────── Updates ─────────────────────────
+
+ private bool _checkingUpdates;
+ /// Asked from About: the running check shows its result there.
+ private bool _reportCheck;
+ private CancellationTokenSource? _download;
+
+ private async void OnCheckForUpdates(object sender, RoutedEventArgs e) => await CheckForUpdatesAsync(quiet: false);
+
+ ///
+ /// Asks GitHub for a newer version and offers it under the page title. Quiet (at start) shows nothing
+ /// unless there is one; from About, the result shows under the button.
+ ///
+ private async Task CheckForUpdatesAsync(bool quiet)
+ {
+ // One check at a time. Asked from About while the quiet one at start runs, that one reports there
+ // when it's done. The button stays enabled, so keyboard focus stays on it.
+ if (!quiet)
+ {
+ _reportCheck = true;
+ ShowUpdateStatus(Loc.T("update.checking"));
+ }
+ if (_checkingUpdates) return;
+ _checkingUpdates = true;
+ try
+ {
+ var release = await _updater.CheckAsync(AppInfo.Version, CancellationToken.None);
+ if (release != null && !_updating) OfferUpdate(release);
+ if (_reportCheck) ShowUpdateStatus(release != null ? Loc.F("update.available", release.Version) : Loc.T("update.latest"));
+ }
+ catch (Exception ex)
+ {
+ // UpdateException carries its own message; anything else is a bug, still not worth a crash.
+ if (_reportCheck) ShowUpdateStatus(ex is UpdateException ? ex.Message : Loc.F("update.failed", ex.Message));
+ }
+ finally
+ {
+ _checkingUpdates = false;
+ _reportCheck = false;
+ }
+ }
+
+ private void ShowUpdateStatus(string text)
+ {
+ UpdateStatus.Text = text;
+ // At the bottom of Help, maybe below the window's edge; and said aloud for screen readers.
+ UpdateStatus.StartBringIntoView();
+ Announce(UpdateStatus, text);
+ }
+
+ private void OfferUpdate(AppRelease release)
+ {
+ var whatsNew = new HyperlinkButton { Content = Loc.T("update.whats_new"), Padding = new Thickness(0, 2, 0, 2), Margin = new Thickness(0, 0, 0, 8) };
+ whatsNew.Click += (_, _) => OpenInBrowser(release.Page);
+ ShowUpdateBar(InfoBarSeverity.Informational, Loc.F("update.available", release.Version), InstallButton(release, "update.install"), whatsNew, closable: true);
+ }
+
+ private Button InstallButton(AppRelease release, string text)
+ {
+ var install = new Button { Content = Loc.T(text), Style = (Style)Application.Current.Resources["AccentButtonStyle"] };
+ AutomationProperties.SetAutomationId(install, "InstallUpdateButton");
+ install.Click += (_, _) => _ = InstallUpdateAsync(release);
+ return install;
+ }
+
+ /// Downloads the new exe, checks it, puts it in place of this one and restarts through it.
+ private async Task InstallUpdateAsync(AppRelease release)
+ {
+ if (_updating) return;
+ if (AppData.StarterExe is not { } exe)
+ {
+ // Running from a build folder, not a download: nothing to replace.
+ ShowUpdateProblem(Loc.T("update.manual"), release, retry: false);
+ return;
+ }
+ _updating = true;
+ var message = Loc.F("update.downloading", release.Version);
+ var bar = new ProgressBar { Maximum = 1, Margin = new Thickness(0, 0, 0, 12) };
+ AutomationProperties.SetName(bar, message);
+ // No overall time limit: a slow download that keeps coming is fine, a stalled one gives up, and
+ // Cancel stops either.
+ var cancel = new Button { Content = Loc.T("update.cancel") };
+ cancel.Click += (_, _) => _download?.Cancel();
+ ShowUpdateBar(InfoBarSeverity.Informational, message, cancel, bar, closable: false);
+ _download = new CancellationTokenSource();
+ try
+ {
+ var downloaded = await _updater.DownloadAsync(release, exe, new Progress(v => bar.Value = v), _download.Token);
+ Updater.Replace(exe, downloaded);
+ }
+ catch (OperationCanceledException) when (_download.IsCancellationRequested)
+ {
+ _updating = false;
+ OfferUpdate(release);
+ return;
+ }
+ catch (Exception ex)
+ {
+ _updating = false;
+ ShowUpdateProblem(ex is UpdateException ? ex.Message : Loc.F("update.failed", ex.Message), release, retry: true);
+ return;
+ }
+ finally
+ {
+ _download.Dispose();
+ _download = null;
+ }
+ // The new version unpacks before its window opens: this one says so and stays until then.
+ ShowUpdateBar(InfoBarSeverity.Informational, Loc.F("update.restarting", release.Version), null,
+ new ProgressBar { IsIndeterminate = true, Margin = new Thickness(0, 0, 0, 12) }, closable: false);
+ // The new exe is in place either way; if it can't be started now, the next start uses it. _updating
+ // stays set, so it isn't downloaded again.
+ if (!await RestartAppAsync())
+ ShowUpdateBar(InfoBarSeverity.Warning, Loc.F("update.restart_failed", release.Version), null, null, closable: true);
+ }
+
+ private static HashSet QueueifyProcesses()
+ {
+ var ids = new HashSet();
+ foreach (var p in System.Diagnostics.Process.GetProcessesByName("Queueify"))
+ using (p) ids.Add(p.Id);
+ return ids;
+ }
+
+ /// A Queueify window from a process that wasn't running before (another copy open already doesn't count).
+ private static bool NewQueueifyWindow(HashSet before)
+ {
+ var found = false;
+ foreach (var p in System.Diagnostics.Process.GetProcessesByName("Queueify"))
+ using (p)
+ found |= !before.Contains(p.Id) && p.MainWindowHandle != 0;
+ return found;
+ }
+
+ private void ShowUpdateProblem(string message, AppRelease release, bool retry)
+ {
+ var page = new HyperlinkButton { Content = Loc.T("update.page"), Padding = new Thickness(0, 2, 0, 2), Margin = new Thickness(0, 0, 0, 8) };
+ page.Click += (_, _) => OpenInBrowser(release.Page);
+ ShowUpdateBar(InfoBarSeverity.Warning, message, retry ? InstallButton(release, "update.retry") : null, page, closable: true);
+ }
+
+ private void ShowUpdateBar(InfoBarSeverity severity, string message, Microsoft.UI.Xaml.Controls.Primitives.ButtonBase? action, UIElement? content, bool closable)
+ {
+ // Keyboard focus in the bar (on the button just pressed) moves to the new button (Cancel, Try again)
+ // instead of falling into the page when that button goes away. Anywhere else, it stays: someone
+ // typing in the search box keeps typing there, and a key never presses Try again by surprise.
+ var focusInBar = IsInside(FocusManager.GetFocusedElement(Root.XamlRoot) as DependencyObject, UpdateBar);
+ var wasOpen = UpdateBar.IsOpen;
+ UpdateBar.Severity = severity;
+ UpdateBar.Message = message;
+ UpdateBar.ActionButton = action;
+ UpdateBar.Content = content;
+ UpdateBar.IsClosable = closable;
+ UpdateBar.IsOpen = true;
+ // Opening, the bar announces itself; later states are said here.
+ if (wasOpen) Announce(UpdateBar, message);
+ if (focusInBar && action != null) action.Loaded += (_, _) => action.Focus(FocusState.Keyboard);
+ }
+
+ private static bool IsInside(DependencyObject? element, DependencyObject container)
+ {
+ for (; element != null; element = VisualTreeHelper.GetParent(element))
+ if (element == container) return true;
+ return false;
+ }
+
+ private static void Announce(UIElement element, string text) =>
+ (FrameworkElementAutomationPeer.FromElement(element) ?? FrameworkElementAutomationPeer.CreatePeerForElement(element))
+ ?.RaiseNotificationEvent(AutomationNotificationKind.Other, AutomationNotificationProcessing.ImportantMostRecent, text, "QueueifyUpdate");
+ private static void OpenInBrowser(Uri page) =>
+ System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(page.AbsoluteUri) { UseShellExecute = true });
+
private void OnOpenDataFolder(object sender, RoutedEventArgs e)
{
Directory.CreateDirectory(AppData.Folder);
@@ -1605,6 +1823,7 @@ private void FillSettingsPage(bool keepTypedKeys = false)
LanguageBox.SelectedItem = LanguageBox.Items.OfType().FirstOrDefault(i => (string)i.Tag == _ui.Language)
?? LanguageBox.Items[0];
UpdateLanguageRestart();
+ UpdateCheckToggle.IsOn = _ui.CheckForUpdates;
SettingsDataPath.Text = AppData.Folder;
FillOcrSettings();
UpdateServiceCards();
@@ -1776,6 +1995,13 @@ private void OnCountryChanged(object sender, SelectionChangedEventArgs e)
CommitSettingsEdit(edited);
}
+ private void OnUpdateCheckToggled(object sender, RoutedEventArgs e)
+ {
+ if (_fillingSettings) return;
+ _ui.CheckForUpdates = UpdateCheckToggle.IsOn;
+ _ui.Save();
+ }
+
private void OnThemeChanged(object sender, SelectionChangedEventArgs e)
{
if (_fillingSettings || ThemeBox.SelectedItem is not ComboBoxItem { Tag: string theme }) return;
diff --git a/README.md b/README.md
index 38a5edf..c604e88 100644
--- a/README.md
+++ b/README.md
@@ -29,8 +29,13 @@ warn the first time because the app isn't signed: *More info → Run anyway*. Th
version takes a moment longer: the exe unpacks the app into `%LOCALAPPDATA%\Queueify\app` (about 70 MB)
and runs it from there. The copy of the previous version is removed by itself.
+**Updates**: when a new version is out, a bar at the top of the window offers it. *Update and restart*
+downloads it, checks it against the release and puts it in place of your exe, under the same name. Help →
+About → *Check for updates* asks right away; Settings → Updates turns off the check at start. (From 1.3.0 or
+earlier, download 1.4.0 by hand once.)
+
Your queue, keys and layout live in `%LOCALAPPDATA%\Queueify` (Help → *Open data folder*). To move to a new
-version, replace the exe. Pinned to the taskbar, Queueify starts the exe you downloaded rather than its
+version by hand, replace the exe. Pinned to the taskbar, Queueify starts the exe you downloaded rather than its
unpacked copy; give the exe one name (say `Queueify.exe`) and keep it when you update, so the pin keeps working.
**Portable mode**: if there's a `Data` folder next to the exe that is empty or has Queueify's files in it,
diff --git a/SECURITY.md b/SECURITY.md
index 0899432..f2ad104 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -23,7 +23,8 @@ Queueify runs with the user's rights on their own PC. It has no servers of its o
| Elevated OCR install (`Add-WindowsCapability`) | Injection into a script that runs as administrator | Only allow-listed language tags reach it; the log path (from the user's profile) is passed Base64-encoded; tests run the script through PowerShell's parser. |
| Cover addresses (from the services and from other PCs through sync) | A file or network path reading local files or sending the Windows login to another machine | Only `http` and `https` addresses are loaded (`CoverUrls`, tested). |
| The app's unpacked copy (`%LOCALAPPDATA%\Queueify\app`) | Changed files run as Queueify | Only the user (or an admin) can write there, as with any per-user app. The starter is native code and loads its imports from System32 only; the app's working folder is its own. A version's folder is used only once fully unpacked and checked against the SHA-256 in the download. |
+| Updates (the exe itself) | A tampered or broken download replacing Queueify | Offered only from Queueify's GitHub releases over HTTPS; the download must match the SHA-256 GitHub lists for it, or it's thrown away and the exe left as it was; it's always written to a new file, never into one someone left next to the exe; installing waits for the user's click ([ADR-0009](docs/adr/0009-update-from-github-releases.md)). Not covered: a release published from a taken-over maintainer account (the exe isn't signed). |
| Clipboard | Leaking data | Written only on explicit "Copy" clicks (sync code, security rules); read only on Ctrl+V or Paste. |
-| Network | Exfiltration | Only Spotify, Tidal, the user's own Firebase project and Windows Update. No telemetry. |
+| Network | Exfiltration | Only Spotify, Tidal, the user's own Firebase project, Windows Update and GitHub (the update check at each start: GitHub sees the address and that Queueify is starting, nothing else; it can be turned off). No telemetry. |
Out of scope: a compromised PC or user account, and the security of Spotify, Tidal and Google's services.
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index c2ff3f6..2d2cf73 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -22,6 +22,7 @@ flowchart LR
MW --> S & M & CAT & CS & O & L & ST
CAT -->|HTTPS| SP[(Spotify Web API)] & TI[(Tidal Open API)]
CS -->|HTTPS REST| FS[(Your Firestore)]
+ MW --> U[Updater] -->|HTTPS| GH[(GitHub releases)]
O --> WOCR[(Windows.Media.Ocr)]
```
@@ -49,6 +50,7 @@ flowchart LR
| `Loc`, `Strings.En/Es` | All texts, the app language and the formats that go with it. |
| `AppData`, `UiState` | Where the data folder is; `settings.json` (synced settings, keys) and `ui.json` (per-PC layout, theme, language). |
| `Countries` | The countries where both services work, named in the app language. |
+| `Updater` | The latest GitHub release: whether it's newer, downloading and checking its exe, swapping it in ([ADR-0009](adr/0009-update-from-github-releases.md)). |
## Data
diff --git a/docs/RELEASING.md b/docs/RELEASING.md
index 43c9d7f..a23bd45 100644
--- a/docs/RELEASING.md
+++ b/docs/RELEASING.md
@@ -31,6 +31,10 @@ the About section shows it.
directly (the branch rule lets admins bypass it), so the release commit and its tag arrive together.
5. The release workflow publishes the exe. Download it once and run it from an empty folder.
+The app updates itself from the latest release ([ADR-0009](adr/0009-update-from-github-releases.md)): it
+looks for the asset `Queueify-X.Y.Z-win-x64.exe` in `https://github.com/PAumedes/Queueify/releases/download/`
+and its SHA-256 digest. Never rename the asset or publish it elsewhere; pre-releases are never offered.
+
If the security rules (`tools/firestore.rules`) changed, say in the release notes that users must copy
and publish them again (Sync → Copy security rules).
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 9685002..be0c89f 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -8,6 +8,7 @@
| Sync (inside the unit suite) | Two simulated PCs against the Firestore emulator, and the security rules | with `QUEUEIFY_FIRESTORE_EMULATOR`; CI |
| UI (`tests\ui\Queueify.UiTests.ps1`) | The published app through UI Automation: tour, pages, panel, settings, language restart | locally, before merging UI changes |
| Sync UI (`tests\ui\Queueify.SyncUiTests.ps1`) | Connecting Sync from the dialog, an album reaching Firestore | locally, with the emulator |
+| Update UI (`tests\ui\Queueify.UpdateUiTests.ps1`) | A copy of the download updating itself from a release served on this PC: offer, refusing a bad download, the setting, the swap and restart | locally |
| Release tool (`tests\tools\Release.Tests.ps1`) | Version bump, changelog and notes | locally; CI |
The OCR test reads `Queueify.Tests\TestData\magazine-page.png`. It's skipped on machines with no text
@@ -25,6 +26,7 @@ dotnet test --project Queueify.Tests # now with the sync tests
tools\package.ps1 # dist\Queueify\Queueify.exe (the download, ~5 min)
powershell -ExecutionPolicy Bypass -File tests\ui\Queueify.UiTests.ps1 -Exe dist\Queueify\Queueify.exe
powershell -ExecutionPolicy Bypass -File tests\ui\Queueify.SyncUiTests.ps1 -Exe dist\Queueify\Queueify.exe
+powershell -ExecutionPolicy Bypass -File tests\ui\Queueify.UpdateUiTests.ps1 -Exe dist\Queueify\Queueify.exe
```
The UI tests run the download itself, in portable mode: they move the `Data` folder next to the exe aside
diff --git a/docs/adr/0009-update-from-github-releases.md b/docs/adr/0009-update-from-github-releases.md
new file mode 100644
index 0000000..ea4debf
--- /dev/null
+++ b/docs/adr/0009-update-from-github-releases.md
@@ -0,0 +1,54 @@
+# ADR-0009: Update from GitHub releases, inside the app
+
+- Status: Accepted
+- Date: 2026-10-14
+
+## Context
+
+Updating meant noticing a new release, downloading it and replacing the exe by hand, keeping its name so a
+taskbar pin still works. The download is a single exe ([ADR-0008](0008-native-aot-and-a-starter-exe.md)),
+and while the app runs nothing has that exe open: the starter unpacks the app, starts it and exits.
+
+## Decision
+
+- At each start (unless turned off in Settings → Updates) and from **Help → About → Check for updates**, the
+ app asks GitHub's API for the latest release (`api.github.com/repos/PAumedes/Queueify/releases/latest`, which
+ skips drafts and pre-releases). It's offered only when its version is higher and it has an asset named
+ `Queueify--win-x64.exe` under `https://github.com/PAumedes/Queueify/releases/download/` with a
+ `sha256:` digest (GitHub computes one for every release asset).
+- The offer is a bar under the page title, in a row of its own. Nothing is downloaded until the user clicks
+ **Update and restart**. Then the exe is downloaded next to the one the user started, always into a new
+ file (`.download`; a file already there is removed first, and if it can't be, nothing is updated; at
+ most 256 MB; a download that sends nothing for 30 s gives up, a slow one doesn't, and **Cancel** stops
+ either), and its SHA-256 compared with GitHub's. The new exe then replaces the old one in one step
+ (MoveFileEx with REPLACE_EXISTING): the name is never free for a file someone else drops in the folder,
+ no other name next to the exe is written (one could be a link to the user's files), and if it fails the
+ exe is as it was. There's no backup copy: the old version is always on the releases page. A read-only exe
+ is updated too.
+- The app then restarts through the new exe, and its window stays (saying so) until the new version's
+ window is open: the first start of a version unpacks for a few seconds.
+- A failed update says why in plain words and offers **Try again** and the release page.
+- When the folder can't be written to, or the app wasn't started from a download (a build folder), the bar
+ offers the release page instead.
+- `QUEUEIFY_UPDATE_SERVER` points the check at a server on this PC (loopback `http` only, anything else is
+ ignored), for the UI tests (`tests\ui\Queueify.UpdateUiTests.ps1`).
+
+## Consequences
+
+- One request to GitHub per start: GitHub sees the address and that Queueify is starting, nothing else;
+ the setting turns it off. GitHub allows 60 unauthenticated requests an hour per address, plenty for a few
+ starts a day.
+- A closed offer comes back at the next start; there's no "skip this version", only the setting.
+- The release's asset name and its digest are now a contract: renaming the asset, or publishing it somewhere
+ else, breaks updating for everyone on older versions ([RELEASING.md](../RELEASING.md)).
+- The trust is GitHub's: the digest comes from the same API as the download link, over HTTPS. It catches a
+ broken or tampered download, not a release published by someone who took over the maintainer's account.
+ Signing the exe would cover that (see ADR-0008 about where a signature would go).
+- The downloaded exe has no "downloaded from the internet" mark, so SmartScreen doesn't ask again.
+- 1.3.0 and earlier can't update themselves: 1.4.0 has to be downloaded once by hand.
+
+## Alternatives considered
+
+- **A separate updater exe**: not needed, since the exe isn't in use while the app runs.
+- **Only a notice with a link**: simpler, but leaves the rename-and-keep-the-name dance to the user.
+- **Checking once a day**: more state to keep for little saving.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 84ceee6..b8c7e1d 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -13,3 +13,4 @@ old one and mark the old one `Superseded by ADR-NNNN`. Start from [`0000-templat
| [0006](0006-release-from-conventional-commits.md) | Releases and changelog from Conventional Commits | Accepted |
| [0007](0007-single-trimmed-exe.md) | One trimmed exe as the download | Packaging superseded by 0008 |
| [0008](0008-native-aot-and-a-starter-exe.md) | Native AOT and a starter exe | Accepted |
+| [0009](0009-update-from-github-releases.md) | Update from GitHub releases, inside the app | Accepted |
diff --git a/tests/ui/Queueify.UpdateUiTests.ps1 b/tests/ui/Queueify.UpdateUiTests.ps1
new file mode 100644
index 0000000..db314ca
--- /dev/null
+++ b/tests/ui/Queueify.UpdateUiTests.ps1
@@ -0,0 +1,199 @@
+# UI tests for updating Queueify from inside the app, driven through Windows UI Automation.
+#
+# powershell -ExecutionPolicy Bypass -File tests\ui\Queueify.UpdateUiTests.ps1 -Exe
+#
+# Never touches the exe under test or any real data: a copy of the exe runs from a scratch folder with a
+# scratch LOCALAPPDATA, and a small web server on this PC plays GitHub (QUEUEIFY_UPDATE_SERVER), offering
+# that same exe as version 99.0.0. Prints PASS/FAIL per check and exits with the number of failures.
+param([Parameter(Mandatory)] [string]$Exe)
+$Exe = (Resolve-Path $Exe).Path
+
+Add-Type -AssemblyName UIAutomationClient, UIAutomationTypes
+$A = [System.Windows.Automation.AutomationElement]
+$Tree = [System.Windows.Automation.TreeScope]
+$Cond = [System.Windows.Automation.Condition]
+$script:failures = 0
+
+function Check([bool]$ok, [string]$what) {
+ if (-not $ok) { $script:failures++ }
+ '{0} {1}' -f $(if ($ok) { 'PASS' } else { 'FAIL' }), $what
+}
+
+$scratch = Join-Path ([System.IO.Path]::GetTempPath()) ("queueify-updatetest-" + [guid]::NewGuid().ToString('N'))
+$folder = Join-Path $scratch 'Apps'
+$copy = Join-Path $folder 'Queueify.exe'
+$env:LOCALAPPDATA = Join-Path $scratch 'local'
+$appCache = Join-Path $env:LOCALAPPDATA 'Queueify\app'
+New-Item -ItemType Directory -Force $folder, (Join-Path $env:LOCALAPPDATA 'Queueify') | Out-Null
+Copy-Item $Exe $copy
+# English texts for the checks, and no quick tour in the way.
+'{ "Language": "en", "TourSeen": true }' | Set-Content -Encoding UTF8 (Join-Path $env:LOCALAPPDATA 'Queueify\ui.json')
+
+function Get-AppProcess {
+ Get-Process -ErrorAction SilentlyContinue | Where-Object { $_.Path -and $_.Path.StartsWith("$appCache\", [StringComparison]::OrdinalIgnoreCase) }
+}
+
+# Waits for a Queueify window that wasn't there before.
+function Wait-App([int[]]$before) {
+ $p = $null
+ for ($i = 0; $i -lt 60 -and -not $p; $i++) {
+ Start-Sleep -Milliseconds 500
+ $p = Get-AppProcess | Where-Object { $_.Id -notin $before -and $_.MainWindowHandle -ne 0 } | Select-Object -First 1
+ }
+ Start-Sleep 3
+ $script:proc = $p
+ $script:root = if ($p) { $A::FromHandle($p.MainWindowHandle) } else { $null }
+}
+
+function Start-App { Start-Process $copy | Out-Null; Wait-App @() }
+
+function Stop-App {
+ Get-AppProcess | ForEach-Object { $_.Kill(); $_.WaitForExit(10000) | Out-Null }
+}
+
+function All { $script:root.FindAll($Tree::Descendants, $Cond::TrueCondition) }
+function Find([string]$name, [string]$type = '*') {
+ All | Where-Object { $_.Current.Name -like $name -and $_.Current.ControlType.ProgrammaticName -like "ControlType.$type" } | Select-Object -First 1
+}
+function Select-Item($el) { $el.GetCurrentPattern([System.Windows.Automation.SelectionItemPattern]::Pattern).Select(); Start-Sleep -Milliseconds 800 }
+function FindId([string]$id) { All | Where-Object { $_.Current.AutomationId -eq $id } | Select-Object -First 1 }
+function Invoke($el) { $el.GetCurrentPattern([System.Windows.Automation.InvokePattern]::Pattern).Invoke(); Start-Sleep -Milliseconds 800 }
+function Wait-Find([string]$name, [int]$seconds = 15) {
+ for ($i = 0; $i -lt $seconds * 2; $i++) { $el = Find $name; if ($el) { return $el }; Start-Sleep -Milliseconds 500 }
+ $null
+}
+
+# ── A pretend GitHub on this PC: path -> response, changed between the checks ──
+$routes = [hashtable]::Synchronized(@{})
+$listener = [System.Net.Sockets.TcpListener]::new([System.Net.IPAddress]::Loopback, 0)
+$listener.Start()
+$server = "http://127.0.0.1:$($listener.LocalEndpoint.Port)/"
+$serve = [powershell]::Create()
+$serve.AddScript({
+ param($listener, $routes)
+ while ($true) {
+ $client = $listener.AcceptTcpClient()
+ try {
+ $stream = $client.GetStream()
+ $reader = New-Object System.IO.StreamReader($stream, [System.Text.Encoding]::ASCII, $false, 1024, $true)
+ $path = ($reader.ReadLine() -split ' ')[1]
+ while ($reader.ReadLine()) { }
+ $r = $routes[$path]
+ if ($r -and $r.Delay) { Start-Sleep -Milliseconds $r.Delay }
+ $status = if ($r -and $r.Status) { $r.Status } elseif ($r) { '200 OK' } else { '404 Not Found' }
+ $body = if ($r) { $r.Body } else { [byte[]]@() }
+ $type = if ($r) { $r.Type } else { 'text/plain' }
+ $head = [System.Text.Encoding]::ASCII.GetBytes("HTTP/1.1 $status`r`nContent-Type: $type`r`nContent-Length: $($body.Length)`r`nConnection: close`r`n`r`n")
+ $stream.Write($head, 0, $head.Length)
+ $stream.Write($body, 0, $body.Length)
+ $stream.Flush()
+ }
+ catch { }
+ finally { $client.Close() }
+ }
+}).AddArgument($listener).AddArgument($routes) | Out-Null
+$serving = $serve.BeginInvoke()
+$env:QUEUEIFY_UPDATE_SERVER = $server
+
+$newExe = [System.IO.File]::ReadAllBytes($Exe)
+$sha256 = (Get-FileHash $Exe -Algorithm SHA256).Hash.ToLowerInvariant()
+function Offer([string]$version, [string]$digest) {
+ $name = "Queueify-$version-win-x64.exe"
+ $json = @"
+{ "tag_name": "v$version", "html_url": "${server}page", "draft": false, "prerelease": false,
+ "assets": [ { "name": "$name", "digest": "sha256:$digest", "browser_download_url": "$server$name" } ] }
+"@
+ $routes['/latest'] = @{ Type = 'application/json'; Body = [System.Text.Encoding]::UTF8.GetBytes($json) }
+ $routes["/$name"] = @{ Type = 'application/octet-stream'; Body = $newExe }
+}
+
+try {
+
+# ── The offer never squeezes the page: a narrow window with the panel open (1.4.0's first try put the bar
+# beside the title, which then wrapped a letter per line) ──
+'{ "Language": "en", "TourSeen": true, "PaneVisible": true, "WindowBounds": [50, 50, 1100, 700] }' | Set-Content -Encoding UTF8 (Join-Path $env:LOCALAPPDATA 'Queueify\ui.json')
+Offer '99.0.0' ('0' * 64)
+Start-App
+Check ($null -ne $script:root) 'Queueify starts from the copy'
+Check ($null -ne (Wait-Find '*new version is out: Queueify 99.0.0*')) 'a newer release is offered at the start'
+$title = (FindId 'PageTitle').Current.BoundingRectangle
+Check (-not $title.IsEmpty -and $title.Height -lt 60 -and $title.Width -gt 100) "the page title keeps its line beside the offer ($($title.Width) x $($title.Height))"
+Check ((Find 'Find an album' 'Edit').Current.HasKeyboardFocus) 'the offer leaves the keyboard in the search box'
+
+# ── A download that doesn't match the release is refused, the exe stays, and it can be tried again ──
+$stamp = (Get-Item $copy).LastWriteTimeUtc
+# From the keyboard: focus on the button, so it can follow to the bar's next one.
+(FindId 'InstallUpdateButton').SetFocus()
+Invoke (FindId 'InstallUpdateButton')
+Check ($null -ne (Wait-Find "*doesn't match the release*")) 'a download that does not match is refused'
+Check (((Get-Item $copy).LastWriteTimeUtc -eq $stamp) -and -not (Test-Path "$copy.download") -and -not (Test-Path "$copy.old")) 'the exe is left as it was'
+Check ($null -ne (Find 'Release page')) 'the release page is offered too'
+$retry = FindId 'InstallUpdateButton'
+Check ($null -ne $retry -and $retry.Current.Name -eq 'Try again' -and $retry.Current.HasKeyboardFocus) 'Try again is offered, with the keyboard on it'
+
+Stop-App
+
+# ── A download that fails can be tried again; then the new exe takes the old one's place, and Queueify
+# restarts through it without a moment with no window ──
+Offer '99.0.0' $sha256
+# Slow to fail, so there's time to go back to adding albums meanwhile.
+$routes['/Queueify-99.0.0-win-x64.exe'] = @{ Status = '404 Not Found'; Delay = 3000; Type = 'text/plain'; Body = [byte[]]@() }
+Start-App
+Invoke (FindId 'InstallUpdateButton')
+(Find 'Find an album' 'Edit').SetFocus()
+Check ($null -ne (Wait-Find '*GitHub answered with an error (404)*')) 'a failed download says so'
+Check ((Find 'Find an album' 'Edit').Current.HasKeyboardFocus) 'a failure doesn''t take the keyboard from the search box'
+Offer '99.0.0' $sha256
+[System.IO.File]::SetLastWriteTimeUtc($copy, [datetime]'2001-01-01')
+$before = @(Get-AppProcess | ForEach-Object Id)
+Invoke (FindId 'InstallUpdateButton')
+$gap = $false
+for ($i = 0; $i -lt 300; $i++) {
+ $windows = @(Get-AppProcess | Where-Object { $_.MainWindowHandle -ne 0 })
+ if ($windows.Count -eq 0) { $gap = $true }
+ if ($windows | Where-Object { $_.Id -notin $before }) { break }
+ Start-Sleep -Milliseconds 100
+}
+Wait-App $before
+Check ($null -ne $script:root) 'Queueify restarts after updating'
+Check (-not $gap) 'a Queueify window is on screen the whole time'
+Check ((Get-FileHash $copy -Algorithm SHA256).Hash.ToLowerInvariant() -eq $sha256 -and (Get-Item $copy).LastWriteTimeUtc.Year -gt 2001) 'the downloaded exe is in place, under the same name'
+Check (-not (Test-Path "$copy.old") -and -not (Test-Path "$copy.download")) 'the old exe is removed after the restart'
+Check (@(Get-AppProcess).Count -eq 1) 'the old copy closed'
+Check ((Get-ChildItem $folder -Name) -join ',' -eq 'Queueify.exe') 'nothing else is left next to the exe'
+Stop-App
+
+# ── The latest version: About says so ──
+$version = (Get-Item $Exe).VersionInfo.FileVersion -replace '^(\d+\.\d+\.\d+).*', '$1'
+Offer $version $sha256
+Start-App
+Check ($null -eq (Find '*new version is out*')) 'no offer when this is the latest version'
+Select-Item (Find 'Help*' 'ListItem')
+Invoke (FindId 'CheckUpdatesButton')
+Check ($null -ne (Wait-Find 'You have the latest version.')) 'About: checking says this is the latest version'
+Stop-App
+
+# ── Turned off in Settings: no check at the start ──
+Offer '99.0.0' $sha256
+Start-App
+Select-Item (Find 'Settings*' 'ListItem')
+$toggle = FindId 'UpdateCheckToggle'
+$toggle.GetCurrentPattern([System.Windows.Automation.TogglePattern]::Pattern).Toggle(); Start-Sleep 1
+Stop-App
+Start-App
+Start-Sleep 3
+Check ($null -eq (Find '*new version is out*')) 'with checks turned off, nothing is offered at the start'
+Select-Item (Find 'Help*' 'ListItem')
+Invoke (FindId 'CheckUpdatesButton')
+Check ($null -ne (Wait-Find '*new version is out: Queueify 99.0.0*')) 'checking by hand still finds it'
+}
+finally {
+ Stop-App
+ $listener.Stop()
+ $serve.Stop(); $serve.Dispose()
+ Remove-Item $scratch -Recurse -Force -ErrorAction SilentlyContinue
+}
+
+''
+"$script:failures failure(s)"
+exit $script:failures