refactor: simplify proxy type handling and improve error handling in network commands

This commit is contained in:
Tunglies
2025-05-16 00:09:34 +08:00
parent 92ae277e3a
commit 53a46d0dc6
11 changed files with 30 additions and 35 deletions

View File

@@ -8,7 +8,7 @@ use tokio::task::spawn_blocking;
/// get the system proxy /// get the system proxy
#[tauri::command] #[tauri::command]
pub async fn get_sys_proxy() -> CmdResult<Mapping> { pub async fn get_sys_proxy() -> CmdResult<Mapping> {
let current = spawn_blocking(move || Sysproxy::get_system_proxy()) let current = spawn_blocking(Sysproxy::get_system_proxy)
.await .await
.map_err(|e| format!("Failed to spawn blocking task for sysproxy: {}", e))? .map_err(|e| format!("Failed to spawn blocking task for sysproxy: {}", e))?
.map_err(|e| format!("Failed to get system proxy: {}", e))?; .map_err(|e| format!("Failed to get system proxy: {}", e))?;
@@ -27,7 +27,7 @@ pub async fn get_sys_proxy() -> CmdResult<Mapping> {
/// get the system proxy /// get the system proxy
#[tauri::command] #[tauri::command]
pub async fn get_auto_proxy() -> CmdResult<Mapping> { pub async fn get_auto_proxy() -> CmdResult<Mapping> {
let current = spawn_blocking(move || Autoproxy::get_auto_proxy()) let current = spawn_blocking(Autoproxy::get_auto_proxy)
.await .await
.map_err(|e| format!("Failed to spawn blocking task for autoproxy: {}", e))? .map_err(|e| format!("Failed to spawn blocking task for autoproxy: {}", e))?
.map_err(|e| format!("Failed to get auto proxy: {}", e))?; .map_err(|e| format!("Failed to get auto proxy: {}", e))?;

View File

@@ -259,11 +259,11 @@ impl PrfItem {
// 选择代理类型 // 选择代理类型
let proxy_type = if self_proxy { let proxy_type = if self_proxy {
ProxyType::SelfProxy ProxyType::Localhost
} else if with_proxy { } else if with_proxy {
ProxyType::SystemProxy ProxyType::System
} else { } else {
ProxyType::NoProxy ProxyType::None
}; };
// 使用网络管理器发送请求 // 使用网络管理器发送请求

View File

@@ -128,9 +128,10 @@ impl WebDavClient {
.build()?; .build()?;
// 尝试检查目录是否存在,如果不存在尝试创建,但创建失败不报错 // 尝试检查目录是否存在,如果不存在尝试创建,但创建失败不报错
if let Err(_) = client if client
.list(dirs::BACKUP_DIR, reqwest_dav::Depth::Number(0)) .list(dirs::BACKUP_DIR, reqwest_dav::Depth::Number(0))
.await .await
.is_err()
{ {
let _ = client.mkcol(dirs::BACKUP_DIR).await; let _ = client.mkcol(dirs::BACKUP_DIR).await;
} }

View File

@@ -89,7 +89,7 @@ impl NotificationSystem {
let system_guard = handle.notification_system.read(); let system_guard = handle.notification_system.read();
let is_emergency = system_guard let is_emergency = system_guard
.as_ref() .as_ref()
.and_then(|sys| Some(*sys.emergency_mode.read())) .map(|sys| *sys.emergency_mode.read())
.unwrap_or(false); .unwrap_or(false);
if is_emergency { if is_emergency {
@@ -110,7 +110,7 @@ impl NotificationSystem {
&window, &window,
"verge://refresh-clash-config", "verge://refresh-clash-config",
"yes", "yes",
&handle, handle,
); );
} }
FrontendEvent::RefreshVerge => { FrontendEvent::RefreshVerge => {
@@ -118,7 +118,7 @@ impl NotificationSystem {
&window, &window,
"verge://refresh-verge-config", "verge://refresh-verge-config",
"yes", "yes",
&handle, handle,
); );
} }
FrontendEvent::NoticeMessage { FrontendEvent::NoticeMessage {
@@ -129,7 +129,7 @@ impl NotificationSystem {
&window, &window,
"verge://notice-message", "verge://notice-message",
(status.clone(), message.clone()), (status.clone(), message.clone()),
&handle, handle,
); );
} }
} }
@@ -273,7 +273,7 @@ impl Default for Handle {
impl Handle { impl Handle {
pub fn global() -> &'static Handle { pub fn global() -> &'static Handle {
static HANDLE: OnceCell<Handle> = OnceCell::new(); static HANDLE: OnceCell<Handle> = OnceCell::new();
HANDLE.get_or_init(|| Handle::default()) HANDLE.get_or_init(Handle::default)
} }
pub fn init(&self, app_handle: &AppHandle) { pub fn init(&self, app_handle: &AppHandle) {

View File

@@ -538,7 +538,7 @@ pub async fn check_ipc_service_status() -> Result<JsonResponse> {
json_response.msg, json_response.msg,
json_response.data.is_some() json_response.data.is_some()
); );
return Ok(json_response); Ok(json_response)
} else { } else {
// 尝试直接解析 // 尝试直接解析
match serde_json::from_value::<JsonResponse>(data.clone()) { match serde_json::from_value::<JsonResponse>(data.clone()) {
@@ -551,7 +551,7 @@ pub async fn check_ipc_service_status() -> Result<JsonResponse> {
json_response.code, json_response.code,
json_response.msg json_response.msg
); );
return Ok(json_response); Ok(json_response)
} }
Err(e) => { Err(e) => {
logging!( logging!(

View File

@@ -385,10 +385,7 @@ impl Timer {
} }
}; };
let profile = match items let profile = match items.iter().find(|item| item.uid.as_deref() == Some(uid)) {
.iter()
.find(|item| item.uid.as_ref().map(|u| u.as_str()) == Some(uid))
{
Some(p) => p, Some(p) => p,
None => { None => {
logging!(warn, Type::Timer, "找不到对应的配置uid={}", uid); logging!(warn, Type::Timer, "找不到对应的配置uid={}", uid);
@@ -441,7 +438,6 @@ impl Timer {
} }
/// Async task with better error handling and logging /// Async task with better error handling and logging
async fn async_task(uid: String) { async fn async_task(uid: String) {
let task_start = std::time::Instant::now(); let task_start = std::time::Instant::now();
logging!(info, Type::Timer, "Running timer task for profile: {}", uid); logging!(info, Type::Timer, "Running timer task for profile: {}", uid);

View File

@@ -442,7 +442,7 @@ impl Tray {
traffic_result = stream.next() => { traffic_result = stream.next() => {
match traffic_result { match traffic_result {
Some(Ok(traffic)) => { Some(Ok(traffic)) => {
if let Ok(speedrate_result) = tokio::time::timeout( if let Ok(Some(rate)) = tokio::time::timeout(
std::time::Duration::from_millis(50), std::time::Duration::from_millis(50),
async { async {
let guard = speed_rate.try_lock(); let guard = speed_rate.try_lock();
@@ -457,12 +457,10 @@ impl Tray {
} }
} }
).await { ).await {
if let Some(rate) = speedrate_result { let _ = tokio::time::timeout(
let _ = tokio::time::timeout( std::time::Duration::from_millis(100),
std::time::Duration::from_millis(100), async { let _ = Tray::global().update_icon(Some(rate)); }
async { let _ = Tray::global().update_icon(Some(rate)); } ).await;
).await;
}
} }
}, },
Some(Err(e)) => { Some(Err(e)) => {

View File

@@ -271,7 +271,7 @@ impl Traffic {
// 设置流超时控制 // 设置流超时控制
let traffic_stream = ws_stream let traffic_stream = ws_stream
.take_while(|msg| { .take_while(|msg| {
let continue_stream = matches!(msg, Ok(_)); let continue_stream = msg.is_ok();
async move { continue_stream }.boxed() async move { continue_stream }.boxed()
}) })
.filter_map(|msg| async move { .filter_map(|msg| async move {

View File

@@ -98,9 +98,9 @@ pub async fn test_delay(url: String) -> anyhow::Result<u32> {
// 如果是TUN模式不使用代理否则使用自身代理 // 如果是TUN模式不使用代理否则使用自身代理
let proxy_type = if !tun_mode { let proxy_type = if !tun_mode {
ProxyType::SelfProxy ProxyType::Localhost
} else { } else {
ProxyType::NoProxy ProxyType::None
}; };
let user_agent = Some("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0".to_string()); let user_agent = Some("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0".to_string());

View File

@@ -1,4 +1,4 @@
use std::fmt::{self, write}; use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Type { pub enum Type {

View File

@@ -274,10 +274,10 @@ impl NetworkManager {
} }
match proxy_type { match proxy_type {
ProxyType::NoProxy => { ProxyType::None => {
builder = builder.no_proxy(); builder = builder.no_proxy();
} }
ProxyType::SelfProxy => { ProxyType::Localhost => {
let port = Config::verge() let port = Config::verge()
.latest() .latest()
.verge_mixed_port .verge_mixed_port
@@ -295,7 +295,7 @@ impl NetworkManager {
builder = builder.proxy(proxy); builder = builder.proxy(proxy);
} }
} }
ProxyType::SystemProxy => { ProxyType::System => {
use sysproxy::Sysproxy; use sysproxy::Sysproxy;
if let Ok(p @ Sysproxy { enable: true, .. }) = Sysproxy::get_system_proxy() { if let Ok(p @ Sysproxy { enable: true, .. }) = Sysproxy::get_system_proxy() {
@@ -420,7 +420,7 @@ impl NetworkManager {
/// 代理类型 /// 代理类型
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub enum ProxyType { pub enum ProxyType {
NoProxy, None,
SelfProxy, Localhost,
SystemProxy, System,
} }