mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-05 05:40:05 +08:00
fix(profile): commit missing companions with the refreshed subscription
This commit is contained in:
@@ -44,15 +44,26 @@ pub(super) async fn build_profile(item: &PrfItem, file_data: Option<String>) ->
|
||||
}
|
||||
}
|
||||
|
||||
async fn append_companion_item(item: &mut PrfItem) -> Result<String> {
|
||||
profiles::append_profile(item).await?;
|
||||
item.uid
|
||||
.clone()
|
||||
.ok_or_else(|| anyhow::anyhow!("appended companion item has no uid"))
|
||||
fn missing_companions(options: &mut PrfOption) -> Vec<PrfItem> {
|
||||
let mut companions = Vec::new();
|
||||
for (reference, build) in [
|
||||
(&mut options.merge, (|| build_merge_profile(None)) as fn() -> PrfItem),
|
||||
(&mut options.script, || build_script_profile(None)),
|
||||
(&mut options.rules, from_rules),
|
||||
(&mut options.proxies, from_proxies),
|
||||
(&mut options.groups, from_groups),
|
||||
] {
|
||||
if reference.is_none() {
|
||||
let item = build();
|
||||
*reference = item.uid.clone();
|
||||
companions.push(item);
|
||||
}
|
||||
}
|
||||
companions
|
||||
}
|
||||
|
||||
async fn prepare_profile_options(source: Option<&PrfOption>) -> Result<PrfOption> {
|
||||
let mut options = PrfOption {
|
||||
fn creation_options(source: Option<&PrfOption>) -> PrfOption {
|
||||
PrfOption {
|
||||
update_interval: source.and_then(|options| options.update_interval),
|
||||
merge: source.and_then(|options| options.merge.clone()),
|
||||
script: source.and_then(|options| options.script.clone()),
|
||||
@@ -60,23 +71,14 @@ async fn prepare_profile_options(source: Option<&PrfOption>) -> Result<PrfOption
|
||||
proxies: source.and_then(|options| options.proxies.clone()),
|
||||
groups: source.and_then(|options| options.groups.clone()),
|
||||
..PrfOption::default()
|
||||
};
|
||||
if options.merge.is_none() {
|
||||
options.merge = Some(append_companion_item(&mut build_merge_profile(None)).await?);
|
||||
}
|
||||
if options.script.is_none() {
|
||||
options.script = Some(append_companion_item(&mut build_script_profile(None)).await?);
|
||||
}
|
||||
|
||||
async fn append_companions(companions: Vec<PrfItem>) -> Result<()> {
|
||||
for mut item in companions {
|
||||
profiles::append_profile(&mut item).await?;
|
||||
}
|
||||
if options.rules.is_none() {
|
||||
options.rules = Some(append_companion_item(&mut from_rules()).await?);
|
||||
}
|
||||
if options.proxies.is_none() {
|
||||
options.proxies = Some(append_companion_item(&mut from_proxies()).await?);
|
||||
}
|
||||
if options.groups.is_none() {
|
||||
options.groups = Some(append_companion_item(&mut from_groups()).await?);
|
||||
}
|
||||
Ok(options)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn from_local(
|
||||
@@ -87,7 +89,8 @@ async fn from_local(
|
||||
) -> Result<PrfItem> {
|
||||
let uid = help::get_uid("L").into();
|
||||
let file = format!("{uid}.yaml").into();
|
||||
let options = prepare_profile_options(option).await?;
|
||||
let mut options = creation_options(option);
|
||||
append_companions(missing_companions(&mut options)).await?;
|
||||
Ok(PrfItem {
|
||||
uid: Some(uid),
|
||||
itype: Some("local".into()),
|
||||
@@ -113,12 +116,16 @@ pub(crate) struct DownloadedSubscription {
|
||||
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,
|
||||
impl DownloadedSubscription {
|
||||
pub(super) fn apply(self, item: &mut PrfItem) -> (String, Vec<PrfItem>) {
|
||||
let option = item.option.get_or_insert_with(PrfOption::default);
|
||||
option.update_interval = option.update_interval.or(self.update_interval_minutes);
|
||||
option.allow_auto_update.get_or_insert(true);
|
||||
item.home = self.home;
|
||||
item.extra = self.extra;
|
||||
item.updated = Some(chrono::Local::now().timestamp() as usize);
|
||||
(self.body, missing_companions(option))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn build_remote_profile(
|
||||
@@ -135,28 +142,22 @@ pub(crate) async fn build_remote_profile(
|
||||
.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 {
|
||||
let mut options = creation_options(option);
|
||||
options.allow_auto_update = option.and_then(|value| value.allow_auto_update);
|
||||
let mut item = 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),
|
||||
})
|
||||
option: Some(options),
|
||||
..Default::default()
|
||||
};
|
||||
let (body, companions) = downloaded.apply(&mut item);
|
||||
append_companions(companions).await?;
|
||||
item.file_data = Some(body);
|
||||
Ok(item)
|
||||
}
|
||||
|
||||
pub(crate) fn subscription_proxy(options: Option<&PrfOption>) -> ProxyType {
|
||||
@@ -212,22 +213,6 @@ pub(crate) async fn download_subscription(
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn prepare_remote_refresh(
|
||||
downloaded: DownloadedSubscription,
|
||||
option: Option<&PrfOption>,
|
||||
) -> Result<RemoteProfileRefresh> {
|
||||
let mut options = prepare_profile_options(option).await?;
|
||||
options.update_interval = options.update_interval.or(downloaded.update_interval_minutes);
|
||||
options.allow_auto_update = Some(option.and_then(|options| options.allow_auto_update).unwrap_or(true));
|
||||
Ok(RemoteProfileRefresh {
|
||||
extra: downloaded.extra,
|
||||
home: downloaded.home,
|
||||
updated: chrono::Local::now().timestamp() as usize,
|
||||
option: options,
|
||||
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())
|
||||
@@ -380,7 +365,14 @@ mod tests {
|
||||
..option
|
||||
};
|
||||
let downloaded = download_subscription(&url, Some(&refresh_option), ProxyType::None).await?;
|
||||
let refresh = prepare_remote_refresh(downloaded, Some(&refresh_option)).await?;
|
||||
let mut refresh = PrfItem {
|
||||
option: Some(PrfOption {
|
||||
groups: None,
|
||||
..refresh_option.clone()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let (body, companions) = downloaded.apply(&mut refresh);
|
||||
server.await??;
|
||||
assert_eq!(item.itype.as_deref(), Some("remote"));
|
||||
assert_eq!(item.name.as_deref(), Some("remote.yaml"));
|
||||
@@ -393,16 +385,19 @@ mod tests {
|
||||
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!(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!(companions.len(), 1);
|
||||
assert_eq!(companions[0].itype.as_deref(), Some("groups"));
|
||||
assert_eq!(
|
||||
refresh.option,
|
||||
PrfOption {
|
||||
Some(PrfOption {
|
||||
update_interval: Some(120),
|
||||
..fetched_option
|
||||
}
|
||||
groups: companions[0].uid.clone(),
|
||||
..refresh_option
|
||||
})
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -127,12 +127,16 @@ pub(super) async fn commit_refresh(
|
||||
body: tristr::alias::String,
|
||||
) -> Result<super::IProfiles> {
|
||||
#[cfg(any(unix, all(windows, feature = "profile-store-windows")))]
|
||||
return commit_recoverable_refresh(uid, candidate, body).await;
|
||||
let mut candidate = commit_recoverable_refresh(uid, candidate, body).await?;
|
||||
#[cfg(not(any(unix, all(windows, feature = "profile-store-windows"))))]
|
||||
{
|
||||
let mut candidate = {
|
||||
write_legacy_refresh(&crate::utils::dirs::app_home_dir()?, &uid, &candidate, body.as_bytes()).await?;
|
||||
Ok(candidate)
|
||||
candidate
|
||||
};
|
||||
for item in candidate.items.iter_mut().flatten() {
|
||||
item.file_data = None;
|
||||
}
|
||||
Ok(candidate)
|
||||
}
|
||||
|
||||
#[cfg(any(not(unix), test))]
|
||||
@@ -161,9 +165,72 @@ async fn write_legacy_refresh(
|
||||
.await
|
||||
.with_context(|| format!("profile body {file} may be incomplete; the index was not updated"))?;
|
||||
drop(target);
|
||||
super::profiles::save_profile_index(&root.join(crate::utils::dirs::PROFILE_YAML), candidate)
|
||||
.await
|
||||
.with_context(|| format!("profile body was written to {file}, but the index was not updated"))
|
||||
let mut created = Vec::new();
|
||||
let result: Result<()> = async {
|
||||
for item in candidate.items.iter().flatten() {
|
||||
let Some(data) = &item.file_data else { continue };
|
||||
let name = item.file.as_deref().context("missing companion filename")?;
|
||||
super::profiles::validate_profile_file(name)?;
|
||||
let path = root.join(crate::utils::dirs::PROFILES_DIR).join(name);
|
||||
let mut options = tokio::fs::OpenOptions::new();
|
||||
options.create_new(true).write(true);
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use windows_sys::Win32::Storage::FileSystem::{DELETE, FILE_GENERIC_WRITE, FILE_SHARE_READ};
|
||||
options
|
||||
.access_mode(FILE_GENERIC_WRITE | DELETE)
|
||||
.share_mode(FILE_SHARE_READ);
|
||||
}
|
||||
let mut file = options.open(&path).await?;
|
||||
let written = async {
|
||||
file.write_all(data.as_bytes()).await?;
|
||||
file.flush().await
|
||||
}
|
||||
.await;
|
||||
created.push((path, file));
|
||||
written?;
|
||||
}
|
||||
super::profiles::save_profile_index(&root.join(crate::utils::dirs::PROFILE_YAML), candidate).await
|
||||
}
|
||||
.await;
|
||||
if let Err(error) = result {
|
||||
let mut error = error;
|
||||
for (path, file) in created {
|
||||
#[cfg(windows)]
|
||||
let cleanup = {
|
||||
use std::os::windows::io::AsRawHandle as _;
|
||||
use windows_sys::Win32::Storage::FileSystem::{
|
||||
FILE_DISPOSITION_INFO, FileDispositionInfo, SetFileInformationByHandle,
|
||||
};
|
||||
let disposition = FILE_DISPOSITION_INFO { DeleteFile: 1 };
|
||||
// Remove only the file this refresh created, even if its parent has been renamed.
|
||||
let deleted = unsafe {
|
||||
SetFileInformationByHandle(
|
||||
file.as_raw_handle(),
|
||||
FileDispositionInfo,
|
||||
(&raw const disposition).cast(),
|
||||
std::mem::size_of::<FILE_DISPOSITION_INFO>() as u32,
|
||||
)
|
||||
};
|
||||
if deleted == 0 {
|
||||
Err(std::io::Error::last_os_error())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
#[cfg(not(windows))]
|
||||
let cleanup = {
|
||||
drop(file);
|
||||
tokio::fs::remove_file(&path).await
|
||||
};
|
||||
if let Err(cleanup) = cleanup {
|
||||
error = error.context(format!("failed to clean up {}: {cleanup}", path.display()));
|
||||
}
|
||||
}
|
||||
return Err(error)
|
||||
.with_context(|| format!("profile body was written to {file}, but the index was not updated"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(any(unix, all(windows, feature = "profile-store-windows")))]
|
||||
@@ -263,10 +330,13 @@ mod tests {
|
||||
let root = home.path();
|
||||
std::fs::create_dir(root.join("profiles"))?;
|
||||
std::fs::create_dir(root.join("profiles.yaml"))?;
|
||||
let profiles = serde_yaml_ng::from_str("items: [{uid: r, file: old.yaml}]")?;
|
||||
let mut profiles: super::super::IProfiles =
|
||||
serde_yaml_ng::from_str("items: [{uid: r, file: old.yaml}, {uid: s, type: script, file: s.js}]")?;
|
||||
profiles.get_item_mut("s")?.file_data = Some("template".into());
|
||||
let result = write_legacy_refresh(root, "r", &profiles, b"new body").await;
|
||||
assert_eq!(std::fs::read(root.join("profiles/old.yaml"))?, b"new body");
|
||||
assert!(result.unwrap_err().to_string().contains("body was written"));
|
||||
assert!(!root.join("profiles/s.js").exists());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{
|
||||
PrfItem, PrfOption, PrfSelected, patch_opt_field,
|
||||
prfitem::{DownloadedSubscription, build_profile, prepare_remote_refresh},
|
||||
prfitem::{DownloadedSubscription, build_profile},
|
||||
profile_storage,
|
||||
};
|
||||
use crate::core::notify::{Refresh, announce};
|
||||
@@ -310,7 +310,6 @@ pub(crate) async fn save_remote_refresh(
|
||||
url: String,
|
||||
file: Option<String>,
|
||||
downloaded: DownloadedSubscription,
|
||||
options: Option<PrfOption>,
|
||||
) -> Result<()> {
|
||||
let uid = uid.to_owned();
|
||||
// Dropping the caller must not separate an issued disk write from its Draft publication.
|
||||
@@ -318,30 +317,25 @@ pub(crate) async fn save_remote_refresh(
|
||||
let _profile_write = PROFILE_WRITE_LOCK.lock().await;
|
||||
anyhow::ensure!(!handle::Handle::global().is_exiting(), "application is exiting");
|
||||
let draft = Config::profiles().await;
|
||||
let snapshot = draft.data_arc();
|
||||
let source = snapshot.get_item(&uid)?;
|
||||
check_refresh_source(source, &url, file.as_ref())?;
|
||||
let name = source.name.clone();
|
||||
drop(snapshot);
|
||||
let refresh = prepare_remote_refresh(downloaded, options.as_ref()).await?;
|
||||
let mut name = None;
|
||||
let mut storage_guard = None;
|
||||
let mut persisted = false;
|
||||
let result = {
|
||||
let storage_guard = &mut storage_guard;
|
||||
let persisted = &mut persisted;
|
||||
let name = &mut name;
|
||||
draft
|
||||
.with_data_modify(|mut candidate| async move {
|
||||
*storage_guard = Some(profile_storage::write().await?);
|
||||
let profile = candidate.get_item_mut(&uid)?;
|
||||
check_refresh_source(profile, &url, file.as_ref())?;
|
||||
profile.extra = refresh.extra;
|
||||
profile.updated = Some(refresh.updated);
|
||||
profile.home = refresh.home;
|
||||
profile.option = PrfOption::merge(profile.option.as_ref(), Some(&refresh.option));
|
||||
*name = profile.name.clone();
|
||||
let (body, companions) = downloaded.apply(profile);
|
||||
profile
|
||||
.file
|
||||
.get_or_insert_with(|| format!("{}.yaml", help::get_uid("R")).into());
|
||||
let candidate = profile_storage::commit_refresh(uid, candidate, refresh.body).await?;
|
||||
candidate.items.get_or_insert_with(Vec::new).extend(companions);
|
||||
let candidate = profile_storage::commit_refresh(uid, candidate, body).await?;
|
||||
*persisted = true;
|
||||
Ok((candidate, ()))
|
||||
})
|
||||
|
||||
@@ -110,7 +110,7 @@ async fn perform_profile_update(uid: &str, source: RefreshSource, overrides: Opt
|
||||
.await;
|
||||
let (strategy, downloaded) = result.map_err(|err| anyhow::anyhow!(mask_err(&format!("{err:#}"))))?;
|
||||
// A persistence error must not replay a successful download with another transport.
|
||||
save_remote_refresh(uid, source.url, source.file, downloaded, options).await?;
|
||||
save_remote_refresh(uid, source.url, source.file, downloaded).await?;
|
||||
if !matches!(strategy, Strategy::Configured) {
|
||||
handle::Handle::notice(NoticeStatus::UpdateWithClashProxy, profile_name);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user