代理修改

This commit is contained in:
2026-07-18 17:46:21 +08:00
parent 2d9a8ddef6
commit e84958e0fc
71 changed files with 1221 additions and 134 deletions
+275 -1
View File
@@ -8,6 +8,17 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "aes"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
dependencies = [
"cfg-if",
"cipher",
"cpufeatures",
]
[[package]]
name = "aho-corasick"
version = "1.1.4"
@@ -47,6 +58,15 @@ version = "1.0.103"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3"
[[package]]
name = "arbitrary"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1"
dependencies = [
"derive_arbitrary",
]
[[package]]
name = "async-broadcast"
version = "0.7.2"
@@ -354,6 +374,25 @@ dependencies = [
"serde",
]
[[package]]
name = "bzip2"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49ecfb22d906f800d4fe833b6282cf4dc1c298f5057ca0b5445e5c209735ca47"
dependencies = [
"bzip2-sys",
]
[[package]]
name = "bzip2-sys"
version = "0.1.13+1.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "225bff33b2141874fe80d71e07d6eec4f85c5c216453dd96388240f96e1acc14"
dependencies = [
"cc",
"pkg-config",
]
[[package]]
name = "cairo-rs"
version = "0.18.5"
@@ -428,6 +467,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e17dd265a7d0f31ef544e1b20e03add05d3b45b491b633b10d67145d2acc1a38"
dependencies = [
"find-msvc-tools",
"jobserver",
"libc",
"shlex",
]
@@ -478,6 +519,16 @@ dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "cipher"
version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
dependencies = [
"crypto-common",
"inout",
]
[[package]]
name = "combine"
version = "4.6.7"
@@ -497,6 +548,12 @@ dependencies = [
"crossbeam-utils",
]
[[package]]
name = "constant_time_eq"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c74b8349d32d297c9134b8c88677813a227df8f779daa29bfc29c183fe3dca6"
[[package]]
name = "cookie"
version = "0.18.1"
@@ -566,6 +623,21 @@ dependencies = [
"libc",
]
[[package]]
name = "crc"
version = "3.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d"
dependencies = [
"crc-catalog",
]
[[package]]
name = "crc-catalog"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853"
[[package]]
name = "crc32fast"
version = "1.5.0"
@@ -684,6 +756,12 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "deflate64"
version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac6b926516df9c60bfa16e107b21086399f8285a44ca9711344b9e553c5146e2"
[[package]]
name = "deranged"
version = "0.5.8"
@@ -693,6 +771,17 @@ dependencies = [
"serde_core",
]
[[package]]
name = "derive_arbitrary"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.118",
]
[[package]]
name = "derive_more"
version = "2.1.1"
@@ -722,6 +811,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
"subtle",
]
[[package]]
@@ -1296,9 +1386,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
dependencies = [
"cfg-if",
"js-sys",
"libc",
"r-efi 5.3.0",
"wasip2",
"wasm-bindgen",
]
[[package]]
@@ -1515,6 +1607,15 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "hmac"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
dependencies = [
"digest",
]
[[package]]
name = "html5ever"
version = "0.38.0"
@@ -1816,6 +1917,15 @@ dependencies = [
"cfb",
]
[[package]]
name = "inout"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
dependencies = [
"generic-array",
]
[[package]]
name = "ipnet"
version = "2.12.0"
@@ -1914,6 +2024,16 @@ dependencies = [
"syn 2.0.118",
]
[[package]]
name = "jobserver"
version = "0.1.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"
dependencies = [
"getrandom 0.4.3",
"libc",
]
[[package]]
name = "js-sys"
version = "0.3.103"
@@ -2043,6 +2163,27 @@ version = "0.4.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
[[package]]
name = "lzma-rs"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "297e814c836ae64db86b36cf2a557ba54368d03f6afcd7d947c266692f71115e"
dependencies = [
"byteorder",
"crc",
]
[[package]]
name = "lzma-sys"
version = "0.1.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5fda04ab3764e6cde78b9974eec4f779acaba7c4e84b36eca3cf77c581b85d27"
dependencies = [
"cc",
"libc",
"pkg-config",
]
[[package]]
name = "markup5ever"
version = "0.38.0"
@@ -2526,6 +2667,16 @@ dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "pbkdf2"
version = "0.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2"
dependencies = [
"digest",
"hmac",
]
[[package]]
name = "percent-encoding"
version = "2.3.2"
@@ -2870,6 +3021,7 @@ dependencies = [
"bytes",
"encoding_rs",
"futures-core",
"futures-util",
"h2",
"http",
"http-body",
@@ -2891,12 +3043,14 @@ dependencies = [
"sync_wrapper",
"tokio",
"tokio-native-tls",
"tokio-util",
"tower",
"tower-http",
"tower-service",
"url",
"wasm-bindgen",
"wasm-bindgen-futures",
"wasm-streams 0.4.2",
"web-sys",
]
@@ -2930,7 +3084,7 @@ dependencies = [
"url",
"wasm-bindgen",
"wasm-bindgen-futures",
"wasm-streams",
"wasm-streams 0.5.0",
"web-sys",
]
@@ -3331,6 +3485,17 @@ dependencies = [
"stable_deref_trait",
]
[[package]]
name = "sha1"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "sha2"
version = "0.10.9"
@@ -3917,6 +4082,7 @@ name = "thing"
version = "0.1.0"
dependencies = [
"chrono",
"futures-util",
"reqwest 0.12.28",
"serde",
"serde_json",
@@ -3925,8 +4091,10 @@ dependencies = [
"tauri-build",
"tauri-plugin-autostart",
"tauri-plugin-opener",
"tokio",
"windows-sys 0.52.0",
"winreg 0.52.0",
"zip",
]
[[package]]
@@ -4553,6 +4721,19 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "wasm-streams"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65"
dependencies = [
"futures-util",
"js-sys",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
]
[[package]]
name = "wasm-streams"
version = "0.5.0"
@@ -5235,6 +5416,15 @@ dependencies = [
"pkg-config",
]
[[package]]
name = "xz2"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "388c44dc09d76f1536602ead6d325eb532f5c122f17782bd57fb47baeeb767e2"
dependencies = [
"lzma-sys",
]
[[package]]
name = "yoke"
version = "0.8.3"
@@ -5345,6 +5535,20 @@ name = "zeroize"
version = "1.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
dependencies = [
"zeroize_derive",
]
[[package]]
name = "zeroize_derive"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.118",
]
[[package]]
name = "zerotrie"
@@ -5379,12 +5583,82 @@ dependencies = [
"syn 2.0.118",
]
[[package]]
name = "zip"
version = "2.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50"
dependencies = [
"aes",
"arbitrary",
"bzip2",
"constant_time_eq",
"crc32fast",
"crossbeam-utils",
"deflate64",
"displaydoc",
"flate2",
"getrandom 0.3.4",
"hmac",
"indexmap 2.14.0",
"lzma-rs",
"memchr",
"pbkdf2",
"sha1",
"thiserror 2.0.18",
"time",
"xz2",
"zeroize",
"zopfli",
"zstd",
]
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zopfli"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249"
dependencies = [
"bumpalo",
"crc32fast",
"log",
"simd-adler32",
]
[[package]]
name = "zstd"
version = "0.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a"
dependencies = [
"zstd-safe",
]
[[package]]
name = "zstd-safe"
version = "7.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d"
dependencies = [
"zstd-sys",
]
[[package]]
name = "zstd-sys"
version = "2.0.16+zstd.1.5.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748"
dependencies = [
"cc",
"pkg-config",
]
[[package]]
name = "zvariant"
version = "5.13.0"
+4 -1
View File
@@ -24,7 +24,10 @@ serde = { version = "1", features = ["derive"] }
serde_json = "1"
serde_yaml = "0.9"
chrono = "0.4"
reqwest = { version = "0.12", features = ["json"] }
reqwest = { version = "0.12", features = ["json", "stream"] }
futures-util = "0.3"
tokio = { version = "1", features = ["io-util"] }
zip = "2"
[target.'cfg(windows)'.dependencies]
winreg = "0.52"
Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.6 KiB

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.0 KiB

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.0 KiB

After

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 KiB

After

Width:  |  Height:  |  Size: 3.4 KiB

@@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
<background android:drawable="@color/ic_launcher_background"/>
</adaptive-icon>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#fff</color>
</resources>
Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 76 KiB

After

Width:  |  Height:  |  Size: 130 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 919 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 231 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

+2 -1
View File
@@ -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
View File
@@ -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();
// 构造下载 URLmihomo 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 &current {
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]
+28 -1
View File
@@ -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) => {