use std::path::{Path, PathBuf}; use anyhow::{bail, Context, Result}; use futures_util::StreamExt; use serde::{Deserialize, Serialize}; const GITEA_LATEST: &str = "https://git.lashman.live/api/v1/repos/lashman/bytesize/releases/latest"; /// Everything the updater will fetch has to live under this prefix. The download /// URL arrives from the frontend, and an unconstrained one there would let /// anything that can reach the webview hand the app a new executable to install. const UPDATE_ORIGIN: &str = "https://git.lashman.live/"; #[derive(Debug, Clone, Serialize)] pub(crate) struct UpdateInfo { pub version: String, pub current_version: String, pub release_url: String, pub body: String, pub download_url: Option, } #[derive(Debug, Deserialize)] struct GiteaRelease { tag_name: String, body: Option, html_url: String, #[serde(default)] assets: Vec, } #[derive(Debug, Deserialize)] struct GiteaAsset { name: String, browser_download_url: String, } pub(crate) async fn check_for_update() -> Result> { let client = reqwest::Client::builder() .user_agent(concat!("ByteSize/", env!("CARGO_PKG_VERSION"))) .build()?; let resp = client.get(GITEA_LATEST).send().await?; if !resp.status().is_success() { // A 404 means the endpoint itself is wrong or the repo has no releases - // not that the app is up to date, which is how it reads if this is only // ever a debug line. if resp.status() == reqwest::StatusCode::NOT_FOUND { tracing::warn!("no release published at {GITEA_LATEST}"); } else { tracing::warn!("update check returned status {}", resp.status()); } return Ok(None); } let body = resp.text().await?; let release: GiteaRelease = serde_json::from_str(&body)?; let latest = release.tag_name.trim_start_matches('v').to_string(); let current = env!("CARGO_PKG_VERSION").to_string(); if is_newer(&latest, ¤t) { let download_url = release .assets .iter() .find(|a| a.name.eq_ignore_ascii_case("ByteSize.exe")) .or_else(|| { release .assets .iter() .find(|a| a.name.to_lowercase().ends_with(".exe")) }) .map(|a| a.browser_download_url.clone()); Ok(Some(UpdateInfo { version: latest, current_version: current, release_url: release.html_url, body: release.body.unwrap_or_default(), download_url, })) } else { Ok(None) } } pub(crate) async fn download_to(url: &str, dest: &Path, mut on_progress: F) -> Result<()> where F: FnMut(u64, Option) + Send, { use std::io::Write; if !url.starts_with(UPDATE_ORIGIN) { bail!("refusing to download an update from {url}"); } if let Some(parent) = dest.parent() { std::fs::create_dir_all(parent).context("creating update parent dir")?; } let client = reqwest::Client::builder() .user_agent(concat!("ByteSize/", env!("CARGO_PKG_VERSION"))) .build()?; let resp = client.get(url).send().await?.error_for_status()?; let total = resp.content_length(); let mut downloaded = 0u64; let mut stream = resp.bytes_stream(); let mut file = std::fs::File::create(dest).context("creating update file")?; while let Some(chunk) = stream.next().await { let chunk = chunk?; file.write_all(&chunk)?; downloaded += chunk.len() as u64; on_progress(downloaded, total); } file.flush()?; Ok(()) } pub(crate) fn pending_update_path(app_dir: &Path) -> PathBuf { app_dir.join("ByteSize.new.exe") } fn last_check_path(app_dir: &Path) -> PathBuf { app_dir.join("temp").join("last-update-check") } /// Returns true if the last successful update check happened more than `ttl` /// ago, or never. The stamp file's mtime is the source of truth. pub(crate) fn should_check(app_dir: &Path, ttl: std::time::Duration) -> bool { let path = last_check_path(app_dir); let Ok(meta) = std::fs::metadata(&path) else { return true; }; let Ok(modified) = meta.modified() else { return true; }; let Ok(elapsed) = modified.elapsed() else { return true; }; elapsed > ttl } pub(crate) fn stamp_check(app_dir: &Path) { let path = last_check_path(app_dir); if let Some(parent) = path.parent() { drop(std::fs::create_dir_all(parent)); } drop(std::fs::write(&path, b"")); } pub(crate) fn has_pending_update(app_dir: &Path) -> bool { pending_update_path(app_dir).is_file() } pub(crate) fn write_apply_script(app_dir: &Path) -> Result { let bat_path = app_dir.join("bytesize-apply-update.bat"); let exe_name = std::env::current_exe() .ok() .and_then(|p| p.file_name().map(|s| s.to_string_lossy().into_owned())) .unwrap_or_else(|| "ByteSize.exe".to_string()); let body = format!( "@echo off\r\n\ timeout /t 3 /nobreak >nul\r\n\ :retry\r\n\ del \"%~dp0{exe_name}\" 2>nul\r\n\ if exist \"%~dp0{exe_name}\" (\r\n\ timeout /t 2 /nobreak >nul\r\n\ goto retry\r\n\ )\r\n\ move /Y \"%~dp0ByteSize.new.exe\" \"%~dp0{exe_name}\" >nul\r\n\ if errorlevel 1 (\r\n\ echo Failed to replace executable\r\n\ pause\r\n\ del \"%~f0\"\r\n\ exit /b 1\r\n\ )\r\n\ start \"\" \"%~dp0{exe_name}\"\r\n\ del \"%~f0\"\r\n" ); std::fs::write(&bat_path, body).context("writing apply script")?; Ok(bat_path) } #[derive(Debug, PartialEq, Eq)] struct VersionParts { nums: Vec, pre: Option, } fn parse_version(v: &str) -> VersionParts { let trimmed = v.trim().trim_start_matches('v'); let (core, pre) = trimmed .split_once('-') .map(|(core, pre)| (core, Some(pre.to_ascii_lowercase()))) .unwrap_or((trimmed, None)); let nums = core .split('.') .map(|s| s.parse::().unwrap_or(0)) .collect(); VersionParts { nums, pre } } fn is_newer(latest: &str, current: &str) -> bool { let mut l = parse_version(latest); let mut c = parse_version(current); let max = l.nums.len().max(c.nums.len()); l.nums.resize(max, 0); c.nums.resize(max, 0); if l.nums != c.nums { return l.nums > c.nums; } match (&l.pre, &c.pre) { (None, Some(_)) => true, (Some(a), Some(b)) => a > b, // A prerelease never outranks a stable tag of the same version. (Some(_) | None, None) => false, } } #[cfg(test)] mod tests { use super::is_newer; #[test] fn version_major_bump() { assert!(is_newer("2.0.0", "1.9.9")); assert!(!is_newer("1.9.9", "2.0.0")); } #[test] fn version_minor_bump() { assert!(is_newer("1.1.0", "1.0.0")); assert!(!is_newer("1.0.0", "1.1.0")); } #[test] fn version_patch_bump() { assert!(is_newer("1.0.1", "1.0.0")); assert!(!is_newer("1.0.0", "1.0.1")); } #[test] fn version_equal() { assert!(!is_newer("1.0.0", "1.0.0")); } #[test] fn version_different_lengths() { assert!(is_newer("1.0.1", "1.0")); assert!(!is_newer("1.0", "1.0.1")); assert!(is_newer("1.1", "1.0.9")); } #[test] fn version_ignores_extra_text() { assert!(is_newer("1.0.0-beta", "0.9.0")); } #[test] fn stable_is_newer_than_matching_prerelease() { assert!(is_newer("1.0.0", "1.0.0-beta")); assert!(!is_newer("1.0.0-beta", "1.0.0")); } #[test] fn prerelease_compares_when_core_matches() { assert!(is_newer("1.0.0-rc", "1.0.0-beta")); assert!(!is_newer("1.0.0-beta", "1.0.0-rc")); } }