diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index be9ec5e..b4b90c8 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -227,6 +227,52 @@ struct DownloadProgress { total: Option, } +#[derive(Clone, Serialize)] +struct UpdateDownloadProgress { + downloaded: u64, + total: Option, +} + +#[tauri::command] +async fn download_update( + app: AppHandle, + state: State<'_, AppState>, + url: String, +) -> Result<(), String> { + let dest = updates::pending_update_path(&state.app_dir); + let app_handle = app.clone(); + updates::download_to(&url, &dest, move |downloaded, total| { + let _ = app_handle.emit( + "update-download-progress", + UpdateDownloadProgress { downloaded, total }, + ); + }) + .await + .map_err(|e| format!("{e:#}")) +} + +#[tauri::command] +fn apply_update(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> { + use std::os::windows::process::CommandExt; + use std::process::Command; + if !updates::has_pending_update(&state.app_dir) { + return Err("no pending update to apply".to_string()); + } + let bat = updates::write_apply_script(&state.app_dir).map_err(|e| format!("{e:#}"))?; + Command::new("cmd") + .args(["/c", "start", "", ""]) + .raw_arg(format!("\"{}\"", bat.to_string_lossy())) + .spawn() + .map_err(|e| format!("spawning apply script: {e}"))?; + app.exit(0); + Ok(()) +} + +#[tauri::command] +fn pending_update(state: State<'_, AppState>) -> bool { + updates::has_pending_update(&state.app_dir) +} + #[tauri::command] async fn download_ffmpeg(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> { let app_dir = state.app_dir.clone(); @@ -999,6 +1045,9 @@ pub fn run() { get_config, save_config, download_ffmpeg, + download_update, + apply_update, + pending_update, start_capture, pause_capture, resume_capture, diff --git a/src-tauri/src/updates.rs b/src-tauri/src/updates.rs index f7c1bd5..614a7a6 100644 --- a/src-tauri/src/updates.rs +++ b/src-tauri/src/updates.rs @@ -1,4 +1,7 @@ -use anyhow::Result; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result}; +use futures_util::StreamExt; use serde::{Deserialize, Serialize}; const GITEA_LATEST: &str = @@ -10,6 +13,7 @@ pub struct UpdateInfo { pub current_version: String, pub release_url: String, pub body: String, + pub download_url: Option, } #[derive(Debug, Deserialize)] @@ -17,6 +21,14 @@ 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 async fn check_for_update() -> Result> { @@ -33,17 +45,77 @@ pub async fn check_for_update() -> Result> { 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 async fn download_to(url: &str, dest: &Path, mut on_progress: F) -> Result<()> +where + F: FnMut(u64, Option) + Send, +{ + 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")?; + use std::io::Write; + 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 fn pending_update_path(app_dir: &Path) -> PathBuf { + app_dir.join("ByteSize.new.exe") +} + +pub fn has_pending_update(app_dir: &Path) -> bool { + pending_update_path(app_dir).is_file() +} + +pub 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 1 /nobreak >nul\r\n\ + del \"%~dp0{exe}\"\r\n\ + move /Y \"%~dp0ByteSize.new.exe\" \"%~dp0{exe}\" >nul\r\n\ + start \"\" \"%~dp0{exe}\"\r\n\ + del \"%~f0\"\r\n", + exe = exe_name + ); + std::fs::write(&bat_path, body).context("writing apply script")?; + Ok(bat_path) +} + fn is_newer(latest: &str, current: &str) -> bool { let mut l: Vec = latest.split('.').filter_map(|s| s.parse().ok()).collect(); let mut c: Vec = current.split('.').filter_map(|s| s.parse().ok()).collect(); diff --git a/src/lib/UpdateBanner.svelte b/src/lib/UpdateBanner.svelte index 964cb19..e8880a2 100644 --- a/src/lib/UpdateBanner.svelte +++ b/src/lib/UpdateBanner.svelte @@ -1,25 +1,69 @@ -{#if info} +{#if info || phase === "ready-to-apply"} {/if} @@ -83,6 +159,11 @@ display: flex; gap: 0.4rem; flex-shrink: 0; + align-items: center; + } + .muted { + color: #7a8e88; + font-size: 0.85rem; } button { font: inherit; diff --git a/src/lib/api.ts b/src/lib/api.ts index f385b3f..87501ab 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -56,6 +56,12 @@ export type UpdateInfo = { current_version: string release_url: string body: string + download_url: string | null +} + +export type UpdateDownloadProgress = { + downloaded: number + total: number | null } export type CaptureRect = { @@ -132,6 +138,15 @@ export const api = { listen("update-available", (e) => handler(e.payload)), onHotkey: (handler: (kind: "start" | "stop" | "pause") => void): Promise => listen<"start" | "stop" | "pause">("hotkey", (e) => handler(e.payload)), + downloadUpdate: (url: string) => invoke("download_update", { url }), + applyUpdate: () => invoke("apply_update"), + pendingUpdate: () => invoke("pending_update"), + onUpdateDownloadProgress: ( + handler: (p: UpdateDownloadProgress) => void, + ): Promise => + listen("update-download-progress", (e) => + handler(e.payload), + ), } export function formatBytes(n: number): string {