diff --git a/.claude/skills/release/SKILL.md b/.claude/skills/release/SKILL.md index dd8c24e..16517a6 100644 --- a/.claude/skills/release/SKILL.md +++ b/.claude/skills/release/SKILL.md @@ -44,5 +44,8 @@ On `release/vX.Y.Z` from an up-to-date `main`: ## 4. After -- Install it on this machine with the **install-locally** skill (from the release, attestation verified). +- From 1.2.0 on, update this machine **as a user would**: *Help → Check for updates* in the installed + previous version, *Download and install*, *Restart now*; then the new version must show *Updated to X.Y.Z* + and `--version` the tag's commit (docs/updating.md, "Measured"). Record the timings there. Otherwise, or + if it fails, install with the **install-locally** skill (from the release, attestation verified). - Report to the maintainer: the release URL, what it contains, what was not verified (other GPUs, Linux). diff --git a/AGENTS.md b/AGENTS.md index a55d230..cd6af01 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -54,6 +54,8 @@ tests/pipeline.rs end to end on synthetic clips examples/transcode.rs - Spawn FFmpeg with `ffmpeg::tool()` or `background_tool()` (no console window); collect stderr with `StderrTail::finish()` after exit; stop with `kill_tree` (Chocolatey and Scoop shims). - Never hard-code an encoder: go through `Capabilities::encoder`. H.265 stays the default codec. +- The network is used only when the user clicks *Check for updates* (docs/updating.md): never a + background check. Updater tests never call GitHub (scripted feed, local listener). - Every text a user reads is a Fluent message: `crate::tr!("id")`, numbers through `NUM` in the message (docs/localization.md). Logs and technical details stay in English. - Qualities are H.265 QPs everywhere; `EncoderSpec::qp` converts for AV1 scales. diff --git a/CHANGELOG.md b/CHANGELOG.md index 9cecdfa..50cb701 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,9 @@ refuses a tag without one. without restarting. - Numbers follow the chosen language and region: `25,0 Mo` in French, the Canadian and Swiss groupings, `25.0 MB` in English. The size limit box accepts a comma or a point. +- *Help → Check for updates*: shows the latest version and what changed, downloads it, checks it against + the published checksums, and restarts on it — the previous version comes back if anything fails. The + application connects only when you click. ### Fixed diff --git a/Cargo.lock b/Cargo.lock index d373904..e95e345 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -512,6 +512,12 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "basic-toml" version = "0.1.10" @@ -782,6 +788,16 @@ dependencies = [ "libc", ] +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "core-foundation-sys" version = "0.8.7" @@ -795,7 +811,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" dependencies = [ "bitflags 1.3.2", - "core-foundation", + "core-foundation 0.9.4", "core-graphics-types", "foreign-types", "libc", @@ -808,7 +824,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" dependencies = [ "bitflags 1.3.2", - "core-foundation", + "core-foundation 0.9.4", "libc", ] @@ -1565,6 +1581,17 @@ dependencies = [ "windows-link", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.3.4" @@ -1782,6 +1809,22 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + [[package]] name = "hybrid-array" version = "0.4.15" @@ -2911,6 +2954,12 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + [[package]] name = "orbclient" version = "0.3.55" @@ -3283,9 +3332,11 @@ dependencies = [ "rust-embed", "serde", "serde_json", + "sha2", "tempfile", "toml 1.2.1+spec-1.1.0", "unic-langid", + "ureq", ] [[package]] @@ -3443,6 +3494,20 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "ron" version = "0.12.3" @@ -3547,6 +3612,80 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation 0.10.1", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -3568,6 +3707,15 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "scoped-tls" version = "1.0.1" @@ -3593,6 +3741,29 @@ dependencies = [ "tiny-skia", ] +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "self_cell" version = "1.3.0" @@ -3868,6 +4039,12 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "syn" version = "2.0.119" @@ -4233,6 +4410,43 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ac5cecf619ca81f66a96482db09687c9f7465af65f4300a8c30cca05bd5a59d" +dependencies = [ + "base64", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "ureq-proto", + "utf8-zero", + "webpki-roots", + "winreg", +] + +[[package]] +name = "ureq-proto" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3" +dependencies = [ + "base64", + "http", + "httparse", + "log", +] + [[package]] name = "url" version = "2.5.8" @@ -4245,6 +4459,12 @@ dependencies = [ "serde", ] +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + [[package]] name = "utf8_iter" version = "1.1.0" @@ -4322,6 +4542,12 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + [[package]] name = "wasip2" version = "1.0.4+wasi-0.2.12" @@ -4557,6 +4783,24 @@ dependencies = [ "web-sys", ] +[[package]] +name = "webpki-root-certs" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "weezl" version = "0.1.12" @@ -4971,7 +5215,7 @@ dependencies = [ "calloop 0.13.0", "cfg_aliases", "concurrent-queue", - "core-foundation", + "core-foundation 0.9.4", "core-graphics", "cursor-icon", "dpi", @@ -5017,6 +5261,16 @@ dependencies = [ "memchr", ] +[[package]] +name = "winreg" +version = "0.56.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10" +dependencies = [ + "cfg-if", + "windows-sys 0.61.2", +] + [[package]] name = "wit-bindgen" version = "0.57.1" @@ -5291,6 +5545,12 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" + [[package]] name = "zerotrie" version = "0.2.5" diff --git a/Cargo.toml b/Cargo.toml index 2417ae6..536d9a0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -45,6 +45,11 @@ log = "0.4.34" rfd = "0.18.0" serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.154" +# The updater (src/update/): SHA-256 of the downloaded executable. +sha2 = "0.11.1" +# The updater's HTTPS client: rustls, certificates checked against the OS's trust store (so a corporate +# proxy's own root works), Windows' proxy settings read like a browser would. +ureq = { version = "3.5.2", features = ["platform-verifier", "win-system-proxy"] } toml = "1.2.1" # Pseudo-localization (debug builds, QVT_PSEUDO=1): every text elongated and bracketed, to spot a text left # in code and a layout that cannot take a longer language. diff --git a/README.md b/README.md index cfaf2da..99a6209 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,14 @@ window opens: videos sent while it is open join its queue. Keyboard shortcuts are under *Help*, with *About* (the version, and this documentation as it was for that version). +## Updating + +*Help → Check for updates* looks for a newer version on GitHub (the only time the application +connects), shows what changed, and on request downloads it, checks it against the release's published +checksums and restarts on it; if the new file cannot be put in place, the previous version comes back. +The program's folder must be writable (not Program Files): otherwise download the new file from the +release page and replace it by hand. How it works: [Updating](docs/updating.md). + ## When something goes wrong The application keeps a log of its last two runs in its data folder (*Profiles → Open profiles.toml @@ -125,6 +133,7 @@ for what is documented and how to measure it. | [Messenger's limits](docs/messenger.md) | What Meta documents, and how to measure the rest. | | [Discord's limits](docs/discord.md) | Upload limits with and without Nitro, formats, the Discord profiles. | | [Localization](docs/localization.md) | How texts are translated, the glossary, adding a language. | +| [Updating](docs/updating.md) | How the application updates itself, what it trusts, the measurements. | | [Architecture](docs/architecture.md) | How the size fitting, the filters and the preview work, with measurements. | | [Changelog](CHANGELOG.md) | What each release changed. | | [Contributing](CONTRIBUTING.md) | Building, testing, rules. | diff --git a/about.toml b/about.toml index e144f8c..90bbc71 100644 --- a/about.toml +++ b/about.toml @@ -16,6 +16,8 @@ accepted = [ "MPL-2.0", "CC0-1.0", "MIT-0", + # webpki-roots (through ureq): Mozilla's list of certificate authorities, a permissive data licence. + "CDLA-Permissive-2.0", ] targets = ["x86_64-pc-windows-msvc"] ignore-build-dependencies = true diff --git a/docs/architecture.md b/docs/architecture.md index 8607993..1c8e91a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -19,6 +19,7 @@ on the GPU by libplacebo. | `src/ffmpeg/` | Probe, encoders, filters, hardware detection, preview decoder, audio decoder. | | `src/player.rs`, `src/audio.rs` | Preview playback with the sound as master clock (`cpal`). | | `src/thumbnails.rs` | The thumbnail strip, by parallel seeks. | +| `src/update/`, `src/app/update_window.rs` | *Check for updates*: the release feed, the state machine, the download and the swap at exit. | | `src/instance.rs` | One window: a second launch hands its files to the open one. | | `src/sendto.rs` | The *Send to* shortcut. | | `src/build_info.rs`, `build.rs` | The version, the commit, links to the documentation of that commit; the icon and version block. | @@ -120,7 +121,8 @@ out 0.03 % over the limit and was re-encoded once, to 97.4 % of it. ## Files written -Next to the videos, only the output and its partial file. FFmpeg writes `.qvt-partial`, checked by +Beside the executable, only during an update the user asked for: `.new` and `.old` +([Updating](updating.md)). Next to the videos, only the output and its partial file. FFmpeg writes `.qvt-partial`, checked by `naming::check_partial` (same folder, marker extension, not the source) before every run; it is renamed once the size is checked, deleted otherwise. An output name that exists gets ` (2)`, ` (3)`…: nothing is ever overwritten. Source metadata (titles, encoder tags, chapters) is not copied. diff --git a/docs/updating.md b/docs/updating.md new file mode 100644 index 0000000..9cf86e7 --- /dev/null +++ b/docs/updating.md @@ -0,0 +1,94 @@ +# Updating + +**TL;DR** — *Help → Check for updates* opens a window that reads the latest GitHub release, shows its notes, +downloads `quick-video-transcoder.exe` beside the running one, checks its SHA-256 against two witnesses, +and on *Restart now* swaps the executable and restarts. The application connects only when the user clicks. +The swap is GameModeExecutor's (lot 13), measured there and here. + +Code: `src/update/` (the rules, the feed, the swap), `src/app/update_window.rs` (the window). Its module doc +comments carry the rules. + +## The window + +| Phase | The window shows | +| --- | --- | +| Checking | a spinner | +| Up to date | *1.1.0 is the latest version*, *Check again* | +| Available | *Version 1.2.0 is available*, the release notes (the changelog section, English), *Download and install (18.9 MB)*, *See it on GitHub* | +| Downloading | a progress bar | +| Ready | *Restart now* — disabled while videos are encoding (a restart would stop them) | +| Updated | *Updated to 1.2.0*, at the first start of the new version | +| Failed | the reason in a sentence, *Details are in the log*, *Try again* or *Check again*, the release page | + +Closing the window hides it: a download goes on and is found again on reopening. All rules live in +`update::Machine` (pure, tested whole); the window draws its phase and sends events. + +## The release, and what is trusted + +One `GET api.github.com/repos/{owner}/{repo}/releases/latest` (60 an hour per IP without a token): the tag +(exactly `vX.Y.Z`, else "an answer this version does not understand"), the notes, and per asset its URL, +size and `digest: sha256:…`. Drafts and pre-releases are refused; a release not newer than the running +version is never offered (no downgrade). The download uses that release's own URLs. + +Two witnesses to the file, both over TLS: the workflow's `SHA256SUMS.txt` and GitHub's digest computed on +upload. They must agree with each other and with the downloaded bytes, else the file is deleted. **What this +does not defend against:** a compromised account or workflow — the hash proves the file is the one +published, not that it is honest. Verifying the build attestation (Sigstore) inside the application was +weighed on 2026-11-23 and left out: the Rust Sigstore crates are heavy and not yet stable; `gh attestation +verify` remains the way to check a download by hand (README). A file fetched by a library carries no Mark of +the Web, so SmartScreen does not see it: the hash is what vouches for it. + +TLS: rustls (through `ureq`), certificates checked against the OS's trust store (`rustls-platform-verifier`: +a corporate proxy's own root is accepted like in a browser), Windows' proxy settings read +(`win-system-proxy`). A generic `User-Agent` with the version, nothing about the user. + +## The swap + +The running executable is never written. Windows refuses to overwrite or delete an executable that runs, but +a separate process can rename it once it has exited: + +1. The download goes to `.new`, beside the executable: the swap is a rename on the same folder, not a + copy. Creating it is also the test that the folder can be written; a read-only folder (Program Files) + fails here and the window offers the release page. +2. *Restart now* writes `updates\pending.txt` (the version being installed) in the data folder, starts a + hidden Windows PowerShell (`-NoProfile -NonInteractive -WindowStyle Hidden`, `CREATE_NO_WINDOW`) and + closes the window the normal way. +3. The script waits for this exact process (`Wait-Process -Id -Timeout 30`), removes an older `.old`, + renames `` to `.old` and `.new` to `` — each step retried up to 10 times, 0.5 s + apart, because OneDrive or an antivirus may hold a file just written — then starts ``. +4. On any failure, it writes the reason to `updates\result.txt`, puts `.old` back if `` is gone, + and starts the executable again. +5. The next start compares `pending.txt` with its own version: equal, *Updated to X* and the `.old` goes; + different, the failure and `result.txt`'s reason, and the unused `.new` goes. A `.new` left without a + pending update (a download never installed) is deleted at start. + +Paths reach the script only as PowerShell single-quoted literals (`'` doubled) through `-LiteralPath`: spaces, +apostrophes and brackets cannot change the command (GameModeExecutor lost a delete to double quotes on +2026-09-17). Why PowerShell: `Wait-Process` waits for one process id, where a batch file could only guess +with a delay. Why not the `self-replace` crate (renaming the running image from inside): never measured +here, and it has no way back when the new file cannot be put in place. + +The protocol proves itself from the second release that carries it: 1.1.0 is the first; the first real +update through it is 1.1.0 → 1.2.0. + +## Measured, 2026-11-23, on the maintainer's machine + +A debug build of the branch, copied to a scratch folder named with a space, an apostrophe and brackets +(`update test [it's]`), run with `QVT_UPDATE_AS=0.9.0` (debug builds only) so the published 1.0.0 counts as +newer: + +| Step | Result | +| --- | --- | +| *Check for updates* | `releases/latest` answered, *Version 1.0.0 is available* with its notes, under a second | +| *Download and install* | 18,912,256 bytes in about a second, both witnesses agreed, *downloaded and verified* | +| *Restart now* | the window closed; the swap left `quick-video-transcoder.exe` with the published 1.0.0's SHA-256 (`a55a5f19…05ee02`) and the debug build as `.old`; 1.0.0 started and came to the foreground | +| Rollback | the same, with `.old` held open by another process: the removal failed ten times, the catch wrote *The process cannot access the file…* to `result.txt`, the executable stayed in place and restarted, and its next start showed the failure and the reason | + +Not measured: behind a proxy; the *Updated to* message from a real release pair (1.0.0 does not read +`pending.txt` — it waits for 1.1.0 → 1.2.0); OneDrive's locks (the retries are there for them). + +## Files written + +Beside the executable: `.new` (the download) and `.old` (the previous version, until the next +start). In the data folder: `updates\pending.txt` and `updates\result.txt`. Nothing else, and only after a +click. diff --git a/i18n/en/quick_video_transcoder.ftl b/i18n/en/quick_video_transcoder.ftl index 2cb7971..0f03db9 100644 --- a/i18n/en/quick_video_transcoder.ftl +++ b/i18n/en/quick_video_transcoder.ftl @@ -593,3 +593,43 @@ sendto-shortcut-description = Trim and re-encode videos to fit a size limit # Errors copying files to the clipboard. $detail: the system's message (technical). clipboard-copy-failed = cannot copy to the clipboard: { $detail } clipboard-unsupported = copying files to the clipboard is only supported on Windows + +## Updates window (src/app/update_window.rs) + +# Help menu item: opens the updates window and checks GitHub at once (the only time the app connects). +menu-help-updates = Check for updates… +# Title of the updates window. +update-title = Updates +# First line of the window. $version: the running version, like 1.0.0 (data). +update-running = This is Quick Video Transcoder { $version }. +update-check = Check for updates +update-check-again = Check again +update-checking = Checking for updates… +# $version: the running version, which is the latest. +update-up-to-date = { $version } is the latest version. +# $version: the newer version found. Above the release notes (shown in English, from the changelog). +update-available = Version { $version } is available +# Button. $mb: the executable's size in megabytes. +update-download = Download and install ({ NUM($mb, decimals: 1) } MB) +# Link to the release on GitHub, in the browser. +update-release-page = See it on GitHub +update-downloading = Downloading { $version }… +# Shown once the file is downloaded and its SHA-256 checked against the release's. +update-ready = { $version } is downloaded and verified. Restarting installs it. +update-restart = Restart now +# Under the disabled restart button while videos are encoding (a restart would stop them). +update-wait-for-encodes = Available once the encodes are finished or stopped. +update-restarting = Installing { $version }: the application closes and comes back… +# Shown at the first start after an update. $version: the new version. +update-updated = Updated to { $version }. +update-see-log = Details are in the log (View → Log). +update-retry = Try again +update-fault-connection = Could not reach GitHub: no connection, or it did not answer. +# $status: the HTTP status GitHub answered with, like 503 (data). +update-fault-status = GitHub answered with an error ({ $status }). Try again later. +update-fault-unexpected = GitHub's answer was not what this version expects. See the release page. +update-fault-not-verified = The downloaded file does not match the published one: it was deleted. Try again. +# The executable's folder is read-only (for instance under Program Files): the user can download it by hand. +update-fault-cannot-write = This copy's folder cannot be written. Download the new version from the release page instead. +# $detail: why the install failed (technical, English: a Windows or PowerShell message). +update-fault-install = The update could not be installed: { $detail } diff --git a/i18n/fr/quick_video_transcoder.ftl b/i18n/fr/quick_video_transcoder.ftl index d2f38ad..d7eecd1 100644 --- a/i18n/fr/quick_video_transcoder.ftl +++ b/i18n/fr/quick_video_transcoder.ftl @@ -440,3 +440,30 @@ sendto-shortcut-description = Découper et réencoder des vidéos pour tenir dan clipboard-copy-failed = impossible de copier dans le Presse-papiers : { $detail } clipboard-unsupported = la copie de fichiers dans le Presse-papiers n’est prise en charge que sous Windows + +## Updates window (src/app/update_window.rs) + +menu-help-updates = Rechercher des mises à jour… +update-title = Mises à jour +update-running = Vous utilisez Quick Video Transcoder { $version }. +update-check = Rechercher des mises à jour +update-check-again = Rechercher à nouveau +update-checking = Recherche de mises à jour… +update-up-to-date = La version { $version } est la plus récente. +update-available = La version { $version } est disponible +update-download = Télécharger et installer ({ NUM($mb, decimals: 1) } Mo) +update-release-page = Voir sur GitHub +update-downloading = Téléchargement de la version { $version }… +update-ready = La version { $version } est téléchargée et vérifiée. Elle s’installera au redémarrage. +update-restart = Redémarrer maintenant +update-wait-for-encodes = Disponible une fois les encodages terminés ou arrêtés. +update-restarting = Installation de la version { $version } : l’application se ferme et revient… +update-updated = Mise à jour vers la version { $version } effectuée. +update-see-log = Détails dans le journal (Affichage > Journal). +update-retry = Réessayer +update-fault-connection = Impossible de joindre GitHub : pas de connexion, ou pas de réponse. +update-fault-status = GitHub a répondu par une erreur ({ $status }). Réessayez plus tard. +update-fault-unexpected = La réponse de GitHub ne correspond pas à ce que cette version attend. Consultez la page de la version. +update-fault-not-verified = Le fichier téléchargé ne correspond pas au fichier publié : il a été supprimé. Réessayez. +update-fault-cannot-write = Le dossier de cette copie n’est pas modifiable. Téléchargez plutôt la nouvelle version depuis sa page. +update-fault-install = La mise à jour n’a pas pu être installée : { $detail } diff --git a/src/app/mod.rs b/src/app/mod.rs index f9bef21..9ce8d95 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -14,6 +14,7 @@ mod preview; mod queue_panel; mod settings; mod timeline; +mod update_window; use std::collections::{HashMap, HashSet, VecDeque}; use std::path::{Path, PathBuf}; @@ -140,6 +141,10 @@ pub struct TranscoderApp { /// The *Send to* shortcut exists (checked at start and after each change). sendto_installed: bool, show_about: bool, + /// *Help → Check for updates* and its window. + updater: update_window::Updater, + /// The swap script is started: close the window at the next frame. + close_for_update: bool, /// The GPU drawing the window and its driver: with the encoder, the key of a parallelism measurement. gpu: String, /// A running measurement of encodes at once, and its key. @@ -219,6 +224,8 @@ impl TranscoderApp { incoming, sendto_installed: crate::sendto::is_installed(), show_about: false, + updater: update_window::Updater::new(), + close_for_update: false, gpu: cc .wgpu_render_state .as_ref() @@ -822,6 +829,10 @@ impl TranscoderApp { .open_url(egui::OpenUrl::new_tab(crate::build_info::documentation())); } ui.separator(); + if ui.button(crate::tr!("menu-help-updates")).clicked() { + ui.close(); + self.open_updates(); + } if ui.button(crate::tr!("menu-help-about")).clicked() { ui.close(); self.show_about = true; @@ -1166,6 +1177,7 @@ impl eframe::App for TranscoderApp { self.handle_dropped_files(&ctx); self.handle_shortcuts(&ctx); self.poll_incoming(&ctx); + self.poll_updates(); self.poll_queue(); self.poll_thumbnails(&ctx); self.update_player(&ctx); @@ -1198,6 +1210,10 @@ impl eframe::App for TranscoderApp { self.shortcuts_window(&ctx); self.profiles_window(&ctx); self.about_window(&ctx); + self.update_window(&ctx); + if self.close_for_update { + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + } self.ffmpeg_window(&ctx); self.take_screenshot(&ctx); } diff --git a/src/app/update_window.rs b/src/app/update_window.rs new file mode 100644 index 0000000..db51c4f --- /dev/null +++ b/src/app/update_window.rs @@ -0,0 +1,382 @@ +//! The *Check for updates* window: draws [`Machine`]'s phase and sends its buttons as events. The rules +//! are in [`crate::update`]; the work runs on a worker thread per effect, reporting back through a channel. + +use std::sync::Arc; + +use crossbeam_channel::{Receiver, Sender, unbounded}; +use eframe::egui; + +use super::TranscoderApp; +use crate::queue::Phase as JobPhase; +use crate::update::feed::GitHub; +use crate::update::install::{self, Paths}; +use crate::update::{Effect, Event, Fault, Machine, Phase, Release, Version}; + +/// The updater as the window sees it. +pub(super) struct Updater { + machine: Machine, + /// The window is shown. + pub(super) open: bool, + sender: Sender, + receiver: Receiver, + /// The data folder and executable are known (else nothing can be installed). + paths: Option, +} + +impl Updater { + /// The updater at start: the outcome of an update the previous run started opens the window. + pub(super) fn new() -> Self { + let current = running_version(); + let paths = Paths::current(); + let settled = paths.as_ref().and_then(|p| install::settle(p, current)); + let (sender, receiver) = unbounded(); + Self { + open: settled.is_some(), + machine: Machine::new(current, settled.unwrap_or(Phase::Idle)), + sender, + receiver, + paths, + } + } +} + +/// This executable's version; in debug builds `QVT_UPDATE_AS=0.9.0` pretends to be older, to try an +/// update against the real latest release. +fn running_version() -> Version { + #[cfg(debug_assertions)] + if let Some(pretend) = std::env::var("QVT_UPDATE_AS") + .ok() + .and_then(|v| Version::parse(&v)) + { + return pretend; + } + Version::current() +} + +impl TranscoderApp { + /// *Help → Check for updates*: opens the window and checks at once. + pub(super) fn open_updates(&mut self) { + self.updater.open = true; + self.send_update(Event::CheckAsked); + } + + /// Applies an event and runs the effect it asks for. + fn send_update(&mut self, event: Event) { + let Some(effect) = self.updater.machine.apply(event) else { + return; + }; + let sender = self.updater.sender.clone(); + let notify = Arc::clone(&self.notify); + match effect { + Effect::Check => { + log::info!("update: checking for updates"); + std::thread::spawn(move || { + let result = crate::update::feed::Feed::latest(&GitHub::new()); + match &result { + Ok(release) => log::info!("update: latest release is {}", release.version), + Err(fault) => log::warn!("update: check failed: {fault:?}"), + } + let _ = sender.send(Event::Checked(result)); + notify(); + }); + } + Effect::Download(release) => { + let Some(paths) = self.updater.paths.clone() else { + let _ = sender.send(Event::Downloaded(Err(Fault::CannotWrite( + "no data folder".to_owned(), + )))); + return; + }; + log::info!( + "update: downloading {} ({} bytes)", + release.version, + release.exe_size + ); + std::thread::spawn(move || { + let progress_sender = sender.clone(); + let progress_notify = Arc::clone(¬ify); + let mut last = 0u64; + let result = install::download(&GitHub::new(), &release, &paths, &mut |done| { + // A message per 1 % is plenty for a progress bar. + if done.saturating_sub(last) > release.exe_size / 100 { + last = done; + let _ = progress_sender.send(Event::Progress(done)); + progress_notify(); + } + }); + match &result { + Ok(()) => log::info!("update: downloaded and verified {}", release.version), + Err(fault) => log::warn!("update: download failed: {fault:?}"), + } + let _ = sender.send(Event::Downloaded(result)); + notify(); + }); + } + Effect::Restart(release) => { + let result = self + .updater + .paths + .as_ref() + .ok_or_else(|| Fault::Launch("no data folder".to_owned())) + .and_then(|paths| install::launch(&release, paths)); + match result { + // The swap script waits for this process: close now, the normal way. + Ok(()) => self.close_for_update = true, + Err(fault) => { + log::warn!("update: cannot start the swap: {fault:?}"); + self.updater.machine.apply(Event::LaunchFailed(fault)); + } + } + } + } + } + + /// Takes the worker's results. + pub(super) fn poll_updates(&mut self) { + while let Ok(event) = self.updater.receiver.try_recv() { + self.send_update(event); + } + } + + fn encoding(&self) -> bool { + self.queue + .jobs + .iter() + .any(|j| matches!(j.phase, JobPhase::Encoding(_) | JobPhase::Waiting)) + } + + pub(super) fn update_window(&mut self, ctx: &egui::Context) { + if !self.updater.open { + return; + } + let mut open = true; + let mut event = None; + let encoding = self.encoding(); + let phase = self.updater.machine.phase().clone(); + egui::Window::new(crate::tr!("update-title")) + .id(egui::Id::unique("update window")) + .open(&mut open) + .collapsible(false) + .resizable(false) + .default_width(460.0) + .anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO) + .show(ctx, |ui| { + ui.label(crate::tr!( + "update-running", + version = running_version().to_string() + )); + ui.add_space(8.0); + event = phase_ui(ui, &phase, encoding); + }); + if let Some(event) = event { + self.send_update(event); + } + // Closing hides the window; a download keeps going and is found again on reopening. + if !open { + self.updater.open = false; + } + } +} + +/// The body of the window for a phase; returns the event a button sent. +fn phase_ui(ui: &mut egui::Ui, phase: &Phase, encoding: bool) -> Option { + let mut event = None; + match phase { + Phase::Idle => { + if ui.button(crate::tr!("update-check")).clicked() { + event = Some(Event::CheckAsked); + } + } + Phase::Checking => { + ui.horizontal(|ui| { + ui.spinner(); + ui.label(crate::tr!("update-checking")); + }); + } + Phase::UpToDate(version) => { + ui.label(crate::tr!( + "update-up-to-date", + version = version.to_string() + )); + ui.add_space(8.0); + if ui.button(crate::tr!("update-check-again")).clicked() { + event = Some(Event::CheckAsked); + } + } + Phase::Available(release) => { + let mb = release.exe_size as f64 / 1e6; + ui.strong(crate::tr!( + "update-available", + version = release.version.to_string() + )); + notes(ui, release); + ui.horizontal(|ui| { + if ui.button(crate::tr!("update-download", mb = mb)).clicked() { + event = Some(Event::DownloadAsked); + } + ui.hyperlink_to(crate::tr!("update-release-page"), &release.page); + }); + } + Phase::Downloading(release, done) => { + ui.label(crate::tr!( + "update-downloading", + version = release.version.to_string() + )); + let fraction = *done as f32 / release.exe_size.max(1) as f32; + ui.add( + egui::ProgressBar::new(fraction) + .show_percentage() + .desired_width(420.0), + ); + } + Phase::Ready(release) => { + ui.label(crate::tr!( + "update-ready", + version = release.version.to_string() + )); + ui.add_space(8.0); + let restart = + ui.add_enabled(!encoding, egui::Button::new(crate::tr!("update-restart"))); + if encoding { + ui.label( + egui::RichText::new(crate::tr!("update-wait-for-encodes")) + .small() + .weak(), + ); + } + if restart.clicked() { + event = Some(Event::RestartAsked); + } + } + Phase::Restarting(release) => { + ui.horizontal(|ui| { + ui.spinner(); + ui.label(crate::tr!( + "update-restarting", + version = release.version.to_string() + )); + }); + } + Phase::Updated(version) => { + ui.label(crate::tr!("update-updated", version = version.to_string())); + } + Phase::Failed { fault, release } => { + ui.colored_label(ui.visuals().error_fg_color, fault_text(fault)); + ui.label( + egui::RichText::new(crate::tr!("update-see-log")) + .small() + .weak(), + ); + ui.add_space(8.0); + ui.horizontal(|ui| { + match release { + Some(release) if !matches!(fault, Fault::CannotWrite(_)) => { + if ui.button(crate::tr!("update-retry")).clicked() { + event = Some(Event::DownloadAsked); + } + } + _ => { + if ui.button(crate::tr!("update-check-again")).clicked() { + event = Some(Event::CheckAsked); + } + } + } + if let Some(release) = release { + ui.hyperlink_to(crate::tr!("update-release-page"), &release.page); + } + }); + } + } + event +} + +/// A block of the release notes. +#[derive(Debug, PartialEq, Eq)] +enum Block { + Heading(String), + Item(String), + Paragraph(String), +} + +/// The release notes (the changelog section, Markdown) as blocks: `#` headings, `- ` items with their +/// wrapped continuation lines joined, paragraphs; emphasis and code marks dropped; the footer after `---` +/// left out. +fn note_blocks(notes: &str) -> Vec { + let mut blocks: Vec = Vec::new(); + for line in notes.lines() { + let line = line.trim_end(); + if line.starts_with("---") { + break; + } + let clean = |text: &str| text.trim().replace(['*', '`'], ""); + if line.starts_with('#') { + blocks.push(Block::Heading(clean(line.trim_start_matches('#')))); + } else if let Some(item) = line.strip_prefix("- ") { + blocks.push(Block::Item(clean(item))); + } else if line.is_empty() { + continue; + } else if let (true, Some(Block::Item(text) | Block::Paragraph(text))) = + (line.starts_with(' '), blocks.last_mut()) + { + text.push(' '); + text.push_str(&clean(line)); + } else { + blocks.push(Block::Paragraph(clean(line))); + } + } + blocks +} + +fn notes(ui: &mut egui::Ui, release: &Release) { + ui.add_space(4.0); + egui::ScrollArea::vertical() + .max_height(220.0) + .auto_shrink([false, true]) + .show(ui, |ui| { + for block in note_blocks(&release.notes) { + match block { + Block::Heading(text) => { + ui.strong(text); + } + Block::Item(text) => { + ui.label(format!("• {text}")); + } + Block::Paragraph(text) => { + ui.label(text); + } + } + } + }); + ui.add_space(6.0); +} + +/// The user's sentence for a fault (the technical detail is in the log). +fn fault_text(fault: &Fault) -> String { + match fault { + Fault::NoConnection(_) => crate::tr!("update-fault-connection"), + Fault::Status(status) => crate::tr!("update-fault-status", status = status.to_string()), + Fault::Unexpected(_) => crate::tr!("update-fault-unexpected"), + Fault::NotVerified => crate::tr!("update-fault-not-verified"), + Fault::CannotWrite(_) => crate::tr!("update-fault-cannot-write"), + Fault::Launch(reason) => crate::tr!("update-fault-install", detail = reason.clone()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn release_notes_join_wrapped_items() { + let notes = "The first release.\n\n### Added\n\n- A queue, filled from *Send to*,\n with `I` / `O`.\n- One file.\n\n---\n\nBuilt from abc."; + assert_eq!( + note_blocks(notes), + [ + Block::Paragraph("The first release.".to_owned()), + Block::Heading("Added".to_owned()), + Block::Item("A queue, filled from Send to, with I / O.".to_owned()), + Block::Item("One file.".to_owned()), + ] + ); + } +} diff --git a/src/lib.rs b/src/lib.rs index 994b529..ecd3cbe 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -23,3 +23,4 @@ pub mod queue; pub mod sendto; pub mod thumbnails; pub mod timecode; +pub mod update; diff --git a/src/update/feed.rs b/src/update/feed.rs new file mode 100644 index 0000000..98fdac6 --- /dev/null +++ b/src/update/feed.rs @@ -0,0 +1,310 @@ +//! Where releases come from: GitHub's REST API for the latest release (tag, notes, assets and their +//! digests), then the assets' download URLs. [`Feed`] is the seam the tests script. +//! +//! What GitHub answers (measured 2026-11-24 on this repository's v1.0.0): `GET +//! api.github.com/repos/{owner}/{repo}/releases/latest` gives `tag_name`, `html_url`, `body`, `draft`, +//! `prerelease` and per asset `name`, `size`, `browser_download_url` and `digest: "sha256:…"`; 60 requests +//! an hour per IP without a token. An asset's URL redirects to a signed `release-assets.githubusercontent.com` +//! URL valid for about an hour. + +use std::io::{Read, Write}; +use std::time::Duration; + +use serde::Deserialize; + +use super::{Fault, Release, Version}; + +/// The executable's asset name in a release. +pub const EXE_ASSET: &str = "quick-video-transcoder.exe"; +/// The checksums' asset name. +pub const SUMS_ASSET: &str = "SHA256SUMS.txt"; + +/// A source of releases. +pub trait Feed: Send + Sync { + /// The latest published release. + fn latest(&self) -> Result; + /// A small text file (the checksums). + fn text(&self, url: &str) -> Result; + /// Streams a file into `out`, calling `progress` with the bytes written so far. Returns the size. + fn download( + &self, + url: &str, + out: &mut dyn Write, + progress: &mut dyn FnMut(u64), + ) -> Result; +} + +/// GitHub, over HTTPS. +pub struct GitHub { + agent: ureq::Agent, + /// `https://api.github.com` (a local listener in tests). + api: String, + /// `owner/repo`. + repo: String, +} + +impl GitHub { + /// This application's own repository. + pub fn new() -> Self { + let repo = crate::build_info::REPOSITORY + .trim_end_matches('/') + .trim_start_matches("https://github.com/") + .to_owned(); + Self::with_api("https://api.github.com", &repo) + } + + /// Another API base, for the tests' listener. + pub fn with_api(api: &str, repo: &str) -> Self { + let agent = ureq::Agent::config_builder() + .tls_config( + ureq::tls::TlsConfig::builder() + .root_certs(ureq::tls::RootCerts::PlatformVerifier) + .build(), + ) + // Reading the whole executable: a slow line may need minutes, a dead one fails sooner. + .timeout_connect(Some(Duration::from_secs(15))) + .timeout_recv_response(Some(Duration::from_secs(30))) + .timeout_recv_body(Some(Duration::from_secs(600))) + // A generic client name: nothing about the user. + .user_agent(format!( + "quick-video-transcoder/{}", + crate::build_info::VERSION + )) + .http_status_as_error(false) + .build() + .new_agent(); + Self { + agent, + api: api.trim_end_matches('/').to_owned(), + repo: repo.to_owned(), + } + } + + fn get(&self, url: &str) -> Result, Fault> { + let response = self + .agent + .get(url) + .header("Accept", "application/vnd.github+json") + .header("X-GitHub-Api-Version", "2022-11-28") + .call() + .map_err(|error| Fault::NoConnection(error.to_string()))?; + let status = response.status().as_u16(); + if status == 200 { + Ok(response) + } else { + log::warn!("update: {url} answered {status}"); + Err(Fault::Status(status)) + } + } +} + +impl Default for GitHub { + fn default() -> Self { + Self::new() + } +} + +#[derive(Deserialize)] +struct ApiRelease { + tag_name: String, + html_url: String, + #[serde(default)] + body: Option, + #[serde(default)] + draft: bool, + #[serde(default)] + prerelease: bool, + #[serde(default)] + assets: Vec, +} + +#[derive(Deserialize)] +struct ApiAsset { + name: String, + size: u64, + browser_download_url: String, + #[serde(default)] + digest: Option, +} + +/// Reads GitHub's answer for the latest release. +pub fn parse_release(json: &str) -> Result { + let api: ApiRelease = serde_json::from_str(json) + .map_err(|error| Fault::Unexpected(format!("not a release: {error}")))?; + if api.draft || api.prerelease { + return Err(Fault::Unexpected(format!( + "{} is a draft or a pre-release", + api.tag_name + ))); + } + let version = Version::from_tag(&api.tag_name) + .ok_or_else(|| Fault::Unexpected(format!("tag {} is not vX.Y.Z", api.tag_name)))?; + let asset = |name: &str| { + api.assets + .iter() + .find(|a| a.name == name) + .ok_or_else(|| Fault::Unexpected(format!("{} has no {name}", api.tag_name))) + }; + let exe = asset(EXE_ASSET)?; + let sums = asset(SUMS_ASSET)?; + let exe_digest = exe + .digest + .as_deref() + .and_then(|d| d.strip_prefix("sha256:")) + .map(str::to_ascii_lowercase); + Ok(Release { + version, + page: api.html_url.clone(), + notes: api.body.clone().unwrap_or_default(), + exe_url: exe.browser_download_url.clone(), + exe_size: exe.size, + exe_digest, + sums_url: sums.browser_download_url.clone(), + }) +} + +impl Feed for GitHub { + fn latest(&self) -> Result { + let url = format!("{}/repos/{}/releases/latest", self.api, self.repo); + let text = self.text(&url)?; + parse_release(&text) + } + + fn text(&self, url: &str) -> Result { + let mut response = self.get(url)?; + response + .body_mut() + .with_config() + .limit(1 << 20) + .read_to_string() + .map_err(|error| Fault::NoConnection(error.to_string())) + } + + fn download( + &self, + url: &str, + out: &mut dyn Write, + progress: &mut dyn FnMut(u64), + ) -> Result { + let mut response = self.get(url)?; + let mut reader = response.body_mut().with_config().limit(512 << 20).reader(); + let mut buffer = vec![0u8; 256 << 10]; + let mut total = 0u64; + loop { + let read = reader + .read(&mut buffer) + .map_err(|error| Fault::NoConnection(error.to_string()))?; + if read == 0 { + return Ok(total); + } + out.write_all(&buffer[..read]) + .map_err(|error| Fault::CannotWrite(error.to_string()))?; + total += read as u64; + progress(total); + } + } +} + +#[cfg(test)] +mod tests { + use std::io::{BufRead, BufReader}; + use std::net::TcpListener; + + use super::*; + + const RELEASE: &str = r##"{ + "tag_name": "v1.1.0", "html_url": "https://github.com/o/r/releases/tag/v1.1.0", + "body": "Added: languages", "draft": false, "prerelease": false, + "assets": [ + {"name": "quick-video-transcoder.exe", "size": 5, "browser_download_url": "URL/exe", + "digest": "sha256:2CF24DBA5FB0A30E26E83B2AC5B9E29E1B161E5C1FA7425E73043362938B9824"}, + {"name": "SHA256SUMS.txt", "size": 92, "browser_download_url": "URL/sums", "digest": null} + ] + }"##; + + #[test] + fn reads_the_latest_release() { + let release = parse_release(RELEASE).unwrap(); + assert_eq!(release.version, Version(1, 1, 0)); + assert_eq!(release.exe_url, "URL/exe"); + assert_eq!(release.sums_url, "URL/sums"); + assert_eq!( + release.exe_digest.as_deref(), + Some("2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824") + ); + assert!(release.notes.contains("languages")); + } + + #[test] + fn refuses_what_it_does_not_understand() { + for (from, to) in [ + ("v1.1.0", "v1.1"), + ("v1.1.0", "1.1.0"), + ("\"draft\": false", "\"draft\": true"), + ("\"prerelease\": false", "\"prerelease\": true"), + ("quick-video-transcoder.exe", "other.exe"), + ("SHA256SUMS.txt", "sums.txt"), + ] { + let json = RELEASE.replace(from, to); + assert!( + matches!(parse_release(&json), Err(Fault::Unexpected(_))), + "{from} -> {to}" + ); + } + assert!(matches!( + parse_release("captive portal"), + Err(Fault::Unexpected(_)) + )); + } + + /// A one-shot HTTP server on 127.0.0.1 answering each request with the next canned response. + fn serve(responses: Vec<(u16, String)>) -> String { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + std::thread::spawn(move || { + for (status, body) in responses { + let Ok((mut stream, _)) = listener.accept() else { + return; + }; + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut line = String::new(); + while reader.read_line(&mut line).is_ok_and(|n| n > 2) { + line.clear(); + } + let _ = write!( + stream, + "HTTP/1.1 {status} X\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + } + }); + format!("http://{address}") + } + + #[test] + fn talks_http_and_reports_statuses() { + let base = serve(vec![ + (200, RELEASE.to_owned()), + (503, "busy".to_owned()), + (200, "hello".to_owned()), + ]); + let feed = GitHub::with_api(&base, "o/r"); + assert_eq!(feed.latest().unwrap().version, Version(1, 1, 0)); + assert_eq!(feed.text(&format!("{base}/x")), Err(Fault::Status(503))); + let mut out = Vec::new(); + let mut seen = 0; + let size = feed + .download(&format!("{base}/exe"), &mut out, &mut |n| seen = n) + .unwrap(); + assert_eq!((size, seen, out.as_slice()), (5, 5, b"hello".as_slice())); + } + + #[test] + fn a_port_nobody_listens_on_is_no_connection() { + let free = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = free.local_addr().unwrap(); + drop(free); + let feed = GitHub::with_api(&format!("http://{address}"), "o/r"); + assert!(matches!(feed.latest(), Err(Fault::NoConnection(_)))); + } +} diff --git a/src/update/install.rs b/src/update/install.rs new file mode 100644 index 0000000..34c315e --- /dev/null +++ b/src/update/install.rs @@ -0,0 +1,435 @@ +//! Downloading and verifying a release beside the executable, the swap at exit, and the verdict at the +//! next start. +//! +//! The swap is GameModeExecutor's, measured there on real updates (2026-09-18/23): the process never +//! touches its own image. It writes `pending.txt` (the version it installs), starts a hidden Windows +//! PowerShell and closes. The script waits for this exact process to end (`Wait-Process -Id`, 30 s at +//! most), renames `` to `.old` and `.new` to `` (renames on the same folder: no copy; +//! retried a few times, since OneDrive or an antivirus may hold a file just written), starts the new +//! executable, and on any failure writes `result.txt`, puts the old executable back and starts it. The next +//! start compares `pending.txt` with its own version ([`settle`]). +//! +//! Write rules (no other path is ever written): `.new` and `.old` beside the running executable, +//! named from it; `pending.txt` and `result.txt` in the data folder's `updates`. Paths reach the script only +//! as PowerShell single-quoted literals (`'` doubled) and through `-LiteralPath`, so spaces, quotes and +//! brackets in a path cannot change the command. + +use std::fs::File; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::process::Stdio; + +use sha2::{Digest, Sha256}; + +use super::feed::{EXE_ASSET, Feed}; +use super::{Fault, Phase, Release, Version}; + +/// The files an update touches. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Paths { + /// The running executable. + pub exe: PathBuf, + /// The downloaded one, beside it. + pub new: PathBuf, + /// The previous one, kept until the new version has started. + pub old: PathBuf, + /// `pending.txt`: the version being installed. + pub pending: PathBuf, + /// `result.txt`: why the swap failed, written by the script. + pub result: PathBuf, +} + +impl Paths { + /// The paths for this executable and data folder. + pub fn new(exe: &Path, data_dir: &Path) -> Self { + let sibling = |suffix: &str| { + let mut name = exe.file_name().unwrap_or_default().to_os_string(); + name.push(suffix); + exe.with_file_name(name) + }; + let updates = data_dir.join("updates"); + Self { + exe: exe.to_path_buf(), + new: sibling(".new"), + old: sibling(".old"), + pending: updates.join("pending.txt"), + result: updates.join("result.txt"), + } + } + + /// The paths of this process, if its executable and data folder are known. + pub fn current() -> Option { + let exe = std::env::current_exe().ok()?; + Some(Self::new(&exe, &crate::profile::data_dir()?)) + } + + /// `true` when `path` is one of the two files this module may write beside the executable. + fn is_sibling(&self, path: &Path) -> bool { + path.parent() == self.exe.parent() && (path == self.new || path == self.old) + } +} + +/// Writes through to a file while hashing what was written. +struct Hashing<'a> { + file: &'a mut File, + hasher: Sha256, +} + +impl Write for Hashing<'_> { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + let written = self.file.write(bytes)?; + self.hasher.update(&bytes[..written]); + Ok(written) + } + + fn flush(&mut self) -> std::io::Result<()> { + self.file.flush() + } +} + +/// The SHA-256 `SHA256SUMS.txt` gives for `name` (` ` lines). +pub fn published_hash(sums: &str, name: &str) -> Option { + sums.lines().find_map(|line| { + let (hash, file) = line.trim().split_once(char::is_whitespace)?; + (file.trim().trim_start_matches('*') == name && hash.len() == 64) + .then(|| hash.to_ascii_lowercase()) + }) +} + +/// Downloads `release`'s executable to `.new` and verifies it against both witnesses; a file that does +/// not verify is deleted. `progress` receives the bytes downloaded so far. +pub fn download( + feed: &dyn Feed, + release: &Release, + paths: &Paths, + progress: &mut dyn FnMut(u64), +) -> Result<(), Fault> { + assert!( + paths.is_sibling(&paths.new), + "the download goes beside the executable" + ); + let sums = feed.text(&release.sums_url)?; + let published = published_hash(&sums, EXE_ASSET) + .ok_or_else(|| Fault::Unexpected(format!("{EXE_ASSET} is not in the checksums")))?; + if let Some(digest) = &release.exe_digest + && *digest != published + { + return Err(Fault::Unexpected( + "GitHub's digest and the checksums disagree".to_owned(), + )); + } + // Creating it is also the test that the folder can be written. + let mut file = File::create(&paths.new) + .map_err(|error| Fault::CannotWrite(format!("{}: {error}", paths.new.display())))?; + let mut writer = Hashing { + file: &mut file, + hasher: Sha256::new(), + }; + let result = feed.download(&release.exe_url, &mut writer, progress); + let actual = hex(&writer.hasher.finalize()); + let flushed = file.sync_all(); + drop(file); + let verdict = match (result, flushed) { + (Err(fault), _) => Err(fault), + (Ok(_), Err(error)) => Err(Fault::CannotWrite(error.to_string())), + (Ok(size), Ok(())) if size != release.exe_size => Err(Fault::Unexpected(format!( + "{size} bytes received, {} published", + release.exe_size + ))), + (Ok(_), Ok(())) if actual != published => { + log::warn!("update: downloaded {actual}, published {published}"); + Err(Fault::NotVerified) + } + (Ok(_), Ok(())) => Ok(()), + }; + if verdict.is_err() { + let _ = std::fs::remove_file(&paths.new); + } + verdict +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +/// A PowerShell single-quoted literal: nothing inside is interpreted, `'` is doubled. +fn quoted(path: &Path) -> String { + format!("'{}'", path.to_string_lossy().replace('\'', "''")) +} + +/// The script run after this process (`pid`) exits. +pub fn swap_script(pid: u32, paths: &Paths) -> String { + let (exe, new, old, result) = ( + quoted(&paths.exe), + quoted(&paths.new), + quoted(&paths.old), + quoted(&paths.result), + ); + format!( + "$ErrorActionPreference = 'Stop' +Wait-Process -Id {pid} -Timeout 30 -ErrorAction SilentlyContinue +function Retry([scriptblock] $Step) {{ + for ($i = 1; ; $i++) {{ + try {{ & $Step; return }} catch {{ if ($i -ge 10) {{ throw }}; Start-Sleep -Milliseconds 500 }} + }} +}} +try {{ + if (Get-Process -Id {pid} -ErrorAction SilentlyContinue) {{ throw 'the application did not close' }} + if (Test-Path -LiteralPath {old}) {{ Retry {{ Remove-Item -LiteralPath {old} -Force }} }} + Retry {{ Move-Item -LiteralPath {exe} -Destination {old} -Force }} + Retry {{ Move-Item -LiteralPath {new} -Destination {exe} }} + Start-Process -FilePath {exe} +}} catch {{ + Set-Content -LiteralPath {result} -Value $_.Exception.Message -Encoding UTF8 + if (-not (Test-Path -LiteralPath {exe}) -and (Test-Path -LiteralPath {old})) {{ + Move-Item -LiteralPath {old} -Destination {exe} -Force + }} + if (-not (Get-Process -Id {pid} -ErrorAction SilentlyContinue)) {{ Start-Process -FilePath {exe} }} +}} +" + ) +} + +/// Writes `pending.txt` and starts the swap script. The caller closes the application at once. +pub fn launch(release: &Release, paths: &Paths) -> Result<(), Fault> { + let updates = paths.pending.parent().expect("pending.txt is in a folder"); + std::fs::create_dir_all(updates) + .and_then(|()| std::fs::write(&paths.pending, release.version.to_string())) + .map_err(|error| Fault::CannotWrite(format!("{}: {error}", paths.pending.display())))?; + let _ = std::fs::remove_file(&paths.result); + let script = swap_script(std::process::id(), paths); + log::info!( + "update: installing {}; the application closes and comes back on it", + release.version + ); + crate::ffmpeg::tool("powershell.exe") + .args([ + "-NoProfile", + "-NonInteractive", + "-WindowStyle", + "Hidden", + "-Command", + ]) + .arg(script) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .map(drop) + .map_err(|error| { + let _ = std::fs::remove_file(&paths.pending); + Fault::Launch(error.to_string()) + }) +} + +/// At start: the outcome of an update the previous run started, if any, and tidying. `None` when no update +/// was pending. A leftover `.new` without a pending update (a download never installed) is deleted. +pub fn settle(paths: &Paths, current: Version) -> Option { + let Ok(text) = std::fs::read_to_string(&paths.pending) else { + if paths.new.is_file() { + let _ = std::fs::remove_file(&paths.new); + } + return None; + }; + let pending = Version::parse(text.trim_start_matches('\u{feff}').trim()); + let reason = std::fs::read_to_string(&paths.result) + .ok() + .map(|r| r.trim_start_matches('\u{feff}').trim().to_owned()); + let _ = std::fs::remove_file(&paths.pending); + let _ = std::fs::remove_file(&paths.result); + if pending == Some(current) { + log::info!("update: updated to {current}"); + if paths.old.is_file() { + let _ = std::fs::remove_file(&paths.old); + } + Some(Phase::Updated(current)) + } else { + // The download that was not installed goes: a new attempt downloads again. + if paths.new.is_file() { + let _ = std::fs::remove_file(&paths.new); + } + let reason = reason.unwrap_or_else(|| "did not take".to_owned()); + log::warn!( + "update: the update to {} failed ({reason}); still {current}", + text.trim() + ); + Some(Phase::Failed { + fault: Fault::Launch(reason), + release: None, + }) + } +} + +#[cfg(test)] +mod tests { + use std::sync::Mutex; + + use super::*; + + /// A scripted feed: fixed checksums and file, no network. + struct Scripted { + sums: String, + file: Vec, + seen: Mutex>, + } + + impl Feed for Scripted { + fn latest(&self) -> Result { + unreachable!() + } + fn text(&self, url: &str) -> Result { + self.seen.lock().unwrap().push(url.to_owned()); + Ok(self.sums.clone()) + } + fn download( + &self, + url: &str, + out: &mut dyn Write, + progress: &mut dyn FnMut(u64), + ) -> Result { + self.seen.lock().unwrap().push(url.to_owned()); + out.write_all(&self.file).unwrap(); + progress(self.file.len() as u64); + Ok(self.file.len() as u64) + } + } + + const HELLO_SHA256: &str = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"; + + fn release(digest: Option<&str>) -> Release { + Release { + version: Version(1, 1, 0), + page: String::new(), + notes: String::new(), + exe_url: "exe-url".to_owned(), + exe_size: 5, + exe_digest: digest.map(str::to_owned), + sums_url: "sums-url".to_owned(), + } + } + + fn setup() -> (tempfile::TempDir, Paths) { + let dir = tempfile::tempdir().unwrap(); + let exe = dir + .path() + .join("app folder") + .join("quick-video-transcoder.exe"); + std::fs::create_dir_all(exe.parent().unwrap()).unwrap(); + std::fs::write(&exe, b"old").unwrap(); + let paths = Paths::new(&exe, &dir.path().join("data")); + (dir, paths) + } + + #[test] + fn names_its_files_beside_the_executable_and_in_the_data_folder() { + let paths = Paths::new( + Path::new(r"C:\Tools\quick-video-transcoder.exe"), + Path::new(r"C:\Data"), + ); + assert_eq!( + paths.new, + Path::new(r"C:\Tools\quick-video-transcoder.exe.new") + ); + assert_eq!( + paths.old, + Path::new(r"C:\Tools\quick-video-transcoder.exe.old") + ); + assert_eq!(paths.pending, Path::new(r"C:\Data\updates\pending.txt")); + assert!(paths.is_sibling(&paths.new)); + assert!(!paths.is_sibling(&paths.exe)); + } + + #[test] + fn reads_the_checksums_file() { + let sums = format!( + "{} quick-video-transcoder.exe\n", + HELLO_SHA256.to_uppercase() + ); + assert_eq!( + published_hash(&sums, "quick-video-transcoder.exe").as_deref(), + Some(HELLO_SHA256) + ); + assert_eq!(published_hash(&sums, "other.exe"), None); + assert_eq!(published_hash("", "quick-video-transcoder.exe"), None); + } + + #[test] + fn keeps_a_verified_download_and_deletes_a_bad_one() { + let (_dir, paths) = setup(); + let good = Scripted { + sums: format!("{HELLO_SHA256} quick-video-transcoder.exe"), + file: b"hello".to_vec(), + seen: Mutex::default(), + }; + download(&good, &release(Some(HELLO_SHA256)), &paths, &mut |_| {}).unwrap(); + assert_eq!(std::fs::read(&paths.new).unwrap(), b"hello"); + assert_eq!( + std::fs::read(&paths.exe).unwrap(), + b"old", + "the executable is untouched" + ); + + let tampered = Scripted { + file: b"hellO".to_vec(), + ..good + }; + assert_eq!( + download(&tampered, &release(Some(HELLO_SHA256)), &paths, &mut |_| {}), + Err(Fault::NotVerified) + ); + assert!(!paths.new.exists(), "a file that did not verify is deleted"); + let disagreeing = release(Some(&"0".repeat(64))); + assert!(matches!( + download(&tampered, &disagreeing, &paths, &mut |_| {}), + Err(Fault::Unexpected(_)) + )); + } + + #[test] + fn the_script_quotes_every_path_and_puts_the_old_executable_back() { + let paths = Paths::new( + Path::new(r"C:\It's [a] folder\quick-video-transcoder.exe"), + Path::new(r"C:\Data"), + ); + let script = swap_script(4242, &paths); + assert!(script.contains("Wait-Process -Id 4242 -Timeout 30")); + assert!(script.contains(r"-LiteralPath 'C:\It''s [a] folder\quick-video-transcoder.exe'")); + assert!(!script.contains("\""), "no double quote reaches PowerShell"); + let rename = script + .find("-Destination 'C:\\It''s [a] folder\\quick-video-transcoder.exe.old'") + .unwrap(); + let start = script.find("Start-Process").unwrap(); + assert!(rename < start, "the swap happens before the restart"); + assert!(script.contains("catch")); + } + + #[test] + fn the_next_start_says_whether_the_update_took() { + let (_dir, paths) = setup(); + assert_eq!(settle(&paths, Version(1, 1, 0)), None); + + std::fs::create_dir_all(paths.pending.parent().unwrap()).unwrap(); + std::fs::write(&paths.pending, "\u{feff}1.1.0\r\n").unwrap(); + std::fs::write(&paths.old, b"old").unwrap(); + assert_eq!( + settle(&paths, Version(1, 1, 0)), + Some(Phase::Updated(Version(1, 1, 0))) + ); + assert!(!paths.old.exists() && !paths.pending.exists()); + + std::fs::write(&paths.pending, "1.1.0").unwrap(); + std::fs::write(&paths.result, "\u{feff}access denied").unwrap(); + assert_eq!( + settle(&paths, Version(1, 0, 0)), + Some(Phase::Failed { + fault: Fault::Launch("access denied".to_owned()), + release: None + }) + ); + assert!(!paths.result.exists()); + + std::fs::write(&paths.new, b"stale").unwrap(); + assert_eq!(settle(&paths, Version(1, 0, 0)), None); + assert!(!paths.new.exists(), "a download never installed is tidied"); + } +} diff --git a/src/update/mod.rs b/src/update/mod.rs new file mode 100644 index 0000000..9c1d5a9 --- /dev/null +++ b/src/update/mod.rs @@ -0,0 +1,340 @@ +//! Updating the application from its GitHub releases, from a window the user opens (*Help → Check for +//! updates*): check, download and verify, then swap the executable and restart. +//! +//! Rules this module is shaped by (docs/updating.md has the design and its measurements): +//! - **Never a silent connection.** Nothing connects unless the user clicked; no check at start. +//! - **The UI reflects [`Machine`]**: every rule (which actions a phase takes, what a result means) lives +//! here; the window draws [`Machine::phase`] and sends [`Event`]s. The worker runs the [`Effect`]s. +//! - **One release, named by its tag.** The check reads the latest release once; the download uses that +//! release's own URLs, so a release published in between cannot mix one version's file with another's +//! hash. A tag that is not exactly `vX.Y.Z` is "a release this version does not understand". Never a +//! downgrade. +//! - **Two witnesses to the file**: the workflow's `SHA256SUMS.txt` and GitHub's own digest of the asset, +//! both fetched over TLS, must equal the downloaded file's SHA-256. They protect against a corrupted or +//! truncated download, not against a compromised account (said in the docs). +//! - **The running executable is never written.** The new one is downloaded beside it +//! (`.new`, same folder, so the swap is a rename), and a hidden PowerShell started at exit waits for +//! this process to end, renames, restarts, and puts the old one back on failure ([`install`]). The +//! version that starts next says whether it worked, from `pending.txt` ([`install::settle`]). +//! - Tests never call GitHub: [`feed::Feed`] is scripted, and the HTTP feed is tested against a listener on +//! 127.0.0.1. + +pub mod feed; +pub mod install; + +use std::fmt; + +/// A version, `major.minor.patch`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct Version(pub u16, pub u16, pub u16); + +impl Version { + /// This executable's version. + pub fn current() -> Self { + Self::parse(crate::build_info::VERSION).expect("Cargo.toml has an x.y.z version") + } + + /// `1.2.3`, without suffix. + pub fn parse(text: &str) -> Option { + let mut parts = text.split('.').map(|p| { + (!p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())) + .then(|| p.parse::().ok()) + .flatten() + }); + let version = Self(parts.next()??, parts.next()??, parts.next()??); + parts.next().is_none().then_some(version) + } + + /// A release tag, exactly `vX.Y.Z`. + pub fn from_tag(tag: &str) -> Option { + Self::parse(tag.strip_prefix('v')?) + } +} + +impl fmt::Display for Version { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}.{}.{}", self.0, self.1, self.2) + } +} + +/// What the latest release offers. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Release { + /// Its version, from the tag. + pub version: Version, + /// Its page on GitHub. + pub page: String, + /// Its notes (the changelog section), Markdown. + pub notes: String, + /// The executable's download URL. + pub exe_url: String, + /// The executable's size in bytes. + pub exe_size: u64, + /// GitHub's SHA-256 of the executable, lower-case hex, when GitHub gives it. + pub exe_digest: Option, + /// `SHA256SUMS.txt`'s download URL. + pub sums_url: String, +} + +/// Why a step failed. Shown to the user by the window (localized there); the log has the details. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Fault { + /// No answer: no connection, DNS, timeout, TLS. The detail is technical. + NoConnection(String), + /// GitHub answered with this HTTP status. + Status(u16), + /// An answer this version does not understand (no such asset, a tag not `vX.Y.Z`, not JSON…). + Unexpected(String), + /// The downloaded file's SHA-256 is not the published one. + NotVerified, + /// The executable's folder cannot be written (installed under Program Files, read-only…). + CannotWrite(String), + /// The restart could not be started. + Launch(String), +} + +/// The updater's state. Starts [`Phase::Idle`], or with the outcome of an update that ran before this +/// start ([`install::settle`]). +#[derive(Clone, Debug, PartialEq)] +pub enum Phase { + /// Nothing asked. + Idle, + /// The check is running. + Checking, + /// This version is the latest. + UpToDate(Version), + /// A newer release exists. + Available(Release), + /// Downloading it: bytes so far. + Downloading(Release, u64), + /// Downloaded and verified beside the executable: restarting installs it. + Ready(Release), + /// The swap script is starting: the application closes now. + Restarting(Release), + /// The previous run updated to this version (said once, at start). + Updated(Version), + /// A step failed; `release` is kept when the failure came after a release was found. + Failed { + /// What failed. + fault: Fault, + /// The release found, if any (to offer its page). + release: Option, + }, +} + +/// What happened, sent by the window (a click) or the worker (a result). +#[derive(Clone, Debug, PartialEq)] +pub enum Event { + /// *Check for updates*. + CheckAsked, + /// The check's result: the latest release, or why it failed. + Checked(Result), + /// *Download and install*. + DownloadAsked, + /// Bytes downloaded so far. + Progress(u64), + /// The download's result (verified or not). + Downloaded(Result<(), Fault>), + /// *Restart now* (the window checks nothing is encoding first). + RestartAsked, + /// The swap script could not be started. + LaunchFailed(Fault), +} + +/// Work the worker must do for an event. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Effect { + /// Read the latest release. + Check, + /// Download and verify this release beside the executable. + Download(Release), + /// Write `pending.txt`, start the swap script and close the application. + Restart(Release), +} + +/// The update state machine. Pure: no I/O, so every rule is tested. +#[derive(Clone, Debug, PartialEq)] +pub struct Machine { + phase: Phase, + current: Version, +} + +impl Machine { + /// A machine for the running version, starting in `phase`. + pub fn new(current: Version, phase: Phase) -> Self { + Self { phase, current } + } + + /// The current phase, for the window. + pub fn phase(&self) -> &Phase { + &self.phase + } + + /// Applies an event and returns the work it asks for. An event the phase does not take (a click on a + /// stale button, a result nobody waits for) changes nothing. + pub fn apply(&mut self, event: Event) -> Option { + use Phase as P; + let (phase, effect) = match (&self.phase, event) { + ( + P::Idle | P::UpToDate(_) | P::Available(_) | P::Updated(_) | P::Failed { .. }, + Event::CheckAsked, + ) => (P::Checking, Some(Effect::Check)), + (P::Checking, Event::Checked(Ok(release))) => { + if release.version > self.current { + (P::Available(release), None) + } else { + // Equal, or older (a release withdrawn): never offered as an update. + (P::UpToDate(self.current), None) + } + } + (P::Checking, Event::Checked(Err(fault))) => ( + P::Failed { + fault, + release: None, + }, + None, + ), + (P::Available(release), Event::DownloadAsked) + | ( + P::Failed { + release: Some(release), + .. + }, + Event::DownloadAsked, + ) => ( + P::Downloading(release.clone(), 0), + Some(Effect::Download(release.clone())), + ), + (P::Downloading(release, _), Event::Progress(done)) => { + (P::Downloading(release.clone(), done), None) + } + (P::Downloading(release, _), Event::Downloaded(Ok(()))) => { + (P::Ready(release.clone()), None) + } + (P::Downloading(release, _), Event::Downloaded(Err(fault))) => ( + P::Failed { + fault, + release: Some(release.clone()), + }, + None, + ), + (P::Ready(release), Event::RestartAsked) => ( + P::Restarting(release.clone()), + Some(Effect::Restart(release.clone())), + ), + (P::Restarting(release), Event::LaunchFailed(fault)) => ( + P::Failed { + fault, + release: Some(release.clone()), + }, + None, + ), + _ => return None, + }; + self.phase = phase; + effect + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn release(version: Version) -> Release { + Release { + version, + page: format!("https://example.invalid/v{version}"), + notes: "### Added\n\n- something".to_owned(), + exe_url: "https://example.invalid/exe".to_owned(), + exe_size: 1000, + exe_digest: Some("ab".repeat(32)), + sums_url: "https://example.invalid/sums".to_owned(), + } + } + + #[test] + fn reads_versions_and_tags_strictly() { + assert_eq!(Version::parse("1.10.0"), Some(Version(1, 10, 0))); + assert_eq!(Version::from_tag("v2.0.1"), Some(Version(2, 0, 1))); + for bad in [ + "1.0", + "1.0.0.0", + "1.0.0-beta", + "v1.0.0", + "1..0", + "", + "a.b.c", + ] { + assert_eq!(Version::parse(bad), None, "{bad}"); + } + assert_eq!(Version::from_tag("1.0.0"), None); + assert_eq!(Version::from_tag("v1.0.0-rc1"), None); + assert!(Version(1, 10, 0) > Version(1, 9, 9)); + assert_eq!(Version(1, 2, 3).to_string(), "1.2.3"); + } + + #[test] + fn checks_downloads_and_restarts_in_order() { + let mut machine = Machine::new(Version(1, 0, 0), Phase::Idle); + assert_eq!( + machine.apply(Event::DownloadAsked), + None, + "nothing to download yet" + ); + assert_eq!(machine.apply(Event::CheckAsked), Some(Effect::Check)); + assert_eq!( + machine.apply(Event::CheckAsked), + None, + "one check at a time" + ); + let newer = release(Version(1, 1, 0)); + assert_eq!(machine.apply(Event::Checked(Ok(newer.clone()))), None); + assert_eq!(machine.phase(), &Phase::Available(newer.clone())); + assert_eq!( + machine.apply(Event::DownloadAsked), + Some(Effect::Download(newer.clone())) + ); + assert_eq!( + machine.apply(Event::CheckAsked), + None, + "not during a download" + ); + machine.apply(Event::Progress(500)); + assert_eq!(machine.phase(), &Phase::Downloading(newer.clone(), 500)); + machine.apply(Event::Downloaded(Ok(()))); + assert_eq!(machine.phase(), &Phase::Ready(newer.clone())); + assert_eq!( + machine.apply(Event::RestartAsked), + Some(Effect::Restart(newer.clone())) + ); + machine.apply(Event::LaunchFailed(Fault::Launch("x".to_owned()))); + assert!(matches!(machine.phase(), Phase::Failed { release: Some(r), .. } if *r == newer)); + } + + #[test] + fn never_offers_the_same_or_an_older_version() { + for latest in [Version(1, 0, 0), Version(0, 9, 0)] { + let mut machine = Machine::new(Version(1, 0, 0), Phase::Idle); + machine.apply(Event::CheckAsked); + machine.apply(Event::Checked(Ok(release(latest)))); + assert_eq!(machine.phase(), &Phase::UpToDate(Version(1, 0, 0))); + assert_eq!(machine.apply(Event::DownloadAsked), None); + } + } + + #[test] + fn a_failed_download_can_be_retried_and_a_failed_check_checked_again() { + let newer = release(Version(1, 1, 0)); + let mut machine = Machine::new(Version(1, 0, 0), Phase::Available(newer.clone())); + machine.apply(Event::DownloadAsked); + machine.apply(Event::Downloaded(Err(Fault::NotVerified))); + assert_eq!( + machine.apply(Event::DownloadAsked), + Some(Effect::Download(newer)) + ); + let mut offline = Machine::new(Version(1, 0, 0), Phase::Checking); + offline.apply(Event::Checked(Err(Fault::NoConnection("dns".to_owned())))); + assert_eq!(offline.apply(Event::DownloadAsked), None); + assert_eq!(offline.apply(Event::CheckAsked), Some(Effect::Check)); + } +}