update download + apply flow

This commit is contained in:
2026-05-12 01:59:39 +03:00
parent 953263028b
commit 61fbe68251
4 changed files with 233 additions and 16 deletions
+49
View File
@@ -227,6 +227,52 @@ struct DownloadProgress {
total: Option<u64>, total: Option<u64>,
} }
#[derive(Clone, Serialize)]
struct UpdateDownloadProgress {
downloaded: u64,
total: Option<u64>,
}
#[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] #[tauri::command]
async fn download_ffmpeg(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> { async fn download_ffmpeg(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> {
let app_dir = state.app_dir.clone(); let app_dir = state.app_dir.clone();
@@ -999,6 +1045,9 @@ pub fn run() {
get_config, get_config,
save_config, save_config,
download_ffmpeg, download_ffmpeg,
download_update,
apply_update,
pending_update,
start_capture, start_capture,
pause_capture, pause_capture,
resume_capture, resume_capture,
+73 -1
View File
@@ -1,4 +1,7 @@
use anyhow::Result; use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use futures_util::StreamExt;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
const GITEA_LATEST: &str = const GITEA_LATEST: &str =
@@ -10,6 +13,7 @@ pub struct UpdateInfo {
pub current_version: String, pub current_version: String,
pub release_url: String, pub release_url: String,
pub body: String, pub body: String,
pub download_url: Option<String>,
} }
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
@@ -17,6 +21,14 @@ struct GiteaRelease {
tag_name: String, tag_name: String,
body: Option<String>, body: Option<String>,
html_url: String, html_url: String,
#[serde(default)]
assets: Vec<GiteaAsset>,
}
#[derive(Debug, Deserialize)]
struct GiteaAsset {
name: String,
browser_download_url: String,
} }
pub async fn check_for_update() -> Result<Option<UpdateInfo>> { pub async fn check_for_update() -> Result<Option<UpdateInfo>> {
@@ -33,17 +45,77 @@ pub async fn check_for_update() -> Result<Option<UpdateInfo>> {
let latest = release.tag_name.trim_start_matches('v').to_string(); let latest = release.tag_name.trim_start_matches('v').to_string();
let current = env!("CARGO_PKG_VERSION").to_string(); let current = env!("CARGO_PKG_VERSION").to_string();
if is_newer(&latest, &current) { if is_newer(&latest, &current) {
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 { Ok(Some(UpdateInfo {
version: latest, version: latest,
current_version: current, current_version: current,
release_url: release.html_url, release_url: release.html_url,
body: release.body.unwrap_or_default(), body: release.body.unwrap_or_default(),
download_url,
})) }))
} else { } else {
Ok(None) Ok(None)
} }
} }
pub async fn download_to<F>(url: &str, dest: &Path, mut on_progress: F) -> Result<()>
where
F: FnMut(u64, Option<u64>) + 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<PathBuf> {
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 { fn is_newer(latest: &str, current: &str) -> bool {
let mut l: Vec<u32> = latest.split('.').filter_map(|s| s.parse().ok()).collect(); let mut l: Vec<u32> = latest.split('.').filter_map(|s| s.parse().ok()).collect();
let mut c: Vec<u32> = current.split('.').filter_map(|s| s.parse().ok()).collect(); let mut c: Vec<u32> = current.split('.').filter_map(|s| s.parse().ok()).collect();
+96 -15
View File
@@ -1,25 +1,69 @@
<script lang="ts"> <script lang="ts">
import { onMount } from "svelte" import { onMount } from "svelte"
import { api, type UpdateInfo } from "./api" import { api, formatBytes, type UpdateInfo, type UpdateDownloadProgress } from "./api"
type Phase = "info" | "downloading" | "ready-to-apply" | "error"
let info: UpdateInfo | null = $state(null) let info: UpdateInfo | null = $state(null)
let phase: Phase = $state("info")
let progress: UpdateDownloadProgress | null = $state(null)
let errMsg: string | null = $state(null)
onMount(() => { onMount(() => {
const unlistenPromise = api.onUpdateAvailable((i) => { let unlistenInfo: (() => void) | null = null
info = i let unlistenProgress: (() => void) | null = null
}) void (async () => {
unlistenInfo = await api.onUpdateAvailable((i) => {
info = i
phase = "info"
})
unlistenProgress = await api.onUpdateDownloadProgress((p) => {
progress = p
})
if (await api.pendingUpdate()) {
phase = "ready-to-apply"
}
})()
return () => { return () => {
unlistenPromise.then((fn) => fn()) unlistenInfo?.()
unlistenProgress?.()
} }
}) })
function dismiss() { function dismiss() {
info = null info = null
phase = "info"
errMsg = null
} }
function viewRelease() { function viewRelease() {
if (info) { if (info) void api.openUrl(info.release_url)
void api.openUrl(info.release_url) }
async function download() {
if (!info?.download_url) {
errMsg = "this release has no downloadable exe asset"
phase = "error"
return
}
phase = "downloading"
progress = null
errMsg = null
try {
await api.downloadUpdate(info.download_url)
phase = "ready-to-apply"
} catch (e) {
errMsg = String(e)
phase = "error"
}
}
async function apply() {
try {
await api.applyUpdate()
} catch (e) {
errMsg = String(e)
phase = "error"
} }
} }
@@ -30,19 +74,51 @@
}) })
</script> </script>
{#if info} {#if info || phase === "ready-to-apply"}
<div class="banner"> <div class="banner">
<div class="text"> <div class="text">
<strong>update available</strong> {#if phase === "ready-to-apply"}
<span class="ver">v{info.version}</span> <strong>update ready to apply</strong>
<span class="from">(you have v{info.current_version})</span> {#if info}
{#if bodyPreview} <span class="ver">v{info.version}</span>
<p class="body">{bodyPreview}{info.body.length > 140 ? "..." : ""}</p> {/if}
<p class="body">click apply to swap and restart, or dismiss to keep the current version.</p>
{:else if phase === "downloading"}
<strong>downloading update...</strong>
{#if info}<span class="ver">v{info.version}</span>{/if}
{#if progress}
<p class="body">
{formatBytes(progress.downloaded)}
{#if progress.total} / {formatBytes(progress.total)}{/if}
</p>
{/if}
{:else if phase === "error"}
<strong>update error</strong>
<p class="body">{errMsg}</p>
{:else if info}
<strong>update available</strong>
<span class="ver">v{info.version}</span>
<span class="from">(you have v{info.current_version})</span>
{#if bodyPreview}
<p class="body">{bodyPreview}{info.body.length > 140 ? "..." : ""}</p>
{/if}
{/if} {/if}
</div> </div>
<div class="actions"> <div class="actions">
<button class="primary" onclick={viewRelease}>view release</button> {#if phase === "ready-to-apply"}
<button onclick={dismiss}>dismiss</button> <button class="primary" onclick={apply}>apply now</button>
<button onclick={dismiss}>dismiss</button>
{:else if phase === "downloading"}
<span class="muted">working...</span>
{:else if phase === "error"}
<button onclick={dismiss}>dismiss</button>
{:else if info}
{#if info.download_url}
<button class="primary" onclick={download}>download</button>
{/if}
<button onclick={viewRelease}>view release</button>
<button onclick={dismiss}>dismiss</button>
{/if}
</div> </div>
</div> </div>
{/if} {/if}
@@ -83,6 +159,11 @@
display: flex; display: flex;
gap: 0.4rem; gap: 0.4rem;
flex-shrink: 0; flex-shrink: 0;
align-items: center;
}
.muted {
color: #7a8e88;
font-size: 0.85rem;
} }
button { button {
font: inherit; font: inherit;
+15
View File
@@ -56,6 +56,12 @@ export type UpdateInfo = {
current_version: string current_version: string
release_url: string release_url: string
body: string body: string
download_url: string | null
}
export type UpdateDownloadProgress = {
downloaded: number
total: number | null
} }
export type CaptureRect = { export type CaptureRect = {
@@ -132,6 +138,15 @@ export const api = {
listen<UpdateInfo>("update-available", (e) => handler(e.payload)), listen<UpdateInfo>("update-available", (e) => handler(e.payload)),
onHotkey: (handler: (kind: "start" | "stop" | "pause") => void): Promise<UnlistenFn> => onHotkey: (handler: (kind: "start" | "stop" | "pause") => void): Promise<UnlistenFn> =>
listen<"start" | "stop" | "pause">("hotkey", (e) => handler(e.payload)), listen<"start" | "stop" | "pause">("hotkey", (e) => handler(e.payload)),
downloadUpdate: (url: string) => invoke<void>("download_update", { url }),
applyUpdate: () => invoke<void>("apply_update"),
pendingUpdate: () => invoke<boolean>("pending_update"),
onUpdateDownloadProgress: (
handler: (p: UpdateDownloadProgress) => void,
): Promise<UnlistenFn> =>
listen<UpdateDownloadProgress>("update-download-progress", (e) =>
handler(e.payload),
),
} }
export function formatBytes(n: number): string { export function formatBytes(n: number): string {