update download + apply flow
This commit is contained in:
@@ -227,6 +227,52 @@ struct DownloadProgress {
|
||||
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]
|
||||
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,
|
||||
|
||||
@@ -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<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
@@ -17,6 +21,14 @@ struct GiteaRelease {
|
||||
tag_name: String,
|
||||
body: Option<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>> {
|
||||
@@ -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 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<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 {
|
||||
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();
|
||||
|
||||
@@ -1,25 +1,69 @@
|
||||
<script lang="ts">
|
||||
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 phase: Phase = $state("info")
|
||||
let progress: UpdateDownloadProgress | null = $state(null)
|
||||
let errMsg: string | null = $state(null)
|
||||
|
||||
onMount(() => {
|
||||
const unlistenPromise = api.onUpdateAvailable((i) => {
|
||||
let unlistenInfo: (() => void) | null = null
|
||||
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 () => {
|
||||
unlistenPromise.then((fn) => fn())
|
||||
unlistenInfo?.()
|
||||
unlistenProgress?.()
|
||||
}
|
||||
})
|
||||
|
||||
function dismiss() {
|
||||
info = null
|
||||
phase = "info"
|
||||
errMsg = null
|
||||
}
|
||||
|
||||
function viewRelease() {
|
||||
if (info) {
|
||||
void api.openUrl(info.release_url)
|
||||
if (info) 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>
|
||||
|
||||
{#if info}
|
||||
{#if info || phase === "ready-to-apply"}
|
||||
<div class="banner">
|
||||
<div class="text">
|
||||
{#if phase === "ready-to-apply"}
|
||||
<strong>update ready to apply</strong>
|
||||
{#if info}
|
||||
<span class="ver">v{info.version}</span>
|
||||
{/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}
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button class="primary" onclick={viewRelease}>view release</button>
|
||||
{#if phase === "ready-to-apply"}
|
||||
<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>
|
||||
{/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;
|
||||
|
||||
@@ -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<UpdateInfo>("update-available", (e) => handler(e.payload)),
|
||||
onHotkey: (handler: (kind: "start" | "stop" | "pause") => void): Promise<UnlistenFn> =>
|
||||
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 {
|
||||
|
||||
Reference in New Issue
Block a user