2025-11-01 16:46:03 +08:00
|
|
|
|
use crate::{config::Config, process::AsyncHandler, utils::dirs};
|
2024-11-08 21:46:15 +08:00
|
|
|
|
use anyhow::Error;
|
|
|
|
|
|
use once_cell::sync::OnceCell;
|
|
|
|
|
|
use parking_lot::Mutex;
|
|
|
|
|
|
use reqwest_dav::list_cmd::{ListEntity, ListFile};
|
2025-10-22 16:25:44 +08:00
|
|
|
|
use smartstring::alias::String;
|
2025-03-13 12:51:20 +08:00
|
|
|
|
use std::{
|
|
|
|
|
|
collections::HashMap,
|
|
|
|
|
|
env::{consts::OS, temp_dir},
|
|
|
|
|
|
io::Write,
|
|
|
|
|
|
path::PathBuf,
|
|
|
|
|
|
sync::Arc,
|
|
|
|
|
|
time::Duration,
|
|
|
|
|
|
};
|
2025-11-01 16:46:03 +08:00
|
|
|
|
use tokio::{fs, time::timeout};
|
2024-11-08 21:46:15 +08:00
|
|
|
|
use zip::write::SimpleFileOptions;
|
|
|
|
|
|
|
2025-04-23 00:29:29 +08:00
|
|
|
|
// 应用版本常量,来自 tauri.conf.json
|
|
|
|
|
|
const APP_VERSION: &str = env!("CARGO_PKG_VERSION");
|
|
|
|
|
|
|
2024-11-27 07:34:34 +08:00
|
|
|
|
const TIMEOUT_UPLOAD: u64 = 300; // 上传超时 5 分钟
|
|
|
|
|
|
const TIMEOUT_DOWNLOAD: u64 = 300; // 下载超时 5 分钟
|
|
|
|
|
|
const TIMEOUT_LIST: u64 = 3; // 列表超时 30 秒
|
|
|
|
|
|
const TIMEOUT_DELETE: u64 = 3; // 删除超时 30 秒
|
|
|
|
|
|
|
|
|
|
|
|
#[derive(Clone)]
|
|
|
|
|
|
struct WebDavConfig {
|
|
|
|
|
|
url: String,
|
|
|
|
|
|
username: String,
|
|
|
|
|
|
password: String,
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
|
|
|
|
|
|
enum Operation {
|
|
|
|
|
|
Upload,
|
|
|
|
|
|
Download,
|
|
|
|
|
|
List,
|
|
|
|
|
|
Delete,
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
impl Operation {
|
|
|
|
|
|
fn timeout(&self) -> u64 {
|
|
|
|
|
|
match self {
|
|
|
|
|
|
Operation::Upload => TIMEOUT_UPLOAD,
|
|
|
|
|
|
Operation::Download => TIMEOUT_DOWNLOAD,
|
|
|
|
|
|
Operation::List => TIMEOUT_LIST,
|
|
|
|
|
|
Operation::Delete => TIMEOUT_DELETE,
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2024-11-08 21:46:15 +08:00
|
|
|
|
pub struct WebDavClient {
|
2024-11-27 07:34:34 +08:00
|
|
|
|
config: Arc<Mutex<Option<WebDavConfig>>>,
|
|
|
|
|
|
clients: Arc<Mutex<HashMap<Operation, reqwest_dav::Client>>>,
|
2024-11-08 21:46:15 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
impl WebDavClient {
|
|
|
|
|
|
pub fn global() -> &'static WebDavClient {
|
|
|
|
|
|
static WEBDAV_CLIENT: OnceCell<WebDavClient> = OnceCell::new();
|
|
|
|
|
|
WEBDAV_CLIENT.get_or_init(|| WebDavClient {
|
2024-11-27 07:34:34 +08:00
|
|
|
|
config: Arc::new(Mutex::new(None)),
|
|
|
|
|
|
clients: Arc::new(Mutex::new(HashMap::new())),
|
2024-11-08 21:46:15 +08:00
|
|
|
|
})
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2024-11-27 07:34:34 +08:00
|
|
|
|
async fn get_client(&self, op: Operation) -> Result<reqwest_dav::Client, Error> {
|
|
|
|
|
|
// 先尝试从缓存获取
|
|
|
|
|
|
{
|
|
|
|
|
|
let clients = self.clients.lock();
|
|
|
|
|
|
if let Some(client) = clients.get(&op) {
|
|
|
|
|
|
return Ok(client.clone());
|
2024-11-08 21:46:15 +08:00
|
|
|
|
}
|
2024-11-27 07:34:34 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 获取或创建配置
|
|
|
|
|
|
let config = {
|
2025-08-26 01:49:51 +08:00
|
|
|
|
// 首先检查是否已有配置
|
|
|
|
|
|
let existing_config = self.config.lock().as_ref().cloned();
|
|
|
|
|
|
|
|
|
|
|
|
if let Some(cfg) = existing_config {
|
|
|
|
|
|
cfg
|
2024-11-27 07:34:34 +08:00
|
|
|
|
} else {
|
2025-08-26 01:49:51 +08:00
|
|
|
|
// 释放锁后获取异步配置
|
|
|
|
|
|
let verge = Config::verge().await.latest_ref().clone();
|
2024-11-27 07:34:34 +08:00
|
|
|
|
if verge.webdav_url.is_none()
|
|
|
|
|
|
|| verge.webdav_username.is_none()
|
|
|
|
|
|
|| verge.webdav_password.is_none()
|
|
|
|
|
|
{
|
2025-10-14 09:24:39 +08:00
|
|
|
|
let msg: String = "Unable to create web dav client, please make sure the webdav config is correct".into();
|
2024-11-27 07:34:34 +08:00
|
|
|
|
return Err(anyhow::Error::msg(msg));
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
let config = WebDavConfig {
|
|
|
|
|
|
url: verge
|
|
|
|
|
|
.webdav_url
|
|
|
|
|
|
.unwrap_or_default()
|
|
|
|
|
|
.trim_end_matches('/')
|
2025-10-14 09:24:39 +08:00
|
|
|
|
.into(),
|
2024-11-27 07:34:34 +08:00
|
|
|
|
username: verge.webdav_username.unwrap_or_default(),
|
|
|
|
|
|
password: verge.webdav_password.unwrap_or_default(),
|
|
|
|
|
|
};
|
2024-11-08 21:46:15 +08:00
|
|
|
|
|
2025-08-26 01:49:51 +08:00
|
|
|
|
// 重新获取锁并存储配置
|
|
|
|
|
|
*self.config.lock() = Some(config.clone());
|
2024-11-27 07:34:34 +08:00
|
|
|
|
config
|
2024-11-09 23:11:02 +08:00
|
|
|
|
}
|
2024-11-27 07:34:34 +08:00
|
|
|
|
};
|
2024-11-09 23:11:02 +08:00
|
|
|
|
|
2024-11-27 07:34:34 +08:00
|
|
|
|
// 创建新的客户端
|
|
|
|
|
|
let client = reqwest_dav::ClientBuilder::new()
|
|
|
|
|
|
.set_agent(
|
|
|
|
|
|
reqwest::Client::builder()
|
|
|
|
|
|
.danger_accept_invalid_certs(true)
|
|
|
|
|
|
.timeout(Duration::from_secs(op.timeout()))
|
2025-06-27 23:30:35 +08:00
|
|
|
|
.user_agent(format!("clash-verge/{APP_VERSION} ({OS} WebDAV-Client)"))
|
2025-04-23 00:42:57 +08:00
|
|
|
|
.redirect(reqwest::redirect::Policy::custom(|attempt| {
|
|
|
|
|
|
// 允许所有请求类型的重定向,包括PUT
|
|
|
|
|
|
if attempt.previous().len() >= 5 {
|
|
|
|
|
|
attempt.error("重定向次数过多")
|
|
|
|
|
|
} else {
|
|
|
|
|
|
attempt.follow()
|
|
|
|
|
|
}
|
|
|
|
|
|
}))
|
2025-08-18 02:02:25 +08:00
|
|
|
|
.build()?,
|
2024-11-27 07:34:34 +08:00
|
|
|
|
)
|
2025-10-22 16:25:44 +08:00
|
|
|
|
.set_host(config.url.into())
|
|
|
|
|
|
.set_auth(reqwest_dav::Auth::Basic(
|
|
|
|
|
|
config.username.into(),
|
|
|
|
|
|
config.password.into(),
|
|
|
|
|
|
))
|
2024-11-27 07:34:34 +08:00
|
|
|
|
.build()?;
|
|
|
|
|
|
|
2025-10-06 16:54:35 +08:00
|
|
|
|
// 尝试检查目录是否存在,如果不存在尝试创建
|
2025-05-16 00:09:34 +08:00
|
|
|
|
if client
|
2024-11-27 07:34:34 +08:00
|
|
|
|
.list(dirs::BACKUP_DIR, reqwest_dav::Depth::Number(0))
|
2025-04-23 01:10:01 +08:00
|
|
|
|
.await
|
2025-05-16 00:09:34 +08:00
|
|
|
|
.is_err()
|
2025-04-23 01:10:01 +08:00
|
|
|
|
{
|
2025-10-06 16:54:35 +08:00
|
|
|
|
match client.mkcol(dirs::BACKUP_DIR).await {
|
|
|
|
|
|
Ok(_) => log::info!("Successfully created backup directory"),
|
|
|
|
|
|
Err(e) => {
|
|
|
|
|
|
log::warn!("Failed to create backup directory: {}", e);
|
|
|
|
|
|
// 清除缓存,强制下次重新尝试
|
|
|
|
|
|
self.reset();
|
|
|
|
|
|
return Err(anyhow::Error::msg(format!(
|
|
|
|
|
|
"Failed to create backup directory: {}",
|
|
|
|
|
|
e
|
|
|
|
|
|
)));
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2024-11-27 07:34:34 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 缓存客户端
|
|
|
|
|
|
{
|
|
|
|
|
|
let mut clients = self.clients.lock();
|
|
|
|
|
|
clients.insert(op, client.clone());
|
2024-11-08 21:46:15 +08:00
|
|
|
|
}
|
2024-11-27 07:34:34 +08:00
|
|
|
|
|
|
|
|
|
|
Ok(client)
|
2024-11-08 21:46:15 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
pub fn reset(&self) {
|
2024-11-27 07:34:34 +08:00
|
|
|
|
*self.config.lock() = None;
|
|
|
|
|
|
self.clients.lock().clear();
|
2024-11-08 21:46:15 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
pub async fn upload(&self, file_path: PathBuf, file_name: String) -> Result<(), Error> {
|
2024-11-27 07:34:34 +08:00
|
|
|
|
let client = self.get_client(Operation::Upload).await?;
|
2025-10-22 16:25:44 +08:00
|
|
|
|
let webdav_path: String = format!("{}/{}", dirs::BACKUP_DIR, file_name).into();
|
2025-04-23 01:10:01 +08:00
|
|
|
|
|
|
|
|
|
|
// 读取文件并上传,如果失败尝试一次重试
|
2025-11-01 16:46:03 +08:00
|
|
|
|
let file_content = fs::read(&file_path).await?;
|
2025-04-23 01:10:01 +08:00
|
|
|
|
|
|
|
|
|
|
// 添加超时保护
|
|
|
|
|
|
let upload_result = timeout(
|
|
|
|
|
|
Duration::from_secs(TIMEOUT_UPLOAD),
|
|
|
|
|
|
client.put(&webdav_path, file_content.clone()),
|
|
|
|
|
|
)
|
|
|
|
|
|
.await;
|
|
|
|
|
|
|
|
|
|
|
|
match upload_result {
|
|
|
|
|
|
Err(_) => {
|
|
|
|
|
|
log::warn!("Upload timed out, retrying once");
|
|
|
|
|
|
tokio::time::sleep(Duration::from_millis(500)).await;
|
|
|
|
|
|
timeout(
|
|
|
|
|
|
Duration::from_secs(TIMEOUT_UPLOAD),
|
|
|
|
|
|
client.put(&webdav_path, file_content),
|
|
|
|
|
|
)
|
|
|
|
|
|
.await??;
|
|
|
|
|
|
Ok(())
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
Ok(Err(e)) => {
|
2025-06-27 23:30:35 +08:00
|
|
|
|
log::warn!("Upload failed, retrying once: {e}");
|
2025-04-23 01:10:01 +08:00
|
|
|
|
tokio::time::sleep(Duration::from_millis(500)).await;
|
|
|
|
|
|
timeout(
|
|
|
|
|
|
Duration::from_secs(TIMEOUT_UPLOAD),
|
|
|
|
|
|
client.put(&webdav_path, file_content),
|
|
|
|
|
|
)
|
|
|
|
|
|
.await??;
|
|
|
|
|
|
Ok(())
|
|
|
|
|
|
}
|
|
|
|
|
|
Ok(Ok(_)) => Ok(()),
|
|
|
|
|
|
}
|
2024-11-08 21:46:15 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2024-11-09 23:11:02 +08:00
|
|
|
|
pub async fn download(&self, filename: String, storage_path: PathBuf) -> Result<(), Error> {
|
2024-11-27 07:34:34 +08:00
|
|
|
|
let client = self.get_client(Operation::Download).await?;
|
2024-11-09 23:11:02 +08:00
|
|
|
|
let path = format!("{}/{}", dirs::BACKUP_DIR, filename);
|
2024-11-27 07:34:34 +08:00
|
|
|
|
|
|
|
|
|
|
let fut = async {
|
|
|
|
|
|
let response = client.get(path.as_str()).await?;
|
|
|
|
|
|
let content = response.bytes().await?;
|
2025-11-01 16:46:03 +08:00
|
|
|
|
fs::write(&storage_path, &content).await?;
|
2024-11-27 07:34:34 +08:00
|
|
|
|
Ok::<(), Error>(())
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
timeout(Duration::from_secs(TIMEOUT_DOWNLOAD), fut).await??;
|
2024-11-09 23:11:02 +08:00
|
|
|
|
Ok(())
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
pub async fn list(&self) -> Result<Vec<ListFile>, Error> {
|
2024-11-27 07:34:34 +08:00
|
|
|
|
let client = self.get_client(Operation::List).await?;
|
2024-11-17 23:57:28 +08:00
|
|
|
|
let path = format!("{}/", dirs::BACKUP_DIR);
|
2024-11-27 07:34:34 +08:00
|
|
|
|
|
|
|
|
|
|
let fut = async {
|
|
|
|
|
|
let files = client
|
|
|
|
|
|
.list(path.as_str(), reqwest_dav::Depth::Number(1))
|
|
|
|
|
|
.await?;
|
|
|
|
|
|
let mut final_files = Vec::new();
|
|
|
|
|
|
for file in files {
|
|
|
|
|
|
if let ListEntity::File(file) = file {
|
|
|
|
|
|
final_files.push(file);
|
|
|
|
|
|
}
|
2024-11-08 21:46:15 +08:00
|
|
|
|
}
|
2024-11-27 07:34:34 +08:00
|
|
|
|
Ok::<Vec<ListFile>, Error>(final_files)
|
|
|
|
|
|
};
|
|
|
|
|
|
|
2024-12-31 04:50:12 +08:00
|
|
|
|
timeout(Duration::from_secs(TIMEOUT_LIST), fut).await?
|
2024-11-08 21:46:15 +08:00
|
|
|
|
}
|
2024-11-09 23:11:02 +08:00
|
|
|
|
|
|
|
|
|
|
pub async fn delete(&self, file_name: String) -> Result<(), Error> {
|
2024-11-27 07:34:34 +08:00
|
|
|
|
let client = self.get_client(Operation::Delete).await?;
|
2024-11-09 23:11:02 +08:00
|
|
|
|
let path = format!("{}/{}", dirs::BACKUP_DIR, file_name);
|
2024-11-27 07:34:34 +08:00
|
|
|
|
|
|
|
|
|
|
let fut = client.delete(&path);
|
|
|
|
|
|
timeout(Duration::from_secs(TIMEOUT_DELETE), fut).await??;
|
2024-11-09 23:11:02 +08:00
|
|
|
|
Ok(())
|
|
|
|
|
|
}
|
2024-11-08 21:46:15 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2025-11-01 16:46:03 +08:00
|
|
|
|
pub async fn create_backup() -> Result<(String, PathBuf), Error> {
|
2024-11-08 21:46:15 +08:00
|
|
|
|
let now = chrono::Local::now().format("%Y-%m-%d_%H-%M-%S").to_string();
|
2025-10-22 16:25:44 +08:00
|
|
|
|
let zip_file_name: String = format!("{OS}-backup-{now}.zip").into();
|
|
|
|
|
|
let zip_path = temp_dir().join(zip_file_name.as_str());
|
2024-11-08 21:46:15 +08:00
|
|
|
|
|
2025-11-01 16:46:03 +08:00
|
|
|
|
let value = zip_path.clone();
|
|
|
|
|
|
let file = AsyncHandler::spawn_blocking(move || std::fs::File::create(&value)).await??;
|
2024-11-08 21:46:15 +08:00
|
|
|
|
let mut zip = zip::ZipWriter::new(file);
|
|
|
|
|
|
zip.add_directory("profiles/", SimpleFileOptions::default())?;
|
|
|
|
|
|
let options = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
|
2025-11-01 16:46:03 +08:00
|
|
|
|
|
|
|
|
|
|
if let Ok(mut entries) = fs::read_dir(dirs::app_profiles_dir()?).await {
|
|
|
|
|
|
while let Some(entry) = entries.next_entry().await? {
|
2024-11-08 21:46:15 +08:00
|
|
|
|
let path = entry.path();
|
|
|
|
|
|
if path.is_file() {
|
2025-08-18 02:02:25 +08:00
|
|
|
|
let file_name_os = entry.file_name();
|
|
|
|
|
|
let file_name = file_name_os
|
|
|
|
|
|
.to_str()
|
|
|
|
|
|
.ok_or_else(|| anyhow::Error::msg("Invalid file name encoding"))?;
|
|
|
|
|
|
let backup_path = format!("profiles/{}", file_name);
|
2024-11-08 21:46:15 +08:00
|
|
|
|
zip.start_file(backup_path, options)?;
|
2025-11-01 16:46:03 +08:00
|
|
|
|
let file_content = fs::read(&path).await?;
|
2025-08-18 02:02:25 +08:00
|
|
|
|
zip.write_all(&file_content)?;
|
2024-11-08 21:46:15 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
zip.start_file(dirs::CLASH_CONFIG, options)?;
|
2025-11-01 16:46:03 +08:00
|
|
|
|
zip.write_all(fs::read(dirs::clash_path()?).await?.as_slice())?;
|
2024-11-09 23:11:02 +08:00
|
|
|
|
|
2025-11-01 16:46:03 +08:00
|
|
|
|
let verge_text = fs::read_to_string(dirs::verge_path()?).await?;
|
|
|
|
|
|
let mut verge_config: serde_json::Value = serde_yaml_ng::from_str(&verge_text)?;
|
2024-11-09 23:11:02 +08:00
|
|
|
|
if let Some(obj) = verge_config.as_object_mut() {
|
|
|
|
|
|
obj.remove("webdav_username");
|
|
|
|
|
|
obj.remove("webdav_password");
|
|
|
|
|
|
obj.remove("webdav_url");
|
|
|
|
|
|
}
|
2024-11-08 21:46:15 +08:00
|
|
|
|
zip.start_file(dirs::VERGE_CONFIG, options)?;
|
2025-08-30 02:24:47 +08:00
|
|
|
|
zip.write_all(serde_yaml_ng::to_string(&verge_config)?.as_bytes())?;
|
2024-11-09 23:11:02 +08:00
|
|
|
|
|
2025-10-22 19:52:44 +08:00
|
|
|
|
let dns_config_path = dirs::app_home_dir()?.join(dirs::DNS_CONFIG);
|
|
|
|
|
|
if dns_config_path.exists() {
|
|
|
|
|
|
zip.start_file(dirs::DNS_CONFIG, options)?;
|
2025-11-01 16:46:03 +08:00
|
|
|
|
zip.write_all(fs::read(&dns_config_path).await?.as_slice())?;
|
2025-10-22 19:52:44 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2024-11-08 21:46:15 +08:00
|
|
|
|
zip.start_file(dirs::PROFILE_YAML, options)?;
|
2025-11-01 16:46:03 +08:00
|
|
|
|
zip.write_all(fs::read(dirs::profiles_path()?).await?.as_slice())?;
|
2024-11-08 21:46:15 +08:00
|
|
|
|
zip.finish()?;
|
|
|
|
|
|
Ok((zip_file_name, zip_path))
|
|
|
|
|
|
}
|