refactor(profile): extract profile models and index rules

Move profile models and index rules into the crate, preserving serialization and returning a typed missing-profile error.
This commit is contained in:
Tunglies
2026-11-30 18:44:12 +08:00
parent b1281d78fe
commit e31c01894a
19 changed files with 1017 additions and 856 deletions
Generated
+13
View File
@@ -1097,6 +1097,7 @@ dependencies = [
"clash-verge-limiter",
"clash-verge-logging",
"clash-verge-media-unlock",
"clash-verge-profile",
"clash-verge-profile-script",
"clash-verge-proxy-view",
"clash-verge-runtime-bundle",
@@ -1232,6 +1233,18 @@ dependencies = [
"tokio",
]
[[package]]
name = "clash-verge-profile"
version = "0.1.0"
dependencies = [
"serde",
"serde_json",
"serde_yaml_ng",
"specta",
"thiserror 2.0.20",
"tristr",
]
[[package]]
name = "clash-verge-profile-script"
version = "0.1.0"
+2
View File
@@ -14,6 +14,7 @@ members = [
"crates/clash-verge-config-render",
"crates/clash-verge-profile-script",
"crates/clash-verge-proxy-view",
"crates/clash-verge-profile",
]
resolver = "2"
@@ -69,6 +70,7 @@ clash-verge-limiter = { path = "crates/clash-verge-limiter" }
clash-verge-subscription = { path = "crates/clash-verge-subscription" }
clash-verge-runtime-bundle = { path = "crates/clash-verge-runtime-bundle" }
clash-verge-proxy-view = { path = "crates/clash-verge-proxy-view" }
clash-verge-profile = { path = "crates/clash-verge-profile" }
clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", branch = "main", version = "2.8.2", default-features = false }
tracing-estuary = { git = "https://github.com/Tunglies/tracing-estuary.git", branch = "main" }
tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" }
+17
View File
@@ -0,0 +1,17 @@
[package]
name = "clash-verge-profile"
version = "0.1.0"
edition = "2024"
[dependencies]
serde = { workspace = true, features = ["derive"] }
specta = { workspace = true, features = ["derive"] }
thiserror = { workspace = true }
tristr = { workspace = true }
[dev-dependencies]
serde_json = { workspace = true }
serde_yaml_ng = { workspace = true }
[lints]
workspace = true
+5
View File
@@ -0,0 +1,5 @@
#[derive(Debug, thiserror::Error)]
#[error("failed to get the profile item \"uid:{uid}\"")]
pub struct ProfileNotFound {
pub(super) uid: String,
}
+407
View File
@@ -0,0 +1,407 @@
mod error;
pub use error::ProfileNotFound;
use serde::{Deserialize, Serialize};
use tristr::alias::String;
macro_rules! patch_opt_field {
($lv:expr, $rv:expr, $key:tt) => {
if ($rv.$key).is_some() {
$lv.$key = $rv.$key.clone();
}
};
}
#[derive(Debug, Clone, Deserialize, Serialize, Default, specta::Type)]
#[serde(default)]
pub struct PrfItem {
pub uid: Option<String>,
/// enum value: remote | local | script | merge
#[serde(rename = "type")]
pub itype: Option<String>,
pub name: Option<String>,
pub file: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub desc: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub selected: Option<Vec<PrfSelected>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub extra: Option<PrfExtra>,
pub updated: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub option: Option<PrfOption>,
#[serde(skip_serializing_if = "Option::is_none")]
pub home: Option<String>,
#[serde(skip)]
pub file_data: Option<String>,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)]
#[serde(default)]
pub struct PrfSelected {
pub name: Option<String>,
pub now: Option<String>,
}
#[derive(Default, Debug, Clone, Copy, Deserialize, Serialize, specta::Type)]
pub struct PrfExtra {
pub upload: u64,
pub download: u64,
pub total: u64,
pub expire: u64,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)]
#[serde(default)]
pub struct PrfOption {
#[serde(skip_serializing_if = "Option::is_none")]
pub user_agent: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub with_proxy: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub self_proxy: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub update_interval: Option<u64>,
/// HTTP request timeout in seconds
/// default is 60 seconds
#[serde(skip_serializing_if = "Option::is_none")]
pub timeout_seconds: Option<u64>,
/// default is `false`
#[serde(skip_serializing_if = "Option::is_none")]
pub danger_accept_invalid_certs: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub allow_auto_update: Option<bool>,
pub merge: Option<String>,
pub script: Option<String>,
pub rules: Option<String>,
pub proxies: Option<String>,
pub groups: Option<String>,
}
impl PrfOption {
pub fn merge(one: Option<&Self>, other: Option<&Self>) -> Option<Self> {
match (one, other) {
(Some(a_ref), Some(b_ref)) => {
let mut result = a_ref.clone();
patch_opt_field!(result, b_ref, user_agent);
patch_opt_field!(result, b_ref, with_proxy);
patch_opt_field!(result, b_ref, self_proxy);
patch_opt_field!(result, b_ref, danger_accept_invalid_certs);
patch_opt_field!(result, b_ref, allow_auto_update);
patch_opt_field!(result, b_ref, update_interval);
patch_opt_field!(result, b_ref, merge);
patch_opt_field!(result, b_ref, script);
patch_opt_field!(result, b_ref, rules);
patch_opt_field!(result, b_ref, proxies);
patch_opt_field!(result, b_ref, groups);
patch_opt_field!(result, b_ref, timeout_seconds);
Some(result)
}
(Some(a_ref), None) => Some(a_ref.clone()),
(None, Some(b_ref)) => Some(b_ref.clone()),
(None, None) => None,
}
}
}
macro_rules! current_field {
($name:ident, $field:ident) => {
pub fn $name(&self) -> Option<&String> {
self.option.as_ref().and_then(|o| o.$field.as_ref())
}
};
}
impl PrfItem {
current_field!(current_merge, merge);
current_field!(current_script, script);
current_field!(current_rules, rules);
current_field!(current_proxies, proxies);
current_field!(current_groups, groups);
}
/// Define the `profiles.yaml` schema
#[derive(Default, Debug, Clone, Deserialize, Serialize, specta::Type)]
#[serde(default)]
pub struct IProfiles {
pub current: Option<String>,
pub items: Option<Vec<PrfItem>>,
}
pub struct IProfilePreview<'a> {
pub uid: &'a String,
pub name: &'a String,
pub is_current: bool,
}
pub struct ProfileDeletePlan {
pub deleting_current: bool,
pub files: Vec<String>,
}
impl IProfiles {
pub fn patch_current(&mut self, current: Option<&String>) {
let items = self.items.get_or_insert_with(Vec::new);
if let Some(current) = current
&& items.iter().any(|item| item.uid.as_ref() == Some(current))
{
self.current = Some(current.clone());
}
}
pub fn get_item(&self, uid: impl AsRef<str>) -> Result<&PrfItem, ProfileNotFound> {
let uid_str = uid.as_ref();
if let Some(items) = self.items.as_ref() {
for each in items.iter() {
if let Some(uid_val) = &each.uid
&& uid_val.as_str() == uid_str
{
return Ok(each);
}
}
}
Err(ProfileNotFound {
uid: uid_str.to_owned(),
})
}
/// Inserts a prepared entry after any required body write.
pub fn append_item(&mut self, item: &PrfItem) {
if self.current.is_none() && matches!(item.itype.as_deref(), Some("remote" | "local")) {
self.current = item.uid.clone();
}
self.items.get_or_insert_with(Vec::new).push(item.clone());
}
/// Returns true if both IDs were found, including when the item stayed at its old position.
pub fn reorder(&mut self, active_id: &str, over_id: &str) -> bool {
let Some(items) = self.items.as_mut() else {
return false;
};
let old_index = items.iter().rposition(|item| item.uid.as_deref() == Some(active_id));
let new_index = items.iter().rposition(|item| item.uid.as_deref() == Some(over_id));
let (Some(old_idx), Some(new_idx)) = (old_index, new_index) else {
return false;
};
let item = items.remove(old_idx);
items.insert(new_idx, item);
true
}
pub fn plan_delete_item(&mut self, uid: &str) -> Result<ProfileDeletePlan, ProfileNotFound> {
let deleting_current = self.current.as_deref().is_none_or(|current| current == uid);
let delete_uids = self.get_item(uid)?.option.as_ref().map_or_else(Vec::new, |op| {
[
op.merge.clone(),
op.script.clone(),
op.rules.clone(),
op.proxies.clone(),
op.groups.clone(),
]
.into_iter()
.collect::<Vec<_>>()
});
let mut items = self.items.take().unwrap_or_default();
let mut files = Vec::new();
if let Some(file) = take_item_file_by_uid(&mut items, Some(uid)) {
files.push(file);
}
for delete_uid in delete_uids {
if let Some(file) = take_item_file_by_uid(&mut items, delete_uid.as_deref()) {
files.push(file);
}
}
if deleting_current {
self.current = None;
for item in items.iter() {
if matches!(item.itype.as_deref(), Some("remote" | "local")) {
self.current = item.uid.clone();
break;
}
}
}
self.items = Some(items);
Ok(ProfileDeletePlan {
deleting_current,
files,
})
}
pub fn profiles_preview(&self) -> Option<Vec<IProfilePreview<'_>>> {
self.items.as_ref().map(|items| {
items
.iter()
.filter_map(|e| {
if let (Some(uid), Some(name)) = (e.uid.as_ref(), e.name.as_ref()) {
let is_current = self.current.as_ref() == Some(uid);
let preview = IProfilePreview { uid, name, is_current };
Some(preview)
} else {
None
}
})
.collect()
})
}
}
fn take_item_file_by_uid(items: &mut Vec<PrfItem>, target_uid: Option<&str>) -> Option<String> {
let index = items.iter().position(|item| item.uid.as_deref() == target_uid)?;
items.remove(index).file
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn old_index_preserves_missing_and_explicit_values() -> Result<(), Box<dyn std::error::Error>> {
let mut profiles: IProfiles = serde_yaml_ng::from_str(
r#"
current: first
items:
- uid: first
type: remote
option: {allow_auto_update: false, update_interval: 0, merge: ""}
file_data: ignored
- uid: second
name: ""
"#,
)?;
let first = profiles.get_item("first")?;
assert!(first.file_data.is_none());
assert_eq!(first.current_merge().map(String::as_str), Some(""));
assert!(first.current_script().is_none());
if let Some(items) = profiles.items.as_mut() {
items[0].file_data = Some("in memory".into());
}
assert_eq!(
serde_json::to_value(&profiles)?,
serde_json::json!({
"current": "first",
"items": [
{"uid": "first", "type": "remote", "name": null, "file": null, "updated": null,
"option": {"allow_auto_update": false, "update_interval": 0, "merge": "",
"script": null, "rules": null, "proxies": null, "groups": null}},
{"uid": "second", "type": null, "name": "", "file": null, "updated": null}
]
})
);
assert_eq!(
serde_json::to_value(serde_yaml_ng::from_str::<IProfiles>("{}")?)?,
serde_json::json!({"current": null, "items": null})
);
Ok(())
}
#[test]
fn merge_overrides_only_explicit_values() {
let base = PrfOption {
user_agent: Some("original".into()),
allow_auto_update: Some(true),
update_interval: Some(60),
merge: Some("original-merge".into()),
..Default::default()
};
let overrides = PrfOption {
user_agent: Some("".into()),
allow_auto_update: Some(false),
update_interval: Some(0),
..Default::default()
};
let expected = PrfOption {
merge: base.merge.clone(),
..overrides.clone()
};
assert_eq!(PrfOption::merge(Some(&base), Some(&overrides)), Some(expected));
assert_eq!(PrfOption::merge(None, None), None);
assert_eq!(
PrfOption::merge(None, Some(&PrfOption::default())),
Some(PrfOption::default())
);
}
#[test]
fn lookup_preview_and_reorder_preserve_duplicate_uid_rules() -> Result<(), Box<dyn std::error::Error>> {
let mut profiles: IProfiles = serde_yaml_ng::from_str(
r#"
current: duplicate
items:
- {uid: duplicate, name: first}
- {uid: duplicate, name: last}
- {uid: target, name: ""}
- {name: no UID}
"#,
)?;
assert_eq!(profiles.get_item("duplicate")?.name.as_deref(), Some("first"));
assert!(!profiles.reorder("missing", "target"));
assert!(!profiles.reorder("duplicate", "missing"));
assert!(profiles.reorder("duplicate", "duplicate"));
assert!(profiles.reorder("duplicate", "target"));
let preview = profiles.profiles_preview().unwrap_or_default();
let names: Vec<_> = preview
.iter()
.map(|item| (item.name.as_str(), item.is_current))
.collect();
assert_eq!(names, [("first", true), ("", false), ("last", true)]);
Ok(())
}
#[test]
fn current_patch_initializes_missing_items_and_only_selects_an_existing_uid() {
let mut profiles = IProfiles::default();
profiles.patch_current(None);
assert!(matches!(&profiles.items, Some(items) if items.is_empty()));
assert!(profiles.current.is_none());
profiles.append_item(&PrfItem {
uid: Some("script".into()),
itype: Some("script".into()),
..Default::default()
});
assert!(profiles.current.is_none());
profiles.append_item(&PrfItem {
uid: Some("local".into()),
itype: Some("local".into()),
..Default::default()
});
assert_eq!(profiles.current.as_deref(), Some("local"));
profiles.patch_current(None);
profiles.patch_current(Some(&String::from("missing")));
assert_eq!(profiles.current.as_deref(), Some("local"));
profiles.patch_current(Some(&String::from("script")));
assert_eq!(profiles.current.as_deref(), Some("script"));
}
#[test]
fn delete_plan_preserves_file_order_and_legacy_missing_uid_matching() -> Result<(), Box<dyn std::error::Error>> {
let mut profiles: IProfiles = serde_yaml_ng::from_str(
r"
items:
- {uid: active, type: remote, file: first.yaml, option: {merge: owned}}
- {uid: owned, type: merge, file: owned.yaml}
- {type: script, file: missing-uid.js}
- {uid: next, type: local, file: next.yaml}
",
)?;
let plan = profiles.plan_delete_item("active")?;
assert!(plan.deleting_current);
assert_eq!(
plan.files,
["first.yaml", "owned.yaml", "missing-uid.js"].map(String::from)
);
assert_eq!(profiles.current.as_deref(), Some("next"));
assert!(profiles.get_item("owned").is_err());
Ok(())
}
}
+1
View File
@@ -41,6 +41,7 @@ clash-verge-runtime-bundle = { workspace = true }
clash-verge-config-render = { workspace = true }
clash-verge-profile-script = { workspace = true }
clash-verge-proxy-view = { workspace = true }
clash-verge-profile = { workspace = true }
tauri-plugin-clash-verge-sysinfo = { workspace = true }
tauri-plugin-clipboard-manager = { workspace = true }
tauri = { workspace = true, features = [
+25 -40
View File
@@ -5,12 +5,13 @@ use crate::core::notify::NoticeStatus;
use crate::utils::window_manager::WindowManager;
use crate::{
config::{
Config, IProfiles, PrfItem, PrfOption,
Config, IProfiles, PrfItem, PrfOption, fetch_remote_profile,
profiles::{
PROFILE_WRITE_LOCK, profiles_append_item_with_filedata_safe, profiles_patch_item_safe,
profiles_reorder_safe, profiles_save_file_safe,
PROFILE_WRITE_LOCK, cleanup_profile_files, profiles_append_item_safe,
profiles_append_item_with_filedata_safe, profiles_patch_item_safe, profiles_reorder_safe,
profiles_save_file_safe, save_profiles,
},
profiles_append_item_safe,
read_profile_item_file,
},
core::{CoreManager, handle, timer::Timer, tray::Tray, validate::ValidationOutcome},
feat,
@@ -71,7 +72,7 @@ pub async fn enhance_profiles() -> CmdResult<ValidationOutcome> {
#[tracing::instrument(skip_all, level = "info", fields(url = %help::mask_url(&url), uid = tracing::field::Empty))]
#[specta::specta]
pub async fn import_profile(url: std::string::String, option: Option<PrfOption>) -> CmdResult {
let item = &mut match PrfItem::from_url(&url, None, None, option.as_ref()).await {
let item = &mut match fetch_remote_profile(&url, None, None, option.as_ref()).await {
Ok(it) => it,
Err(e) => {
logging!(error, Type::Cmd, "[导入订阅] 下载失败: {e:#}");
@@ -161,7 +162,8 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult {
let result = profiles
.with_data_modify::<_, _, _, anyhow::Error>(|mut candidate| async move {
let original = candidate.clone();
let (should_update, plan) = candidate.plan_delete_item(&index)?;
let plan = candidate.plan_delete_item(&index)?;
let should_update = plan.deleting_current;
let guard = if should_update {
match CoreManager::global()
.update_config_forced_with_profiles(&candidate, &original)
@@ -171,11 +173,11 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult {
Err(outcome) => return Ok((original, Err(outcome))),
}
} else {
candidate.save_file().await?;
save_profiles(&candidate).await?;
None
};
let current = candidate.current.clone();
plan.cleanup().await;
cleanup_profile_files(plan.files).await;
Ok((candidate, Ok((should_update, current, guard))))
})
.await
@@ -210,15 +212,11 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult {
Ok(())
}
async fn restore_previous_profile(prev_profile: &str) -> CmdResult<()> {
async fn restore_previous_profile(prev_profile: &String) -> CmdResult<()> {
logging!(info, Type::Cmd, "尝试恢复到之前的配置: {}", prev_profile);
let restore_profiles = IProfiles {
current: Some(prev_profile.into()),
items: None,
};
Config::profiles()
.await
.edit_draft(|d| d.patch_config(&restore_profiles));
.edit_draft(|d| d.patch_current(Some(prev_profile)));
Config::profiles().await.apply();
crate::process::AsyncHandler::spawn(|| async move {
if let Err(e) = profiles_save_file_safe().await {
@@ -236,10 +234,7 @@ async fn commit_current_profile(profiles: &Draft<IProfiles>, current: Option<Str
profiles
.with_data_modify(|mut committed| async move {
committed.patch_config(&IProfiles {
current: Some(current),
items: None,
});
committed.patch_current(Some(&current));
Ok((committed, ()))
})
.await
@@ -397,16 +392,12 @@ pub async fn patch_profiles_config(profiles: ProfileSelection) -> CmdResult<Vali
});
let _profile_write_guard = PROFILE_WRITE_LOCK.lock().await;
let profiles = IProfiles {
current: profiles.current,
items: None,
};
let target_profile = profiles.current.as_ref();
let previous_profile = Config::profiles().await.data_arc().current.clone();
Config::profiles().await.edit_draft(|d| {
d.patch_config(&profiles);
d.patch_current(target_profile);
});
perform_config_update(target_profile, previous_profile.as_ref())
@@ -492,20 +483,17 @@ pub async fn view_profile(index: std::string::String) -> CmdResult {
#[tauri::command]
#[specta::specta]
pub async fn read_profile_file(index: std::string::String) -> CmdResult<std::string::String> {
let item = {
let file = {
let profiles = Config::profiles().await;
let profiles_ref = profiles.latest_arc();
PrfItem {
file: profiles_ref
.get_item(&index)
.with_error_code("PROFILE_READ_FAILED")?
.file
.to_owned(),
..Default::default()
}
profiles_ref
.get_item(&index)
.with_error_code("PROFILE_READ_FAILED")?
.file
.clone()
};
if let Some(file) = item.file.as_ref() {
if let Some(file) = file.as_ref() {
let path = dirs::app_profiles_dir()
.with_error_code("PROFILE_READ_FAILED")?
.join(file.as_str());
@@ -521,7 +509,9 @@ pub async fn read_profile_file(index: std::string::String) -> CmdResult<std::str
}
}
let data = item.read_file().await.with_error_code("PROFILE_READ_FAILED")?;
let data = read_profile_item_file(file.as_deref())
.await
.with_error_code("PROFILE_READ_FAILED")?;
Ok(data.into())
}
@@ -575,12 +565,7 @@ mod tests {
current: Some("a".into()),
items: Some(vec![profile("a"), profile("b")]),
});
profiles.edit_draft(|draft| {
draft.patch_config(&IProfiles {
current: Some("b".into()),
items: None,
});
});
profiles.edit_draft(|draft| draft.patch_current(Some(&"b".into())));
profiles
.with_data_modify(|mut committed| async move {
committed.items.get_or_insert_with(Vec::new).push(profile("new"));
+2 -8
View File
@@ -2,7 +2,7 @@ use super::CmdResult;
use crate::{
cmd::StringifyErr as _,
cmd::validate::{ValidationNoticeTarget, handle_validation_notice},
config::{Config, IProfiles, PrfItem},
config::{Config, IProfiles, read_profile_item_file},
core::auto_backup::{self, AutoBackupTrigger},
core::{
CoreManager, handle,
@@ -58,13 +58,7 @@ pub async fn save_profile_file(
))
})?;
let original_content = if original_existed {
PrfItem {
file: Some(rel_path.clone()),
..Default::default()
}
.read_file()
.await
.stringify_err()?
read_profile_item_file(Some(rel_path.as_str())).await.stringify_err()?
} else {
String::new()
};
+9 -5
View File
@@ -1,7 +1,11 @@
use super::{IClashTemp, IProfiles, IVerge, MixedPort};
use crate::core::notify::NoticeStatus;
use crate::{
config::{PrfItem, profiles_append_item_to_safe, runtime::IRuntime},
config::{
prfitem::{build_merge_profile, build_script_profile},
profiles::{load_profiles, profiles_append_item_to_safe, save_profiles},
runtime::IRuntime,
},
constants::{files, timing},
core::{
CoreManager,
@@ -45,7 +49,7 @@ impl Config {
Self {
clash_config: Draft::new(IClashTemp::new().await),
verge_config: Draft::new(IVerge::new().await),
profiles_config: Draft::new(IProfiles::new().await),
profiles_config: Draft::new(load_profiles().await),
runtime_config: Draft::new(IRuntime::default()),
}
})
@@ -137,11 +141,11 @@ impl Config {
}
if profiles.latest_arc().get_item("Merge").is_err() {
let merge_item = &mut PrfItem::from_merge(Some("Merge".into()));
let merge_item = &mut build_merge_profile(Some("Merge".into()));
profiles_append_item_to_safe(&profiles, merge_item).await?;
}
if profiles.latest_arc().get_item("Script").is_err() {
let script_item = &mut PrfItem::from_script(Some("Script".into()));
let script_item = &mut build_script_profile(Some("Script".into()));
profiles_append_item_to_safe(&profiles, script_item).await?;
}
Ok(())
@@ -310,7 +314,7 @@ impl Config {
let _profile_write = super::profiles::PROFILE_WRITE_LOCK.lock().await;
let profiles = Self::profiles().await;
profiles.apply();
logging_error!(Type::Config, profiles.data_arc().save_file().await);
logging_error!(Type::Config, save_profiles(&profiles.data_arc()).await);
});
let _ = tokio::join!(save_clash_task, save_verge_task, save_profiles_task);
+3 -1
View File
@@ -12,7 +12,9 @@ pub(crate) mod snapshot;
mod verge;
pub(crate) use self::config::Config;
pub use self::{clash::*, encrypt::*, mixed_port::*, prfitem::*, profiles::*, verge::*};
pub(crate) use self::prfitem::{fetch_remote_profile, read_profile_item_file};
pub use self::{clash::*, encrypt::*, mixed_port::*, profiles::*, verge::*};
pub use clash_verge_profile::{PrfExtra, PrfItem, PrfOption, PrfSelected};
macro_rules! patch_opt_field {
($lv:expr, $rv:expr, $key:tt) => {
+311 -382
View File
@@ -1,4 +1,4 @@
use super::patch_opt_field;
use super::{PrfExtra, PrfItem, PrfOption};
use crate::{
config::profiles,
@@ -10,7 +10,6 @@ use crate::{
};
use anyhow::{Context as _, Result, bail};
use clash_verge_subscription::decode_subscription;
use serde::{Deserialize, Serialize};
use std::time::Duration;
use tokio::fs;
use tristr::alias::String;
@@ -18,396 +17,266 @@ use tristr::alias::String;
use reqwest_dav::re_exports::url::form_urlencoded;
use tauri::Url;
#[derive(Debug, Clone, Deserialize, Serialize, Default, specta::Type)]
#[serde(default)]
pub struct PrfItem {
pub uid: Option<String>,
/// enum value: remote | local | script | merge
#[serde(rename = "type")]
pub itype: Option<String>,
pub name: Option<String>,
pub file: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub desc: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub selected: Option<Vec<PrfSelected>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub extra: Option<PrfExtra>,
pub updated: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub option: Option<PrfOption>,
#[serde(skip_serializing_if = "Option::is_none")]
pub home: Option<String>,
#[serde(skip)]
pub file_data: Option<String>,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)]
#[serde(default)]
pub struct PrfSelected {
pub name: Option<String>,
pub now: Option<String>,
}
#[derive(Default, Debug, Clone, Copy, Deserialize, Serialize, specta::Type)]
pub struct PrfExtra {
pub upload: u64,
pub download: u64,
pub total: u64,
pub expire: u64,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)]
#[serde(default)]
pub struct PrfOption {
#[serde(skip_serializing_if = "Option::is_none")]
pub user_agent: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub with_proxy: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub self_proxy: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub update_interval: Option<u64>,
/// HTTP request timeout in seconds
/// default is 60 seconds
#[serde(skip_serializing_if = "Option::is_none")]
pub timeout_seconds: Option<u64>,
/// default is `false`
#[serde(skip_serializing_if = "Option::is_none")]
pub danger_accept_invalid_certs: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub allow_auto_update: Option<bool>,
pub merge: Option<String>,
pub script: Option<String>,
pub rules: Option<String>,
pub proxies: Option<String>,
pub groups: Option<String>,
}
impl PrfOption {
pub(crate) fn merge(one: Option<&Self>, other: Option<&Self>) -> Option<Self> {
match (one, other) {
(Some(a_ref), Some(b_ref)) => {
let mut result = a_ref.clone();
patch_opt_field!(result, b_ref, user_agent);
patch_opt_field!(result, b_ref, with_proxy);
patch_opt_field!(result, b_ref, self_proxy);
patch_opt_field!(result, b_ref, danger_accept_invalid_certs);
patch_opt_field!(result, b_ref, allow_auto_update);
patch_opt_field!(result, b_ref, update_interval);
patch_opt_field!(result, b_ref, merge);
patch_opt_field!(result, b_ref, script);
patch_opt_field!(result, b_ref, rules);
patch_opt_field!(result, b_ref, proxies);
patch_opt_field!(result, b_ref, groups);
patch_opt_field!(result, b_ref, timeout_seconds);
Some(result)
}
(Some(a_ref), None) => Some(a_ref.clone()),
(None, Some(b_ref)) => Some(b_ref.clone()),
(None, None) => None,
/// Builds an item from a partial value that must include `itype`.
pub(super) async fn build_profile(item: &PrfItem, file_data: Option<String>) -> Result<PrfItem> {
let itype = item
.itype
.as_ref()
.ok_or_else(|| anyhow::anyhow!("type should not be null"))?;
match itype.as_str() {
"remote" => {
let url = item
.url
.as_ref()
.ok_or_else(|| anyhow::anyhow!("url should not be null"))?;
let name = item.name.as_ref();
let desc = item.desc.as_ref();
let option = item.option.as_ref();
fetch_remote_profile(url, name, desc, option).await
}
"local" => {
let name = item.name.clone().unwrap_or_else(|| "Local File".into());
let desc = item.desc.clone().unwrap_or_else(|| "".into());
let option = item.option.as_ref();
from_local(name, desc, file_data, option).await
}
typ => bail!("invalid profile item type \"{typ}\""),
}
}
impl PrfItem {
/// Builds an item from a partial value that must include `itype`.
pub(super) async fn from(item: &Self, file_data: Option<String>) -> Result<Self> {
let itype = item
.itype
.as_ref()
.ok_or_else(|| anyhow::anyhow!("type should not be null"))?;
match itype.as_str() {
"remote" => {
let url = item
.url
.as_ref()
.ok_or_else(|| anyhow::anyhow!("url should not be null"))?;
let name = item.name.as_ref();
let desc = item.desc.as_ref();
let option = item.option.as_ref();
Self::from_url(url, name, desc, option).await
}
"local" => {
let name = item.name.clone().unwrap_or_else(|| "Local File".into());
let desc = item.desc.clone().unwrap_or_else(|| "".into());
let option = item.option.as_ref();
Self::from_local(name, desc, file_data, option).await
}
typ => bail!("invalid profile item type \"{typ}\""),
}
}
async fn append_companion_item(item: &mut Self) -> Result<String> {
profiles::profiles_append_item_safe(item).await?;
item.uid
.clone()
.ok_or_else(|| anyhow::anyhow!("appended companion item has no uid"))
}
async fn ensure_companion_items(
merge: &mut Option<String>,
script: &mut Option<String>,
rules: &mut Option<String>,
proxies: &mut Option<String>,
groups: &mut Option<String>,
) -> Result<()> {
if merge.is_none() {
*merge = Some(Self::append_companion_item(&mut Self::from_merge(None)).await?);
}
if script.is_none() {
*script = Some(Self::append_companion_item(&mut Self::from_script(None)).await?);
}
if rules.is_none() {
*rules = Some(Self::append_companion_item(&mut Self::from_rules()).await?);
}
if proxies.is_none() {
*proxies = Some(Self::append_companion_item(&mut Self::from_proxies()).await?);
}
if groups.is_none() {
*groups = Some(Self::append_companion_item(&mut Self::from_groups()).await?);
}
Ok(())
}
async fn from_local(
name: String,
desc: String,
file_data: Option<String>,
option: Option<&PrfOption>,
) -> Result<Self> {
let uid = help::get_uid("L").into();
let file = format!("{uid}.yaml").into();
let opt_ref = option.as_ref();
let update_interval = opt_ref.and_then(|o| o.update_interval);
let mut merge = opt_ref.and_then(|o| o.merge.clone());
let mut script = opt_ref.and_then(|o| o.script.clone());
let mut rules = opt_ref.and_then(|o| o.rules.clone());
let mut proxies = opt_ref.and_then(|o| o.proxies.clone());
let mut groups = opt_ref.and_then(|o| o.groups.clone());
Self::ensure_companion_items(&mut merge, &mut script, &mut rules, &mut proxies, &mut groups).await?;
Ok(Self {
uid: Some(uid),
itype: Some("local".into()),
name: Some(name),
desc: Some(desc),
file: Some(file),
url: None,
selected: None,
extra: None,
option: Some(PrfOption {
update_interval,
merge,
script,
rules,
proxies,
groups,
..PrfOption::default()
}),
home: None,
updated: Some(chrono::Local::now().timestamp() as usize),
file_data: Some(file_data.unwrap_or_else(|| tmpl::ITEM_LOCAL.into())),
})
}
pub(crate) async fn from_url(
url: &str,
name: Option<&String>,
desc: Option<&String>,
option: Option<&PrfOption>,
) -> Result<Self> {
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));
let allow_auto_update = Some(allow_auto_update_enabled(option));
let user_agent = option.and_then(|o| o.user_agent.clone());
let update_interval = option.and_then(|o| o.update_interval);
let timeout = option.and_then(|o| o.timeout_seconds).unwrap_or(20);
let mut merge = option.and_then(|o| o.merge.clone());
let mut script = option.and_then(|o| o.script.clone());
let mut rules = option.and_then(|o| o.rules.clone());
let mut proxies = option.and_then(|o| o.proxies.clone());
let mut groups = option.and_then(|o| o.groups.clone());
let proxy_type = if self_proxy {
ProxyType::Localhost
} else if with_proxy {
ProxyType::System
} else {
ProxyType::None
};
let url = fix_dirty_url(url)?;
let resp = match NetworkManager::new()
.get(
url.as_str(),
proxy_type,
Some(timeout),
user_agent.clone(),
accept_invalid_certs,
)
.await
{
Ok(r) => r,
Err(e) => {
tokio::time::sleep(Duration::from_millis(100)).await;
return Err(e).context("failed to fetch remote profile");
}
};
let status_code = resp.status();
if !status_code.is_success() {
bail!("failed to fetch remote profile with status {status_code}")
}
let document = decode_subscription(&url, resp.headers(), resp.text())?;
let update_interval = update_interval.or(document.update_interval_minutes);
let extra = document.usage.map(|usage| PrfExtra {
upload: usage.upload,
download: usage.download,
total: usage.total,
expire: usage.expire,
});
let uid = help::get_uid("R").into();
let file = format!("{uid}.yaml").into();
let name = name
.cloned()
.unwrap_or_else(|| document.filename.map_or_else(|| "Remote File".into(), Into::into));
Self::ensure_companion_items(&mut merge, &mut script, &mut rules, &mut proxies, &mut groups).await?;
Ok(Self {
uid: Some(uid),
itype: Some("remote".into()),
name: Some(name),
desc: desc.cloned(),
file: Some(file),
url: Some(url.as_str().into()),
selected: None,
extra,
option: Some(PrfOption {
update_interval,
merge,
script,
rules,
proxies,
groups,
allow_auto_update,
..PrfOption::default()
}),
home: document.home.map(Into::into),
updated: Some(chrono::Local::now().timestamp() as usize),
file_data: Some(document.body.into()),
})
}
pub(super) fn from_merge(uid: Option<String>) -> Self {
let (id, template) = if let Some(uid) = uid {
(uid, tmpl::ITEM_MERGE.into())
} else {
(help::get_uid("m").into(), tmpl::ITEM_MERGE_EMPTY.into())
};
let file = format!("{id}.yaml").into();
Self {
uid: Some(id),
itype: Some("merge".into()),
file: Some(file),
updated: Some(chrono::Local::now().timestamp() as usize),
file_data: Some(template),
..Default::default()
}
}
pub(super) fn from_script(uid: Option<String>) -> Self {
let id = if let Some(uid) = uid {
uid
} else {
help::get_uid("s").into()
};
let file = format!("{id}.js").into(); // js ext
Self {
uid: Some(id),
itype: Some("script".into()),
file: Some(file),
updated: Some(chrono::Local::now().timestamp() as usize),
file_data: Some(tmpl::ITEM_SCRIPT.into()),
..Default::default()
}
}
fn new_seq_item(prefix: &str, itype: &str, template: &str) -> Self {
let uid = help::get_uid(prefix).into();
let file = format!("{uid}.yaml").into(); // yaml ext
Self {
uid: Some(uid),
itype: Some(itype.into()),
file: Some(file),
updated: Some(chrono::Local::now().timestamp() as usize),
file_data: Some(template.into()),
..Default::default()
}
}
fn from_rules() -> Self {
Self::new_seq_item("r", "rules", tmpl::ITEM_RULES)
}
fn from_proxies() -> Self {
Self::new_seq_item("p", "proxies", tmpl::ITEM_PROXIES)
}
fn from_groups() -> Self {
Self::new_seq_item("g", "groups", tmpl::ITEM_GROUPS)
}
pub(crate) async fn read_file(&self) -> Result<String> {
let file = self
.file
.as_ref()
.ok_or_else(|| anyhow::anyhow!("could not find the file"))?;
let path = dirs::app_profiles_dir()?.join(file.as_str());
let content = fs::read_to_string(&path)
.await
.with_context(|| format!("failed to read the file \"{}\"", path.display()))?;
Ok(content.into())
}
async fn append_companion_item(item: &mut PrfItem) -> Result<String> {
profiles::profiles_append_item_safe(item).await?;
item.uid
.clone()
.ok_or_else(|| anyhow::anyhow!("appended companion item has no uid"))
}
macro_rules! current_field {
($name:ident, $field:ident) => {
pub(crate) fn $name(&self) -> Option<&String> {
self.option.as_ref().and_then(|o| o.$field.as_ref())
async fn ensure_companion_items(
merge: &mut Option<String>,
script: &mut Option<String>,
rules: &mut Option<String>,
proxies: &mut Option<String>,
groups: &mut Option<String>,
) -> Result<()> {
if merge.is_none() {
*merge = Some(append_companion_item(&mut build_merge_profile(None)).await?);
}
if script.is_none() {
*script = Some(append_companion_item(&mut build_script_profile(None)).await?);
}
if rules.is_none() {
*rules = Some(append_companion_item(&mut from_rules()).await?);
}
if proxies.is_none() {
*proxies = Some(append_companion_item(&mut from_proxies()).await?);
}
if groups.is_none() {
*groups = Some(append_companion_item(&mut from_groups()).await?);
}
Ok(())
}
async fn from_local(
name: String,
desc: String,
file_data: Option<String>,
option: Option<&PrfOption>,
) -> Result<PrfItem> {
let uid = help::get_uid("L").into();
let file = format!("{uid}.yaml").into();
let opt_ref = option.as_ref();
let update_interval = opt_ref.and_then(|o| o.update_interval);
let mut merge = opt_ref.and_then(|o| o.merge.clone());
let mut script = opt_ref.and_then(|o| o.script.clone());
let mut rules = opt_ref.and_then(|o| o.rules.clone());
let mut proxies = opt_ref.and_then(|o| o.proxies.clone());
let mut groups = opt_ref.and_then(|o| o.groups.clone());
ensure_companion_items(&mut merge, &mut script, &mut rules, &mut proxies, &mut groups).await?;
Ok(PrfItem {
uid: Some(uid),
itype: Some("local".into()),
name: Some(name),
desc: Some(desc),
file: Some(file),
url: None,
selected: None,
extra: None,
option: Some(PrfOption {
update_interval,
merge,
script,
rules,
proxies,
groups,
..PrfOption::default()
}),
home: None,
updated: Some(chrono::Local::now().timestamp() as usize),
file_data: Some(file_data.unwrap_or_else(|| tmpl::ITEM_LOCAL.into())),
})
}
pub(crate) async fn fetch_remote_profile(
url: &str,
name: Option<&String>,
desc: Option<&String>,
option: Option<&PrfOption>,
) -> Result<PrfItem> {
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));
let allow_auto_update = Some(allow_auto_update_enabled(option));
let user_agent = option.and_then(|o| o.user_agent.clone());
let update_interval = option.and_then(|o| o.update_interval);
let timeout = option.and_then(|o| o.timeout_seconds).unwrap_or(20);
let mut merge = option.and_then(|o| o.merge.clone());
let mut script = option.and_then(|o| o.script.clone());
let mut rules = option.and_then(|o| o.rules.clone());
let mut proxies = option.and_then(|o| o.proxies.clone());
let mut groups = option.and_then(|o| o.groups.clone());
let proxy_type = if self_proxy {
ProxyType::Localhost
} else if with_proxy {
ProxyType::System
} else {
ProxyType::None
};
let url = fix_dirty_url(url)?;
let resp = match NetworkManager::new()
.get(
url.as_str(),
proxy_type,
Some(timeout),
user_agent.clone(),
accept_invalid_certs,
)
.await
{
Ok(r) => r,
Err(e) => {
tokio::time::sleep(Duration::from_millis(100)).await;
return Err(e).context("failed to fetch remote profile");
}
};
let status_code = resp.status();
if !status_code.is_success() {
bail!("failed to fetch remote profile with status {status_code}")
}
let document = decode_subscription(&url, resp.headers(), resp.text())?;
let update_interval = update_interval.or(document.update_interval_minutes);
let extra = document.usage.map(|usage| PrfExtra {
upload: usage.upload,
download: usage.download,
total: usage.total,
expire: usage.expire,
});
let uid = help::get_uid("R").into();
let file = format!("{uid}.yaml").into();
let name = name
.cloned()
.unwrap_or_else(|| document.filename.map_or_else(|| "Remote File".into(), Into::into));
ensure_companion_items(&mut merge, &mut script, &mut rules, &mut proxies, &mut groups).await?;
Ok(PrfItem {
uid: Some(uid),
itype: Some("remote".into()),
name: Some(name),
desc: desc.cloned(),
file: Some(file),
url: Some(url.as_str().into()),
selected: None,
extra,
option: Some(PrfOption {
update_interval,
merge,
script,
rules,
proxies,
groups,
allow_auto_update,
..PrfOption::default()
}),
home: document.home.map(Into::into),
updated: Some(chrono::Local::now().timestamp() as usize),
file_data: Some(document.body.into()),
})
}
impl PrfItem {
current_field!(current_merge, merge);
current_field!(current_script, script);
current_field!(current_rules, rules);
current_field!(current_proxies, proxies);
current_field!(current_groups, groups);
pub(super) fn build_merge_profile(uid: Option<String>) -> PrfItem {
let (id, template) = if let Some(uid) = uid {
(uid, tmpl::ITEM_MERGE.into())
} else {
(help::get_uid("m").into(), tmpl::ITEM_MERGE_EMPTY.into())
};
let file = format!("{id}.yaml").into();
PrfItem {
uid: Some(id),
itype: Some("merge".into()),
file: Some(file),
updated: Some(chrono::Local::now().timestamp() as usize),
file_data: Some(template),
..Default::default()
}
}
pub(super) fn build_script_profile(uid: Option<String>) -> PrfItem {
let id = if let Some(uid) = uid {
uid
} else {
help::get_uid("s").into()
};
let file = format!("{id}.js").into(); // js ext
PrfItem {
uid: Some(id),
itype: Some("script".into()),
file: Some(file),
updated: Some(chrono::Local::now().timestamp() as usize),
file_data: Some(tmpl::ITEM_SCRIPT.into()),
..Default::default()
}
}
fn new_seq_item(prefix: &str, itype: &str, template: &str) -> PrfItem {
let uid = help::get_uid(prefix).into();
let file = format!("{uid}.yaml").into(); // yaml ext
PrfItem {
uid: Some(uid),
itype: Some(itype.into()),
file: Some(file),
updated: Some(chrono::Local::now().timestamp() as usize),
file_data: Some(template.into()),
..Default::default()
}
}
fn from_rules() -> PrfItem {
new_seq_item("r", "rules", tmpl::ITEM_RULES)
}
fn from_proxies() -> PrfItem {
new_seq_item("p", "proxies", tmpl::ITEM_PROXIES)
}
fn from_groups() -> PrfItem {
new_seq_item("g", "groups", tmpl::ITEM_GROUPS)
}
pub(crate) async fn read_profile_item_file(file: Option<&str>) -> Result<String> {
let file = file.ok_or_else(|| anyhow::anyhow!("could not find the file"))?;
let path = dirs::app_profiles_dir()?.join(file);
let content = fs::read_to_string(&path)
.await
.with_context(|| format!("failed to read the file \"{}\"", path.display()))?;
Ok(content.into())
}
fn allow_auto_update_enabled(option: Option<&PrfOption>) -> bool {
@@ -442,3 +311,63 @@ fn fix_dirty_url(input: &str) -> Result<Url> {
Ok(url)
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::{
io::{AsyncBufReadExt as _, AsyncWriteExt as _, BufReader},
net::TcpListener,
};
#[tokio::test]
async fn fetch_remote_profile_maps_response_to_profile_model() -> Result<()> {
const BODY: &str = "# keep this comment\nproxies: []\n";
let listener = TcpListener::bind("127.0.0.1:0").await?;
let url = format!("http://{}/subscription", listener.local_addr()?);
let server = tokio::spawn(async move {
let (socket, _) = listener.accept().await?;
let mut socket = BufReader::new(socket);
let mut line = std::string::String::new();
loop {
line.clear();
if socket.read_line(&mut line).await? == 0 || line == "\r\n" {
break;
}
}
let response = format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\
Content-Disposition: attachment; filename=remote.yaml\r\n\
Profile-Update-Interval: 2\r\n\
Profile-Web-Page-Url: https://example.invalid/\r\n\
Subscription-Userinfo: upload=1; download=2; total=3; expire=4\r\n\r\n{BODY}",
BODY.len()
);
socket.get_mut().write_all(response.as_bytes()).await
});
let option = PrfOption {
update_interval: Some(0),
allow_auto_update: Some(false),
timeout_seconds: Some(5),
merge: Some("test-merge".into()),
script: Some("test-script".into()),
rules: Some("test-rules".into()),
proxies: Some("test-proxies".into()),
groups: Some("test-groups".into()),
..Default::default()
};
let item: clash_verge_profile::PrfItem = fetch_remote_profile(&url, None, None, Some(&option)).await?;
server.await??;
assert_eq!(item.itype.as_deref(), Some("remote"));
assert_eq!(item.name.as_deref(), Some("remote.yaml"));
assert_eq!(item.home.as_deref(), Some("https://example.invalid/"));
assert_eq!(item.file_data.as_deref(), Some(BODY));
assert_eq!(item.current_merge().map(String::as_str), Some("test-merge"));
let usage = item.extra.context("expected decoded usage")?;
assert_eq!((usage.upload, usage.download, usage.total, usage.expire), (1, 2, 3, 4));
let fetched_option = item.option.context("expected profile options")?;
assert_eq!(fetched_option.update_interval, Some(0));
assert_eq!(fetched_option.allow_auto_update, Some(false));
Ok(())
}
}
+204 -404
View File
@@ -1,7 +1,4 @@
use super::{
PrfOption, patch_opt_field,
prfitem::{PrfItem, PrfSelected},
};
use super::{PrfItem, PrfOption, PrfSelected, patch_opt_field, prfitem::build_profile};
use crate::core::notify::{Refresh, announce};
use crate::utils::retry::{RetryError, RetryPolicy, retry, retry_with_state};
use crate::{
@@ -15,9 +12,9 @@ use crate::{
use anyhow::{Context as _, Result, bail};
use clash_verge_draft::Draft;
use clash_verge_logging::{Type, logging};
pub use clash_verge_profile::{IProfilePreview, IProfiles};
use clash_verge_subscription::normalize_profile_home_url;
use futures::FutureExt as _;
use serde::{Deserialize, Serialize};
use serde_yaml_ng::Mapping;
use std::num::NonZeroUsize;
use std::{
@@ -49,359 +46,218 @@ const SELECTED_NODES_SETTLE_INTERVAL: Duration = Duration::from_secs(1);
/// Bounds startup waiting; remaining selections continue restoring in the background.
const SELECTED_NODES_FIRST_PASS_BUDGET: Duration = Duration::from_secs(3);
/// Define the `profiles.yaml` schema
#[derive(Default, Debug, Clone, Deserialize, Serialize, specta::Type)]
#[serde(default)]
pub struct IProfiles {
pub current: Option<String>,
pub items: Option<Vec<PrfItem>>,
}
pub struct IProfilePreview<'a> {
pub uid: &'a String,
pub name: &'a String,
pub is_current: bool,
}
pub(crate) struct ProfileDeletePlan {
files: Vec<String>,
}
impl ProfileDeletePlan {
pub(crate) async fn cleanup(self) {
let Ok(dir) = dirs::app_profiles_dir() else {
return;
};
for file in self.files {
let path = dir.join(file.as_str());
if let Err(error) = path.remove_if_exists().await {
logging!(
warn,
Type::Config,
"Failed to remove deleted profile file {}: {error:#}",
path.display()
);
}
pub(crate) async fn cleanup_profile_files(files: Vec<String>) {
let Ok(dir) = dirs::app_profiles_dir() else {
return;
};
for file in files {
let path = dir.join(file.as_str());
if let Err(error) = path.remove_if_exists().await {
logging!(
warn,
Type::Config,
"Failed to remove deleted profile file {}: {error:#}",
path.display()
);
}
}
}
impl IProfiles {
fn take_item_file_by_uid(items: &mut Vec<PrfItem>, target_uid: Option<&str>) -> Option<String> {
let index = items.iter().position(|item| item.uid.as_deref() == target_uid)?;
items.remove(index).file
}
pub(crate) async fn load_profiles() -> IProfiles {
let path = match dirs::profiles_path() {
Ok(p) => p,
Err(err) => {
logging!(error, Type::Config, "failed to get profiles path: {err:#}");
return IProfiles::default();
}
};
pub async fn new() -> Self {
let path = match dirs::profiles_path() {
Ok(p) => p,
Err(err) => {
logging!(error, Type::Config, "failed to get profiles path: {err:#}");
return Self::default();
}
};
match help::read_yaml::<Self>(&path).await {
Ok(mut profiles) => {
let items = profiles.items.get_or_insert_with(Vec::new);
let mut home_changed = false;
for item in items.iter_mut() {
if item.uid.is_none() {
item.uid = Some(help::get_uid("d").into());
}
if item.itype.as_deref() == Some("remote") {
item.option
.get_or_insert_with(PrfOption::default)
.allow_auto_update
.get_or_insert(true);
}
if item
.home
.as_deref()
.is_some_and(|home| normalize_profile_home_url(home).is_none())
{
item.home = None;
home_changed = true;
}
match help::read_yaml::<IProfiles>(&path).await {
Ok(mut profiles) => {
let items = profiles.items.get_or_insert_with(Vec::new);
let mut home_changed = false;
for item in items.iter_mut() {
if item.uid.is_none() {
item.uid = Some(help::get_uid("d").into());
}
if item.itype.as_deref() == Some("remote") {
item.option
.get_or_insert_with(PrfOption::default)
.allow_auto_update
.get_or_insert(true);
}
if home_changed && let Err(err) = profiles.save_file().await {
logging!(error, Type::Config, "无法保存已清理的 profiles.yaml: {err:#}");
}
profiles
}
Err(err) => {
logging!(error, Type::Config, "failed to read profiles.yaml: {err:#}");
Self::default()
}
}
}
pub async fn save_file(&self) -> Result<()> {
help::save_yaml(&dirs::profiles_path()?, self, Some("# Profiles Config for Clash Verge")).await
}
/// 只修改current,valid和chain
pub fn patch_config(&mut self, patch: &Self) {
if self.items.is_none() {
self.items = Some(vec![]);
}
if let Some(current) = &patch.current
&& let Some(items) = self.items.as_ref()
{
let some_uid = Some(current);
if items.iter().any(|e| e.uid.as_ref() == some_uid) {
self.current = some_uid.cloned();
}
}
}
pub fn get_item(&self, uid: impl AsRef<str>) -> Result<&PrfItem> {
let uid_str = uid.as_ref();
if let Some(items) = self.items.as_ref() {
for each in items.iter() {
if let Some(uid_val) = &each.uid
&& uid_val.as_str() == uid_str
if item
.home
.as_deref()
.is_some_and(|home| normalize_profile_home_url(home).is_none())
{
return Ok(each);
item.home = None;
home_changed = true;
}
}
}
bail!("failed to get the profile item \"uid:{}\"", uid_str);
}
async fn append_item(&mut self, item: &mut PrfItem) -> Result<()> {
let uid = &item.uid;
if uid.is_none() {
bail!("the uid should not be null");
}
if let Some(file_data) = item.file_data.take() {
if item.file.is_none() {
bail!("the file should not be null");
if home_changed && let Err(err) = save_profiles(&profiles).await {
logging!(error, Type::Config, "无法保存已清理的 profiles.yaml: {err:#}");
}
let file = item
.file
.clone()
.ok_or_else(|| anyhow::anyhow!("file field is required when file_data is provided"))?;
let path = dirs::app_profiles_dir()?.join(file.as_str());
fs::write(&path, file_data.as_bytes())
.await
.with_context(|| format!("failed to write to file \"{file}\""))?;
profiles
}
if self.current.is_none() && (item.itype == Some("remote".into()) || item.itype == Some("local".into())) {
self.current = uid.to_owned();
Err(err) => {
logging!(error, Type::Config, "failed to read profiles.yaml: {err:#}");
IProfiles::default()
}
}
}
if self.items.is_none() {
self.items = Some(vec![]);
}
pub(crate) async fn save_profiles(profiles: &IProfiles) -> Result<()> {
help::save_yaml(
&dirs::profiles_path()?,
profiles,
Some("# Profiles Config for Clash Verge"),
)
.await
}
if let Some(items) = self.items.as_mut() {
items.push(item.to_owned());
}
Ok(())
async fn append_item(profiles: &mut IProfiles, item: &mut PrfItem) -> Result<()> {
if item.uid.is_none() {
bail!("the uid should not be null");
}
async fn reorder(&mut self, active_id: &str, over_id: &str) -> Result<()> {
{
let Some(items) = self.items.as_mut() else {
return Ok(());
};
let old_index = items.iter().rposition(|item| item.uid.as_deref() == Some(active_id));
let new_index = items.iter().rposition(|item| item.uid.as_deref() == Some(over_id));
let (Some(old_idx), Some(new_idx)) = (old_index, new_index) else {
return Ok(());
};
let item = items.remove(old_idx);
items.insert(new_idx, item);
if let Some(file_data) = item.file_data.take() {
if item.file.is_none() {
bail!("the file should not be null");
}
self.save_file().await
let file = item
.file
.clone()
.ok_or_else(|| anyhow::anyhow!("file field is required when file_data is provided"))?;
let path = dirs::app_profiles_dir()?.join(file.as_str());
fs::write(&path, file_data.as_bytes())
.await
.with_context(|| format!("failed to write to file \"{file}\""))?;
}
async fn patch_item(&mut self, uid: &str, item: &PrfItem) -> Result<()> {
if let Some(file) = &item.file {
Self::validate_profile_file(file)?;
profiles.append_item(item);
Ok(())
}
async fn patch_item(profiles: &mut IProfiles, uid: &str, item: &PrfItem) -> Result<()> {
if let Some(file) = &item.file {
validate_profile_file(file)?;
}
let mut items = profiles.items.take().unwrap_or_default();
for each in items.iter_mut() {
if each.uid.as_deref() == Some(uid) {
patch_opt_field!(each, item, itype);
patch_opt_field!(each, item, name);
patch_opt_field!(each, item, desc);
patch_opt_field!(each, item, file);
patch_opt_field!(each, item, url);
patch_opt_field!(each, item, selected);
patch_opt_field!(each, item, extra);
patch_opt_field!(each, item, updated);
patch_opt_field!(each, item, option);
profiles.items = Some(items);
return save_profiles(profiles).await;
}
}
let mut items = self.items.take().unwrap_or_default();
profiles.items = Some(items);
bail!("failed to find the profile item \"uid:{uid}\"")
}
fn validate_profile_file(file: &str) -> Result<()> {
let mut components = Path::new(file).components();
if file.is_empty()
|| file.contains('/')
|| file.contains('\\')
|| !matches!(
(components.next(), components.next()),
(Some(Component::Normal(_)), None)
)
{
bail!("profile file must be a single filename");
}
Ok(())
}
/// Updates fields returned by a remote profile refresh.
async fn update_item(profiles: &mut IProfiles, uid: &str, item: &mut PrfItem) -> Result<()> {
if profiles.items.is_none() {
profiles.items = Some(vec![]);
}
let _ = profiles.get_item(uid)?;
if let Some(items) = profiles.items.as_mut() {
for each in items.iter_mut() {
if each.uid.as_deref() == Some(uid) {
patch_opt_field!(each, item, itype);
patch_opt_field!(each, item, name);
patch_opt_field!(each, item, desc);
patch_opt_field!(each, item, file);
patch_opt_field!(each, item, url);
patch_opt_field!(each, item, selected);
patch_opt_field!(each, item, extra);
patch_opt_field!(each, item, updated);
patch_opt_field!(each, item, option);
each.extra = item.extra;
each.updated = item.updated;
each.home = item.home.to_owned();
each.option = PrfOption::merge(each.option.as_ref(), item.option.as_ref());
if let Some(file_data) = item.file_data.take() {
let file = each.file.take();
let file =
file.unwrap_or_else(|| item.file.take().unwrap_or_else(|| format!("{}.yaml", uid).into()));
self.items = Some(items);
return self.save_file().await;
each.file = Some(file.clone());
let path = dirs::app_profiles_dir()?.join(file.as_str());
fs::write(&path, file_data.as_bytes())
.await
.with_context(|| format!("failed to write to file \"{file}\""))?;
}
break;
}
}
self.items = Some(items);
bail!("failed to find the profile item \"uid:{uid}\"")
}
fn validate_profile_file(file: &str) -> Result<()> {
let mut components = Path::new(file).components();
if file.is_empty()
|| file.contains('/')
|| file.contains('\\')
|| !matches!(
(components.next(), components.next()),
(Some(Component::Normal(_)), None)
)
save_profiles(profiles).await
}
/// Raise intervals below `min_minutes`. `None`/`0` mean "never auto-update", left alone.
/// Returns how many changed so the caller can skip a pointless write.
pub(crate) fn raise_short_update_intervals(profiles: &mut IProfiles, min_minutes: u64) -> usize {
let mut raised = 0;
for item in profiles.items.iter_mut().flatten() {
let Some(option) = item.option.as_mut() else {
continue;
};
if option
.update_interval
.is_some_and(|interval| (1..min_minutes).contains(&interval))
{
bail!("profile file must be a single filename");
}
Ok(())
}
/// Updates fields returned by a remote profile refresh.
async fn update_item(&mut self, uid: &str, item: &mut PrfItem) -> Result<()> {
if self.items.is_none() {
self.items = Some(vec![]);
}
let _ = self.get_item(uid)?;
if let Some(items) = self.items.as_mut() {
for each in items.iter_mut() {
if each.uid.as_deref() == Some(uid) {
each.extra = item.extra;
each.updated = item.updated;
each.home = item.home.to_owned();
each.option = PrfOption::merge(each.option.as_ref(), item.option.as_ref());
if let Some(file_data) = item.file_data.take() {
let file = each.file.take();
let file =
file.unwrap_or_else(|| item.file.take().unwrap_or_else(|| format!("{}.yaml", uid).into()));
each.file = Some(file.clone());
let path = dirs::app_profiles_dir()?.join(file.as_str());
fs::write(&path, file_data.as_bytes())
.await
.with_context(|| format!("failed to write to file \"{file}\""))?;
}
break;
}
}
}
self.save_file().await
}
/// Raise intervals below `min_minutes`. `None`/`0` mean "never auto-update", left alone.
/// Returns how many changed so the caller can skip a pointless write.
pub fn raise_short_update_intervals(&mut self, min_minutes: u64) -> usize {
let mut raised = 0;
for item in self.items.iter_mut().flatten() {
let Some(option) = item.option.as_mut() else {
continue;
};
if option
.update_interval
.is_some_and(|interval| (1..min_minutes).contains(&interval))
{
option.update_interval = Some(min_minutes);
raised += 1;
}
}
raised
}
pub(crate) fn plan_delete_item(&mut self, uid: &str) -> Result<(bool, ProfileDeletePlan)> {
let deleting_current = self.current.as_deref().is_none_or(|current| current == uid);
let delete_uids = self.get_item(uid)?.option.as_ref().map_or_else(Vec::new, |op| {
[
op.merge.clone(),
op.script.clone(),
op.rules.clone(),
op.proxies.clone(),
op.groups.clone(),
]
.into_iter()
.collect::<Vec<_>>()
});
let mut items = self.items.take().unwrap_or_default();
let mut files = Vec::new();
if let Some(file) = Self::take_item_file_by_uid(&mut items, Some(uid)) {
files.push(file);
}
for delete_uid in delete_uids {
if let Some(file) = Self::take_item_file_by_uid(&mut items, delete_uid.as_deref()) {
files.push(file);
}
}
if deleting_current {
self.current = None;
for item in items.iter() {
if item.itype == Some("remote".into()) || item.itype == Some("local".into()) {
self.current = item.uid.clone();
break;
}
}
}
self.items = Some(items);
Ok((deleting_current, ProfileDeletePlan { files }))
}
/// 获取current指向的订阅内容
pub async fn current_mapping(&self) -> Result<Mapping> {
match (self.current.as_ref(), self.items.as_ref()) {
(Some(current), Some(items)) => {
if let Some(item) = items.iter().find(|e| e.uid.as_ref() == Some(current)) {
let file_path = match item.file.as_ref() {
Some(file) => dirs::app_profiles_dir()?.join(file.as_str()),
None => bail!("failed to get the file field"),
};
return help::read_mapping(&file_path).await;
}
bail!("failed to find the current profile \"uid:{current}\"");
}
_ => Ok(Mapping::new()),
option.update_interval = Some(min_minutes);
raised += 1;
}
}
pub fn profiles_preview(&self) -> Option<Vec<IProfilePreview<'_>>> {
self.items.as_ref().map(|items| {
items
.iter()
.filter_map(|e| {
if let (Some(uid), Some(name)) = (e.uid.as_ref(), e.name.as_ref()) {
let is_current = self.current.as_ref() == Some(uid);
let preview = IProfilePreview { uid, name, is_current };
Some(preview)
} else {
None
}
})
.collect()
})
raised
}
pub(crate) async fn current_mapping(profiles: &IProfiles) -> Result<Mapping> {
match (profiles.current.as_ref(), profiles.items.as_ref()) {
(Some(current), Some(items)) => {
if let Some(item) = items.iter().find(|e| e.uid.as_ref() == Some(current)) {
let file_path = match item.file.as_ref() {
Some(file) => dirs::app_profiles_dir()?.join(file.as_str()),
None => bail!("failed to get the file field"),
};
return help::read_mapping(&file_path).await;
}
bail!("failed to find the current profile \"uid:{current}\"");
}
_ => Ok(Mapping::new()),
}
}
@@ -409,7 +265,7 @@ impl IProfiles {
use crate::config::Config;
pub(crate) async fn profiles_append_item_with_filedata_safe(item: &PrfItem, file_data: Option<String>) -> Result<()> {
let item = &mut PrfItem::from(item, file_data).await?;
let item = &mut build_profile(item, file_data).await?;
profiles_append_item_safe(item).await
}
@@ -436,26 +292,40 @@ pub(crate) async fn profiles_append_item_safe(item: &mut PrfItem) -> Result<()>
pub(super) async fn profiles_append_item_to_safe(profiles: &Draft<IProfiles>, item: &mut PrfItem) -> Result<()> {
profiles
.with_data_modify(|mut profiles| async move {
profiles.append_item(item).await?;
append_item(&mut profiles, item).await?;
Ok((profiles, ()))
})
.await
}
pub(crate) async fn profiles_patch_item_safe(index: &str, item: &PrfItem) -> Result<()> {
with_profiles_edit(|mut profiles| async move { profiles.patch_item(index, item).await.map(|_| profiles) }).await
with_profiles_edit(|mut profiles| async move {
patch_item(&mut profiles, index, item).await?;
Ok(profiles)
})
.await
}
pub(crate) async fn profiles_reorder_safe(active_id: &str, over_id: &str) -> Result<()> {
with_profiles_edit(|mut profiles| async move { profiles.reorder(active_id, over_id).await.map(|_| profiles) }).await
with_profiles_edit(|mut profiles| async move {
if profiles.reorder(active_id, over_id) {
save_profiles(&profiles).await?;
}
Ok(profiles)
})
.await
}
pub(crate) async fn profiles_save_file_safe() -> Result<()> {
with_profiles_edit(|profiles| async move { profiles.save_file().await.map(|_| profiles) }).await
with_profiles_edit(|profiles| async move { save_profiles(&profiles).await.map(|_| profiles) }).await
}
pub(crate) async fn profiles_update_item_safe(index: &str, item: &mut PrfItem) -> Result<()> {
with_profiles_edit(|mut profiles| async move { profiles.update_item(index, item).await.map(|_| profiles) }).await
with_profiles_edit(|mut profiles| async move {
update_item(&mut profiles, index, item).await?;
Ok(profiles)
})
.await
}
#[derive(Debug, PartialEq, Eq)]
@@ -784,7 +654,7 @@ pub(crate) async fn record_selected_node(group_name: &str, node: &str) -> Result
now: Some(node.into()),
}),
}
profiles.save_file().await?;
save_profiles(&profiles).await?;
Ok((profiles, true))
})
.await
@@ -813,7 +683,7 @@ pub(crate) async fn forget_selected_node(group_name: &str) -> Result<()> {
if !selected.is_empty() {
item.selected = Some(selected);
}
profiles.save_file().await?;
save_profiles(&profiles).await?;
Ok((profiles, true))
})
.await
@@ -844,7 +714,7 @@ async fn persist_reconciled_selected(
}
profile.selected = (!selected.is_empty()).then_some(selected);
profiles.save_file().await?;
save_profiles(&profiles).await?;
Ok((profiles, true))
})
.await
@@ -1128,19 +998,6 @@ mod tests {
use super::*;
use tauri_plugin_mihomo::models::Proxy;
fn deletion_item(uid: &str, kind: &str, file: &str, merge: Option<&str>) -> PrfItem {
PrfItem {
uid: Some(uid.into()),
itype: Some(kind.into()),
file: Some(file.into()),
option: merge.map(|uid| PrfOption {
merge: Some(uid.into()),
..PrfOption::default()
}),
..PrfItem::default()
}
}
fn interval_item(uid: &str, update_interval: Option<u64>) -> PrfItem {
PrfItem {
uid: Some(uid.into()),
@@ -1153,43 +1010,6 @@ mod tests {
}
}
#[tokio::test]
async fn missing_reorder_ids_preserve_ordered_items() -> Result<()> {
let mut profiles = IProfiles {
current: Some("a".into()),
items: Some(vec![
PrfItem {
uid: Some("a".into()),
..PrfItem::default()
},
PrfItem {
uid: Some("b".into()),
..PrfItem::default()
},
PrfItem {
uid: Some("c".into()),
..PrfItem::default()
},
]),
};
let expected = Some(vec![Some("a"), Some("b"), Some("c")]);
profiles.reorder("missing", "b").await?;
let ordered_uids = profiles
.items
.as_ref()
.map(|items| items.iter().map(|item| item.uid.as_deref()).collect::<Vec<_>>());
assert_eq!(ordered_uids, expected);
profiles.reorder("a", "missing").await?;
let ordered_uids = profiles
.items
.as_ref()
.map(|items| items.iter().map(|item| item.uid.as_deref()).collect::<Vec<_>>());
assert_eq!(ordered_uids, expected);
Ok(())
}
#[test]
fn raising_intervals_only_touches_those_scheduled_too_often() {
let mut profiles = IProfiles {
@@ -1210,7 +1030,7 @@ mod tests {
]),
};
assert_eq!(profiles.raise_short_update_intervals(1440), 2);
assert_eq!(raise_short_update_intervals(&mut profiles, 1440), 2);
let intervals: Vec<Option<u64>> = profiles
.items
@@ -1224,32 +1044,12 @@ mod tests {
);
assert_eq!(
profiles.raise_short_update_intervals(1440),
raise_short_update_intervals(&mut profiles, 1440),
0,
"a second pass must be a no-op, so re-running the migration cannot churn the file"
);
}
#[test]
fn delete_plan_defers_files_and_selects_replacement() -> Result<()> {
let mut profiles = IProfiles {
current: Some("a".into()),
items: Some(vec![
deletion_item("a", "remote", "a.yaml", Some("owned")),
deletion_item("owned", "merge", "owned.yaml", None),
deletion_item("b", "local", "b.yaml", None),
]),
};
let (should_update, plan) = profiles.plan_delete_item("a")?;
assert!(should_update);
assert_eq!(profiles.current.as_deref(), Some("b"));
assert_eq!(plan.files, vec![String::from("a.yaml"), String::from("owned.yaml")]);
assert!(profiles.get_item("owned").is_err());
Ok(())
}
fn selected(group: &str, node: &str) -> PrfSelected {
PrfSelected {
name: Some(group.into()),
+2 -2
View File
@@ -2,7 +2,7 @@ use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode};
use crate::core::notify::NoticeStatus;
use crate::core::service::StageRequest;
use crate::{
config::{Config, IProfiles, runtime::IRuntime},
config::{Config, IProfiles, profiles::save_profiles, runtime::IRuntime},
constants::timing,
core::{
handle,
@@ -243,7 +243,7 @@ impl CoreManager {
crate::config::profiles::restore_selected_nodes().await;
return Ok(Err(outcome));
}
match candidate.save_file().await {
match save_profiles(candidate).await {
Ok(()) => {
tracing::Span::current().record("outcome", "committed");
Ok(Ok(guard))
+2 -3
View File
@@ -6,7 +6,7 @@ use crate::core::handle::Handle;
use crate::core::notify::NoticeStatus;
use crate::utils::dirs;
use crate::{
config::{Config, IProfiles, IVerge, PrfItem},
config::{Config, IProfiles, IVerge, PrfItem, profiles::current_mapping},
constants,
utils::tmpl,
};
@@ -139,8 +139,7 @@ async fn collect_profile_items(profiles: &IProfiles) -> Result<RenderProfile> {
None => return Ok(default_profile()),
};
let current = profiles
.current_mapping()
let current = current_mapping(profiles)
.await
.with_context(|| format!("failed to read current profile \"{current_profile_uid}\""))?;
+2 -2
View File
@@ -1,5 +1,5 @@
use crate::{
config::{Config, IClashTemp, IProfiles, IVerge},
config::{Config, IClashTemp, IVerge, profiles::load_profiles},
core::{CoreManager, auto_backup, backup, proxy_control, proxy_control::SystemProxyStateUnknown},
process::AsyncHandler,
utils::{
@@ -46,7 +46,7 @@ async fn finalize_restored_verge_config(
});
clash_draft.apply();
let restored_profiles = IProfiles::new().await;
let restored_profiles = load_profiles().await;
let profiles_draft = Config::profiles().await;
profiles_draft.edit_draft(|d| {
*d = restored_profiles;
+2 -2
View File
@@ -8,7 +8,7 @@ use crate::{
config::{
Config,
dns::{ProfileDnsSettings, dns_override_source},
profiles::PROFILE_WRITE_LOCK,
profiles::{PROFILE_WRITE_LOCK, current_mapping},
},
constants::files::DNS_CONFIG,
core::CoreManager,
@@ -36,7 +36,7 @@ pub async fn set_dns_override(
);
let source = dns_override_source(
profiles.current.as_deref().unwrap_or_default(),
&profiles.current_mapping().await?,
&current_mapping(&profiles).await?,
)?;
if enabled && let Some(source) = source.as_ref().filter(|source| Some(*source) != confirmation.as_ref()) {
return Ok(DnsOverrideOutcome::ConfirmationRequired { source: source.clone() });
+2 -2
View File
@@ -2,7 +2,7 @@ use crate::core::notify::NoticeStatus;
use crate::core::notify::{Refresh, announce};
use crate::{
cmd,
config::{Config, PrfItem, PrfOption, profiles::profiles_update_item_safe},
config::{Config, PrfOption, fetch_remote_profile, profiles::profiles_update_item_safe},
core::{CoreManager, handle, tray, validate::ValidationOutcome},
process::AsyncHandler,
utils::help::{mask_err, mask_url},
@@ -289,7 +289,7 @@ async fn perform_profile_update(
}
tracing::Span::current().record("strategy", name);
let started = std::time::Instant::now();
let result = PrfItem::from_url(url, None, None, options.as_ref()).await;
let result = fetch_remote_profile(url, None, None, options.as_ref()).await;
let elapsed_field = match strategy {
Strategy::Configured => "configured_elapsed",
Strategy::Clash => "clash_elapsed",
+6 -3
View File
@@ -1,5 +1,8 @@
use crate::{
config::{Config, IClashTemp, IProfiles, IVerge},
config::{
Config, IClashTemp, IProfiles, IVerge,
profiles::{raise_short_update_intervals, save_profiles},
},
constants,
core::handle,
logging,
@@ -266,9 +269,9 @@ pub async fn migrate_short_update_intervals() -> Result<()> {
if profiles.items.is_none() {
anyhow::bail!("profiles.yaml was not loaded; refusing to record the migration as done");
}
let raised = profiles.raise_short_update_intervals(min);
let raised = raise_short_update_intervals(&mut profiles, min);
if raised > 0 {
profiles.save_file().await?;
save_profiles(&profiles).await?;
}
Ok((profiles, raised))
})
+2 -2
View File
@@ -5,7 +5,7 @@ use tauri::Url;
use tristr::alias::String;
use crate::{
config::{Config, PrfItem, profiles},
config::{Config, PrfItem, fetch_remote_profile, profiles},
core::{CoreManager, handle, timer::Timer},
utils::help,
};
@@ -113,7 +113,7 @@ async fn import_subscription(url: &str, name: Option<&String>) {
}
async fn fetch_profile_item(url: &str, name: Option<&String>) -> Option<PrfItem> {
match PrfItem::from_url(url, name, None, None).await {
match fetch_remote_profile(url, name, None, None).await {
Ok(item) => Some(item),
Err(e) => {
logging!(error, Type::Config, "failed to parse profile from url: {:?}", e);