优化调整、BT下载(有bug)

This commit is contained in:
zhongluofeng
2026-08-27 18:25:45 +08:00
parent 4dd60f42a1
commit d21649c60e
34 changed files with 4991 additions and 198 deletions
+70 -11
View File
@@ -17,11 +17,11 @@ mod types;
pub use autoswitch::{pick_best, start_auto_switch_loop};
pub use pseudo::is_pseudo_node;
pub use system_proxy::get_system_proxy_windows;
pub use types::{InstallProgress, KernelInfo, KernelUpdateInfo, ProfileMeta, ProxySettings, ProxyStatus};
pub use types::{InstallProgress, KernelInfo, KernelUpdateInfo, ProfileMeta, ProxySettings, ProxyStatus, TrafficSnapshot};
pub use commands::{
proxy_activate_profile, proxy_apply_kernel_update, proxy_cancel_kernel_install, proxy_check_kernel_update, proxy_clear_system_proxy,
proxy_close_connection, proxy_confirm_install, proxy_delete_profile, proxy_get_connections, proxy_get_proxies,
proxy_get_settings, proxy_get_system_proxy, proxy_import_profile, proxy_kernel_info,
proxy_get_settings, proxy_get_system_proxy, proxy_import_profile, proxy_kernel_info, proxy_traffic,
proxy_patch_configs, proxy_restart, proxy_save_settings, proxy_select_proxy, proxy_set_system_proxy,
proxy_start, proxy_status, proxy_stop, proxy_test_delay, proxy_update_profile, proxy_version,
};
@@ -45,10 +45,19 @@ struct SettingsCacheEntry {
settings: ProxySettings,
}
/// 流量速率差分基线:记录上次采样的会话总量与时刻,用于计算实时速率
struct TrafficBaseline {
download_total: u64,
upload_total: u64,
at: Instant,
}
pub struct MihomoManager {
root: PathBuf,
client: Client,
settings_cache: Mutex<Option<SettingsCacheEntry>>,
/// 流量速率差分基线:记录上次采样总量与时刻,由两次 /connections 总量差异计算实时速率
traffic_baseline: Mutex<Option<TrafficBaseline>>,
/// 内核安装/更新的取消标志(前端「停止下载」置位,下载循环轮询后中止)
kernel_cancel: Arc<AtomicBool>,
/// 取消唤醒通道:让停滞在流式读取(stream.next 最多等 30s)中的下载立即感知取消,
@@ -75,6 +84,7 @@ impl MihomoManager {
.build()
.unwrap_or_else(|_| Client::new()),
settings_cache: Mutex::new(None),
traffic_baseline: Mutex::new(None),
kernel_cancel: Arc::new(AtomicBool::new(false)),
kernel_cancel_tx: tokio::sync::watch::channel(false).0,
install_confirm: std::sync::Mutex::new(None),
@@ -308,16 +318,23 @@ impl MihomoManager {
/// 手动启动与 App 自启共用,保证设置语义一致(mihomo 运行期间自动跟随系统代理)。
pub fn apply_auto_system_proxy(&self) {
let settings = self.load_settings();
if settings.auto_system_proxy && !settings.system_proxy && !system_proxy::get_system_proxy_windows() {
let addr = format!("127.0.0.1:{}", settings.mixed_port);
if let Err(e) = system_proxy::set_system_proxy_windows(&addr) {
crate::logger::log_warn("mihomo", &format!("自动开启系统代理失败: {}", e));
return;
}
let mut s = settings;
s.system_proxy = true;
let _ = self.save_settings(&s);
if !settings.auto_system_proxy {
return;
}
// 以注册表实际状态为准判断是否已开启:settings.system_proxy 是会话内标志,
// 上次退出 cleanup_on_exit 只清注册表不会回写该标志,重启后会残留 true,
// 若用它做守卫会导致「启动时自动开启系统代理」永远被短路而不生效。
if system_proxy::get_system_proxy_windows() {
return;
}
let addr = format!("127.0.0.1:{}", settings.mixed_port);
if let Err(e) = system_proxy::set_system_proxy_windows(&addr) {
crate::logger::log_warn("mihomo", &format!("自动开启系统代理失败: {}", e));
return;
}
let mut s = settings;
s.system_proxy = true;
let _ = self.save_settings(&s);
}
/// 应用启动时检查是否需要自动启动 mihomo 和系统代理
@@ -450,6 +467,48 @@ impl MihomoManager {
self.api_get("/connections").await
}
/// 拉取 /connections 并计算实时流量快照。
/// 速率由两次采样的会话总量差分得出;mihomo 重启导致总量回退时自动重置基线。
pub async fn traffic_snapshot(&self) -> Result<TrafficSnapshot, String> {
let conns = self.get_connections().await?;
let upload_total = conns["uploadTotal"].as_u64().unwrap_or(0);
let download_total = conns["downloadTotal"].as_u64().unwrap_or(0);
let active_connections = conns["connections"].as_array().map(|a| a.len()).unwrap_or(0);
let (upload_speed, download_speed) = {
let base = self.traffic_baseline.lock().unwrap();
match base.as_ref() {
// 正常差分:总量单调递增才计算速率
Some(b) if upload_total >= b.upload_total && download_total >= b.download_total => {
let dt = b.at.elapsed().as_secs_f64();
if dt > 0.0 {
let up = ((upload_total - b.upload_total) as f64 / dt).max(0.0) as u64;
let down = ((download_total - b.download_total) as f64 / dt).max(0.0) as u64;
(up, down)
} else {
(0, 0)
}
}
// 无基线或总量回退(mihomo 重启):本帧速率为 0,下方重置基线
_ => (0, 0),
}
};
*self.traffic_baseline.lock().unwrap() = Some(TrafficBaseline {
download_total,
upload_total,
at: Instant::now(),
});
Ok(TrafficSnapshot {
download_total,
upload_total,
download_speed,
upload_speed,
active_connections,
})
}
pub async fn close_connection(&self, id: &str) -> Result<(), String> {
self.api_request(
reqwest::Method::DELETE,