Compare commits

...
30 changed files with 153 additions and 209 deletions
Generated
+1
View File
@@ -1124,6 +1124,7 @@ dependencies = [
"rfd 0.18.0", "rfd 0.18.0",
"runas", "runas",
"rustls", "rustls",
"semver 1.0.28",
"serde", "serde",
"serde_json", "serde_json",
"serde_yaml_ng", "serde_yaml_ng",
-1
View File
@@ -56,7 +56,6 @@
"@tauri-apps/plugin-updater": "2.14.1", "@tauri-apps/plugin-updater": "2.14.1",
"ahooks": "^3.10.0", "ahooks": "^3.10.0",
"cidr-block": "^2.3.0", "cidr-block": "^2.3.0",
"compare-versions": "^6.1.1",
"dayjs": "1.11.23", "dayjs": "1.11.23",
"foxact": "^0.3.12", "foxact": "^0.3.12",
"foxts": "^5.9.1", "foxts": "^5.9.1",
-3
View File
@@ -245,9 +245,6 @@ importers:
cidr-block: cidr-block:
specifier: ^2.3.0 specifier: ^2.3.0
version: 2.3.0 version: 2.3.0
compare-versions:
specifier: ^6.1.1
version: 6.1.1
dayjs: dayjs:
specifier: 1.11.23 specifier: 1.11.23
version: 1.11.23 version: 1.11.23
+1
View File
@@ -64,6 +64,7 @@ chrono = { workspace = true }
boa_engine = "0.22.0" boa_engine = "0.22.0"
http-body-util = "0.1.5" http-body-util = "0.1.5"
percent-encoding = "2.3.2" percent-encoding = "2.3.2"
semver = "1.0"
reqwest = { workspace = true } reqwest = { workspace = true }
sysproxy = { git = "https://github.com/clash-verge-rev/sysproxy-rs.git", rev = "2c9d0a538052aac6e44ad413156a6e848da262b9", version = "0.7.2", features = [ sysproxy = { git = "https://github.com/clash-verge-rev/sysproxy-rs.git", rev = "2c9d0a538052aac6e44ad413156a6e848da262b9", version = "0.7.2", features = [
"guard", "guard",
+1 -5
View File
@@ -6,8 +6,6 @@ pub mod notification;
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, specta::Type)] #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, specta::Type)]
pub enum NoticeStatus { pub enum NoticeStatus {
#[serde(rename = "info")]
Info,
#[serde(rename = "import_sub_url::ok")] #[serde(rename = "import_sub_url::ok")]
ImportSubUrlOk, ImportSubUrlOk,
#[serde(rename = "import_sub_url::error")] #[serde(rename = "import_sub_url::error")]
@@ -83,8 +81,7 @@ impl NoticeStatus {
/// test both derive their variant list from here; expected strings stay /// test both derive their variant list from here; expected strings stay
/// hand-written in the test so renames cannot slip through. /// hand-written in the test so renames cannot slip through.
#[cfg(test)] #[cfg(test)]
pub const ALL: [Self; 34] = [ pub const ALL: [Self; 33] = [
Self::Info,
Self::ImportSubUrlOk, Self::ImportSubUrlOk,
Self::ImportSubUrlError, Self::ImportSubUrlError,
Self::SetConfigError, Self::SetConfigError,
@@ -129,7 +126,6 @@ mod tests {
fn notice_status_wire_contract() -> Result<(), serde_json::Error> { fn notice_status_wire_contract() -> Result<(), serde_json::Error> {
let statuses = NoticeStatus::ALL; let statuses = NoticeStatus::ALL;
let expected = [ let expected = [
"info",
"import_sub_url::ok", "import_sub_url::ok",
"import_sub_url::error", "import_sub_url::error",
"set_config::error", "set_config::error",
+2 -2
View File
@@ -387,11 +387,11 @@ fn sample_frontend_events(uid: &str) -> Vec<(FrontendEvent<'_>, &'static str, se
), ),
( (
FrontendEvent::NoticeMessage { FrontendEvent::NoticeMessage {
status: NoticeStatus::Info, status: NoticeStatus::UpdateFailed,
message: Arc::from("ok"), message: Arc::from("ok"),
}, },
"verge://notice-message", "verge://notice-message",
json!(["info", "ok"]), json!(["update_failed", "ok"]),
), ),
( (
FrontendEvent::TimerUpdated { profile_index: uid }, FrontendEvent::TimerUpdated { profile_index: uid },
+140 -119
View File
@@ -1,21 +1,20 @@
use crate::{config::Config, singleton, utils::dirs}; use crate::{config::Config, singleton, utils::dirs};
use anyhow::{Context as _, Result}; use anyhow::{Context as _, Result};
use chrono::Utc;
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use parking_lot::Mutex; use parking_lot::Mutex;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::{ use std::{
path::PathBuf, path::PathBuf,
sync::atomic::{AtomicBool, AtomicU64, Ordering}, sync::atomic::{AtomicU64, Ordering},
time::Duration, time::Duration,
}; };
use tauri_plugin_updater::{Update, UpdaterExt as _}; use tauri_plugin_updater::{Update, UpdaterExt as _};
use tokio_util::sync::CancellationToken; use tokio_util::sync::CancellationToken;
pub struct SilentUpdater { pub struct SilentUpdater {
update_ready: AtomicBool,
manual_cancel: Mutex<Option<CancellationToken>>, manual_cancel: Mutex<Option<CancellationToken>>,
background_cancel: Mutex<Option<CancellationToken>>, background_cancel: Mutex<Option<CancellationToken>>,
download_lock: tokio::sync::Mutex<()>,
} }
#[derive(Serialize, specta::Type)] #[derive(Serialize, specta::Type)]
@@ -31,21 +30,16 @@ singleton!(SilentUpdater, SILENT_UPDATER);
impl SilentUpdater { impl SilentUpdater {
const fn new() -> Self { const fn new() -> Self {
Self { Self {
update_ready: AtomicBool::new(false),
manual_cancel: Mutex::new(None), manual_cancel: Mutex::new(None),
background_cancel: Mutex::new(None), background_cancel: Mutex::new(None),
download_lock: tokio::sync::Mutex::const_new(()),
} }
} }
pub fn is_update_ready(&self) -> bool {
self.update_ready.load(Ordering::Acquire)
}
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
struct UpdateCacheMeta { struct UpdateCacheMeta {
version: String, version: String,
downloaded_at: String,
} }
impl SilentUpdater { impl SilentUpdater {
@@ -53,36 +47,45 @@ impl SilentUpdater {
Ok(dirs::app_home_dir()?.join("update_cache")) Ok(dirs::app_home_dir()?.join("update_cache"))
} }
fn write_cache(bytes: &[u8], version: &str) -> Result<()> { /// Writes the payload through a temp file so a crash leaves no partial `pending_update.bin`;
/// installer-sized IO stays off the async runtime.
async fn write_cache(bytes: Vec<u8>, version: &str) -> Result<()> {
let cache_dir = Self::cache_dir()?; let cache_dir = Self::cache_dir()?;
std::fs::create_dir_all(&cache_dir) let version = version.to_owned();
.with_context(|| format!("failed to create update cache directory {}", cache_dir.display()))?; tokio::task::spawn_blocking(move || -> Result<()> {
std::fs::create_dir_all(&cache_dir)
.with_context(|| format!("failed to create update cache directory {}", cache_dir.display()))?;
let bin_path = cache_dir.join("pending_update.bin"); let bin_path = cache_dir.join("pending_update.bin");
std::fs::write(&bin_path, bytes) let tmp_path = cache_dir.join("pending_update.bin.tmp");
.with_context(|| format!("failed to write update cache {}", bin_path.display()))?; std::fs::write(&tmp_path, &bytes)
.with_context(|| format!("failed to write update cache {}", tmp_path.display()))?;
std::fs::rename(&tmp_path, &bin_path)
.with_context(|| format!("failed to rename update cache {}", bin_path.display()))?;
let meta = UpdateCacheMeta { let meta = UpdateCacheMeta { version };
version: version.to_string(), let meta_path = cache_dir.join("pending_update.json");
downloaded_at: Utc::now().to_rfc3339(), std::fs::write(&meta_path, serde_json::to_string_pretty(&meta)?)
}; .with_context(|| format!("failed to write update metadata {}", meta_path.display()))?;
let meta_path = cache_dir.join("pending_update.json");
std::fs::write(&meta_path, serde_json::to_string_pretty(&meta)?)
.with_context(|| format!("failed to write update metadata {}", meta_path.display()))?;
logging!( logging!(
info, info,
Type::System, Type::System,
"Update cache written: version={}, size={} bytes", "Update cache written: version={}, size={} bytes",
version, meta.version,
bytes.len() bytes.len()
); );
Ok(()) Ok(())
})
.await?
} }
fn read_cache_bytes() -> Result<Vec<u8>> { async fn read_cache_bytes() -> Result<Vec<u8>> {
let bin_path = Self::cache_dir()?.join("pending_update.bin"); let bin_path = Self::cache_dir()?.join("pending_update.bin");
std::fs::read(&bin_path).with_context(|| format!("failed to read update cache {}", bin_path.display())) tokio::task::spawn_blocking(move || {
std::fs::read(&bin_path).with_context(|| format!("failed to read update cache {}", bin_path.display()))
})
.await?
} }
fn read_cache_meta() -> Result<UpdateCacheMeta> { fn read_cache_meta() -> Result<UpdateCacheMeta> {
@@ -91,28 +94,24 @@ impl SilentUpdater {
Ok(serde_json::from_str(&content)?) Ok(serde_json::from_str(&content)?)
} }
fn delete_cache() { async fn delete_cache() {
if let Ok(cache_dir) = Self::cache_dir() if let Ok(cache_dir) = Self::cache_dir()
&& cache_dir.exists() && cache_dir.exists()
{ {
if let Err(e) = std::fs::remove_dir_all(&cache_dir) { let display = cache_dir.display().to_string();
logging!( match tokio::task::spawn_blocking(move || std::fs::remove_dir_all(&cache_dir)).await {
warn, Ok(Ok(())) => logging!(info, Type::System, "Update cache deleted"),
Type::System, Ok(Err(e)) => logging!(warn, Type::System, "Failed to delete update cache {display}: {e}"),
"Failed to delete update cache {}: {e}", Err(e) => logging!(warn, Type::System, "Failed to delete update cache {display}: {e}"),
cache_dir.display()
);
} else {
logging!(info, Type::System, "Update cache deleted");
} }
} }
} }
/// Returns the cached installer for `update`, deleting a cache that does not match it. /// Returns the cached installer for `update`, deleting a cache that does not match it.
fn verified_cache(update: &Update) -> Option<Vec<u8>> { async fn verified_cache(update: &Update) -> Option<Vec<u8>> {
let meta = Self::read_cache_meta().ok()?; let meta = Self::read_cache_meta().ok()?;
let bytes = if meta.version == update.version { let bytes = if meta.version == update.version {
Self::read_cache_bytes().and_then(|bytes| { Self::read_cache_bytes().await.and_then(|bytes| {
update.verify(&bytes)?; update.verify(&bytes)?;
Ok(bytes) Ok(bytes)
}) })
@@ -128,7 +127,7 @@ impl SilentUpdater {
"Update cache v{} is unusable: {e:#}, cleaning up", "Update cache v{} is unusable: {e:#}, cleaning up",
meta.version meta.version
); );
Self::delete_cache(); Self::delete_cache().await;
None None
} }
} }
@@ -142,33 +141,13 @@ pub fn is_build_to_stable(current: &str, remote: &str) -> bool {
!build.is_empty() && !base.contains('-') && base == remote.trim_start_matches('v') !build.is_empty() && !base.contains('-') && base == remote.trim_start_matches('v')
} }
/// Compares numeric version components after stripping version suffixes. /// Order by semver; versions that fail to parse order only by exact match.
fn version_lte(a: &str, b: &str) -> bool { fn version_lte(a: &str, b: &str) -> bool {
let parse = |v: &str| -> Vec<u64> { let parse = |v: &str| semver::Version::parse(v.trim_start_matches('v'));
v.trim_start_matches('v') match (parse(a), parse(b)) {
.split(['-', '+']) (Ok(a), Ok(b)) => a <= b,
.next() _ => a == b,
.unwrap_or("0")
.split('.')
.filter_map(|part| part.parse::<u64>().ok())
.collect()
};
let a_parts = parse(a);
let b_parts = parse(b);
let len = a_parts.len().max(b_parts.len());
for i in 0..len {
let av = a_parts.get(i).copied().unwrap_or(0);
let bv = b_parts.get(i).copied().unwrap_or(0);
if av < bv {
return true;
}
if av > bv {
return false;
}
} }
true // equal
} }
/// Maps UI language to one of the three NSIS translations, defaulting to English. /// Maps UI language to one of the three NSIS translations, defaulting to English.
@@ -202,6 +181,8 @@ const MIRRORS: [&str; 2] = ["https://update.hwdns.net/", "https://gh-proxy.org/"
/// A source delivering less than this per window is dropped for the next one. /// A source delivering less than this per window is dropped for the next one.
const MIN_PROGRESS: u64 = 1024 * 1024; const MIN_PROGRESS: u64 = 1024 * 1024;
const PROGRESS_WINDOW: Duration = Duration::from_secs(30); const PROGRESS_WINDOW: Duration = Duration::from_secs(30);
/// Bounds the startup check so a black-holed endpoint cannot stall startup.
const CHECK_TIMEOUT: Duration = Duration::from_secs(30);
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
const INSTALL_TIMEOUT: Duration = Duration::from_secs(30); const INSTALL_TIMEOUT: Duration = Duration::from_secs(30);
#[cfg(not(target_os = "windows"))] #[cfg(not(target_os = "windows"))]
@@ -302,7 +283,7 @@ impl SilentUpdater {
/// re-trigger. A timeout abandons the await, not the detached install task; a successful /// re-trigger. A timeout abandons the await, not the detached install task; a successful
/// Windows install exits the process inside the plugin (#2558). /// Windows install exits the process inside the plugin (#2558).
async fn install(update: Update, bytes: Vec<u8>) -> Result<()> { async fn install(update: Update, bytes: Vec<u8>) -> Result<()> {
Self::delete_cache(); Self::delete_cache().await;
let install = tokio::task::spawn_blocking(move || update.install(&bytes)); let install = tokio::task::spawn_blocking(move || update.install(&bytes));
match tokio::time::timeout(INSTALL_TIMEOUT, install).await { match tokio::time::timeout(INSTALL_TIMEOUT, install).await {
Ok(result) => Ok(result??), Ok(result) => Ok(result??),
@@ -315,7 +296,7 @@ impl SilentUpdater {
/// Installs a newer cached update before normal startup, if the user confirms. /// Installs a newer cached update before normal startup, if the user confirms.
pub async fn try_install_on_startup(&self, app_handle: &tauri::AppHandle) -> bool { pub async fn try_install_on_startup(&self, app_handle: &tauri::AppHandle) -> bool {
if !Config::verge().await.latest_arc().auto_check_update.unwrap_or(true) { if !Config::verge().await.latest_arc().auto_check_update.unwrap_or(true) {
Self::delete_cache(); Self::delete_cache().await;
return false; return false;
} }
@@ -323,7 +304,11 @@ impl SilentUpdater {
let meta = match Self::read_cache_meta() { let meta = match Self::read_cache_meta() {
Ok(meta) => meta, Ok(meta) => meta,
Err(_) => return false, // No cache, nothing to do Err(_) => {
// A bin without its meta is a torn write from a previous session.
Self::delete_cache().await;
return false;
}
}; };
let cached_version = &meta.version; let cached_version = &meta.version;
@@ -336,50 +321,62 @@ impl SilentUpdater {
cached_version, cached_version,
current_version current_version
); );
Self::delete_cache(); Self::delete_cache().await;
return false; return false;
} }
logging!( logging!(
info, info,
Type::System, Type::System,
"Update cache version ({}) > current ({}), asking user to install", "Update cache version ({}) > current ({}), checking the server",
cached_version, cached_version,
current_version current_version
); );
// Preserve the cache when skipped so the next launch asks again. // Installing requires the server manifest's signature, so an offline launch keeps
if !Self::ask_user_to_install(app_handle, cached_version).await { // the cache and waits for a connected one.
logging!(info, Type::System, "User skipped update install, starting normally"); let checked = tokio::time::timeout(CHECK_TIMEOUT, Self::check(app_handle)).await;
return false; let update = match checked {
} Ok(Ok(Some(u))) => u,
Ok(Ok(None)) => {
let update = match Self::check(app_handle).await {
Ok(Some(u)) => u,
Ok(None) => {
logging!( logging!(
info, info,
Type::System, Type::System,
"No update available from server, cache may be stale, cleaning up" "No update available from server, cache may be stale, cleaning up"
); );
Self::delete_cache(); Self::delete_cache().await;
return false; return false;
} }
Err(e) => { Ok(Err(e)) => {
logging!( logging!(
warn, warn,
Type::System, Type::System,
"Failed to check for update at startup: {e:#}, will retry next launch" "Failed to check for update at startup: {e:#}, will retry next launch"
); );
return false; // Keep cache for next attempt return false;
}
Err(_) => {
logging!(
warn,
Type::System,
"Startup update check timed out, will retry next launch"
);
return false;
} }
}; };
let Some(bytes) = Self::verified_cache(&update) else { let Some(bytes) = Self::verified_cache(&update).await else {
return false; return false;
}; };
let version = update.version.clone(); let version = update.version.clone();
// Preserve the cache when skipped so the next launch asks again.
if !Self::ask_user_to_install(app_handle, &version).await {
logging!(info, Type::System, "User skipped update install, starting normally");
return false;
}
logging!(info, Type::System, "Installing cached update v{version} at startup..."); logging!(info, Type::System, "Installing cached update v{version} at startup...");
Self::show_update_splash(app_handle, &version); Self::show_update_splash(app_handle, &version);
@@ -406,9 +403,13 @@ impl SilentUpdater {
on_event: impl Fn(DownloadEvent) + Sync, on_event: impl Fn(DownloadEvent) + Sync,
) -> Result<InstallUpdateOutcome> { ) -> Result<InstallUpdateOutcome> {
let cancel = CancellationToken::new(); let cancel = CancellationToken::new();
*self.manual_cancel.lock() = Some(cancel.clone()); {
let mut slot = self.manual_cancel.lock();
anyhow::ensure!(slot.is_none(), "an update install is already in progress");
*slot = Some(cancel.clone());
}
let prepared = tokio::select! { let prepared = tokio::select! {
prepared = Self::prepare_install(app_handle, version, &on_event) => Some(prepared), prepared = self.prepare_install(app_handle, version, &on_event) => Some(prepared),
() = cancel.cancelled() => None, () = cancel.cancelled() => None,
}; };
// `cancel_download` cancels under the lock, so once the token is taken back its state is // `cancel_download` cancels under the lock, so once the token is taken back its state is
@@ -429,6 +430,7 @@ impl SilentUpdater {
} }
async fn prepare_install( async fn prepare_install(
&self,
app_handle: &tauri::AppHandle, app_handle: &tauri::AppHandle,
version: &str, version: &str,
on_event: &(impl Fn(DownloadEvent) + Sync), on_event: &(impl Fn(DownloadEvent) + Sync),
@@ -439,7 +441,8 @@ impl SilentUpdater {
else { else {
return Ok(None); return Ok(None);
}; };
let bytes = match Self::verified_cache(&update) { let _download_guard = self.download_lock.lock().await;
let bytes = match Self::verified_cache(&update).await {
Some(bytes) => bytes, Some(bytes) => bytes,
None => download(&update, on_event).await?, None => download(&update, on_event).await?,
}; };
@@ -454,13 +457,12 @@ impl SilentUpdater {
} }
/// Drops the downloaded update and aborts a background download in flight. /// Drops the downloaded update and aborts a background download in flight.
pub fn discard_pending(&self) { pub async fn discard_pending(&self) {
let cancel = self.background_cancel.lock().take(); let cancel = self.background_cancel.lock().take();
if let Some(cancel) = cancel { if let Some(cancel) = cancel {
cancel.cancel(); cancel.cancel();
} }
self.update_ready.store(false, Ordering::Release); Self::delete_cache().await;
Self::delete_cache();
} }
} }
@@ -582,11 +584,6 @@ impl SilentUpdater {
return Ok(()); return Ok(());
} }
if self.is_update_ready() {
logging!(debug, Type::System, "Silent update skipped: update already pending");
return Ok(());
}
logging!(info, Type::System, "Silent updater: checking for updates..."); logging!(info, Type::System, "Silent updater: checking for updates...");
let updater = app_handle.updater()?; let updater = app_handle.updater()?;
@@ -605,22 +602,13 @@ impl SilentUpdater {
let version = update.version.as_str(); let version = update.version.as_str();
logging!(info, Type::System, "Silent updater: update available: v{version}"); logging!(info, Type::System, "Silent updater: update available: v{version}");
if let Some(body) = &update.body let download_guard = self.download_lock.lock().await;
&& body.to_lowercase().contains("break change") // A discard that arrived while waiting for the lock must not start a doomed download.
{ if cancel.is_cancelled() {
logging!(
info,
Type::System,
"Silent updater: breaking change detected in v{version}, notifying frontend"
);
super::handle::Handle::notice(
super::notify::NoticeStatus::Info,
format!("New version v{version} contains breaking changes. Please update manually."),
);
return Ok(()); return Ok(());
} }
if Self::verified_cache(&update).is_some() { if Self::verified_cache(&update).await.is_some() {
logging!(info, Type::System, "Silent updater: v{version} already cached"); logging!(info, Type::System, "Silent updater: v{version} already cached");
} else { } else {
logging!(info, Type::System, "Silent updater: downloading v{version}..."); logging!(info, Type::System, "Silent updater: downloading v{version}...");
@@ -634,23 +622,26 @@ impl SilentUpdater {
}; };
let bytes = bytes?; let bytes = bytes?;
logging!(info, Type::System, "Silent updater: download complete"); logging!(info, Type::System, "Silent updater: download complete");
Self::write_cache(&bytes, version)?; Self::write_cache(bytes, version).await?;
} }
drop(download_guard);
// Serialized with `discard_pending` in the verge patch, which holds the same lock. // Serialized with `discard_pending` in the verge patch, which holds the same lock;
let _config_write = Config::lock_config_write().await; // the deletion itself is idempotent, so it runs after the lock.
if cancel.is_cancelled() || !Config::verge().await.latest_arc().auto_check_update.unwrap_or(true) { let discard = {
let _config_write = Config::lock_config_write().await;
cancel.is_cancelled() || !Config::verge().await.latest_arc().auto_check_update.unwrap_or(true)
};
if discard {
logging!( logging!(
info, info,
Type::System, Type::System,
"Silent updater: auto check was disabled, discarding v{version}" "Silent updater: auto check was disabled, discarding v{version}"
); );
Self::delete_cache(); Self::delete_cache().await;
return Ok(()); return Ok(());
} }
self.update_ready.store(true, Ordering::Release);
logging!( logging!(
info, info,
Type::System, Type::System,
@@ -674,3 +665,33 @@ impl SilentUpdater {
} }
} }
} }
#[cfg(test)]
mod tests {
use super::{is_build_to_stable, version_lte};
#[test]
fn version_lte_orders_prereleases_below_their_release() {
assert!(version_lte("2.2.0-beta.1", "2.2.0"));
assert!(!version_lte("2.2.0", "2.2.0-alpha.1"));
assert!(version_lte("2.2.0", "2.2.0"));
assert!(version_lte("2.1.9", "2.2.0"));
assert!(!version_lte("2.2.1", "2.2.0"));
}
#[test]
fn version_lte_strips_prefixes_and_falls_back_to_equality() {
assert!(version_lte("v2.2.0", "2.2.0"));
assert!(version_lte("2.2.0+5", "2.2.1"));
assert!(version_lte("2.1.1臻fix", "2.1.1臻fix"));
assert!(!version_lte("2.1.1臻fix", "2.2.0"));
}
#[test]
fn is_build_to_stable_matches_build_metadata_to_the_same_base() {
assert!(is_build_to_stable("2.4.3+5", "2.4.3"));
assert!(!is_build_to_stable("2.4.3+5", "2.4.4"));
assert!(!is_build_to_stable("2.4.3", "2.4.3"));
assert!(!is_build_to_stable("2.4.3-beta+5", "2.4.3"));
}
}
+1 -1
View File
@@ -164,7 +164,7 @@ pub(super) async fn apply(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, e
match patch { match patch {
Patch::Verge { patch, .. } => { Patch::Verge { patch, .. } => {
if patch.auto_check_update == Some(false) { if patch.auto_check_update == Some(false) {
SilentUpdater::global().discard_pending(); SilentUpdater::global().discard_pending().await;
} }
if effects.contains(&Effect::ClashConfig) { if effects.contains(&Effect::ClashConfig) {
announce(Refresh::Clash); announce(Refresh::Clash);
@@ -306,19 +306,8 @@ export function UpdateViewer({ ref }: { ref?: Ref<UpdateViewerRef> }) {
return updateInfo?.body return updateInfo?.body
}, [activeLanguage, t, updateInfo]) }, [activeLanguage, t, updateInfo])
const breakChangeFlag = useMemo(() => {
if (!updateInfo?.body) {
return false
}
return updateInfo?.body.toLowerCase().includes('break change')
}, [updateInfo])
const onUpdate = useLockFn(async () => { const onUpdate = useLockFn(async () => {
if (!updateInfo?.body) return if (!updateInfo?.body) return
if (breakChangeFlag) {
showNotice.error('settings.modals.update.messages.breakChangeError')
return
}
if (updateState) return if (updateState) return
setUpdateState(true) setUpdateState(true)
setDownload({ downloaded: 0, total: 0 }) setDownload({ downloaded: 0, total: 0 })
@@ -15,7 +15,7 @@ import {
} from '@/services/cmds' } from '@/services/cmds'
import { mutate } from '@/services/mutate' import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service' import { showNotice } from '@/services/notice-service'
import { checkUpdateSafe as checkUpdate } from '@/services/update' import { checkForUpdate as checkUpdate } from '@/services/update'
import { version } from '@root/package.json' import { version } from '@root/package.json'
import { BackupViewer } from './mods/backup-viewer' import { BackupViewer } from './mods/backup-viewer'
+2 -2
View File
@@ -1,5 +1,5 @@
import { fetchCacheData, setCacheData, useQuery } from '@/services/query-client' import { fetchCacheData, setCacheData, useQuery } from '@/services/query-client'
import { checkUpdateSafe } from '@/services/update' import { checkForUpdate } from '@/services/update'
import { useVerge } from './use-verge' import { useVerge } from './use-verge'
@@ -26,7 +26,7 @@ export const useUpdate = (enabled: boolean = true) => {
const shouldCheck = enabled && auto_check_update !== false const shouldCheck = enabled && auto_check_update !== false
const fetchUpdate = async () => { const fetchUpdate = async () => {
const result = await checkUpdateSafe() const result = await checkForUpdate()
updateLastCheckTime() updateLastCheckTime()
return result return result
} }
-1
View File
@@ -445,7 +445,6 @@
"update": "تحديث" "update": "تحديث"
}, },
"messages": { "messages": {
"breakChangeError": "هذا الإصدار هو تحديث رئيسي ولا يدعم التحديث داخل التطبيق. يرجى إلغاء التثبيت وتنزيل الإصدار الجديد وتثبيته يدويًا",
"available": "يتوفّر إصدار جديد" "available": "يتوفّر إصدار جديد"
}, },
"alerts": { "alerts": {
-1
View File
@@ -445,7 +445,6 @@
"update": "Aktualisieren" "update": "Aktualisieren"
}, },
"messages": { "messages": {
"breakChangeError": "Dies ist eine wichtige Aktualisierung. Die In-App-Aktualisierung wird nicht unterstützt. Bitte deinstallieren Sie die Software und laden Sie die neue Version manuell herunter und installieren Sie sie.",
"available": "Eine neue Version ist verfügbar" "available": "Eine neue Version ist verfügbar"
}, },
"alerts": { "alerts": {
-1
View File
@@ -445,7 +445,6 @@
"update": "Update" "update": "Update"
}, },
"messages": { "messages": {
"breakChangeError": "This version is a major update and does not support in-app updates. Please uninstall it and manually download and install the new version",
"available": "A new version is available" "available": "A new version is available"
}, },
"alerts": { "alerts": {
-1
View File
@@ -445,7 +445,6 @@
"update": "Actualizar" "update": "Actualizar"
}, },
"messages": { "messages": {
"breakChangeError": "Esta es una actualización importante y no se admite la actualización desde dentro de la aplicación. Desinstale e instale manualmente la nueva versión.",
"available": "Hay una nueva versión disponible" "available": "Hay una nueva versión disponible"
}, },
"alerts": { "alerts": {
-1
View File
@@ -445,7 +445,6 @@
"update": "به‌روزرسانی" "update": "به‌روزرسانی"
}, },
"messages": { "messages": {
"breakChangeError": "این نسخه یک به‌روزرسانی اساسی است و پشتیبانی از به‌روزرسانی درون برنامه را پشتیبانی نمی‌کند. لطفاً پس از حذف، دستی دانلود و نصب کنید.",
"available": "نسخه جدیدی در دسترس است" "available": "نسخه جدیدی در دسترس است"
}, },
"alerts": { "alerts": {
-1
View File
@@ -445,7 +445,6 @@
"update": "Perbarui" "update": "Perbarui"
}, },
"messages": { "messages": {
"breakChangeError": "Versi ini adalah pembaruan besar dan tidak mendukung pembaruan dalam aplikasi. Harap hapus instalasi dan unduh serta instal versi baru secara manual",
"available": "Versi baru tersedia" "available": "Versi baru tersedia"
}, },
"alerts": { "alerts": {
-1
View File
@@ -445,7 +445,6 @@
"update": "更新" "update": "更新"
}, },
"messages": { "messages": {
"breakChangeError": "このバージョンは重大な更新であり、アプリケーション内での更新はサポートされていません。アンインストールしてから手動でダウンロードしてインストールしてください。",
"available": "新しいバージョンが利用可能です" "available": "新しいバージョンが利用可能です"
}, },
"alerts": { "alerts": {
-1
View File
@@ -445,7 +445,6 @@
"update": "업데이트" "update": "업데이트"
}, },
"messages": { "messages": {
"breakChangeError": "이 버전은 메이저 업데이트로 앱 내 업데이트를 지원하지 않습니다. 프로그램을 제거한 뒤 새 버전을 수동으로 설치하세요",
"available": "새 버전을 사용할 수 있습니다" "available": "새 버전을 사용할 수 있습니다"
}, },
"alerts": { "alerts": {
-1
View File
@@ -445,7 +445,6 @@
"update": "Atualizar" "update": "Atualizar"
}, },
"messages": { "messages": {
"breakChangeError": "Esta versão é uma atualização importante e não oferece suporte a atualizações dentro do aplicativo. Desinstale-a e baixe e instale a nova versão manualmente",
"available": "Uma nova versão está disponível" "available": "Uma nova versão está disponível"
}, },
"alerts": { "alerts": {
-1
View File
@@ -445,7 +445,6 @@
"update": "Обновить" "update": "Обновить"
}, },
"messages": { "messages": {
"breakChangeError": "Это крупное обновление, которое не поддерживает обновление внутри приложения. Пожалуйста, удалите текущую версию и загрузите установочный файл вручную.",
"available": "Доступна новая версия" "available": "Доступна новая версия"
}, },
"alerts": { "alerts": {
-1
View File
@@ -445,7 +445,6 @@
"update": "Güncelle" "update": "Güncelle"
}, },
"messages": { "messages": {
"breakChangeError": "Bu sürüm büyük bir güncellemedir ve uygulama içi güncellemeleri desteklemez. Lütfen kaldırın ve yeni sürümü manuel olarak indirip kurun",
"available": "Yeni bir sürüm mevcut" "available": "Yeni bir sürüm mevcut"
}, },
"alerts": { "alerts": {
-1
View File
@@ -445,7 +445,6 @@
"update": "Яңарту" "update": "Яңарту"
}, },
"messages": { "messages": {
"breakChangeError": "Бу зур яңарту, ул кушымта эчендә яңартылмый. Борып алып ташлап, яңадан урнаштыру сорала.",
"available": "Яңа версия бар" "available": "Яңа версия бар"
}, },
"alerts": { "alerts": {
-1
View File
@@ -445,7 +445,6 @@
"update": "更新" "update": "更新"
}, },
"messages": { "messages": {
"breakChangeError": "此版本为重大更新,不支持应用内更新,请卸载后手动下载安装",
"available": "有新版本可用" "available": "有新版本可用"
}, },
"alerts": { "alerts": {
-1
View File
@@ -445,7 +445,6 @@
"update": "更新" "update": "更新"
}, },
"messages": { "messages": {
"breakChangeError": "此版本為重大更新,不支援應用程式內更新,請解除安裝後手動下載安裝",
"available": "有新版本可用" "available": "有新版本可用"
}, },
"alerts": { "alerts": {
-1
View File
@@ -621,7 +621,6 @@ export type NetworkInterfaceView_Serialize = {
} }
export type NoticeStatus = export type NoticeStatus =
| 'info'
| 'import_sub_url::ok' | 'import_sub_url::ok'
| 'import_sub_url::error' | 'import_sub_url::error'
| 'set_config::error' | 'set_config::error'
-3
View File
@@ -35,9 +35,6 @@ const handlers: Record<
NoticeStatus, NoticeStatus,
(msg: string, navigate: NavigateFunction) => void (msg: string, navigate: NavigateFunction) => void
> = { > = {
info: (msg) => {
if (msg) showNotice.info(msg)
},
'import_sub_url::ok': (_msg, navigate) => { 'import_sub_url::ok': (_msg, navigate) => {
// 空 msg 传入,我们不希望导致 后端-前端-后端 死循环,这里只做提醒。 // 空 msg 传入,我们不希望导致 后端-前端-后端 死循环,这里只做提醒。
// 未来细分事件通知时,可以考虑传入订阅 ID 或其他标识符 // 未来细分事件通知时,可以考虑传入订阅 ID 或其他标识符
+4 -44
View File
@@ -3,51 +3,11 @@ import {
type CheckOptions, type CheckOptions,
type Update, type Update,
} from '@tauri-apps/plugin-updater' } from '@tauri-apps/plugin-updater'
import { compareVersions as compareSemver } from 'compare-versions'
import { version as appVersion } from '@root/package.json' // The plugin's version comparator is overridden in src-tauri/src/lib.rs, so an update
// returned by `check` is already installable and needs no extra filtering here.
const normalizeVersion = (input: string | null | undefined): string | null => { export const checkForUpdate = async (
if (typeof input !== 'string') return null
const trimmed = input.trim()
if (!trimmed) return null
return trimmed.replace(/^v/i, '')
}
const compareVersions = (a: string | null, b: string | null): number | null => {
if (!a || !b) return null
try {
return compareSemver(a, b)
} catch {
return null
}
}
const localVersionNormalized = normalizeVersion(appVersion)
export const checkUpdateSafe = async (
options?: CheckOptions, options?: CheckOptions,
): Promise<Update | null> => { ): Promise<Update | null> => {
const result = await check(options ?? {}) return check(options ?? {})
if (!result) return null
const remoteVersion = result.version
const comparison = compareVersions(remoteVersion, localVersionNormalized)
const isBuildToStable =
/^\d+\.\d+\.\d+\+[0-9A-Za-z.-]+$/.test(localVersionNormalized ?? '') &&
remoteVersion === localVersionNormalized?.split('+')[0]
if (comparison !== null && comparison <= 0 && !isBuildToStable) {
try {
await result.close()
} catch (err) {
console.warn('[updater] failed to close stale update resource', err)
}
return null
}
return result
} }
export type { CheckOptions }
-1
View File
@@ -709,7 +709,6 @@ export const translationKeys = [
'settings.modals.update.title', 'settings.modals.update.title',
'settings.modals.update.actions.goToRelease', 'settings.modals.update.actions.goToRelease',
'settings.modals.update.actions.update', 'settings.modals.update.actions.update',
'settings.modals.update.messages.breakChangeError',
'settings.modals.update.messages.available', 'settings.modals.update.messages.available',
'settings.modals.update.alerts.note', 'settings.modals.update.alerts.note',
'settings.modals.update.alerts.tip', 'settings.modals.update.alerts.tip',
-1
View File
@@ -1263,7 +1263,6 @@ export interface TranslationResources {
} }
messages: { messages: {
available: string available: string
breakChangeError: string
} }
title: string title: string
} }