Files
clash-verge-rev/src-tauri/src/utils/resolve/scheme.rs
T
Tunglies 3e3084cd34 refactor: replace smartstring with tristr for backend strings (#8673)
* refactor(config): adopt tristr for config strings

Wire the tristr git dependency (pinned rev) and switch the config and
enhance modules from smartstring::alias::String to tristr::alias::String.
Drop the smartstring-era per-field specta overrides except the three
webdav fields required by serialize_with and the ipc::JsonValue bridge:
tristr maps to Primitive::str natively and the generated bindings stay
byte-identical (gen-contract --check passes).

Call sites in not-yet-migrated modules (cmd/core/feat/utils) are bridged
with explicit tristr::alias::String paths and as_str().into() conversions;
each bridge is absorbed when its module migrates.

* refactor(cmd): adopt tristr for command strings

Switch the cmd module from smartstring::alias::String to
tristr::alias::String and drop its smartstring-era per-field specta
overrides (ProfileSelection/ProfileCreate/ProfilePatch, RuntimeLogs);
bindings stay byte-identical. Calls into not-yet-migrated feat/core
functions keep smartstring-typed locals via full paths until those
modules migrate.

* refactor(core): adopt tristr for core strings

Switch the core module (validate, timer, sysopt, backup, hotkey, tray,
manager, notify) from smartstring::alias::String to tristr::alias::String
and drop the smartstring-era specta overrides on ValidationOutcome and
the notify payload structs; bindings stay byte-identical. WebDAV calls
from the not-yet-migrated feat module are bridged with as_str().into().

* refactor(feat): adopt tristr for feature strings

Switch the feat module (backup, icon, dns, profile, clash) from
smartstring::alias::String to tristr::alias::String, drop its
smartstring-era specta overrides (IconInfo, backup listings,
DnsOverrideOutcome), and absorb the temporary smartstring-typed bridge
locals the cmd module used to call into feat.

* refactor(utils): adopt tristr for utility strings

Switch utils/network.rs and utils/resolve/scheme.rs from
smartstring::alias::String to tristr::alias::String and absorb the
temporary user_agent and profile-name bridge conversions.

* refactor(deps): drop smartstring in favor of tristr

Remove the smartstring workspace and member dependencies and its
Cargo.lock entry; tristr is the only string representation left.

* build(deps): bump tristr to fuzz-harness fix rev

Pin 3738d8c renames the stale vstr path dependency in the upstream
fuzz manifest so its seven targets build again; library code is
unchanged from 3756ed1a.
2026-11-17 08:36:22 +00:00

161 lines
5.1 KiB
Rust

use crate::core::notify::NoticeStatus;
use anyhow::Result;
use percent_encoding::percent_decode_str;
use tauri::Url;
use tristr::alias::String;
use crate::{
config::{Config, PrfItem, profiles},
core::{CoreManager, handle, timer::Timer},
utils::help,
};
use clash_verge_logging::{Type, logging, logging_error};
pub(super) async fn resolve_scheme(param: &str) -> Result<()> {
let param_str = if param.starts_with("[") && param.len() > 4 {
param
.get(2..param.len() - 2)
.ok_or_else(|| anyhow::anyhow!("Invalid string slice boundaries"))?
} else {
param
};
let masked_deep_link = help::mask_url(param_str);
logging!(debug, Type::Config, "received deep link: {masked_deep_link}");
let link_parsed = Url::parse(param_str)
.map_err(|e| anyhow::anyhow!("failed to parse deep link: {e:?}, param: {masked_deep_link}"))?;
let Some((url, name)) = extract_subscription_info(&link_parsed) else {
logging!(
warn,
Type::Config,
"missing url parameter in deep link: {masked_deep_link}"
);
return Ok(());
};
import_subscription(&url, name.as_ref()).await;
Ok(())
}
fn extract_subscription_info(link_parsed: &Url) -> Option<(std::string::String, Option<String>)> {
if !matches!(link_parsed.scheme(), "clash" | "clash-verge") {
return None;
}
let name = link_parsed
.query_pairs()
.find(|(key, _)| key == "name")
.map(|(_, value)| value.into());
let url = extract_subscription_url(link_parsed)?;
Some((url, name))
}
fn extract_subscription_url(link_parsed: &Url) -> Option<std::string::String> {
let query = link_parsed.query()?;
let prefix = "url=";
let pos = query.find(prefix)?;
let raw_url = query[pos + prefix.len()..].trim();
Some(decode_subscription_url(raw_url))
}
fn decode_subscription_url(raw_url: &str) -> std::string::String {
// Avoid double-decoding nested subscription URLs; decode only when needed.
if Url::parse(raw_url).is_ok() {
return raw_url.to_string();
}
let mut candidate = raw_url.to_string();
for _ in 0..2 {
let next = percent_decode_str(&candidate).decode_utf8_lossy().to_string();
if next == candidate {
break;
}
candidate = next;
if Url::parse(&candidate).is_ok() {
break;
}
}
candidate
}
async fn import_subscription(url: &str, name: Option<&String>) {
let had_current_profile = {
let profiles = Config::profiles().await;
profiles.latest_arc().current.is_some()
};
let Some(mut item) = fetch_profile_item(url, name).await else {
return;
};
let uid = item.uid.clone().unwrap_or_default();
if let Err(e) = profiles::profiles_append_item_safe(&mut item).await {
logging!(error, Type::Config, "failed to import subscription url: {:?}", e);
Config::profiles().await.discard();
handle::Handle::notice(NoticeStatus::ImportSubUrlError, e.to_string());
return;
}
if let Err(e) = profiles::profiles_save_file_safe().await {
logging!(error, Type::Config, "failed to save imported subscription: {e:#}");
handle::Handle::notice(NoticeStatus::ImportSubUrlError, e.to_string());
return;
}
logging_error!(Type::Timer, Timer::global().refresh().await);
handle::Handle::notice(
NoticeStatus::ImportSubUrlOk,
"", // 空 msg 传入,我们不希望导致 后端-前端-后端 死循环,这里只做提醒。
);
post_import_updates(&uid, had_current_profile).await;
}
async fn fetch_profile_item(url: &str, name: Option<&String>) -> Option<PrfItem> {
match PrfItem::from_url(url, name, None, None).await {
Ok(item) => Some(item),
Err(e) => {
logging!(error, Type::Config, "failed to parse profile from url: {:?}", e);
handle::Handle::notice(NoticeStatus::ImportSubUrlError, e.to_string());
None
}
}
}
async fn post_import_updates(uid: &str, had_current_profile: bool) {
handle::Handle::refresh_verge();
handle::Handle::notify_profile_changed(uid);
let should_update_core = if uid.is_empty() || had_current_profile {
false
} else {
let profiles = Config::profiles().await;
profiles.latest_arc().current.as_deref() == Some(uid)
};
if should_update_core {
refresh_core_config().await;
}
}
async fn refresh_core_config() {
logging!(
info,
Type::Config,
"Deep link import set current profile; refreshing core config"
);
match CoreManager::global().update_config_forced().await {
Ok(outcome) if outcome.is_valid() => handle::Handle::refresh_clash(),
Ok(outcome) => {
let message = outcome.to_string();
logging!(warn, Type::Config, "Apply config failed: {}", message);
handle::Handle::notice(NoticeStatus::ConfigValidateError, message);
}
Err(err) => {
logging!(error, Type::Config, "Apply config error: {err:#}");
handle::Handle::notice(NoticeStatus::UpdateFailed, format!("{err}"));
}
}
}