代理修改
This commit is contained in:
@@ -10,7 +10,7 @@ use logger::{
|
||||
use mihomo_manager::{
|
||||
proxy_activate_profile, proxy_check_kernel_update, proxy_clear_system_proxy, proxy_close_connection, proxy_delete_profile,
|
||||
proxy_get_connections, proxy_get_proxies, proxy_get_settings, proxy_get_system_proxy,
|
||||
proxy_import_profile, proxy_kernel_info, proxy_patch_configs, proxy_restart, proxy_save_settings,
|
||||
proxy_import_profile, proxy_install_kernel, proxy_kernel_info, 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_kernel, proxy_update_profile, proxy_version, MihomoManager,
|
||||
};
|
||||
@@ -59,6 +59,7 @@ pub fn run() {
|
||||
proxy_kernel_info,
|
||||
proxy_check_kernel_update,
|
||||
proxy_update_kernel,
|
||||
proxy_install_kernel,
|
||||
proxy_status,
|
||||
proxy_start,
|
||||
proxy_stop,
|
||||
|
||||
+383
-70
@@ -1,13 +1,15 @@
|
||||
use chrono::Local;
|
||||
use futures_util::StreamExt;
|
||||
use reqwest::Client;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_yaml::Value as YamlValue;
|
||||
use std::fs;
|
||||
use std::io::{Read, Write};
|
||||
use std::path::PathBuf;
|
||||
use tauri::{AppHandle, Manager};
|
||||
use tauri::{AppHandle, Emitter, Manager};
|
||||
use tauri::path::BaseDirectory;
|
||||
|
||||
use crate::process_manager::{ProcessInfo, ProcessManager, StartProcessParams};
|
||||
use crate::process_manager::{ProcessInfo, ProcessManager, StartProcessParams, setup_creation_flags};
|
||||
|
||||
// ===================== 数据结构 =====================
|
||||
|
||||
@@ -44,6 +46,10 @@ pub struct ProxySettings {
|
||||
pub auto_switch_group: String,
|
||||
#[serde(default)]
|
||||
pub auto_switch_region: String,
|
||||
/// 内核下载镜像源列表(前缀拼接到 GitHub URL 前)。
|
||||
/// 空字符串 = 直连 GitHub,其余为镜像站前缀(含尾斜杠)。
|
||||
#[serde(default = "default_kernel_mirrors")]
|
||||
pub kernel_mirrors: Vec<String>,
|
||||
}
|
||||
|
||||
fn default_mixed_port() -> u16 { 7890 }
|
||||
@@ -51,6 +57,15 @@ fn default_external_controller() -> String { "127.0.0.1:9090".into() }
|
||||
fn default_mode() -> String { "rule".into() }
|
||||
fn default_log_level() -> String { "info".into() }
|
||||
fn default_auto_switch_interval() -> u32 { 5 }
|
||||
/// 默认镜像源:空串=直连 GitHub 优先,后续为公益镜像(按稳定性排序)
|
||||
fn default_kernel_mirrors() -> Vec<String> {
|
||||
vec![
|
||||
String::new(),
|
||||
"https://ghproxy.net/".into(),
|
||||
"https://gh-proxy.com/".into(),
|
||||
"https://ghfast.top/".into(),
|
||||
]
|
||||
}
|
||||
|
||||
impl Default for ProxySettings {
|
||||
fn default() -> Self {
|
||||
@@ -70,6 +85,7 @@ impl Default for ProxySettings {
|
||||
auto_switch_interval: 5,
|
||||
auto_switch_group: String::new(),
|
||||
auto_switch_region: String::new(),
|
||||
kernel_mirrors: default_kernel_mirrors(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -116,6 +132,19 @@ pub struct ProxyStatus {
|
||||
pub restart_count: u32,
|
||||
}
|
||||
|
||||
/// 内核安装进度事件载荷
|
||||
/// - stage: downloading | extracting | replacing | done | error
|
||||
/// - percent: 0-100(无 total_bytes 时为 0,前端按 downloadedBytes 显示)
|
||||
#[derive(Serialize, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct InstallProgress {
|
||||
pub stage: String,
|
||||
pub percent: u8,
|
||||
pub downloaded_bytes: u64,
|
||||
pub total_bytes: Option<u64>,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
// ===================== MihomoManager =====================
|
||||
|
||||
pub struct MihomoManager {
|
||||
@@ -236,9 +265,15 @@ impl MihomoManager {
|
||||
let path = self.kernel_path();
|
||||
let exists = path.exists();
|
||||
let version = if exists {
|
||||
std::process::Command::new(&path)
|
||||
.arg("-v")
|
||||
.output()
|
||||
let mut cmd = std::process::Command::new(&path);
|
||||
cmd.arg("-v");
|
||||
// 隐藏控制台窗口(mihomo.exe -v 也会弹窗)
|
||||
setup_creation_flags(&mut cmd);
|
||||
// 重定向 stdio,避免继承主进程控制台
|
||||
cmd.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.stdin(std::process::Stdio::null());
|
||||
cmd.output()
|
||||
.ok()
|
||||
.and_then(|o| String::from_utf8(o.stdout).ok())
|
||||
.and_then(|s| {
|
||||
@@ -270,14 +305,38 @@ impl MihomoManager {
|
||||
}
|
||||
|
||||
/// 检查 GitHub 上的最新 mihomo 版本
|
||||
/// 策略:优先用 API(能拿到完整资产列表,命名变化时更健壮),
|
||||
/// 失败时回退到重定向解析(不受 API rate limit 限制)
|
||||
pub async fn check_kernel_update(&self) -> Result<KernelUpdateInfo, String> {
|
||||
let resp: serde_json::Value = self
|
||||
match self.fetch_latest_via_api().await {
|
||||
Ok(info) => Ok(info),
|
||||
Err(api_err) => {
|
||||
eprintln!("[kernel] API 查询失败,回退到重定向解析: {}", api_err);
|
||||
self.fetch_latest_via_redirect().await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 通过 GitHub API 查询最新版本(受 rate limit 限制:未认证 60次/小时/IP)
|
||||
async fn fetch_latest_via_api(&self) -> Result<KernelUpdateInfo, String> {
|
||||
let resp = self
|
||||
.client
|
||||
.get("https://api.github.com/repos/MetaCubeX/mihomo/releases/latest")
|
||||
.header("User-Agent", "thing-app")
|
||||
.timeout(std::time::Duration::from_secs(15))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("请求 GitHub API 失败: {}", e))?
|
||||
.map_err(|e| format!("请求 GitHub API 失败: {}", e))?;
|
||||
let status = resp.status();
|
||||
if !status.is_success() {
|
||||
let body = resp.text().await.unwrap_or_default();
|
||||
return Err(format!(
|
||||
"GitHub API 返回 HTTP {}:{}",
|
||||
status.as_u16(),
|
||||
if body.len() > 300 { format!("{}...", &body[..300]) } else { body }
|
||||
));
|
||||
}
|
||||
let resp: serde_json::Value = resp
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| format!("解析 GitHub 响应失败: {}", e))?;
|
||||
@@ -288,33 +347,92 @@ impl MihomoManager {
|
||||
.unwrap_or("unknown")
|
||||
.to_string();
|
||||
|
||||
// 查找 windows amd64 zip 资产(非 compatible 版本)
|
||||
let download_url = resp
|
||||
.get("assets")
|
||||
.and_then(|a| a.as_array())
|
||||
.and_then(|assets| {
|
||||
assets.iter().find_map(|asset| {
|
||||
let assets_arr = resp.get("assets").and_then(|a| a.as_array());
|
||||
|
||||
// 收集所有 windows amd64 zip 候选资产(排除 compatible/arm64/386)
|
||||
let candidates: Vec<(String, String)> = assets_arr
|
||||
.map(|assets| {
|
||||
assets.iter().filter_map(|asset| {
|
||||
let name = asset.get("name")?.as_str()?;
|
||||
let url = asset.get("browser_download_url")?.as_str()?;
|
||||
// 匹配 mihomo-windows-amd64-v*.zip,排除 compatible/arm64
|
||||
if name.starts_with("mihomo-windows-amd64-")
|
||||
&& name.ends_with(".zip")
|
||||
&& !name.contains("compatible")
|
||||
&& !name.contains("arm64")
|
||||
&& !name.contains("386")
|
||||
{
|
||||
Some(url.to_string())
|
||||
Some((name.to_string(), url.to_string()))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
}).collect()
|
||||
})
|
||||
.ok_or_else(|| "未找到适用的 Windows amd64 内核资产".to_string())?;
|
||||
.unwrap_or_default();
|
||||
|
||||
// 当前版本
|
||||
// 按优先级匹配:v3 标准 > v3-go124 > v3-go123 > v3 其他 > v2 > v1 > 旧命名
|
||||
let download_url = candidates
|
||||
.iter().find(|(n, _)| n.contains("-v3-v") && !n.contains("-go"))
|
||||
.or_else(|| candidates.iter().find(|(n, _)| n.contains("-v3-go124-")))
|
||||
.or_else(|| candidates.iter().find(|(n, _)| n.contains("-v3-go123-")))
|
||||
.or_else(|| candidates.iter().find(|(n, _)| n.contains("-v3-go")))
|
||||
.or_else(|| candidates.iter().find(|(n, _)| n.contains("-v2-v")))
|
||||
.or_else(|| candidates.iter().find(|(n, _)| n.contains("-v1-v")))
|
||||
.or_else(|| candidates.iter().find(|(n, _)| {
|
||||
!n.contains("-v1-") && !n.contains("-v2-") && !n.contains("-v3-")
|
||||
}))
|
||||
.map(|(_, u)| u.clone())
|
||||
.ok_or_else(|| {
|
||||
let candidates_str = candidates.iter()
|
||||
.map(|(n, _)| n.as_str())
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
format!("API 未找到适用的 Windows amd64 内核资产。候选:[{}]", candidates_str)
|
||||
})?;
|
||||
|
||||
Ok(self.build_update_info(latest_version, download_url))
|
||||
}
|
||||
|
||||
/// 通过 releases/latest 重定向解析版本号(不受 API rate limit 限制)
|
||||
/// 访问 https://github.com/MetaCubeX/mihomo/releases/latest 会 302 到
|
||||
/// https://github.com/MetaCubeX/mihomo/releases/tag/v1.19.13
|
||||
/// 从最终 URL 提取版本号后,按 v1.19+ 稳定命名规则构造下载 URL
|
||||
async fn fetch_latest_via_redirect(&self) -> Result<KernelUpdateInfo, String> {
|
||||
let resp = self
|
||||
.client
|
||||
.get("https://github.com/MetaCubeX/mihomo/releases/latest")
|
||||
.header("User-Agent", "thing-app")
|
||||
.timeout(std::time::Duration::from_secs(15))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("请求 GitHub releases 页面失败: {}", e))?;
|
||||
|
||||
// 从重定向后的最终 URL 提取版本号
|
||||
let final_url = resp.url().to_string();
|
||||
let latest_version = final_url
|
||||
.rsplit('/')
|
||||
.next()
|
||||
.filter(|s| s.starts_with('v') && s.chars().any(|c| c == '.'))
|
||||
.ok_or_else(|| format!("无法从重定向 URL 提取版本号: {}", final_url))?
|
||||
.to_string();
|
||||
|
||||
// 构造下载 URL:mihomo v1.19+ 稳定使用 -v3-vX.X.X.zip 命名(CPU level v3)
|
||||
let download_url = format!(
|
||||
"https://github.com/MetaCubeX/mihomo/releases/download/{}/mihomo-windows-amd64-v3-{}.zip",
|
||||
latest_version, latest_version
|
||||
);
|
||||
|
||||
eprintln!(
|
||||
"[kernel] 重定向解析成功: version={}, url={}",
|
||||
latest_version, download_url
|
||||
);
|
||||
Ok(self.build_update_info(latest_version, download_url))
|
||||
}
|
||||
|
||||
/// 根据最新版本和下载 URL 构造更新信息(含当前版本比较)
|
||||
fn build_update_info(&self, latest_version: String, download_url: String) -> KernelUpdateInfo {
|
||||
let current = self.kernel_info().version;
|
||||
let has_update = match ¤t {
|
||||
Some(c) => {
|
||||
// 简单比较:从当前版本字符串提取版本号
|
||||
let cur_ver = c
|
||||
.split_whitespace()
|
||||
.find(|s| s.starts_with('v') && s.chars().filter(|c| *c == '.').count() >= 2)
|
||||
@@ -323,85 +441,266 @@ impl MihomoManager {
|
||||
}
|
||||
None => true,
|
||||
};
|
||||
|
||||
Ok(KernelUpdateInfo {
|
||||
KernelUpdateInfo {
|
||||
current_version: current,
|
||||
latest_version,
|
||||
download_url,
|
||||
has_update,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// 下载并安装内核更新
|
||||
pub async fn update_kernel(&self) -> Result<KernelInfo, String> {
|
||||
/// 下载并安装内核(首次安装与更新共用此方法)
|
||||
/// - mirror_prefix: 用户选择的镜像源前缀(空串=直连 GitHub)
|
||||
/// - 流式下载:实时推送下载进度到前端
|
||||
/// - zip crate 解压:替代 PowerShell,避免执行策略问题
|
||||
/// - 备份旧内核:替换前备份为 .bak
|
||||
/// 任何阶段失败都会 emit error 事件,避免前端进度卡在初始状态
|
||||
pub async fn install_kernel(&self, app: &AppHandle, mirror_prefix: String) -> Result<KernelInfo, String> {
|
||||
let result = self.install_kernel_inner(app, mirror_prefix).await;
|
||||
if let Err(ref e) = result {
|
||||
let _ = app.emit(
|
||||
"kernel-install-progress",
|
||||
InstallProgress {
|
||||
stage: "error".into(),
|
||||
percent: 0,
|
||||
downloaded_bytes: 0,
|
||||
total_bytes: None,
|
||||
message: e.clone(),
|
||||
},
|
||||
);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
async fn install_kernel_inner(&self, app: &AppHandle, mirror_prefix: String) -> Result<KernelInfo, String> {
|
||||
let info = self.check_kernel_update().await?;
|
||||
let zip_path = self.cores_dir().join("mihomo-update.zip");
|
||||
let extract_dir = self.cores_dir().join("mihomo-update-tmp");
|
||||
|
||||
// 下载 zip
|
||||
let resp = self
|
||||
.client
|
||||
.get(&info.download_url)
|
||||
.header("User-Agent", "thing-app")
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("下载内核失败: {}", e))?;
|
||||
if !resp.status().is_success() {
|
||||
return Err(format!("下载失败: HTTP {}", resp.status()));
|
||||
}
|
||||
let bytes = resp
|
||||
.bytes()
|
||||
.await
|
||||
.map_err(|e| format!("读取下载内容失败: {}", e))?;
|
||||
fs::write(&zip_path, &bytes).map_err(|e| format!("保存 zip 失败: {}", e))?;
|
||||
// 拼接用户选择的镜像源 URL
|
||||
let url = if mirror_prefix.is_empty() {
|
||||
info.download_url.clone()
|
||||
} else {
|
||||
format!("{}{}", mirror_prefix, info.download_url)
|
||||
};
|
||||
let label = if mirror_prefix.is_empty() { "GitHub 直连".to_string() } else { mirror_prefix.clone() };
|
||||
let _ = app.emit(
|
||||
"kernel-install-progress",
|
||||
InstallProgress {
|
||||
stage: "downloading".into(),
|
||||
percent: 0,
|
||||
downloaded_bytes: 0,
|
||||
total_bytes: None,
|
||||
message: format!("正在下载:{}", label),
|
||||
},
|
||||
);
|
||||
|
||||
// 清理旧解压目录
|
||||
// 单源下载(用户已选择)
|
||||
match self.download_with_progress(app, &url, &zip_path).await {
|
||||
Ok(()) => {}
|
||||
Err(e) => {
|
||||
let msg = format!("下载失败({}):{}", label, e);
|
||||
let _ = app.emit(
|
||||
"kernel-install-progress",
|
||||
InstallProgress {
|
||||
stage: "error".into(),
|
||||
percent: 0,
|
||||
downloaded_bytes: 0,
|
||||
total_bytes: None,
|
||||
message: msg.clone(),
|
||||
},
|
||||
);
|
||||
let _ = fs::remove_file(&zip_path);
|
||||
return Err(msg);
|
||||
}
|
||||
}
|
||||
|
||||
// 解压阶段
|
||||
let _ = app.emit(
|
||||
"kernel-install-progress",
|
||||
InstallProgress {
|
||||
stage: "extracting".into(),
|
||||
percent: 92,
|
||||
downloaded_bytes: 0,
|
||||
total_bytes: None,
|
||||
message: "正在解压...".into(),
|
||||
},
|
||||
);
|
||||
if extract_dir.exists() {
|
||||
fs::remove_dir_all(&extract_dir).ok();
|
||||
}
|
||||
fs::create_dir_all(&extract_dir).map_err(|e| e.to_string())?;
|
||||
|
||||
// 用 PowerShell 解压
|
||||
let output = std::process::Command::new("powershell")
|
||||
.args([
|
||||
"-NoProfile",
|
||||
"-Command",
|
||||
&format!(
|
||||
"Expand-Archive -Path '{}' -DestinationPath '{}' -Force",
|
||||
zip_path.to_string_lossy(),
|
||||
extract_dir.to_string_lossy()
|
||||
),
|
||||
])
|
||||
.output()
|
||||
.map_err(|e| format!("解压失败: {}", e))?;
|
||||
if !output.status.success() {
|
||||
let err = String::from_utf8_lossy(&output.stderr);
|
||||
return Err(format!("解压失败: {}", err));
|
||||
if let Err(e) = self.extract_zip(&zip_path, &extract_dir) {
|
||||
let _ = app.emit(
|
||||
"kernel-install-progress",
|
||||
InstallProgress {
|
||||
stage: "error".into(),
|
||||
percent: 0,
|
||||
downloaded_bytes: 0,
|
||||
total_bytes: None,
|
||||
message: format!("解压失败:{}", e),
|
||||
},
|
||||
);
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
// 查找解压出的 mihomo.exe
|
||||
let new_exe = extract_dir.join("mihomo.exe");
|
||||
if !new_exe.exists() {
|
||||
// 可能在不同子目录
|
||||
return Err("解压后未找到 mihomo.exe".into());
|
||||
}
|
||||
// 在解压目录中递归查找 exe 文件
|
||||
// mihomo zip 内的 exe 名字通常与 zip 同名(如 mihomo-windows-amd64-v3-v1.19.13.exe),
|
||||
// 不是固定的 mihomo.exe,所以查找唯一的 .exe 文件即可
|
||||
let new_exe = self
|
||||
.find_exe_in_dir(&extract_dir)
|
||||
.ok_or_else(|| "解压后未找到任何 .exe 文件".to_string())?;
|
||||
|
||||
// 备份旧内核
|
||||
// 替换阶段
|
||||
let _ = app.emit(
|
||||
"kernel-install-progress",
|
||||
InstallProgress {
|
||||
stage: "replacing".into(),
|
||||
percent: 96,
|
||||
downloaded_bytes: 0,
|
||||
total_bytes: None,
|
||||
message: "正在安装...".into(),
|
||||
},
|
||||
);
|
||||
let kernel = self.kernel_path();
|
||||
if kernel.exists() {
|
||||
let bak = self.cores_dir().join("mihomo.exe.bak");
|
||||
fs::remove_file(&bak).ok();
|
||||
fs::rename(&kernel, &bak).map_err(|e| format!("备份旧内核失败: {}", e))?;
|
||||
}
|
||||
|
||||
// 移动新内核
|
||||
fs::rename(&new_exe, &kernel).map_err(|e| format!("替换内核失败: {}", e))?;
|
||||
|
||||
// 清理临时文件
|
||||
fs::remove_file(&zip_path).ok();
|
||||
fs::remove_dir_all(&extract_dir).ok();
|
||||
|
||||
Ok(self.kernel_info())
|
||||
let final_info = self.kernel_info();
|
||||
let _ = app.emit(
|
||||
"kernel-install-progress",
|
||||
InstallProgress {
|
||||
stage: "done".into(),
|
||||
percent: 100,
|
||||
downloaded_bytes: 0,
|
||||
total_bytes: None,
|
||||
message: format!(
|
||||
"安装完成 ({})",
|
||||
final_info.version.as_deref().unwrap_or("unknown")
|
||||
),
|
||||
},
|
||||
);
|
||||
Ok(final_info)
|
||||
}
|
||||
|
||||
/// 流式下载并实时推送进度事件
|
||||
async fn download_with_progress(
|
||||
&self,
|
||||
app: &AppHandle,
|
||||
url: &str,
|
||||
dest: &PathBuf,
|
||||
) -> Result<(), String> {
|
||||
let resp = self
|
||||
.client
|
||||
.get(url)
|
||||
.header("User-Agent", "thing-app")
|
||||
.timeout(std::time::Duration::from_secs(30))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("请求失败: {}", e))?;
|
||||
if !resp.status().is_success() {
|
||||
return Err(format!("HTTP {}", resp.status()));
|
||||
}
|
||||
let total = resp.content_length();
|
||||
let mut stream = resp.bytes_stream();
|
||||
let mut file = fs::File::create(dest).map_err(|e| format!("创建文件失败: {}", e))?;
|
||||
let mut downloaded: u64 = 0;
|
||||
let mut last_percent: u8 = 0;
|
||||
while let Some(chunk) = stream.next().await {
|
||||
let chunk = chunk.map_err(|e| format!("读取流失败: {}", e))?;
|
||||
file.write_all(&chunk).map_err(|e| format!("写入文件失败: {}", e))?;
|
||||
downloaded += chunk.len() as u64;
|
||||
// 下载占总进度的 0-90%
|
||||
let percent = match total {
|
||||
Some(t) if t > 0 => ((downloaded as f64 / t as f64) * 90.0) as u8,
|
||||
_ => 0,
|
||||
};
|
||||
// 仅在变化超过 1% 时 emit,避免事件轰炸
|
||||
if percent >= last_percent + 1 {
|
||||
last_percent = percent;
|
||||
let _ = app.emit(
|
||||
"kernel-install-progress",
|
||||
InstallProgress {
|
||||
stage: "downloading".into(),
|
||||
percent,
|
||||
downloaded_bytes: downloaded,
|
||||
total_bytes: total,
|
||||
message: format!("已下载 {:.2} MB", downloaded as f64 / 1024.0 / 1024.0),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
file.flush().map_err(|e| format!("flush 失败: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 用 zip crate 解压(纯 Rust,避免 PowerShell 执行策略问题)
|
||||
fn extract_zip(&self, zip_path: &PathBuf, dest: &PathBuf) -> Result<(), String> {
|
||||
let file = fs::File::open(zip_path).map_err(|e| format!("打开 zip 失败: {}", e))?;
|
||||
let mut archive = zip::ZipArchive::new(file).map_err(|e| format!("读取 zip 失败: {}", e))?;
|
||||
for i in 0..archive.len() {
|
||||
let mut entry = archive
|
||||
.by_index(i)
|
||||
.map_err(|e| format!("读取条目失败: {}", e))?;
|
||||
let outpath = match entry.enclosed_name() {
|
||||
Some(p) => dest.join(p),
|
||||
None => continue,
|
||||
};
|
||||
if entry.is_dir() {
|
||||
fs::create_dir_all(&outpath).map_err(|e| e.to_string())?;
|
||||
} else {
|
||||
if let Some(parent) = outpath.parent() {
|
||||
fs::create_dir_all(parent).map_err(|e| e.to_string())?;
|
||||
}
|
||||
let mut outfile = fs::File::create(&outpath).map_err(|e| e.to_string())?;
|
||||
let mut buf = [0u8; 8192];
|
||||
loop {
|
||||
let n = entry.read(&mut buf).map_err(|e| e.to_string())?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
outfile.write_all(&buf[..n]).map_err(|e| e.to_string())?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 递归查找目录中的 .exe 文件
|
||||
/// mihomo zip 内的 exe 名字不固定(可能含版本号、CPU level 等),
|
||||
/// 策略:收集所有 .exe,优先返回名字含 "mihomo" 的,否则返回第一个
|
||||
fn find_exe_in_dir(&self, dir: &PathBuf) -> Option<PathBuf> {
|
||||
let mut exes: Vec<PathBuf> = Vec::new();
|
||||
self.collect_exes(dir, &mut exes);
|
||||
if exes.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// 优先选名字含 mihomo 的
|
||||
exes.iter()
|
||||
.find(|p| p.file_name().and_then(|n| n.to_str()).map(|s| s.to_lowercase().contains("mihomo")).unwrap_or(false))
|
||||
.or_else(|| exes.first())
|
||||
.cloned()
|
||||
}
|
||||
|
||||
fn collect_exes(&self, dir: &PathBuf, out: &mut Vec<PathBuf>) {
|
||||
if let Ok(entries) = fs::read_dir(dir) {
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
self.collect_exes(&path, out);
|
||||
} else if path.extension().and_then(|e| e.to_str()).map(|s| s.eq_ignore_ascii_case("exe")).unwrap_or(false) {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 配置生成 ----------
|
||||
@@ -848,8 +1147,22 @@ pub async fn proxy_check_kernel_update(
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn proxy_update_kernel(state: tauri::State<'_, MihomoManager>) -> Result<KernelInfo, String> {
|
||||
state.update_kernel().await
|
||||
pub async fn proxy_update_kernel(
|
||||
state: tauri::State<'_, MihomoManager>,
|
||||
app: AppHandle,
|
||||
mirror_prefix: Option<String>,
|
||||
) -> Result<KernelInfo, String> {
|
||||
state.install_kernel(&app, mirror_prefix.unwrap_or_default()).await
|
||||
}
|
||||
|
||||
/// 首次安装内核(与 update_kernel 共用 install_kernel 实现,语义独立便于前端区分场景)
|
||||
#[tauri::command]
|
||||
pub async fn proxy_install_kernel(
|
||||
state: tauri::State<'_, MihomoManager>,
|
||||
app: AppHandle,
|
||||
mirror_prefix: Option<String>,
|
||||
) -> Result<KernelInfo, String> {
|
||||
state.install_kernel(&app, mirror_prefix.unwrap_or_default()).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
|
||||
@@ -6,6 +6,24 @@ use std::thread;
|
||||
use std::time::Duration;
|
||||
use tauri::{AppHandle, Emitter, Manager};
|
||||
|
||||
// Windows 平台用于隐藏控制台窗口的标志位
|
||||
// CREATE_NO_WINDOW = 0x08000000,阻止子进程创建新的控制台窗口
|
||||
#[cfg(windows)]
|
||||
pub const CREATE_NO_WINDOW: u32 = 0x08000000;
|
||||
|
||||
/// 为 Command 设置平台特定的创建标志(Windows 上隐藏控制台窗口)
|
||||
/// 公开以便其他模块(如 mihomo_manager 调用 mihomo -v 查询版本)复用
|
||||
#[cfg(windows)]
|
||||
pub fn setup_creation_flags(cmd: &mut Command) {
|
||||
use std::os::windows::process::CommandExt;
|
||||
cmd.creation_flags(CREATE_NO_WINDOW);
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
pub fn setup_creation_flags(_cmd: &mut Command) {
|
||||
// 非 Windows 平台无需处理
|
||||
}
|
||||
|
||||
/// 进程状态枚举
|
||||
#[derive(Serialize, Clone, Debug)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
@@ -94,6 +112,8 @@ impl ProcessManager {
|
||||
cmd.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.stdin(Stdio::null());
|
||||
// Windows 上隐藏控制台窗口(mihomo.exe 是控制台程序,否则会弹黑框)
|
||||
setup_creation_flags(&mut cmd);
|
||||
|
||||
let child = cmd
|
||||
.spawn()
|
||||
@@ -123,6 +143,8 @@ impl ProcessManager {
|
||||
}
|
||||
|
||||
/// 停止指定进程
|
||||
/// kill 在主线程执行(快速),wait 移到后台线程执行避免阻塞前端
|
||||
/// Windows 上 kill 后 wait 可能需要等待子进程清理资源,有几十毫秒到几百毫秒延迟
|
||||
pub fn stop(&self, id: &str) -> Result<(), String> {
|
||||
let mut processes = self.processes.lock().map_err(|e| e.to_string())?;
|
||||
|
||||
@@ -131,7 +153,11 @@ impl ProcessManager {
|
||||
.child
|
||||
.kill()
|
||||
.map_err(|e| format!("终止进程 '{}' 失败: {}", id, e))?;
|
||||
let _ = entry.child.wait();
|
||||
// 后台等待子进程退出,避免阻塞当前调用线程(前端会感知卡顿)
|
||||
// child 已 move 进闭包,wait 在后台完成
|
||||
thread::spawn(move || {
|
||||
let _ = entry.child.wait();
|
||||
});
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("进程 '{}' 不存在", id))
|
||||
@@ -240,6 +266,7 @@ impl ProcessManager {
|
||||
cmd.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.stdin(Stdio::null());
|
||||
setup_creation_flags(&mut cmd);
|
||||
|
||||
match cmd.spawn() {
|
||||
Ok(new_child) => {
|
||||
|
||||
Reference in New Issue
Block a user