feat #14740: updater and release scripts
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,218 @@
|
||||
//! Self-update (Windows only): checks the release feed (`plugins.updater`
|
||||
//! in `tauri.conf.json`) at startup and every 6 h, tells the main window
|
||||
//! about a newer version and installs it when the user asks, but never while
|
||||
//! a recording runs or a call is being processed.
|
||||
//!
|
||||
//! On Windows the NSIS installer runs in passive mode for the current user
|
||||
//! (no admin rights) and restarts the app; installing ends this process.
|
||||
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::Mutex;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
use serde::Serialize;
|
||||
use tauri::{AppHandle, Emitter, Manager};
|
||||
use tauri_plugin_updater::{Update, UpdaterExt};
|
||||
|
||||
use crate::state::AppState;
|
||||
|
||||
const CHECK_INTERVAL: Duration = Duration::from_secs(6 * 60 * 60);
|
||||
/// Progress steps while the download size is unknown.
|
||||
const MIB: u64 = 1024 * 1024;
|
||||
/// Why the banner cannot install yet; the banner shows the same hint.
|
||||
const BUSY: &str = "Nach der laufenden Aufnahme/Verarbeitung möglich";
|
||||
|
||||
/// The newest update found, and whether one is being installed.
|
||||
#[derive(Default)]
|
||||
pub struct PendingUpdate {
|
||||
update: Mutex<Option<Update>>,
|
||||
installing: AtomicBool,
|
||||
}
|
||||
|
||||
/// Payload of `update-available` and answer of `get_update`.
|
||||
#[derive(Serialize, Clone, Debug, PartialEq)]
|
||||
pub struct UpdateInfo {
|
||||
pub version: String,
|
||||
/// `false` while a recording runs or a call is being processed.
|
||||
pub can_install: bool,
|
||||
}
|
||||
|
||||
/// Payload of `update-progress`.
|
||||
#[derive(Serialize, Clone, Debug, PartialEq)]
|
||||
pub struct Progress {
|
||||
pub downloaded: u64,
|
||||
/// `None` if the server sends no size.
|
||||
pub total: Option<u64>,
|
||||
}
|
||||
|
||||
/// Starts the periodic update check. Only on Windows: Debian builds do not
|
||||
/// update themselves.
|
||||
pub fn spawn(app: AppHandle) {
|
||||
if !cfg!(windows) {
|
||||
log::info!("update check disabled on this platform");
|
||||
return;
|
||||
}
|
||||
thread::spawn(move || loop {
|
||||
tauri::async_runtime::block_on(check(&app));
|
||||
thread::sleep(CHECK_INTERVAL);
|
||||
});
|
||||
}
|
||||
|
||||
/// Asks the release feed for a newer version. Failures (offline, no release
|
||||
/// yet) are expected and only logged.
|
||||
async fn check(app: &AppHandle) {
|
||||
let result = match app.updater() {
|
||||
Ok(updater) => updater.check().await,
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
match result {
|
||||
Ok(Some(update)) => {
|
||||
log::info!("update available: {}", update.version);
|
||||
let version = update.version.clone();
|
||||
*lock(&app.state::<PendingUpdate>().update) = Some(update);
|
||||
let _ = app.emit("update-available", info(app, version));
|
||||
}
|
||||
Ok(None) => log::info!("no update available"),
|
||||
Err(e) => log::info!("update check failed: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn info(app: &AppHandle, version: String) -> UpdateInfo {
|
||||
UpdateInfo {
|
||||
version,
|
||||
can_install: !app.state::<AppState>().recording_or_processing(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The update found by the last check, if any.
|
||||
#[tauri::command]
|
||||
pub fn get_update(app: AppHandle) -> Option<UpdateInfo> {
|
||||
let version = lock(&app.state::<PendingUpdate>().update)
|
||||
.as_ref()
|
||||
.map(|update| update.version.clone())?;
|
||||
Some(info(&app, version))
|
||||
}
|
||||
|
||||
/// Downloads, verifies and installs the update found, then restarts the
|
||||
/// app. Returns only on failure.
|
||||
#[tauri::command]
|
||||
pub async fn install_update(app: AppHandle) -> Result<(), String> {
|
||||
let pending = app.state::<PendingUpdate>();
|
||||
if pending.installing.swap(true, Ordering::SeqCst) {
|
||||
return Err("Das Update wird bereits installiert".to_string());
|
||||
}
|
||||
let result = download_and_install(&app).await;
|
||||
pending.installing.store(false, Ordering::SeqCst);
|
||||
if let Err(e) = &result {
|
||||
log::error!("update failed: {e}");
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
async fn download_and_install(app: &AppHandle) -> Result<(), String> {
|
||||
let update = lock(&app.state::<PendingUpdate>().update)
|
||||
.clone()
|
||||
.ok_or_else(|| "Kein Update verfügbar".to_string())?;
|
||||
let state = app.state::<AppState>();
|
||||
if state.recording_or_processing() {
|
||||
return Err(BUSY.to_string());
|
||||
}
|
||||
log::info!("downloading update {}", update.version);
|
||||
let mut meter = ProgressMeter::default();
|
||||
let bytes = update
|
||||
.download(
|
||||
|chunk, total| {
|
||||
if let Some(progress) = meter.add(chunk, total) {
|
||||
let _ = app.emit("update-progress", progress);
|
||||
}
|
||||
},
|
||||
|| {},
|
||||
)
|
||||
.await
|
||||
.map_err(|e| format!("Download fehlgeschlagen: {e}"))?;
|
||||
// A call may have started during the download.
|
||||
if state.recording_or_processing() {
|
||||
return Err(BUSY.to_string());
|
||||
}
|
||||
log::info!("installing update {}", update.version);
|
||||
// On Windows this starts the installer and ends the app.
|
||||
update
|
||||
.install(bytes)
|
||||
.map_err(|e| format!("Installation fehlgeschlagen: {e}"))?;
|
||||
app.restart()
|
||||
}
|
||||
|
||||
/// Counts downloaded bytes and decides when the banner hears about them:
|
||||
/// at every whole percent, or every MiB while the size is unknown.
|
||||
#[derive(Default)]
|
||||
struct ProgressMeter {
|
||||
downloaded: u64,
|
||||
reported_step: Option<u64>,
|
||||
}
|
||||
|
||||
impl ProgressMeter {
|
||||
fn add(&mut self, chunk: usize, total: Option<u64>) -> Option<Progress> {
|
||||
self.downloaded += chunk as u64;
|
||||
let step = match total {
|
||||
Some(total) if total > 0 => self.downloaded * 100 / total,
|
||||
_ => self.downloaded / MIB,
|
||||
};
|
||||
if self.reported_step == Some(step) {
|
||||
return None;
|
||||
}
|
||||
self.reported_step = Some(step);
|
||||
Some(Progress {
|
||||
downloaded: self.downloaded,
|
||||
total,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Locks ignoring poisoning, like the app state does.
|
||||
fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
|
||||
mutex
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn reported(meter: &mut ProgressMeter, chunks: &[usize], total: Option<u64>) -> Vec<u64> {
|
||||
chunks
|
||||
.iter()
|
||||
.filter_map(|&chunk| meter.add(chunk, total))
|
||||
.map(|progress| progress.downloaded)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn progress_is_reported_once_per_whole_percent() {
|
||||
let mut meter = ProgressMeter::default();
|
||||
// 1000 bytes: 10 bytes are one percent.
|
||||
let chunks = [4, 4, 4, 4, 4, 980];
|
||||
assert_eq!(reported(&mut meter, &chunks, Some(1000)), [4, 12, 20, 1000]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_chunk_is_always_reported() {
|
||||
let mut meter = ProgressMeter::default();
|
||||
assert_eq!(
|
||||
meter.add(1, Some(1_000_000)),
|
||||
Some(Progress {
|
||||
downloaded: 1,
|
||||
total: Some(1_000_000)
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_size_progress_is_reported_every_mib() {
|
||||
let mut meter = ProgressMeter::default();
|
||||
let half = (MIB / 2) as usize;
|
||||
let reports = reported(&mut meter, &[half, half, half, half, half], None);
|
||||
assert_eq!(reports, [MIB / 2, MIB, 2 * MIB]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user