juicewrld-desktopsrc-taurisrcupdate.rs
1.4.2Released Nov 21, 2026
update.rs
162 lines7.6 KBRust//! Updates, through Tauri's updater and the site's endpoint (plugins.updater in tauri.conf.json://! /api/app/update/<target>/<arch>/<version>, which answers 204 or the new version with its installer and signature).//! A minute after start and then every few hours the app asks. A newer version downloads quietly: the installer, its//! minisign signature checked against the public key in tauri.conf.json and bound to the version it was signed for. The//! title bar then offers "Update ready" (bar.js), which restarts into it: the app closes, the installer runs silently//! (`/S /UPDATE /R`) and opens the new version. An update nobody restarted for installs as the app closes, without//! opening it again. Nothing installs while the app is open, so playback is never cut off.//!//! A portable copy (no uninstaller beside the exe) installs only from the title bar, and the installer then puts the app//! in place as a first install does, shortcuts included (nsis/installer.nsi), and opens it.use serde::Serialize;use serde_json::json;use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Mutex, MutexGuard};use std::time::{Duration, SystemTime};use tauri::{AppHandle, Manager};use tauri_plugin_updater::{Update, UpdaterExt};/// The first look, once the site has loaded and settled.const FIRST: Duration = Duration::from_secs(60);/// Then this often, on the wall clock, so a PC that slept through it looks soon after it wakes (within TICK).const EVERY: Duration = Duration::from_secs(4 * 3600);const TICK: Duration = Duration::from_secs(10 * 60);/// The check itself, and the whole download (4 MB; minutes on a slow line): past that it waits for the next look.const CHECK_TIMEOUT: Duration = Duration::from_secs(30);const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(10 * 60);/// What the title bar offers once an update has downloaded.pub struct Offer { pub version: String, /// The app runs from its install folder; a portable copy's update installs the app. pub installed: bool,}pub struct Updates { /// The downloaded update, its signature already checked. ready: Mutex<Option<(Update, Vec<u8>)>>, /// Update ready was pressed: the new version opens once installed. restart: AtomicBool,}fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> { m.lock().unwrap_or_else(|e| e.into_inner())}impl Updates { pub fn offer(&self) -> Option<Offer> { lock(&self.ready).as_ref().map(|(u, _)| Offer { version: u.version.clone(), installed: installed() }) }}/// The installer leaves its uninstaller beside the exe it installs; the portable exe runs from anywhere else.fn installed() -> bool { std::env::current_exe().map(|exe| exe.with_file_name("uninstall.exe").is_file()).unwrap_or(false)}/// Starts the looks for updates, on a thread of their own. A debug build (npm run dev) never looks: it isn't a release,/// and it would count as an install.pub fn start(app: &AppHandle) { if cfg!(debug_assertions) { return; } let app = app.clone(); let _ = std::thread::Builder::new().name("updates".into()).spawn(move || { std::thread::sleep(FIRST); let mut last: Option<SystemTime> = None; loop { // A clock set back reads as due. if last.is_none_or(|t| t.elapsed().map_or(true, |e| e >= EVERY)) { last = Some(SystemTime::now()); tauri::async_runtime::block_on(check(&app)); } std::thread::sleep(TICK); } });}/// One look: a newer version than the one running (and than one already downloaded) downloads, then the bar offers it.async fn check(app: &AppHandle) { let updater = match app.updater_builder().timeout(CHECK_TIMEOUT).build() { Ok(u) => u, Err(e) => return eprintln!("[update] no updater ({e})"), }; let mut update = match updater.check().await { Ok(Some(u)) => u, Ok(None) => return, Err(e) => return eprintln!("[update] couldn't check ({e})"), }; let state = app.state::<Updates>(); if state.offer().is_some_and(|o| o.version == update.version) { return; } eprintln!("[update] {} is out; downloading it", update.version); update.timeout = Some(DOWNLOAD_TIMEOUT); match update.download(|_, _| {}, || {}).await { Ok(bytes) => { eprintln!("[update] {} is ready", update.version); *lock(&state.ready) = Some((update, bytes)); crate::bar_call(app, "update", json!(state.offer())); } Err(e) => eprintln!("[update] the download failed ({e}); trying again at the next look"), }}/// Update ready, pressed: the app closes, and installs the update as it goes (`on_exit`), then opens again.pub fn restart(app: &AppHandle) -> Result<(), String> { let state = app.state::<Updates>(); if lock(&state.ready).is_none() { return Err("no update is ready".into()); } state.restart.store(true, Ordering::SeqCst); app.exit(0); Ok(())}/// The app is closing (RunEvent::Exit, after the window and its state are saved): a downloaded update installs now. The/// installer opens the new version only when Update ready asked for it; a portable copy installs only then.pub fn on_exit(app: &AppHandle) { let state = app.state::<Updates>(); let restart = state.restart.load(Ordering::SeqCst); let Some((update, bytes)) = lock(&state.ready).take() else { return }; if !restart && !installed() { return; } eprintln!("[update] installing {}{}", update.version, if restart { ", then opening it" } else { "" }); // On success this hands over to the installer and ends the process. if let Err(e) = update.restart_after_install(restart).install(&bytes) { eprintln!("[update] couldn't start the installer ({e})"); if restart { // Asked to restart: open this version again rather than leave nothing on screen. app.restart(); } }}mod tests { use tauri_plugin_updater::Config; /// The plugin reads plugins.updater as the app starts, and a value it refuses stops the app: read it the same way here. fn the_updater_config_is_one_the_plugin_takes() { let conf: serde_json::Value = serde_json::from_str(include_str!("../tauri.conf.json")).expect("tauri.conf.json"); let config: Config = serde_json::from_value(conf["plugins"]["updater"].clone()).expect("plugins.updater"); assert_eq!(config.endpoints.len(), 1); let endpoint = config.endpoints[0].as_str().replace("%7B", "{").replace("%7D", "}"); assert_eq!(endpoint, "https://juicewrld.io/api/app/update/{{target}}/{{arch}}/{{current_version}}"); assert!(config.require_signed_version, "a signature must name the version it was made for"); assert!(!config.dangerous_insecure_transport_protocol && !config.dangerous_accept_invalid_certs); // Silent installs: the title bar's restart and the install on close both run the installer with /S. let windows = config.windows.expect("plugins.updater.windows"); assert_eq!(windows.install_mode.to_string(), "quiet"); assert_eq!(windows.install_mode.nsis_args(), ["/S"]); // A minisign public key: its text, base64 as Tauri keeps it, ends with the key line ("RW" and 54 more). let text = String::from_utf8(base64::Engine::decode(&base64::engine::general_purpose::STANDARD, &config.pubkey).expect("base64")).expect("text"); assert!(text.starts_with("untrusted comment: minisign public key: ")); assert!(text.trim_end().lines().last().is_some_and(|l| l.starts_with("RW") && l.len() == 56)); }}