feat #14740: check for updates from the settings
Adds a "Nach Updates suchen" button to the settings' new Updates section, next to the app's own version. It runs check_for_update_now, the very same feed check the background loop uses (one implementation, shared via UpdateSchedule), so a manual check counts as an attempt for the same scheduler: success resets the 6 h interval and the failure count, a failure advances the backoff by one step, and a manual and a background check never run at the same time (serialized). An available update leaves the same state the background check does, so the main window's banner still shows it; the settings also show it inline with the existing "Installieren & neu starten" button and busy guard/hint. "None" and "error" results are shown inline (unlike the background check, which never surfaces its errors). On Linux (can_self_update) the button still asks the feed but offers no install, since Debian builds never self-update. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -32,6 +32,12 @@ struct CallEnded {
|
|||||||
id: CallId,
|
id: CallId,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// This build's own version, for the settings' "Updates" section.
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn get_app_version(app: AppHandle) -> String {
|
||||||
|
app.package_info().version.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn get_settings(state: State<'_, AppState>) -> Settings {
|
pub fn get_settings(state: State<'_, AppState>) -> Settings {
|
||||||
state.settings()
|
state.settings()
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ use tauri_plugin_autostart::MacosLauncher;
|
|||||||
use tauri_plugin_log::{RotationStrategy, Target, TargetKind, TimezoneStrategy};
|
use tauri_plugin_log::{RotationStrategy, Target, TargetKind, TimezoneStrategy};
|
||||||
|
|
||||||
use crate::state::AppState;
|
use crate::state::AppState;
|
||||||
use crate::updater::PendingUpdate;
|
use crate::updater::{PendingUpdate, UpdateSchedule};
|
||||||
|
|
||||||
/// Command-line flag the login item starts the app with; the main window
|
/// Command-line flag the login item starts the app with; the main window
|
||||||
/// then stays hidden in the tray.
|
/// then stays hidden in the tray.
|
||||||
@@ -98,6 +98,7 @@ pub fn run() {
|
|||||||
processing::clear_upload_dir(app.handle());
|
processing::clear_upload_dir(app.handle());
|
||||||
app.manage(state);
|
app.manage(state);
|
||||||
app.manage(PendingUpdate::default());
|
app.manage(PendingUpdate::default());
|
||||||
|
app.manage(UpdateSchedule::default());
|
||||||
app.manage(backend::LoginWaiters::default());
|
app.manage(backend::LoginWaiters::default());
|
||||||
// Windows are created here (`create: false` in tauri.conf.json)
|
// Windows are created here (`create: false` in tauri.conf.json)
|
||||||
// instead of by Tauri before `setup` runs: their webviews load
|
// instead of by Tauri before `setup` runs: their webviews load
|
||||||
@@ -130,6 +131,7 @@ pub fn run() {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
.invoke_handler(tauri::generate_handler![
|
.invoke_handler(tauri::generate_handler![
|
||||||
|
commands::get_app_version,
|
||||||
commands::get_settings,
|
commands::get_settings,
|
||||||
commands::save_settings,
|
commands::save_settings,
|
||||||
commands::set_api_key,
|
commands::set_api_key,
|
||||||
@@ -160,6 +162,8 @@ pub fn run() {
|
|||||||
backend::upload_transcript,
|
backend::upload_transcript,
|
||||||
updater::get_update,
|
updater::get_update,
|
||||||
updater::install_update,
|
updater::install_update,
|
||||||
|
updater::check_for_update_now,
|
||||||
|
updater::can_self_update,
|
||||||
])
|
])
|
||||||
.run(tauri::generate_context!())
|
.run(tauri::generate_context!())
|
||||||
.expect("error while building tauri application");
|
.expect("error while building tauri application");
|
||||||
|
|||||||
@@ -209,7 +209,12 @@ impl AppState {
|
|||||||
pending_prompts: Mutex::new(VecDeque::new()),
|
pending_prompts: Mutex::new(VecDeque::new()),
|
||||||
processing: Mutex::new(HashSet::new()),
|
processing: Mutex::new(HashSet::new()),
|
||||||
devices_busy: AtomicBool::new(false),
|
devices_busy: AtomicBool::new(false),
|
||||||
backend_url: crate::backend::BACKEND_URL.to_string(),
|
// Defensive: BACKEND_URL itself must never have a trailing
|
||||||
|
// slash (see backend::tests::backend_urls_have_no_trailing…),
|
||||||
|
// but a stored key's base_url is compared against this field.
|
||||||
|
backend_url: crate::backend::BACKEND_URL
|
||||||
|
.trim_end_matches('/')
|
||||||
|
.to_string(),
|
||||||
backend_key_lock: Mutex::new(()),
|
backend_key_lock: Mutex::new(()),
|
||||||
uploading: Mutex::new(HashSet::new()),
|
uploading: Mutex::new(HashSet::new()),
|
||||||
}
|
}
|
||||||
|
|||||||
+158
-23
@@ -2,10 +2,15 @@
|
|||||||
//! in `tauri.conf.json`) at startup and every 6 h (sooner after a failed
|
//! in `tauri.conf.json`) at startup and every 6 h (sooner after a failed
|
||||||
//! check), tells the main window about a newer version and installs it when
|
//! check), 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
|
//! the user asks, but never while a recording runs or a call is being
|
||||||
//! processed.
|
//! processed. The settings' "Nach Updates suchen" button
|
||||||
|
//! ([`check_for_update_now`]) runs the very same check immediately, counts
|
||||||
|
//! as an attempt for the same scheduler ([`UpdateSchedule`]) and never runs
|
||||||
|
//! at the same time as the background loop.
|
||||||
//!
|
//!
|
||||||
//! On Windows the NSIS installer runs in passive mode for the current user
|
//! On Windows the NSIS installer runs in passive mode for the current user
|
||||||
//! (no admin rights) and restarts the app; installing ends this process.
|
//! (no admin rights) and restarts the app; installing ends this process.
|
||||||
|
//! Debian builds never self-update; a manual check still asks the feed
|
||||||
|
//! there (see [`can_self_update`]).
|
||||||
|
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
@@ -58,6 +63,71 @@ pub struct UpdateInfo {
|
|||||||
pub can_install: bool,
|
pub can_install: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Answer of `check_for_update_now`: what a check (background or manual)
|
||||||
|
/// found. `Available` leaves the same state `get_update` reads and fires
|
||||||
|
/// the same `update-available` event as the background loop, so the main
|
||||||
|
/// window's banner shows it too.
|
||||||
|
#[derive(Serialize, Clone, Debug, PartialEq)]
|
||||||
|
#[serde(tag = "status", rename_all = "lowercase")]
|
||||||
|
pub enum UpdateCheckResult {
|
||||||
|
/// No newer version on the feed.
|
||||||
|
None,
|
||||||
|
Available {
|
||||||
|
version: String,
|
||||||
|
},
|
||||||
|
/// The feed could not be asked; safe to show (never a secret).
|
||||||
|
Error {
|
||||||
|
message: String,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
/// When the last check attempt (background or manual) started and how many
|
||||||
|
/// failed in a row, shared so a manual check feeds the same scheduler the
|
||||||
|
/// background loop uses: success resets the 6 h interval and the failure
|
||||||
|
/// count, a failure advances the backoff by one step. `running` also
|
||||||
|
/// serializes checks, so a manual and a background check never run at once.
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct UpdateSchedule {
|
||||||
|
state: Mutex<Schedule>,
|
||||||
|
running: tokio::sync::Mutex<()>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default, Clone, Copy)]
|
||||||
|
struct Schedule {
|
||||||
|
last_attempt: Option<SystemTime>,
|
||||||
|
failures: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UpdateSchedule {
|
||||||
|
/// Whether a check is due at `now`, per the last recorded attempt.
|
||||||
|
fn is_due(&self, now: SystemTime) -> bool {
|
||||||
|
let s = lock(&self.state);
|
||||||
|
check_due(s.last_attempt, s.failures, now)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Records the outcome of a check attempt that started at `now`.
|
||||||
|
fn record(&self, now: SystemTime, success: bool) {
|
||||||
|
let mut s = lock(&self.state);
|
||||||
|
s.last_attempt = Some(now);
|
||||||
|
s.failures = if success {
|
||||||
|
0
|
||||||
|
} else {
|
||||||
|
s.failures.saturating_add(1)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs one check attempt right now: serialized against any other check
|
||||||
|
/// (background or manual) via `running`, and recorded for the
|
||||||
|
/// scheduler exactly like a background attempt.
|
||||||
|
async fn run(&self, app: &AppHandle) -> UpdateCheckResult {
|
||||||
|
let _serialize = self.running.lock().await;
|
||||||
|
let now = SystemTime::now();
|
||||||
|
let result = check(app).await;
|
||||||
|
self.record(now, !matches!(result, UpdateCheckResult::Error { .. }));
|
||||||
|
result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Payload of `update-progress`.
|
/// Payload of `update-progress`.
|
||||||
#[derive(Serialize, Clone, Debug, PartialEq)]
|
#[derive(Serialize, Clone, Debug, PartialEq)]
|
||||||
pub struct Progress {
|
pub struct Progress {
|
||||||
@@ -67,27 +137,19 @@ pub struct Progress {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Starts the periodic update check. Only on Windows: Debian builds do not
|
/// Starts the periodic update check. Only on Windows: Debian builds do not
|
||||||
/// update themselves.
|
/// update themselves (a manual check from the settings still asks the feed
|
||||||
|
/// on Linux, see `check_for_update_now`).
|
||||||
pub fn spawn(app: AppHandle) {
|
pub fn spawn(app: AppHandle) {
|
||||||
if !cfg!(windows) {
|
if !cfg!(windows) {
|
||||||
log::info!("update check disabled on this platform");
|
log::info!("update check disabled on this platform");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
thread::spawn(move || {
|
thread::spawn(move || loop {
|
||||||
let mut last_attempt = None;
|
let now = SystemTime::now();
|
||||||
let mut failures = 0;
|
if app.state::<UpdateSchedule>().is_due(now) {
|
||||||
loop {
|
tauri::async_runtime::block_on(app.state::<UpdateSchedule>().run(&app));
|
||||||
let now = SystemTime::now();
|
|
||||||
if check_due(last_attempt, failures, now) {
|
|
||||||
last_attempt = Some(now);
|
|
||||||
if tauri::async_runtime::block_on(check(&app)) {
|
|
||||||
failures = 0;
|
|
||||||
} else {
|
|
||||||
failures = failures.saturating_add(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
thread::sleep(WAKE_INTERVAL);
|
|
||||||
}
|
}
|
||||||
|
thread::sleep(WAKE_INTERVAL);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -110,9 +172,11 @@ fn check_due(last_attempt: Option<SystemTime>, failures: u32, now: SystemTime) -
|
|||||||
.map_or(true, |elapsed| elapsed >= wait)
|
.map_or(true, |elapsed| elapsed >= wait)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Asks the release feed for a newer version; `false` if the check failed.
|
/// Asks the release feed for a newer version: the one implementation the
|
||||||
/// Failures (offline, no release yet) are expected and only logged.
|
/// background loop and a manual check (`check_for_update_now`) both run.
|
||||||
async fn check(app: &AppHandle) -> bool {
|
/// A failed check (offline, no release yet) is expected; only logged here,
|
||||||
|
/// and shown to the user only by a manual check (via the returned message).
|
||||||
|
async fn check(app: &AppHandle) -> UpdateCheckResult {
|
||||||
let result = match app.updater_builder().timeout(CHECK_TIMEOUT).build() {
|
let result = match app.updater_builder().timeout(CHECK_TIMEOUT).build() {
|
||||||
Ok(updater) => updater.check().await,
|
Ok(updater) => updater.check().await,
|
||||||
Err(e) => Err(e),
|
Err(e) => Err(e),
|
||||||
@@ -122,16 +186,18 @@ async fn check(app: &AppHandle) -> bool {
|
|||||||
log::info!("update available: {}", update.version);
|
log::info!("update available: {}", update.version);
|
||||||
let version = update.version.clone();
|
let version = update.version.clone();
|
||||||
*lock(&app.state::<PendingUpdate>().update) = Some(update);
|
*lock(&app.state::<PendingUpdate>().update) = Some(update);
|
||||||
let _ = app.emit("update-available", info(app, version));
|
let _ = app.emit("update-available", info(app, version.clone()));
|
||||||
true
|
UpdateCheckResult::Available { version }
|
||||||
}
|
}
|
||||||
Ok(None) => {
|
Ok(None) => {
|
||||||
log::info!("no update available");
|
log::info!("no update available");
|
||||||
true
|
UpdateCheckResult::None
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
log::info!("update check failed: {e}");
|
log::info!("update check failed: {e}");
|
||||||
false
|
UpdateCheckResult::Error {
|
||||||
|
message: format!("Update-Server nicht erreichbar: {e}"),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -161,6 +227,24 @@ fn info(app: &AppHandle, version: String) -> UpdateInfo {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// "Nach Updates suchen" in the settings: runs the same check as the
|
||||||
|
/// background loop, immediately, reusing its scheduling (a success resets
|
||||||
|
/// the 6 h interval and the failure count, same as a background success)
|
||||||
|
/// and never running at the same time as a background check. Works on
|
||||||
|
/// every platform; see `can_self_update` for whether this build can then
|
||||||
|
/// install what it finds.
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn check_for_update_now(app: AppHandle) -> UpdateCheckResult {
|
||||||
|
app.state::<UpdateSchedule>().run(&app).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether this build can install an update itself (Windows only: Debian
|
||||||
|
/// builds ship a `.deb` and never self-update, see `spawn`).
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn can_self_update() -> bool {
|
||||||
|
cfg!(windows)
|
||||||
|
}
|
||||||
|
|
||||||
/// The update found by the last check, if any.
|
/// The update found by the last check, if any.
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn get_update(app: AppHandle) -> Option<UpdateInfo> {
|
pub fn get_update(app: AppHandle) -> Option<UpdateInfo> {
|
||||||
@@ -350,4 +434,55 @@ mod tests {
|
|||||||
let reports = reported(&mut meter, &[half, half, half, half, half], None);
|
let reports = reported(&mut meter, &[half, half, half, half, half], None);
|
||||||
assert_eq!(reports, [MIB / 2, MIB, 2 * MIB]);
|
assert_eq!(reports, [MIB / 2, MIB, 2 * MIB]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn update_check_result_maps_to_a_tagged_status() {
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_value(UpdateCheckResult::None).unwrap(),
|
||||||
|
serde_json::json!({"status": "none"})
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_value(UpdateCheckResult::Available {
|
||||||
|
version: "0.3.0".into()
|
||||||
|
})
|
||||||
|
.unwrap(),
|
||||||
|
serde_json::json!({"status": "available", "version": "0.3.0"})
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_value(UpdateCheckResult::Error {
|
||||||
|
message: "Update-Server nicht erreichbar: x".into()
|
||||||
|
})
|
||||||
|
.unwrap(),
|
||||||
|
serde_json::json!({"status": "error", "message": "Update-Server nicht erreichbar: x"})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A manual check feeds the very scheduler the background loop reads
|
||||||
|
/// (`record` is the one function either kind of attempt calls): a
|
||||||
|
/// failure advances the backoff by exactly the one step a single
|
||||||
|
/// failure always does (never more just for being a manual attempt),
|
||||||
|
/// and a success resets the interval to 6 h and the failure count.
|
||||||
|
#[test]
|
||||||
|
fn a_manual_checks_result_feeds_the_background_scheduler() {
|
||||||
|
let schedule = UpdateSchedule::default();
|
||||||
|
assert!(schedule.is_due(t0()), "nothing attempted yet");
|
||||||
|
|
||||||
|
// One failed manual check: due again after the 1st retry delay,
|
||||||
|
// exactly as check_due(_, 1, _) says, not sooner and not later.
|
||||||
|
schedule.record(t0(), false);
|
||||||
|
assert!(!schedule.is_due(t0() + MIN - Duration::from_secs(1)));
|
||||||
|
assert!(schedule.is_due(t0() + MIN));
|
||||||
|
|
||||||
|
// A second failed attempt (background or manual, the scheduler does
|
||||||
|
// not distinguish) advances to the 2nd retry delay, not further.
|
||||||
|
schedule.record(t0() + MIN, false);
|
||||||
|
assert!(!schedule.is_due(t0() + MIN + 5 * MIN - Duration::from_secs(1)));
|
||||||
|
assert!(schedule.is_due(t0() + MIN + 5 * MIN));
|
||||||
|
|
||||||
|
// A manual check that then succeeds resets the interval to 6 h and
|
||||||
|
// the failure count, exactly like a background success.
|
||||||
|
schedule.record(t0() + MIN, true);
|
||||||
|
assert!(!schedule.is_due(t0() + MIN + 6 * HOUR - MIN));
|
||||||
|
assert!(schedule.is_due(t0() + MIN + 6 * HOUR));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,8 @@
|
|||||||
onRecordingState,
|
onRecordingState,
|
||||||
onUpdateAvailable,
|
onUpdateAvailable,
|
||||||
onUpdateProgress,
|
onUpdateProgress,
|
||||||
|
updateProgressText,
|
||||||
|
UPDATE_BUSY_HINT,
|
||||||
type UpdateInfo,
|
type UpdateInfo,
|
||||||
type UpdateProgress,
|
type UpdateProgress,
|
||||||
} from './api'
|
} from './api'
|
||||||
@@ -62,16 +64,7 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function megabytes(bytes: number): string {
|
let progressText = $derived(updateProgressText(progress))
|
||||||
return (bytes / 1024 / 1024).toLocaleString('de-DE', { maximumFractionDigits: 1 }) + ' MB'
|
|
||||||
}
|
|
||||||
|
|
||||||
let progressText = $derived.by(() => {
|
|
||||||
if (!progress) return 'Update wird heruntergeladen…'
|
|
||||||
if (progress.total === null) return `Update wird heruntergeladen… ${megabytes(progress.downloaded)}`
|
|
||||||
if (progress.downloaded >= progress.total) return 'Update wird installiert…'
|
|
||||||
return `Update wird heruntergeladen… ${Math.floor((progress.downloaded * 100) / progress.total)} %`
|
|
||||||
})
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
{#if update}
|
{#if update}
|
||||||
@@ -84,7 +77,7 @@
|
|||||||
Installieren & neu starten
|
Installieren & neu starten
|
||||||
</button>
|
</button>
|
||||||
{#if !update.can_install}
|
{#if !update.can_install}
|
||||||
<span class="hint">Nach der laufenden Aufnahme/Verarbeitung möglich</span>
|
<span class="hint">{UPDATE_BUSY_HINT}</span>
|
||||||
{/if}
|
{/if}
|
||||||
{/if}
|
{/if}
|
||||||
{#if error}
|
{#if error}
|
||||||
|
|||||||
@@ -137,6 +137,15 @@ export interface UpdateProgress {
|
|||||||
total: number | null
|
total: number | null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Why the install button is disabled, shown next to it as a hint. */
|
||||||
|
export const UPDATE_BUSY_HINT = 'Nach der laufenden Aufnahme/Verarbeitung möglich'
|
||||||
|
|
||||||
|
/** What a check (background or manual) found. */
|
||||||
|
export type UpdateCheckResult =
|
||||||
|
| { status: 'none' }
|
||||||
|
| { status: 'available'; version: string }
|
||||||
|
| { status: 'error'; message: string }
|
||||||
|
|
||||||
export interface Levels {
|
export interface Levels {
|
||||||
mic: number
|
mic: number
|
||||||
out: number
|
out: number
|
||||||
@@ -185,6 +194,14 @@ export const uploadTranscript = (id: CallId) => invoke<void>('upload_transcript'
|
|||||||
export const getUpdate = () => invoke<UpdateInfo | null>('get_update')
|
export const getUpdate = () => invoke<UpdateInfo | null>('get_update')
|
||||||
/** Resolves only on failure: on success the app restarts. */
|
/** Resolves only on failure: on success the app restarts. */
|
||||||
export const installUpdate = () => invoke<void>('install_update')
|
export const installUpdate = () => invoke<void>('install_update')
|
||||||
|
/** This build's own version, for the settings' "Updates" section. */
|
||||||
|
export const getAppVersion = () => invoke<string>('get_app_version')
|
||||||
|
/** Whether this build can install an update itself (Windows only). */
|
||||||
|
export const canSelfUpdate = () => invoke<boolean>('can_self_update')
|
||||||
|
/** "Nach Updates suchen": runs the same check as the background loop,
|
||||||
|
* immediately. An `available` result leaves the same state `getUpdate`
|
||||||
|
* reads, so the main window's banner shows it too. */
|
||||||
|
export const checkForUpdateNow = () => invoke<UpdateCheckResult>('check_for_update_now')
|
||||||
|
|
||||||
export const onRecordingState = (handler: (state: RecordingState) => void): Promise<UnlistenFn> =>
|
export const onRecordingState = (handler: (state: RecordingState) => void): Promise<UnlistenFn> =>
|
||||||
listen<RecordingState>('recording-state', (event) => handler(event.payload))
|
listen<RecordingState>('recording-state', (event) => handler(event.payload))
|
||||||
@@ -218,6 +235,19 @@ export function meterFill(level: number): number {
|
|||||||
return Math.min(1, Math.max(0, (db + 60) / 60))
|
return Math.min(1, Math.max(0, (db + 60) / 60))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function megabytes(bytes: number): string {
|
||||||
|
return (bytes / 1024 / 1024).toLocaleString('de-DE', { maximumFractionDigits: 1 }) + ' MB'
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Text shown while an update installs (the banner and the settings'
|
||||||
|
* Updates section share this). */
|
||||||
|
export function updateProgressText(progress: UpdateProgress | null): string {
|
||||||
|
if (!progress) return 'Update wird heruntergeladen…'
|
||||||
|
if (progress.total === null) return `Update wird heruntergeladen… ${megabytes(progress.downloaded)}`
|
||||||
|
if (progress.downloaded >= progress.total) return 'Update wird installiert…'
|
||||||
|
return `Update wird heruntergeladen… ${Math.floor((progress.downloaded * 100) / progress.total)} %`
|
||||||
|
}
|
||||||
|
|
||||||
/** Error text of a rejected command. */
|
/** Error text of a rejected command. */
|
||||||
export function errorText(err: unknown): string {
|
export function errorText(err: unknown): string {
|
||||||
return typeof err === 'string' ? err : err instanceof Error ? err.message : String(err)
|
return typeof err === 'string' ? err : err instanceof Error ? err.message : String(err)
|
||||||
|
|||||||
@@ -6,17 +6,26 @@
|
|||||||
backendLogout,
|
backendLogout,
|
||||||
backendServer,
|
backendServer,
|
||||||
backendStatus,
|
backendStatus,
|
||||||
|
canSelfUpdate,
|
||||||
|
checkForUpdateNow,
|
||||||
errorText,
|
errorText,
|
||||||
|
getAppVersion,
|
||||||
getSettings,
|
getSettings,
|
||||||
|
getUpdate,
|
||||||
hasApiKey,
|
hasApiKey,
|
||||||
|
installUpdate,
|
||||||
listDevices,
|
listDevices,
|
||||||
meterFill,
|
meterFill,
|
||||||
onBackendChanged,
|
onBackendChanged,
|
||||||
onBackendLoginError,
|
onBackendLoginError,
|
||||||
|
onUpdateAvailable,
|
||||||
|
onUpdateProgress,
|
||||||
openBackendKeysPage,
|
openBackendKeysPage,
|
||||||
saveSettings,
|
saveSettings,
|
||||||
setApiKey,
|
setApiKey,
|
||||||
testDevices,
|
testDevices,
|
||||||
|
updateProgressText,
|
||||||
|
UPDATE_BUSY_HINT,
|
||||||
type BackendServer,
|
type BackendServer,
|
||||||
type BackendStatus,
|
type BackendStatus,
|
||||||
type DeviceInfo,
|
type DeviceInfo,
|
||||||
@@ -24,6 +33,9 @@
|
|||||||
type Devices,
|
type Devices,
|
||||||
type Service,
|
type Service,
|
||||||
type Settings,
|
type Settings,
|
||||||
|
type UpdateCheckResult,
|
||||||
|
type UpdateInfo,
|
||||||
|
type UpdateProgress,
|
||||||
} from '../lib/api'
|
} from '../lib/api'
|
||||||
|
|
||||||
const services: { id: Service; name: string }[] = [
|
const services: { id: Service; name: string }[] = [
|
||||||
@@ -48,19 +60,84 @@
|
|||||||
// Status answers can arrive out of order; only the newest is applied.
|
// Status answers can arrive out of order; only the newest is applied.
|
||||||
let statusRequest = 0
|
let statusRequest = 0
|
||||||
|
|
||||||
|
let appVersion = $state('')
|
||||||
|
/** `null` until known: whether this build can install an update itself
|
||||||
|
* (Windows only); avoids guessing wrong for an instant. */
|
||||||
|
let selfUpdateCapable = $state<boolean | null>(null)
|
||||||
|
let checking = $state(false)
|
||||||
|
let checkResult = $state<UpdateCheckResult | null>(null)
|
||||||
|
let pendingUpdate = $state<UpdateInfo | null>(null)
|
||||||
|
let installing = $state(false)
|
||||||
|
let installProgress = $state<UpdateProgress | null>(null)
|
||||||
|
let installError = $state('')
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
load()
|
load()
|
||||||
backendServer()
|
backendServer()
|
||||||
.then((s) => (server = s))
|
.then((s) => (server = s))
|
||||||
.catch((err) => (backendError = errorText(err)))
|
.catch((err) => (backendError = errorText(err)))
|
||||||
refreshBackend()
|
refreshBackend()
|
||||||
|
getAppVersion()
|
||||||
|
.then((v) => (appVersion = v))
|
||||||
|
.catch(() => {})
|
||||||
|
canSelfUpdate()
|
||||||
|
.then((v) => (selfUpdateCapable = v))
|
||||||
|
.catch(() => {})
|
||||||
|
getUpdate()
|
||||||
|
.then((u) => (pendingUpdate = u))
|
||||||
|
.catch(() => {})
|
||||||
const unlisten = [
|
const unlisten = [
|
||||||
onBackendChanged(refreshBackend),
|
onBackendChanged(refreshBackend),
|
||||||
onBackendLoginError((msg) => (backendError = msg)),
|
onBackendLoginError((msg) => (backendError = msg)),
|
||||||
|
onUpdateAvailable((info) => (pendingUpdate = info)),
|
||||||
|
onUpdateProgress((progress) => (installProgress = progress)),
|
||||||
]
|
]
|
||||||
return () => unlisten.forEach((u) => u.then((off) => off()))
|
return () => unlisten.forEach((u) => u.then((off) => off()))
|
||||||
})
|
})
|
||||||
|
|
||||||
|
/** "Nach Updates suchen": runs the same check as the background loop,
|
||||||
|
* immediately. An available update also arrives via `update-available`
|
||||||
|
* (so the main window's banner shows it too), but is applied here as
|
||||||
|
* well in case that event is missed. */
|
||||||
|
async function checkUpdateNow() {
|
||||||
|
checking = true
|
||||||
|
checkResult = null
|
||||||
|
try {
|
||||||
|
const result = await checkForUpdateNow()
|
||||||
|
checkResult = result
|
||||||
|
if (result.status === 'available') pendingUpdate = await getUpdate()
|
||||||
|
} catch (err) {
|
||||||
|
checkResult = { status: 'error', message: errorText(err) }
|
||||||
|
} finally {
|
||||||
|
checking = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshPendingUpdate() {
|
||||||
|
try {
|
||||||
|
pendingUpdate = await getUpdate()
|
||||||
|
} catch {
|
||||||
|
// Optional refresh; the next event or check tries again.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "Installieren & neu starten" for the update found above; reuses the
|
||||||
|
* install command and guard the main window's banner uses. */
|
||||||
|
async function installUpdateNow() {
|
||||||
|
installing = true
|
||||||
|
installProgress = null
|
||||||
|
installError = ''
|
||||||
|
try {
|
||||||
|
// Returns only on failure: on success the app restarts.
|
||||||
|
await installUpdate()
|
||||||
|
} catch (err) {
|
||||||
|
installError = errorText(err)
|
||||||
|
refreshPendingUpdate()
|
||||||
|
} finally {
|
||||||
|
installing = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** Checks the stored key with the backend. */
|
/** Checks the stored key with the backend. */
|
||||||
async function refreshBackend() {
|
async function refreshBackend() {
|
||||||
const request = ++statusRequest
|
const request = ++statusRequest
|
||||||
@@ -377,6 +454,48 @@
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section class="card">
|
||||||
|
<h2>Updates</h2>
|
||||||
|
<div class="grid">
|
||||||
|
<span>Version</span>
|
||||||
|
<span>{appVersion || '…'}</span>
|
||||||
|
</div>
|
||||||
|
<div class="update-check">
|
||||||
|
<button class="btn" disabled={checking} onclick={checkUpdateNow}>
|
||||||
|
{checking ? 'Suche…' : 'Nach Updates suchen'}
|
||||||
|
</button>
|
||||||
|
{#if checkResult?.status === 'none'}
|
||||||
|
<span class="muted">Keine neue Version verfügbar (aktuell: {appVersion})</span>
|
||||||
|
{:else if checkResult?.status === 'error'}
|
||||||
|
<span class="error">{checkResult.message}</span>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{#if pendingUpdate && selfUpdateCapable !== null}
|
||||||
|
<div class="update-available">
|
||||||
|
<span>Update verfügbar (v{pendingUpdate.version})</span>
|
||||||
|
{#if selfUpdateCapable}
|
||||||
|
{#if installing}
|
||||||
|
<span>{updateProgressText(installProgress)}</span>
|
||||||
|
{:else}
|
||||||
|
<button class="btn primary small" disabled={!pendingUpdate.can_install} onclick={installUpdateNow}>
|
||||||
|
Installieren & neu starten
|
||||||
|
</button>
|
||||||
|
{#if !pendingUpdate.can_install}
|
||||||
|
<span class="muted">{UPDATE_BUSY_HINT}</span>
|
||||||
|
{/if}
|
||||||
|
{/if}
|
||||||
|
{#if installError}
|
||||||
|
<span class="error">{installError}</span>
|
||||||
|
{/if}
|
||||||
|
{:else}
|
||||||
|
<span class="muted">
|
||||||
|
Updates gibt es unter Windows automatisch; unter Linux bitte das .deb neu installieren.
|
||||||
|
</span>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</section>
|
||||||
|
|
||||||
<div class="footer">
|
<div class="footer">
|
||||||
<button class="btn primary" onclick={() => run(persist, 'Einstellungen gespeichert ✓')}>
|
<button class="btn primary" onclick={() => run(persist, 'Einstellungen gespeichert ✓')}>
|
||||||
Speichern
|
Speichern
|
||||||
@@ -503,6 +622,15 @@
|
|||||||
overflow-wrap: anywhere;
|
overflow-wrap: anywhere;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.update-check,
|
||||||
|
.update-available {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 6px 10px;
|
||||||
|
margin-top: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
.footer {
|
.footer {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
|||||||
Reference in New Issue
Block a user