mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-01 10:40:14 +08:00
Separate download and scheduling policy from the subscription use case while retaining the existing write path.
454 lines
15 KiB
Rust
454 lines
15 KiB
Rust
use super::{PrfExtra, PrfItem, PrfOption};
|
|
|
|
use crate::{
|
|
config::profiles,
|
|
utils::{
|
|
dirs, help,
|
|
network::{NetworkManager, ProxyType},
|
|
tmpl,
|
|
},
|
|
};
|
|
use anyhow::{Context as _, Result, bail};
|
|
use clash_verge_subscription::decode_subscription;
|
|
use std::time::Duration;
|
|
use tokio::fs;
|
|
use tristr::alias::String;
|
|
// TODO, use other re-export
|
|
use reqwest_dav::re_exports::url::form_urlencoded;
|
|
use tauri::Url;
|
|
|
|
/// 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();
|
|
build_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}\""),
|
|
}
|
|
}
|
|
|
|
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"))
|
|
}
|
|
|
|
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())),
|
|
})
|
|
}
|
|
|
|
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 user_agent = option.and_then(|o| o.user_agent.clone());
|
|
let timeout = option.and_then(|o| o.timeout_seconds).unwrap_or(20);
|
|
|
|
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,
|
|
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 extra = document.usage.map(|usage| PrfExtra {
|
|
upload: usage.upload,
|
|
download: usage.download,
|
|
total: usage.total,
|
|
expire: usage.expire,
|
|
});
|
|
Ok(DownloadedSubscription {
|
|
suggested_name: document.filename,
|
|
update_interval_minutes: document.update_interval_minutes,
|
|
home: document.home.map(Into::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,
|
|
})
|
|
}
|
|
|
|
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 {
|
|
option.and_then(|o| o.allow_auto_update).unwrap_or(true)
|
|
}
|
|
|
|
/// Fix URLs where query parameters are incorrectly appended to the path segment
|
|
///
|
|
/// Incorrect Example: https://example.com/path¶m1=value1
|
|
fn fix_dirty_url(input: &str) -> Result<Url> {
|
|
let mut url = match Url::parse(input) {
|
|
Ok(u) => u,
|
|
Err(e) => {
|
|
return Err(anyhow::anyhow!(
|
|
"failed to parse subscription URL: {:?}, input: {}",
|
|
e,
|
|
help::mask_url(input)
|
|
));
|
|
}
|
|
};
|
|
|
|
if url.query().is_none() && url.path().contains('&') {
|
|
let path = url.path().to_string();
|
|
|
|
if let Some((clean_path, dirty_params)) = path.split_once('&') {
|
|
url.set_path(clean_path);
|
|
|
|
url.query_pairs_mut()
|
|
.extend_pairs(form_urlencoded::parse(dirty_params.as_bytes()));
|
|
}
|
|
}
|
|
|
|
Ok(url)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use tokio::{
|
|
io::{AsyncBufReadExt as _, AsyncWriteExt as _, BufReader},
|
|
net::TcpListener,
|
|
};
|
|
|
|
#[tokio::test]
|
|
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 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()
|
|
);
|
|
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),
|
|
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 = 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"));
|
|
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));
|
|
|
|
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(())
|
|
}
|
|
}
|