diff --git a/crates/clash-verge-runtime-bundle/src/lib.rs b/crates/clash-verge-runtime-bundle/src/lib.rs index 24902c6e4..0e904d7f3 100644 --- a/crates/clash-verge-runtime-bundle/src/lib.rs +++ b/crates/clash-verge-runtime-bundle/src/lib.rs @@ -56,7 +56,26 @@ pub async fn collect_runtime_bundle(config_file: &Path) -> Result Result> { - Ok(collect_runtime_parts(Value::Mapping(config.clone()), config_root)?.remote_providers) + let config_root = std::fs::canonicalize(config_root)?; + let mut destinations = HashSet::new(); + let mut remote_providers = Vec::new(); + for section in ["proxy-providers", "rule-providers"] { + let Some(providers) = config.get(section).and_then(Value::as_mapping) else { + continue; + }; + for (name, provider) in providers { + plan_provider( + section, + name, + provider, + &config_root, + &mut destinations, + None, + &mut remote_providers, + )?; + } + } + Ok(remote_providers) } #[derive(Default)] @@ -206,70 +225,96 @@ fn collect_provider_assets( }; for (name, provider) in providers.iter_mut() { - let Some(provider) = provider.as_mapping_mut() else { - continue; - }; - let Some(raw_path) = provider.get("path").and_then(Value::as_str) else { - continue; - }; - // Match mihomo's `type` classification and leave malformed-but-accepted providers untouched. - let is_remote = provider.get("type").and_then(Value::as_str) == Some("http"); - let url = provider.get("url").and_then(Value::as_str).map(str::to_owned); - let destination = match (is_remote, url) { - (true, Some(url)) => { - let destination = provider_destination(config_root, raw_path)?; - // Reserve remote destinations too; copied and downloaded files must not collide. - let reserved = TriStr::from(destination.as_str()); - if destinations.insert(reserved.clone()) { - remote_providers.push(RemoteProviderRef { - section, - name: name.as_str().unwrap_or_default().to_owned(), - destination: reserved, - url, - }); - } else { - match remote_providers - .iter() - .find(|declared| declared.destination == destination) - { - Some(declared) if declared.url == url => {} - Some(_) => return Err(RuntimeBundleError::DifferentSources(destination)), - None => return Err(RuntimeBundleError::DuplicateDestination(destination)), - } + if let Some(destination) = plan_provider( + section, + name, + provider, + config_root, + destinations, + Some(assets), + remote_providers, + )? && let Some(provider) = provider.as_mapping_mut() + { + provider.insert(Value::String("path".to_owned()), Value::String(destination)); + } + } + Ok(()) +} + +fn plan_provider( + section: &'static str, + name: &Value, + provider: &Value, + config_root: &Path, + destinations: &mut HashSet, + assets: Option<&mut Vec>, + remote_providers: &mut Vec, +) -> Result> { + let Some(raw_path) = provider + .as_mapping() + .and_then(|provider| provider.get("path")) + .and_then(Value::as_str) + else { + return Ok(None); + }; + // Match mihomo's `type` classification and leave malformed-but-accepted providers untouched. + let is_remote = provider.get("type").and_then(Value::as_str) == Some("http"); + let url = provider.get("url").and_then(Value::as_str); + let destination = match (is_remote, url) { + (true, Some(url)) => { + let destination = provider_destination(config_root, raw_path)?; + // Reserve remote destinations too; copied and downloaded files must not collide. + let reserved = TriStr::from(destination.as_str()); + if destinations.insert(reserved.clone()) { + remote_providers.push(RemoteProviderRef { + section, + name: name.as_str().unwrap_or_default().to_owned(), + destination: reserved, + url: url.to_owned(), + }); + } else { + match remote_providers + .iter() + .find(|declared| declared.destination == destination) + { + Some(declared) if declared.url == url => {} + Some(_) => return Err(RuntimeBundleError::DifferentSources(destination)), + None => return Err(RuntimeBundleError::DuplicateDestination(destination)), } - destination } - (true, None) => { + destination + } + (true, None) => { + logging!( + warn, + Type::Config, + "remote provider {name:?} declares no url; leaving its path to the core" + ); + return Ok(None); + } + (false, _) => { + let Ok(source) = local_provider_source(config_root, raw_path) else { logging!( warn, Type::Config, - "remote provider {name:?} declares no url; leaving its path to the core" + "local provider {name:?} is unavailable at {raw_path:?}; leaving its path to the core" ); - continue; + return Ok(None); + }; + let destination = destination_below_root(config_root, &source)?; + let reserved = TriStr::from(destination.as_str()); + if destinations.insert(reserved.clone()) + && let Some(assets) = assets + { + assets.push(RuntimeAsset { + source: source.to_string_lossy().into_owned(), + destination: reserved, + }); } - (false, _) => { - let Ok(source) = local_provider_source(config_root, raw_path) else { - logging!( - warn, - Type::Config, - "local provider {name:?} is unavailable at {raw_path:?}; leaving its path to the core" - ); - continue; - }; - let destination = destination_below_root(config_root, &source)?; - let reserved = TriStr::from(destination.as_str()); - if destinations.insert(reserved.clone()) { - assets.push(RuntimeAsset { - source: source.to_string_lossy().into_owned(), - destination: reserved, - }); - } - destination - } - }; - provider.insert(Value::String("path".to_owned()), Value::String(destination)); - } - Ok(()) + destination + } + }; + Ok(Some(destination)) } /// Stages file-based ssh keys, which mihomo resolves against the core home directory. diff --git a/src-tauri/src/config/mod.rs b/src-tauri/src/config/mod.rs index aeaad049d..59e8bf35d 100644 --- a/src-tauri/src/config/mod.rs +++ b/src-tauri/src/config/mod.rs @@ -14,7 +14,7 @@ pub(crate) mod snapshot; mod verge; pub(crate) use self::config::Config; -pub(crate) use self::prfitem::{build_remote_profile, fetch_remote_refresh, read_profile_item_file}; +pub(crate) use self::prfitem::{build_remote_profile, download_subscription, read_profile_item_file}; pub use self::{clash::*, encrypt::*, mixed_port::*, profiles::*, verge::*}; pub use clash_verge_profile::{PrfExtra, PrfItem, PrfOption, PrfSelected}; diff --git a/src-tauri/src/config/prfitem.rs b/src-tauri/src/config/prfitem.rs index 2eedf9fbf..a82416211 100644 --- a/src-tauri/src/config/prfitem.rs +++ b/src-tauri/src/config/prfitem.rs @@ -117,7 +117,7 @@ async fn from_local( }) } -struct DownloadedSubscription { +pub(crate) struct DownloadedSubscription { url: Url, suggested_name: Option, extra: Option, @@ -172,12 +172,7 @@ pub(crate) async fn build_remote_profile( }) } -pub(crate) async fn fetch_remote_refresh(url: &str, option: Option<&PrfOption>) -> Result { - let downloaded = download_subscription(url, option).await?; - prepare_remote_refresh(downloaded, option).await -} - -async fn download_subscription(url: &str, option: Option<&PrfOption>) -> Result { +pub(crate) async fn download_subscription(url: &str, option: Option<&PrfOption>) -> Result { let with_proxy = option.is_some_and(|o| o.with_proxy.unwrap_or(false)); let self_proxy = option.is_some_and(|o| o.self_proxy.unwrap_or(false)); let accept_invalid_certs = option.is_some_and(|o| o.danger_accept_invalid_certs.unwrap_or(false)); @@ -233,7 +228,7 @@ async fn download_subscription(url: &str, option: Option<&PrfOption>) -> Result< }) } -async fn prepare_remote_refresh( +pub(crate) async fn prepare_remote_refresh( downloaded: DownloadedSubscription, option: Option<&PrfOption>, ) -> Result { @@ -417,14 +412,12 @@ mod tests { ..Default::default() }; let item: clash_verge_profile::PrfItem = build_remote_profile(&url, None, None, Some(&option)).await?; - let refresh = fetch_remote_refresh( - &url, - Some(&PrfOption { - update_interval: None, - ..option - }), - ) - .await?; + let refresh_option = PrfOption { + update_interval: None, + ..option + }; + let downloaded = download_subscription(&url, Some(&refresh_option)).await?; + let refresh = prepare_remote_refresh(downloaded, Some(&refresh_option)).await?; server.await??; assert_eq!(item.itype.as_deref(), Some("remote")); assert_eq!(item.name.as_deref(), Some("remote.yaml")); diff --git a/src-tauri/src/config/profiles.rs b/src-tauri/src/config/profiles.rs index a3f4d850a..1bed1ee0b 100644 --- a/src-tauri/src/config/profiles.rs +++ b/src-tauri/src/config/profiles.rs @@ -1,6 +1,6 @@ use super::{ PrfItem, PrfOption, PrfSelected, patch_opt_field, - prfitem::{RemoteProfileRefresh, build_profile}, + prfitem::{DownloadedSubscription, RemoteProfileRefresh, build_profile, prepare_remote_refresh}, profile_storage, }; use crate::core::notify::{Refresh, announce}; @@ -314,11 +314,23 @@ pub(crate) async fn profiles_save_file_safe() -> Result<()> { with_profiles_edit(|profiles| async move { save_profiles(&profiles).await.map(|_| profiles) }).await } +fn check_refresh_source(profiles: &IProfiles, uid: &str, url: &str, file: Option<&String>) -> Result<()> { + let current = profiles.get_item(uid)?; + anyhow::ensure!( + current.itype.as_deref() == Some("remote") + && current.url.as_deref() == Some(url) + && current.file.as_ref() == file, + "profile source or filename changed during refresh" + ); + Ok(()) +} + pub(crate) async fn apply_remote_refresh_safe( uid: &str, url: &str, file: Option, - refresh: RemoteProfileRefresh, + downloaded: DownloadedSubscription, + options: Option, ) -> Result<()> { let uid = uid.to_owned(); let url = url.to_owned(); @@ -327,6 +339,8 @@ pub(crate) async fn apply_remote_refresh_safe( let _profile_write = PROFILE_WRITE_LOCK.lock().await; anyhow::ensure!(!handle::Handle::global().is_exiting(), "application is exiting"); let draft = Config::profiles().await; + check_refresh_source(&draft.data_arc(), &uid, &url, file.as_ref())?; + let refresh = prepare_remote_refresh(downloaded, options.as_ref()).await?; let mut storage_guard = None; let mut persisted = false; let result = { @@ -335,13 +349,7 @@ pub(crate) async fn apply_remote_refresh_safe( draft .with_data_modify(|mut candidate| async move { *storage_guard = Some(profile_storage::write().await?); - let current = candidate.get_item(&uid)?; - anyhow::ensure!( - current.itype.as_deref() == Some("remote") - && current.url.as_deref() == Some(url.as_str()) - && current.file == file, - "profile source or filename changed during refresh" - ); + check_refresh_source(&candidate, &uid, &url, file.as_ref())?; stage_remote_refresh(&mut candidate, &uid, &refresh)?; let candidate = profile_storage::commit_refresh(uid, candidate, refresh.body).await?; *persisted = true; diff --git a/src-tauri/src/feat/subscription.rs b/src-tauri/src/feat/subscription.rs index 1031210c7..335b37390 100644 --- a/src-tauri/src/feat/subscription.rs +++ b/src-tauri/src/feat/subscription.rs @@ -1,5 +1,5 @@ use crate::{ - config::{Config, PrfOption, fetch_remote_refresh, profile_storage, profiles::apply_remote_refresh_safe}, + config::{Config, PrfOption, download_subscription, profile_storage, profiles::apply_remote_refresh_safe}, core::{ CoreManager, handle, notify::{NoticeStatus, Refresh, announce}, @@ -109,7 +109,7 @@ async fn perform_profile_update( } tracing::Span::current().record("strategy", name); let started = std::time::Instant::now(); - let result = fetch_remote_refresh(url, options.as_ref()).await; + let result = download_subscription(url, options.as_ref()).await; let elapsed_field = match strategy { Strategy::Configured => "configured_elapsed", Strategy::Clash => "clash_elapsed", @@ -131,9 +131,9 @@ async fn perform_profile_update( ) .await; let last_err = match result { - Ok((strategy, refresh)) => { + Ok((strategy, downloaded)) => { // A persistence error must not replay a successful download with another transport. - apply_remote_refresh_safe(uid, url, source.file.clone(), refresh).await?; + apply_remote_refresh_safe(uid, url, source.file.clone(), downloaded, merged_opt).await?; if !matches!(strategy, Strategy::Configured) { handle::Handle::notice(NoticeStatus::UpdateWithClashProxy, profile_name.as_str()); }