mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-03 12:20:05 +08:00
refactor(profile): separate subscription refresh and scheduling policy
Separate download and scheduling policy from the subscription use case while retaining the existing write path.
This commit is contained in:
@@ -12,7 +12,7 @@ pub(crate) mod snapshot;
|
||||
mod verge;
|
||||
|
||||
pub(crate) use self::config::Config;
|
||||
pub(crate) use self::prfitem::{fetch_remote_profile, read_profile_item_file};
|
||||
pub(crate) use self::prfitem::{build_remote_profile, fetch_remote_refresh, read_profile_item_file};
|
||||
pub use self::{clash::*, encrypt::*, mixed_port::*, profiles::*, verge::*};
|
||||
pub use clash_verge_profile::{PrfExtra, PrfItem, PrfOption, PrfSelected};
|
||||
|
||||
|
||||
+132
-52
@@ -32,7 +32,7 @@ pub(super) async fn build_profile(item: &PrfItem, file_data: Option<String>) ->
|
||||
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
|
||||
build_remote_profile(url, name, desc, option).await
|
||||
}
|
||||
"local" => {
|
||||
let name = item.name.clone().unwrap_or_else(|| "Local File".into());
|
||||
@@ -117,24 +117,72 @@ async fn from_local(
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn fetch_remote_profile(
|
||||
struct DownloadedSubscription {
|
||||
url: Url,
|
||||
suggested_name: Option<std::string::String>,
|
||||
extra: Option<PrfExtra>,
|
||||
update_interval_minutes: Option<u64>,
|
||||
home: Option<String>,
|
||||
body: String,
|
||||
}
|
||||
|
||||
pub(crate) struct RemoteProfileRefresh {
|
||||
pub(super) extra: Option<PrfExtra>,
|
||||
pub(super) home: Option<String>,
|
||||
pub(super) updated: usize,
|
||||
pub(super) option: PrfOption,
|
||||
pub(super) body: String,
|
||||
}
|
||||
|
||||
pub(crate) async fn build_remote_profile(
|
||||
url: &str,
|
||||
name: Option<&String>,
|
||||
desc: Option<&String>,
|
||||
option: Option<&PrfOption>,
|
||||
) -> Result<PrfItem> {
|
||||
let mut downloaded = download_subscription(url, option).await?;
|
||||
let uid: String = help::get_uid("R").into();
|
||||
let file = format!("{uid}.yaml").into();
|
||||
let name = name
|
||||
.cloned()
|
||||
.or_else(|| downloaded.suggested_name.take().map(Into::into))
|
||||
.unwrap_or_else(|| "Remote File".into());
|
||||
let url = downloaded.url.as_str().into();
|
||||
let RemoteProfileRefresh {
|
||||
extra,
|
||||
home,
|
||||
updated,
|
||||
option,
|
||||
body,
|
||||
} = prepare_remote_refresh(downloaded, option).await?;
|
||||
|
||||
Ok(PrfItem {
|
||||
uid: Some(uid),
|
||||
itype: Some("remote".into()),
|
||||
name: Some(name),
|
||||
desc: desc.cloned(),
|
||||
file: Some(file),
|
||||
url: Some(url),
|
||||
selected: None,
|
||||
extra,
|
||||
option: Some(option),
|
||||
home,
|
||||
updated: Some(updated),
|
||||
file_data: Some(body),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn fetch_remote_refresh(url: &str, option: Option<&PrfOption>) -> Result<RemoteProfileRefresh> {
|
||||
let downloaded = download_subscription(url, option).await?;
|
||||
prepare_remote_refresh(downloaded, option).await
|
||||
}
|
||||
|
||||
async fn download_subscription(url: &str, option: Option<&PrfOption>) -> Result<DownloadedSubscription> {
|
||||
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
|
||||
@@ -151,7 +199,7 @@ pub(crate) async fn fetch_remote_profile(
|
||||
url.as_str(),
|
||||
proxy_type,
|
||||
Some(timeout),
|
||||
user_agent.clone(),
|
||||
user_agent,
|
||||
accept_invalid_certs,
|
||||
)
|
||||
.await
|
||||
@@ -169,43 +217,52 @@ pub(crate) async fn fetch_remote_profile(
|
||||
}
|
||||
|
||||
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()
|
||||
}),
|
||||
Ok(DownloadedSubscription {
|
||||
suggested_name: document.filename,
|
||||
update_interval_minutes: document.update_interval_minutes,
|
||||
home: document.home.map(Into::into),
|
||||
updated: Some(chrono::Local::now().timestamp() as usize),
|
||||
file_data: Some(document.body.into()),
|
||||
body: document.body.into(),
|
||||
url,
|
||||
extra,
|
||||
})
|
||||
}
|
||||
|
||||
async fn prepare_remote_refresh(
|
||||
downloaded: DownloadedSubscription,
|
||||
option: Option<&PrfOption>,
|
||||
) -> Result<RemoteProfileRefresh> {
|
||||
let mut resolved = PrfOption {
|
||||
update_interval: option
|
||||
.and_then(|o| o.update_interval)
|
||||
.or(downloaded.update_interval_minutes),
|
||||
merge: option.and_then(|o| o.merge.clone()),
|
||||
script: option.and_then(|o| o.script.clone()),
|
||||
rules: option.and_then(|o| o.rules.clone()),
|
||||
proxies: option.and_then(|o| o.proxies.clone()),
|
||||
groups: option.and_then(|o| o.groups.clone()),
|
||||
allow_auto_update: Some(allow_auto_update_enabled(option)),
|
||||
..PrfOption::default()
|
||||
};
|
||||
ensure_companion_items(
|
||||
&mut resolved.merge,
|
||||
&mut resolved.script,
|
||||
&mut resolved.rules,
|
||||
&mut resolved.proxies,
|
||||
&mut resolved.groups,
|
||||
)
|
||||
.await?;
|
||||
Ok(RemoteProfileRefresh {
|
||||
extra: downloaded.extra,
|
||||
home: downloaded.home,
|
||||
updated: chrono::Local::now().timestamp() as usize,
|
||||
option: resolved,
|
||||
body: downloaded.body,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -321,20 +378,11 @@ mod tests {
|
||||
};
|
||||
|
||||
#[tokio::test]
|
||||
async fn fetch_remote_profile_maps_response_to_profile_model() -> Result<()> {
|
||||
async fn import_and_refresh_share_subscription_decoding() -> 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\
|
||||
@@ -343,7 +391,19 @@ mod tests {
|
||||
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
|
||||
for _ in 0..2 {
|
||||
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;
|
||||
}
|
||||
}
|
||||
socket.get_mut().write_all(response.as_bytes()).await?;
|
||||
}
|
||||
Ok::<_, std::io::Error>(())
|
||||
});
|
||||
let option = PrfOption {
|
||||
update_interval: Some(0),
|
||||
@@ -356,7 +416,15 @@ mod tests {
|
||||
groups: Some("test-groups".into()),
|
||||
..Default::default()
|
||||
};
|
||||
let item: clash_verge_profile::PrfItem = fetch_remote_profile(&url, None, None, Some(&option)).await?;
|
||||
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?;
|
||||
server.await??;
|
||||
assert_eq!(item.itype.as_deref(), Some("remote"));
|
||||
assert_eq!(item.name.as_deref(), Some("remote.yaml"));
|
||||
@@ -368,6 +436,18 @@ mod tests {
|
||||
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));
|
||||
|
||||
assert_eq!(refresh.body.as_str(), BODY);
|
||||
assert_eq!(refresh.home, item.home);
|
||||
let usage = refresh.extra.context("expected refresh usage")?;
|
||||
assert_eq!((usage.upload, usage.download, usage.total, usage.expire), (1, 2, 3, 4));
|
||||
assert_eq!(
|
||||
refresh.option,
|
||||
PrfOption {
|
||||
update_interval: Some(120),
|
||||
..fetched_option
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
use super::{PrfItem, PrfOption, PrfSelected, patch_opt_field, prfitem::build_profile};
|
||||
use super::{
|
||||
PrfItem, PrfOption, PrfSelected, patch_opt_field,
|
||||
prfitem::{RemoteProfileRefresh, build_profile},
|
||||
};
|
||||
use crate::core::notify::{Refresh, announce};
|
||||
use crate::utils::retry::{RetryError, RetryPolicy, retry, retry_with_state};
|
||||
use crate::{
|
||||
@@ -188,37 +191,26 @@ fn validate_profile_file(file: &str) -> Result<()> {
|
||||
}
|
||||
|
||||
/// 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![]);
|
||||
}
|
||||
|
||||
async fn apply_remote_refresh(profiles: &mut IProfiles, uid: &str, refresh: RemoteProfileRefresh) -> Result<()> {
|
||||
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) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
if let Some(each) = profiles
|
||||
.items
|
||||
.iter_mut()
|
||||
.flatten()
|
||||
.find(|item| item.uid.as_deref() == Some(uid))
|
||||
{
|
||||
each.extra = refresh.extra;
|
||||
each.updated = Some(refresh.updated);
|
||||
each.home = refresh.home;
|
||||
each.option = PrfOption::merge(each.option.as_ref(), Some(&refresh.option));
|
||||
let file = each
|
||||
.file
|
||||
.get_or_insert_with(|| format!("{}.yaml", help::get_uid("R")).into());
|
||||
let path = dirs::app_profiles_dir()?.join(file.as_str());
|
||||
fs::write(&path, refresh.body.as_bytes())
|
||||
.await
|
||||
.with_context(|| format!("failed to write to file \"{file}\""))?;
|
||||
}
|
||||
|
||||
save_profiles(profiles).await
|
||||
@@ -320,9 +312,9 @@ pub(crate) async fn profiles_save_file_safe() -> Result<()> {
|
||||
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<()> {
|
||||
pub(crate) async fn apply_remote_refresh_safe(index: &str, refresh: RemoteProfileRefresh) -> Result<()> {
|
||||
with_profiles_edit(|mut profiles| async move {
|
||||
update_item(&mut profiles, index, item).await?;
|
||||
apply_remote_refresh(&mut profiles, index, refresh).await?;
|
||||
Ok(profiles)
|
||||
})
|
||||
.await
|
||||
|
||||
Reference in New Issue
Block a user