Compare commits
17 Commits
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "clash-verge",
|
||||
"version": "0.0.15",
|
||||
"version": "0.0.16",
|
||||
"license": "GPL-3.0",
|
||||
"scripts": {
|
||||
"dev": "cargo tauri dev",
|
||||
@@ -32,7 +32,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@actions/github": "^5.0.0",
|
||||
"@tauri-apps/cli": "^1.0.0-rc.4",
|
||||
"@tauri-apps/cli": "^1.0.0-rc.5",
|
||||
"@types/fs-extra": "^9.0.13",
|
||||
"@types/js-cookie": "^3.0.1",
|
||||
"@types/react": "^17.0.0",
|
||||
|
||||
@@ -50,7 +50,7 @@ async function resolveSidecar() {
|
||||
const sidecarFile = `clash-${host}${ext}`;
|
||||
const sidecarPath = path.join(sidecarDir, sidecarFile);
|
||||
|
||||
if (!(await fs.pathExists(sidecarDir))) await fs.mkdir(sidecarDir);
|
||||
await fs.mkdirp(sidecarDir);
|
||||
if (await fs.pathExists(sidecarPath)) return;
|
||||
|
||||
// download sidecar
|
||||
@@ -59,7 +59,7 @@ async function resolveSidecar() {
|
||||
const tempZip = path.join(tempDir, binInfo.zipfile);
|
||||
const tempExe = path.join(tempDir, binInfo.exefile);
|
||||
|
||||
if (!(await fs.pathExists(tempDir))) await fs.mkdir(tempDir);
|
||||
await fs.mkdirp(tempDir);
|
||||
if (!(await fs.pathExists(tempZip))) await downloadFile(binInfo.url, tempZip);
|
||||
|
||||
if (binInfo.zip === "zip") {
|
||||
@@ -96,8 +96,10 @@ async function resolveMmdb() {
|
||||
const url =
|
||||
"https://github.com/Dreamacro/maxmind-geoip/releases/latest/download/Country.mmdb";
|
||||
|
||||
const resPath = path.join(cwd, "src-tauri", "resources", "Country.mmdb");
|
||||
const resDir = path.join(cwd, "src-tauri", "resources");
|
||||
const resPath = path.join(resDir, "Country.mmdb");
|
||||
if (await fs.pathExists(resPath)) return;
|
||||
await fs.mkdirp(resDir);
|
||||
await downloadFile(url, resPath);
|
||||
}
|
||||
|
||||
@@ -118,5 +120,5 @@ async function downloadFile(url, path) {
|
||||
}
|
||||
|
||||
/// main
|
||||
resolveSidecar();
|
||||
resolveMmdb();
|
||||
resolveSidecar().catch(console.error);
|
||||
resolveMmdb().catch(console.error);
|
||||
|
||||
41
src-tauri/Cargo.lock
generated
41
src-tauri/Cargo.lock
generated
@@ -3510,10 +3510,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri"
|
||||
version = "1.0.0-rc.2"
|
||||
version = "1.0.0-rc.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3571de0bcfd1f4f7599cbb3fe42f28ea9f52c3e89914ff04eaba68b5ee36bb51"
|
||||
checksum = "bb0c4a4ffd1f9b02cc3e974ce902f8132fb3d08ec6cce4ca193f97d921f5bce4"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"attohttpc",
|
||||
"base64",
|
||||
"bincode",
|
||||
@@ -3560,9 +3561,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-build"
|
||||
version = "1.0.0-rc.1"
|
||||
version = "1.0.0-rc.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a35ca6c70dce0dbe3441ab9e6d4ebae9a2315cfe8823662ac86cf517b22831e8"
|
||||
checksum = "855e47d8cfb2219fc14d2eed2c09bfb35f9ecd71a40ca2084aeeee2d23e0b60d"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"cargo_toml",
|
||||
@@ -3573,9 +3574,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-codegen"
|
||||
version = "1.0.0-rc.1"
|
||||
version = "1.0.0-rc.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d06ecdbd6beaf7348259f82885742f013c0c96ac139445ec7c4b8050cd18349"
|
||||
checksum = "eef4656d174ba982198266da0c016573fe6c7c760e4290f05c8c384fe180007e"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"blake3",
|
||||
@@ -3594,9 +3595,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-macros"
|
||||
version = "1.0.0-rc.1"
|
||||
version = "1.0.0-rc.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ba9ab86a4e81b31b227800c120b452dae137754e06d75b75c41c06cd06d301e2"
|
||||
checksum = "a0993f5a867e321d26200b2d6394cdf482bd6cc5a0e4691bcabf811544f51cd4"
|
||||
dependencies = [
|
||||
"heck 0.4.0",
|
||||
"proc-macro2",
|
||||
@@ -3630,9 +3631,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-runtime"
|
||||
version = "0.3.1"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c683b979ec4841b86048a282cd86afbc13b418a0f546904b27fad06e882ad5d7"
|
||||
checksum = "851cd65e2c9df4dd70a4f9e115fb2441ac89f1c80df79de0c15a448b4acd7768"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"http",
|
||||
@@ -3649,9 +3650,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-runtime-wry"
|
||||
version = "0.3.1"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec025e7c906451fd7ff9e46d106a2e1b5b73e48013d13d52ffce614212b63fdc"
|
||||
checksum = "0184f95e065fb80afadf53f0a5f87a75af2da774d0524fe8cb2976fbec4a0bf2"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"ico",
|
||||
@@ -3667,9 +3668,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-utils"
|
||||
version = "1.0.0-rc.1"
|
||||
version = "1.0.0-rc.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "abcbfec197c4cb959376607ac2fd99cecca02bd6d52b794bd882959501e34533"
|
||||
checksum = "0ad38ad698838886bf22ecb91c4b3d1ce178fdff7901ac7bff370103a4f51e59"
|
||||
dependencies = [
|
||||
"ctor",
|
||||
"glob",
|
||||
@@ -4309,9 +4310,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "webview2-com"
|
||||
version = "0.11.0"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1975ce3573344c099935fe3903f1708dac69efe8539f1efee3ae54d8f9315fbb"
|
||||
checksum = "bb8e90ac2d9ce39cdb70017aaec641be09fbdd702b7b332b9896d053eb469524"
|
||||
dependencies = [
|
||||
"webview2-com-macros",
|
||||
"webview2-com-sys",
|
||||
@@ -4332,9 +4333,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "webview2-com-sys"
|
||||
version = "0.11.0"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9a746838a94b7391f707209a246e3436d81d1e71832126a65a897d3ee5511040"
|
||||
checksum = "92160310b3322397e4ff8a8285a7429d73a07a68fda44ee80879605b93e53f76"
|
||||
dependencies = [
|
||||
"regex",
|
||||
"serde",
|
||||
@@ -4560,9 +4561,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wry"
|
||||
version = "0.13.1"
|
||||
version = "0.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "194b2750d8fe10fef189af5e2ca09e56cb8c5458a365d2b32842b024351f58c9"
|
||||
checksum = "620bfe8ed3cde9310f32a69ffc654dfd8dae4ac5a0e08d6fbf0205a996fc7f0f"
|
||||
dependencies = [
|
||||
"cocoa",
|
||||
"core-graphics",
|
||||
|
||||
@@ -10,7 +10,7 @@ edition = "2021"
|
||||
build = "build.rs"
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "1.0.0-rc.1", features = [] }
|
||||
tauri-build = { version = "1.0.0-rc.3", features = [] }
|
||||
|
||||
[dependencies]
|
||||
dirs = "4.0.0"
|
||||
@@ -18,7 +18,7 @@ chrono = "0.4.19"
|
||||
serde_json = "1.0"
|
||||
serde_yaml = "0.8"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
tauri = { version = "1.0.0-rc.2", features = ["shell-all", "system-tray", "updater", "window-all"] }
|
||||
tauri = { version = "1.0.0-rc.3", features = ["shell-all", "system-tray", "updater", "window-all"] }
|
||||
tauri-plugin-shadows = { git = "https://github.com/tauri-apps/tauri-plugin-shadows", features = ["tauri-impl"] }
|
||||
tauri-plugin-vibrancy = { git = "https://github.com/tauri-apps/tauri-plugin-vibrancy", features = ["tauri-impl"] }
|
||||
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
# Default Config For Clash Core
|
||||
|
||||
mixed-port: 7890
|
||||
log-level: info
|
||||
allow-lan: false
|
||||
external-controller: 127.0.0.1:9090
|
||||
mode: rule
|
||||
secret: ""
|
||||
@@ -1,16 +0,0 @@
|
||||
# Profile Template for clash verge
|
||||
|
||||
# the profile's name
|
||||
name: New Profile
|
||||
|
||||
# the description of this profile(optional)
|
||||
description:
|
||||
|
||||
# proxies defination (optional, the same as clash)
|
||||
proxies:
|
||||
|
||||
# proxy-groups (optional, the same as clash)
|
||||
proxy-groups:
|
||||
|
||||
# rules (optional, the same as clash)
|
||||
rules:
|
||||
@@ -1,3 +0,0 @@
|
||||
# Profiles Config for Clash Verge
|
||||
|
||||
current: 0
|
||||
@@ -1,6 +0,0 @@
|
||||
# Defaulf Config For Clash Verge
|
||||
|
||||
theme_mode: light
|
||||
enable_self_startup: false
|
||||
enable_system_proxy: false
|
||||
system_proxy_bypass: localhost;127.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;192.168.*;<local>
|
||||
@@ -5,7 +5,7 @@ use crate::{
|
||||
};
|
||||
use serde_yaml::Mapping;
|
||||
use std::process::Command;
|
||||
use tauri::State;
|
||||
use tauri::{api, State};
|
||||
|
||||
/// get all profiles from `profiles.yaml`
|
||||
/// do not acquire the lock of ProfileLock
|
||||
@@ -34,13 +34,9 @@ pub async fn import_profile(
|
||||
with_proxy: bool,
|
||||
profiles_state: State<'_, ProfilesState>,
|
||||
) -> Result<(), String> {
|
||||
match fetch_profile(&url, with_proxy).await {
|
||||
Some(result) => {
|
||||
let mut profiles = profiles_state.0.lock().unwrap();
|
||||
profiles.import_from_url(url, result)
|
||||
}
|
||||
None => Err(format!("failed to fetch profile from `{}`", url)),
|
||||
}
|
||||
let result = fetch_profile(&url, with_proxy).await?;
|
||||
let mut profiles = profiles_state.0.lock().unwrap();
|
||||
profiles.import_from_url(url, result)
|
||||
}
|
||||
|
||||
/// new a profile
|
||||
@@ -82,23 +78,22 @@ pub async fn update_profile(
|
||||
Err(_) => return Err("failed to get profiles lock".into()),
|
||||
};
|
||||
|
||||
match fetch_profile(&url, with_proxy).await {
|
||||
Some(result) => match profiles_state.0.lock() {
|
||||
Ok(mut profiles) => {
|
||||
profiles.update_item(index, result)?;
|
||||
let result = fetch_profile(&url, with_proxy).await?;
|
||||
|
||||
// reactivate the profile
|
||||
let current = profiles.current.clone().unwrap_or(0);
|
||||
if current == index {
|
||||
let clash = clash_state.0.lock().unwrap();
|
||||
profiles.activate(&clash)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
match profiles_state.0.lock() {
|
||||
Ok(mut profiles) => {
|
||||
profiles.update_item(index, result)?;
|
||||
|
||||
// reactivate the profile
|
||||
let current = profiles.current.clone().unwrap_or(0);
|
||||
if current == index {
|
||||
let clash = clash_state.0.lock().unwrap();
|
||||
profiles.activate(&clash)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
Err(_) => Err("failed to get profiles lock".into()),
|
||||
},
|
||||
None => Err(format!("failed to fetch profile from `{}`", url)),
|
||||
}
|
||||
Err(_) => Err("failed to get profiles lock".into()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -265,7 +260,7 @@ pub fn get_verge_config(verge_state: State<'_, VergeState>) -> Result<VergeConfi
|
||||
/// patch the verge config
|
||||
/// this command only save the config and not responsible for other things
|
||||
#[tauri::command]
|
||||
pub async fn patch_verge_config(
|
||||
pub fn patch_verge_config(
|
||||
payload: VergeConfig,
|
||||
verge_state: State<'_, VergeState>,
|
||||
) -> Result<(), String> {
|
||||
@@ -273,6 +268,12 @@ pub async fn patch_verge_config(
|
||||
verge.patch_config(payload)
|
||||
}
|
||||
|
||||
/// kill all sidecars when update app
|
||||
#[tauri::command]
|
||||
pub fn kill_sidecars() {
|
||||
api::process::kill_children();
|
||||
}
|
||||
|
||||
/// open app config dir
|
||||
#[tauri::command]
|
||||
pub fn open_app_dir() -> Result<(), String> {
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
use super::{Clash, ClashInfo};
|
||||
use crate::utils::{config, dirs};
|
||||
use crate::utils::{config, dirs, tmpl};
|
||||
use reqwest::header::HeaderMap;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_yaml::{Mapping, Value};
|
||||
use std::collections::HashMap;
|
||||
use std::env::temp_dir;
|
||||
use std::fs::File;
|
||||
use std::fs::{remove_file, File};
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
@@ -60,7 +60,7 @@ pub struct ProfileResponse {
|
||||
pub name: String,
|
||||
pub file: String,
|
||||
pub data: String,
|
||||
pub extra: ProfileExtra,
|
||||
pub extra: Option<ProfileExtra>,
|
||||
}
|
||||
|
||||
static PROFILE_YAML: &str = "profiles.yaml";
|
||||
@@ -117,7 +117,7 @@ impl Profiles {
|
||||
mode: Some(format!("rule")),
|
||||
url: Some(url),
|
||||
selected: Some(vec![]),
|
||||
extra: Some(result.extra),
|
||||
extra: result.extra,
|
||||
updated: Some(now as usize),
|
||||
});
|
||||
|
||||
@@ -155,16 +155,7 @@ impl Profiles {
|
||||
let file = format!("{}.yaml", now);
|
||||
let path = dirs::app_home_dir().join("profiles").join(&file);
|
||||
|
||||
let file_data = b"# Profile Template for clash verge\n
|
||||
# proxies defination (optional, the same as clash)
|
||||
proxies:\n
|
||||
# proxy-groups (optional, the same as clash)
|
||||
proxy-groups:\n
|
||||
# rules (optional, the same as clash)
|
||||
rules:\n\n
|
||||
";
|
||||
|
||||
match File::create(&path).unwrap().write(file_data) {
|
||||
match File::create(&path).unwrap().write(tmpl::ITEM_CONFIG) {
|
||||
Ok(_) => {
|
||||
items.push(ProfileItem {
|
||||
name: Some(name),
|
||||
@@ -203,7 +194,7 @@ rules:\n\n
|
||||
File::create(file_path).unwrap().write(file_data).unwrap();
|
||||
|
||||
items[index].name = Some(result.name);
|
||||
items[index].extra = Some(result.extra);
|
||||
items[index].extra = result.extra;
|
||||
items[index].updated = Some(now);
|
||||
|
||||
self.items = Some(items);
|
||||
@@ -249,7 +240,18 @@ rules:\n\n
|
||||
return Err("index out of bound".into());
|
||||
}
|
||||
|
||||
items.remove(index);
|
||||
let mut rm_item = items.remove(index);
|
||||
|
||||
// delete the file
|
||||
if let Some(file) = rm_item.file.take() {
|
||||
let file_path = dirs::app_home_dir().join("profiles").join(file);
|
||||
|
||||
if file_path.exists() {
|
||||
if let Err(err) = remove_file(file_path) {
|
||||
log::error!("{err}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut should_change = false;
|
||||
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
use crate::utils::{config, dirs, sysopt::SysProxyConfig};
|
||||
use crate::{
|
||||
core::Clash,
|
||||
utils::{config, dirs, sysopt::SysProxyConfig},
|
||||
};
|
||||
use auto_launch::{AutoLaunch, AutoLaunchBuilder};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tauri::api::path::resource_dir;
|
||||
use std::sync::Arc;
|
||||
use tauri::{api::path::resource_dir, async_runtime::Mutex};
|
||||
|
||||
/// ### `verge.yaml` schema
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
@@ -13,14 +17,23 @@ pub struct VergeConfig {
|
||||
/// maybe be able to set the alpha
|
||||
pub theme_blur: Option<bool>,
|
||||
|
||||
/// enable traffic graph default is true
|
||||
pub traffic_graph: Option<bool>,
|
||||
|
||||
/// can the app auto startup
|
||||
pub enable_auto_launch: Option<bool>,
|
||||
|
||||
/// set system proxy
|
||||
pub enable_system_proxy: Option<bool>,
|
||||
|
||||
/// enable proxy guard
|
||||
pub enable_proxy_guard: Option<bool>,
|
||||
|
||||
/// set system proxy bypass
|
||||
pub system_proxy_bypass: Option<String>,
|
||||
|
||||
/// proxy guard duration
|
||||
pub proxy_guard_duration: Option<u64>,
|
||||
}
|
||||
|
||||
static VERGE_CONFIG: &str = "verge.yaml";
|
||||
@@ -50,6 +63,9 @@ pub struct Verge {
|
||||
pub cur_sysproxy: Option<SysProxyConfig>,
|
||||
|
||||
pub auto_launch: Option<AutoLaunch>,
|
||||
|
||||
/// record whether the guard async is running or not
|
||||
guard_state: Arc<Mutex<bool>>,
|
||||
}
|
||||
|
||||
impl Default for Verge {
|
||||
@@ -65,6 +81,7 @@ impl Verge {
|
||||
old_sysproxy: None,
|
||||
cur_sysproxy: None,
|
||||
auto_launch: None,
|
||||
guard_state: Arc::new(Mutex::new(false)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,6 +106,9 @@ impl Verge {
|
||||
|
||||
self.cur_sysproxy = Some(sysproxy);
|
||||
}
|
||||
|
||||
// launchs the system proxy guard
|
||||
Verge::guard_proxy(self.guard_state.clone());
|
||||
}
|
||||
|
||||
/// reset the sysproxy
|
||||
@@ -151,10 +171,9 @@ impl Verge {
|
||||
|
||||
let auto_launch = self.auto_launch.clone().unwrap();
|
||||
|
||||
let result = if enable {
|
||||
auto_launch.enable()
|
||||
} else {
|
||||
auto_launch.disable()
|
||||
let result = match enable {
|
||||
true => auto_launch.enable(),
|
||||
false => auto_launch.disable(),
|
||||
};
|
||||
|
||||
match result {
|
||||
@@ -166,24 +185,6 @@ impl Verge {
|
||||
}
|
||||
}
|
||||
|
||||
// fn guard_thread(&mut self) -> Result<(), String> {
|
||||
// let sysproxy = self.cur_sysproxy.clone();
|
||||
|
||||
// use std::{thread, time};
|
||||
// tauri::async_runtime::spawn(async move {
|
||||
// if let Some(sysproxy) = sysproxy {
|
||||
// sysproxy.set_sys();
|
||||
// }
|
||||
|
||||
// let ten_millis = time::Duration::from_millis(10);
|
||||
// let now = time::Instant::now();
|
||||
|
||||
// thread::sleep(ten_millis);
|
||||
// });
|
||||
|
||||
// Ok(())
|
||||
// }
|
||||
|
||||
/// patch verge config
|
||||
/// There should be only one update at a time here
|
||||
/// so call the save_file at the end is savely
|
||||
@@ -195,6 +196,9 @@ impl Verge {
|
||||
if patch.theme_blur.is_some() {
|
||||
self.config.theme_blur = patch.theme_blur;
|
||||
}
|
||||
if patch.traffic_graph.is_some() {
|
||||
self.config.traffic_graph = patch.traffic_graph;
|
||||
}
|
||||
|
||||
// should update system startup
|
||||
if patch.enable_auto_launch.is_some() {
|
||||
@@ -206,9 +210,12 @@ impl Verge {
|
||||
// should update system proxy
|
||||
if patch.enable_system_proxy.is_some() {
|
||||
let enable = patch.enable_system_proxy.unwrap();
|
||||
|
||||
if let Some(mut sysproxy) = self.cur_sysproxy.take() {
|
||||
sysproxy.enable = enable;
|
||||
if sysproxy.set_sys().is_err() {
|
||||
self.cur_sysproxy = Some(sysproxy);
|
||||
|
||||
log::error!("failed to set system proxy");
|
||||
return Err("failed to set system proxy".into());
|
||||
}
|
||||
@@ -217,16 +224,107 @@ impl Verge {
|
||||
self.config.enable_system_proxy = Some(enable);
|
||||
}
|
||||
|
||||
// todo
|
||||
// should update system proxy too
|
||||
if patch.system_proxy_bypass.is_some() {
|
||||
self.config.system_proxy_bypass = patch.system_proxy_bypass;
|
||||
let bypass = patch.system_proxy_bypass.unwrap();
|
||||
|
||||
if let Some(mut sysproxy) = self.cur_sysproxy.take() {
|
||||
if sysproxy.enable {
|
||||
sysproxy.bypass = bypass.clone();
|
||||
|
||||
if sysproxy.set_sys().is_err() {
|
||||
self.cur_sysproxy = Some(sysproxy);
|
||||
|
||||
log::error!("failed to set system proxy");
|
||||
return Err("failed to set system proxy".into());
|
||||
}
|
||||
}
|
||||
|
||||
self.cur_sysproxy = Some(sysproxy);
|
||||
}
|
||||
|
||||
self.config.system_proxy_bypass = Some(bypass);
|
||||
}
|
||||
|
||||
// proxy guard
|
||||
// only change it
|
||||
if patch.enable_proxy_guard.is_some() {
|
||||
self.config.enable_proxy_guard = patch.enable_proxy_guard;
|
||||
}
|
||||
if patch.proxy_guard_duration.is_some() {
|
||||
self.config.proxy_guard_duration = patch.proxy_guard_duration;
|
||||
}
|
||||
|
||||
// relaunch the guard
|
||||
if patch.enable_system_proxy.is_some() || patch.enable_proxy_guard.is_some() {
|
||||
Verge::guard_proxy(self.guard_state.clone());
|
||||
}
|
||||
|
||||
self.config.save_file()
|
||||
}
|
||||
}
|
||||
|
||||
impl Verge {
|
||||
/// launch a system proxy guard
|
||||
/// read config from file directly
|
||||
pub fn guard_proxy(guard_state: Arc<Mutex<bool>>) {
|
||||
use tokio::time::{sleep, Duration};
|
||||
|
||||
tauri::async_runtime::spawn(async move {
|
||||
// if it is running, exit
|
||||
let mut state = guard_state.lock().await;
|
||||
if *state {
|
||||
return;
|
||||
}
|
||||
*state = true;
|
||||
std::mem::drop(state);
|
||||
|
||||
// default duration is 10s
|
||||
let mut wait_secs = 10u64;
|
||||
|
||||
loop {
|
||||
sleep(Duration::from_secs(wait_secs)).await;
|
||||
|
||||
log::debug!("[Guard]: heartbeat detection");
|
||||
|
||||
let verge = Verge::new();
|
||||
|
||||
let enable_proxy = verge.config.enable_system_proxy.unwrap_or(false);
|
||||
let enable_guard = verge.config.enable_proxy_guard.unwrap_or(false);
|
||||
let guard_duration = verge.config.proxy_guard_duration.unwrap_or(10);
|
||||
|
||||
// update duration
|
||||
wait_secs = guard_duration;
|
||||
|
||||
// stop loop
|
||||
if !enable_guard || !enable_proxy {
|
||||
break;
|
||||
}
|
||||
|
||||
log::info!("[Guard]: try to guard proxy");
|
||||
|
||||
let clash = Clash::new();
|
||||
|
||||
match &clash.info.port {
|
||||
Some(port) => {
|
||||
let bypass = verge.config.system_proxy_bypass.clone();
|
||||
let sysproxy = SysProxyConfig::new(true, port.clone(), bypass);
|
||||
|
||||
if let Err(err) = sysproxy.set_sys() {
|
||||
log::error!("[Guard]: {err}");
|
||||
log::error!("[Guard]: fail to set system proxy");
|
||||
}
|
||||
}
|
||||
None => log::error!("[Guard]: fail to parse clash port"),
|
||||
}
|
||||
}
|
||||
|
||||
let mut state = guard_state.lock().await;
|
||||
*state = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Get the target app_path
|
||||
fn get_app_path(app_name: &str) -> String {
|
||||
#[cfg(target_os = "linux")]
|
||||
|
||||
@@ -74,6 +74,7 @@ fn main() -> std::io::Result<()> {
|
||||
cmds::restart_sidecar,
|
||||
cmds::get_sys_proxy,
|
||||
cmds::get_cur_proxy,
|
||||
cmds::kill_sidecars,
|
||||
cmds::open_app_dir,
|
||||
cmds::open_logs_dir,
|
||||
// clash
|
||||
|
||||
@@ -22,66 +22,63 @@ fn parse_string<T: FromStr>(target: &str, key: &str) -> Option<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// fetch and parse the profile
|
||||
pub async fn fetch_profile(url: &str, with_proxy: bool) -> Option<ProfileResponse> {
|
||||
/// fetch and parse the profile url
|
||||
/// maybe it contains some Subscription infomations, maybe not
|
||||
pub async fn fetch_profile(url: &str, with_proxy: bool) -> Result<ProfileResponse, String> {
|
||||
let builder = reqwest::ClientBuilder::new();
|
||||
let client = match with_proxy {
|
||||
true => builder.build(),
|
||||
false => builder.no_proxy().build(),
|
||||
};
|
||||
let resp = match client {
|
||||
Ok(client) => match client.get(url).send().await {
|
||||
Ok(res) => res,
|
||||
Err(_) => return None,
|
||||
},
|
||||
Err(_) => return None,
|
||||
|
||||
let resp = match client.unwrap().get(url).send().await {
|
||||
Ok(res) => res,
|
||||
Err(_) => return Err("failed to create https client".into()),
|
||||
};
|
||||
|
||||
let header = resp.headers();
|
||||
|
||||
// parse the Subscription Userinfo
|
||||
let extra = {
|
||||
let sub_info = match header.get("Subscription-Userinfo") {
|
||||
Some(value) => value.to_str().unwrap_or(""),
|
||||
None => "",
|
||||
};
|
||||
let extra = match header.get("Subscription-Userinfo") {
|
||||
Some(value) => {
|
||||
let sub_info = value.to_str().unwrap_or("");
|
||||
|
||||
ProfileExtra {
|
||||
upload: parse_string(sub_info, "upload=").unwrap_or(0),
|
||||
download: parse_string(sub_info, "download=").unwrap_or(0),
|
||||
total: parse_string(sub_info, "total=").unwrap_or(0),
|
||||
expire: parse_string(sub_info, "expire=").unwrap_or(0),
|
||||
Some(ProfileExtra {
|
||||
upload: parse_string(sub_info, "upload=").unwrap_or(0),
|
||||
download: parse_string(sub_info, "download=").unwrap_or(0),
|
||||
total: parse_string(sub_info, "total=").unwrap_or(0),
|
||||
expire: parse_string(sub_info, "expire=").unwrap_or(0),
|
||||
})
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
|
||||
// parse the `name` and `file`
|
||||
let (name, file) = {
|
||||
let file = {
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs();
|
||||
let file = format!("{}.yaml", now);
|
||||
let name = header.get("Content-Disposition").unwrap().to_str().unwrap();
|
||||
let name = parse_string::<String>(name, "filename=");
|
||||
format!("{}.yaml", now)
|
||||
};
|
||||
|
||||
match name {
|
||||
Some(f) => (f, file),
|
||||
None => (file.clone(), file),
|
||||
let name = match header.get("Content-Disposition") {
|
||||
Some(name) => {
|
||||
let name = name.to_str().unwrap();
|
||||
parse_string::<String>(name, "filename=").unwrap_or(file.clone())
|
||||
}
|
||||
None => file.clone(),
|
||||
};
|
||||
|
||||
// get the data
|
||||
let data = match resp.text_with_charset("utf-8").await {
|
||||
Ok(d) => d,
|
||||
Err(_) => return None,
|
||||
};
|
||||
|
||||
Some(ProfileResponse {
|
||||
file,
|
||||
name,
|
||||
data,
|
||||
extra,
|
||||
})
|
||||
match resp.text_with_charset("utf-8").await {
|
||||
Ok(data) => Ok(ProfileResponse {
|
||||
file,
|
||||
name,
|
||||
data,
|
||||
extra,
|
||||
}),
|
||||
Err(_) => Err("failed to parse the response data".into()),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
extern crate serde_yaml;
|
||||
|
||||
use crate::utils::dirs;
|
||||
use crate::utils::{dirs, tmpl};
|
||||
use chrono::Local;
|
||||
use log::LevelFilter;
|
||||
use log4rs::append::console::ConsoleAppender;
|
||||
@@ -41,44 +41,22 @@ fn init_log(log_dir: &PathBuf) {
|
||||
}
|
||||
|
||||
/// Initialize all the files from resources
|
||||
fn init_config_file(app_dir: &PathBuf, res_dir: &PathBuf) {
|
||||
fn init_config(app_dir: &PathBuf) -> std::io::Result<()> {
|
||||
// target path
|
||||
let clash_path = app_dir.join("config.yaml");
|
||||
let verge_path = app_dir.join("verge.yaml");
|
||||
let profile_path = app_dir.join("profiles.yaml");
|
||||
let mmdb_path = app_dir.join("Country.mmdb");
|
||||
|
||||
// template path
|
||||
let clash_tmpl = res_dir.join("config_tmp.yaml");
|
||||
let verge_tmpl = res_dir.join("verge_tmp.yaml");
|
||||
let profiles_tmpl = res_dir.join("profiles_tmp.yaml");
|
||||
let mmdb_tmpl = res_dir.join("Country.mmdb");
|
||||
|
||||
if !clash_path.exists() {
|
||||
if clash_tmpl.exists() {
|
||||
fs::copy(clash_tmpl, clash_path).unwrap();
|
||||
} else {
|
||||
// make sure that the config.yaml not null
|
||||
let content = b"\
|
||||
mixed-port: 7890\n\
|
||||
log-level: info\n\
|
||||
allow-lan: false\n\
|
||||
external-controller: 127.0.0.1:9090\n\
|
||||
secret: \"\"\n";
|
||||
File::create(clash_path).unwrap().write(content).unwrap();
|
||||
}
|
||||
File::create(clash_path)?.write(tmpl::CLASH_CONFIG)?;
|
||||
}
|
||||
|
||||
// only copy it
|
||||
if !verge_path.exists() && verge_tmpl.exists() {
|
||||
fs::copy(verge_tmpl, verge_path).unwrap();
|
||||
if !verge_path.exists() {
|
||||
File::create(verge_path)?.write(tmpl::VERGE_CONFIG)?;
|
||||
}
|
||||
if !profile_path.exists() && profiles_tmpl.exists() {
|
||||
fs::copy(profiles_tmpl, profile_path).unwrap();
|
||||
}
|
||||
if !mmdb_path.exists() && mmdb_tmpl.exists() {
|
||||
fs::copy(mmdb_tmpl, mmdb_path).unwrap();
|
||||
if !profile_path.exists() {
|
||||
File::create(profile_path)?.write(tmpl::PROFILES_CONFIG)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// initialize app
|
||||
@@ -101,5 +79,14 @@ pub fn init_app(package_info: &PackageInfo) {
|
||||
}
|
||||
|
||||
init_log(&log_dir);
|
||||
init_config_file(&app_dir, &res_dir);
|
||||
if let Err(err) = init_config(&app_dir) {
|
||||
log::error!("{err}");
|
||||
}
|
||||
|
||||
// copy the resource file
|
||||
let mmdb_path = app_dir.join("Country.mmdb");
|
||||
let mmdb_tmpl = res_dir.join("Country.mmdb");
|
||||
if !mmdb_path.exists() && mmdb_tmpl.exists() {
|
||||
fs::copy(mmdb_tmpl, mmdb_path).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,3 +5,4 @@ pub mod init;
|
||||
pub mod resolve;
|
||||
pub mod server;
|
||||
pub mod sysopt;
|
||||
pub mod tmpl;
|
||||
|
||||
@@ -1,24 +1,10 @@
|
||||
use super::{init, server};
|
||||
use crate::{core::Profiles, states};
|
||||
use tauri::{App, AppHandle, Manager};
|
||||
use tauri_plugin_shadows::Shadows;
|
||||
|
||||
/// handle something when start app
|
||||
pub fn resolve_setup(app: &App) {
|
||||
// set shadow when window decorations
|
||||
let window = app.get_window("main").unwrap();
|
||||
window.set_shadow(true);
|
||||
|
||||
// enable system blur
|
||||
use tauri_plugin_vibrancy::Vibrancy;
|
||||
#[cfg(target_os = "windows")]
|
||||
window.apply_blur();
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
use tauri_plugin_vibrancy::MacOSVibrancy;
|
||||
#[allow(deprecated)]
|
||||
window.apply_vibrancy(MacOSVibrancy::AppearanceBased);
|
||||
}
|
||||
resolve_window(app);
|
||||
|
||||
// setup a simple http server for singleton
|
||||
server::embed_server(&app.handle());
|
||||
@@ -58,3 +44,34 @@ pub fn resolve_reset(app_handle: &AppHandle) {
|
||||
|
||||
verge.reset_sysproxy();
|
||||
}
|
||||
|
||||
/// customize the window theme
|
||||
fn resolve_window(app: &App) {
|
||||
let window = app.get_window("main").unwrap();
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
use tauri_plugin_shadows::Shadows;
|
||||
use tauri_plugin_vibrancy::Vibrancy;
|
||||
|
||||
window.set_decorations(false).unwrap();
|
||||
window.set_shadow(true);
|
||||
window.apply_blur();
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
use tauri::LogicalSize;
|
||||
use tauri::Size::Logical;
|
||||
window.set_decorations(true).unwrap();
|
||||
window
|
||||
.set_size(Logical(LogicalSize {
|
||||
width: 800.0,
|
||||
height: 610.0,
|
||||
}))
|
||||
.unwrap();
|
||||
// use tauri_plugin_vibrancy::MacOSVibrancy;
|
||||
// #[allow(deprecated)]
|
||||
// window.apply_vibrancy(MacOSVibrancy::AppearanceBased);
|
||||
}
|
||||
}
|
||||
|
||||
42
src-tauri/src/utils/tmpl.rs
Normal file
42
src-tauri/src/utils/tmpl.rs
Normal file
@@ -0,0 +1,42 @@
|
||||
///! Some config file template
|
||||
|
||||
/// template for clash core `config.yaml`
|
||||
pub const CLASH_CONFIG: &[u8] = br#"# Default Config For Clash Core
|
||||
|
||||
mixed-port: 7890
|
||||
log-level: info
|
||||
allow-lan: false
|
||||
external-controller: 127.0.0.1:9090
|
||||
mode: rule
|
||||
secret: ""
|
||||
"#;
|
||||
|
||||
/// template for `profiles.yaml`
|
||||
pub const PROFILES_CONFIG: &[u8] = b"# Profiles Config for Clash Verge
|
||||
|
||||
current: 0
|
||||
items: ~
|
||||
";
|
||||
|
||||
/// template for `verge.yaml`
|
||||
pub const VERGE_CONFIG: &[u8] = b"# Defaulf Config For Clash Verge
|
||||
|
||||
theme_mode: light
|
||||
theme_blur: false
|
||||
traffic_graph: true
|
||||
enable_self_startup: false
|
||||
enable_system_proxy: false
|
||||
enable_proxy_guard: false
|
||||
proxy_guard_duration: 10
|
||||
system_proxy_bypass: localhost;127.*;10.*;192.168.*;<local>
|
||||
";
|
||||
|
||||
/// template for new a profile item
|
||||
pub const ITEM_CONFIG: &[u8] = b"# Profile Template for clash verge\n\n
|
||||
# proxies defination (optional, the same as clash)
|
||||
proxies:\n
|
||||
# proxy-groups (optional, the same as clash)
|
||||
proxy-groups:\n
|
||||
# rules (optional, the same as clash)
|
||||
rules:\n\n
|
||||
";
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"package": {
|
||||
"productName": "clash-verge",
|
||||
"version": "0.0.15"
|
||||
"version": "0.0.16"
|
||||
},
|
||||
"build": {
|
||||
"distDir": "../dist",
|
||||
|
||||
@@ -4,6 +4,7 @@ body {
|
||||
"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
|
||||
sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
:root {
|
||||
|
||||
@@ -20,8 +20,8 @@
|
||||
position: relative;
|
||||
flex: 0 1 180px;
|
||||
width: 100%;
|
||||
max-width: 180px;
|
||||
max-height: 180px;
|
||||
max-width: 168px;
|
||||
max-height: 168px;
|
||||
margin: 0 auto;
|
||||
padding: 0 8px;
|
||||
text-align: center;
|
||||
@@ -79,3 +79,9 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.macos.layout {
|
||||
.layout__right .the-content {
|
||||
top: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,23 @@
|
||||
import useSWR from "swr";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useRecoilValue } from "recoil";
|
||||
import { Box, Typography } from "@mui/material";
|
||||
import { ArrowDownward, ArrowUpward } from "@mui/icons-material";
|
||||
import { getInfomation } from "../../services/api";
|
||||
import { ApiType } from "../../services/types";
|
||||
import { getInfomation } from "../../services/api";
|
||||
import { getVergeConfig } from "../../services/cmds";
|
||||
import { atomClashPort } from "../../states/setting";
|
||||
import parseTraffic from "../../utils/parse-traffic";
|
||||
import useTrafficGraph from "./use-traffic-graph";
|
||||
|
||||
const LayoutTraffic = () => {
|
||||
const portValue = useRecoilValue(atomClashPort);
|
||||
const [traffic, setTraffic] = useState({ up: 0, down: 0 });
|
||||
const { canvasRef, appendData, toggleStyle } = useTrafficGraph();
|
||||
|
||||
// whether hide traffic graph
|
||||
const { data } = useSWR("getVergeConfig", getVergeConfig);
|
||||
const trafficGraph = data?.traffic_graph ?? true;
|
||||
|
||||
useEffect(() => {
|
||||
let ws: WebSocket | null = null;
|
||||
@@ -19,7 +27,9 @@ const LayoutTraffic = () => {
|
||||
ws = new WebSocket(`ws://${server}/traffic?token=${secret}`);
|
||||
|
||||
ws.addEventListener("message", (event) => {
|
||||
setTraffic(JSON.parse(event.data) as ApiType.TrafficItem);
|
||||
const data = JSON.parse(event.data) as ApiType.TrafficItem;
|
||||
appendData(data);
|
||||
setTraffic(data);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -44,7 +54,14 @@ const LayoutTraffic = () => {
|
||||
};
|
||||
|
||||
return (
|
||||
<Box width="110px">
|
||||
<Box width="110px" position="relative" onClick={toggleStyle}>
|
||||
{trafficGraph && (
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
style={{ width: "100%", height: 60, marginBottom: 6 }}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Box mb={1.5} display="flex" alignItems="center" whiteSpace="nowrap">
|
||||
<ArrowUpward
|
||||
fontSize="small"
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
DialogContentText,
|
||||
DialogTitle,
|
||||
} from "@mui/material";
|
||||
import { killSidecars } from "../../services/cmds";
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
@@ -31,6 +32,7 @@ const UpdateDialog = (props: Props) => {
|
||||
try {
|
||||
setUploading(true);
|
||||
uploadingState = true;
|
||||
await killSidecars();
|
||||
await installUpdate();
|
||||
await relaunch();
|
||||
} catch (error) {
|
||||
|
||||
146
src/components/layout/use-traffic-graph.ts
Normal file
146
src/components/layout/use-traffic-graph.ts
Normal file
@@ -0,0 +1,146 @@
|
||||
import { useRef } from "react";
|
||||
|
||||
const minPoint = 10;
|
||||
const maxPoint = 36;
|
||||
|
||||
const refLineAlpha = 0.5;
|
||||
const refLineWidth = 2;
|
||||
const refLineColor = "#ccc";
|
||||
|
||||
const upLineAlpha = 0.6;
|
||||
const upLineWidth = 4;
|
||||
const upLineColor = "#9c27b0";
|
||||
|
||||
const downLineAlpha = 1;
|
||||
const downLineWidth = 4;
|
||||
const downLineColor = "#5b5c9d";
|
||||
|
||||
/**
|
||||
* draw the traffic graph
|
||||
*/
|
||||
export default function useTrafficGraph() {
|
||||
type TrafficData = { up: number; down: number };
|
||||
const listRef = useRef<TrafficData[]>([]);
|
||||
const styleRef = useRef(true);
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null!);
|
||||
|
||||
const drawGraph = () => {
|
||||
const canvas = canvasRef.current!;
|
||||
|
||||
if (!canvas) return;
|
||||
|
||||
const context = canvas.getContext("2d")!;
|
||||
const width = canvas.width;
|
||||
const height = canvas.height;
|
||||
const l1 = height * 0.2;
|
||||
const l2 = height * 0.6;
|
||||
const dl = height * 0.4;
|
||||
|
||||
context.clearRect(0, 0, width, height);
|
||||
|
||||
// Reference lines
|
||||
context.beginPath();
|
||||
context.globalAlpha = refLineAlpha;
|
||||
context.lineWidth = refLineWidth;
|
||||
context.strokeStyle = refLineColor;
|
||||
context.moveTo(0, l1);
|
||||
context.lineTo(width, l1);
|
||||
context.moveTo(0, l2);
|
||||
context.lineTo(width, l2);
|
||||
context.stroke();
|
||||
context.closePath();
|
||||
|
||||
const countY = (value: number) => {
|
||||
let v = value;
|
||||
if (v < 1024) v = (v / 1024) * dl;
|
||||
else if (v < 1048576) v = dl + (v / 1048576) * dl;
|
||||
else v = 2 * dl + (v / 10485760) * l1;
|
||||
return height - v;
|
||||
};
|
||||
|
||||
const drawBezier = (list: number[]) => {
|
||||
const len = list.length;
|
||||
const size = Math.min(Math.max(len, minPoint), maxPoint);
|
||||
const axis = width / size;
|
||||
|
||||
let lx = 0;
|
||||
let ly = height;
|
||||
let llx = 0;
|
||||
let lly = height;
|
||||
|
||||
list.forEach((val, index) => {
|
||||
const x = (axis * index) | 0;
|
||||
const y = countY(val);
|
||||
const s = 0.25;
|
||||
|
||||
if (index === 0) context.moveTo(x, y);
|
||||
else {
|
||||
let nx = (axis * (index + 1)) | 0;
|
||||
let ny = index < len - 1 ? countY(list[index + 1]) | 0 : 0;
|
||||
const ax = (lx + (x - llx) * s) | 0;
|
||||
const ay = (ly + (y - lly) * s) | 0;
|
||||
const bx = (x - (nx - lx) * s) | 0;
|
||||
const by = (y - (ny - ly) * s) | 0;
|
||||
context.bezierCurveTo(ax, ay, bx, by, x, y);
|
||||
}
|
||||
|
||||
llx = lx;
|
||||
lly = ly;
|
||||
lx = x;
|
||||
ly = y;
|
||||
});
|
||||
};
|
||||
|
||||
const drawLine = (list: number[]) => {
|
||||
const len = list.length;
|
||||
const size = Math.min(Math.max(len, minPoint), maxPoint);
|
||||
const axis = width / size;
|
||||
|
||||
list.forEach((val, index) => {
|
||||
const x = (axis * index) | 0;
|
||||
const y = countY(val);
|
||||
|
||||
if (index === 0) context.moveTo(x, y);
|
||||
else context.lineTo(x, y);
|
||||
});
|
||||
};
|
||||
|
||||
const listUp = listRef.current.map((v) => v.up);
|
||||
const listDown = listRef.current.map((v) => v.down);
|
||||
const lineStyle = styleRef.current;
|
||||
|
||||
context.beginPath();
|
||||
context.globalAlpha = upLineAlpha;
|
||||
context.lineWidth = upLineWidth;
|
||||
context.strokeStyle = upLineColor;
|
||||
lineStyle ? drawLine(listUp) : drawBezier(listUp);
|
||||
context.stroke();
|
||||
context.closePath();
|
||||
|
||||
context.beginPath();
|
||||
context.globalAlpha = downLineAlpha;
|
||||
context.lineWidth = downLineWidth;
|
||||
context.strokeStyle = downLineColor;
|
||||
lineStyle ? drawLine(listDown) : drawBezier(listDown);
|
||||
context.stroke();
|
||||
context.closePath();
|
||||
};
|
||||
|
||||
const appendData = (data: TrafficData) => {
|
||||
const list = listRef.current;
|
||||
if (list.length > maxPoint) list.shift();
|
||||
list.push(data);
|
||||
drawGraph();
|
||||
};
|
||||
|
||||
const toggleStyle = () => {
|
||||
styleRef.current = !styleRef.current;
|
||||
drawGraph();
|
||||
};
|
||||
|
||||
return {
|
||||
canvasRef,
|
||||
appendData,
|
||||
toggleStyle,
|
||||
};
|
||||
}
|
||||
@@ -59,8 +59,11 @@ const ProfileItem: React.FC<Props> = (props) => {
|
||||
const progress = Math.round(((download + upload) * 100) / (total + 0.1));
|
||||
const fromnow = updated > 0 ? dayjs(updated * 1000).fromNow() : "";
|
||||
|
||||
// url or file mode
|
||||
const isUrlMode = itemData.url && extra;
|
||||
// local file mode
|
||||
// remote file mode
|
||||
// subscription url mode
|
||||
const hasUrl = !!itemData.url;
|
||||
const hasExtra = !!extra; // only subscription url has extra info
|
||||
|
||||
const onView = async () => {
|
||||
setAnchorEl(null);
|
||||
@@ -178,7 +181,8 @@ const ProfileItem: React.FC<Props> = (props) => {
|
||||
{name}
|
||||
</Typography>
|
||||
|
||||
{isUrlMode && (
|
||||
{/* only if has url can it be updated */}
|
||||
{hasUrl && (
|
||||
<IconButton
|
||||
sx={{
|
||||
width: 26,
|
||||
@@ -197,43 +201,43 @@ const ProfileItem: React.FC<Props> = (props) => {
|
||||
)}
|
||||
</Box>
|
||||
|
||||
{isUrlMode ? (
|
||||
<>
|
||||
<Box sx={boxStyle}>
|
||||
<Typography noWrap title={`From: ${from}`}>
|
||||
{from}
|
||||
</Typography>
|
||||
{/* the second line show url's info or description */}
|
||||
{hasUrl ? (
|
||||
<Box sx={boxStyle}>
|
||||
<Typography noWrap title={`From: ${from}`}>
|
||||
{from}
|
||||
</Typography>
|
||||
|
||||
<Typography
|
||||
noWrap
|
||||
flex="1 0 auto"
|
||||
fontSize={14}
|
||||
textAlign="right"
|
||||
title="updated time"
|
||||
>
|
||||
{fromnow}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ ...boxStyle, fontSize: 14 }}>
|
||||
<span title="used / total">
|
||||
{parseTraffic(upload + download)} / {parseTraffic(total)}
|
||||
</span>
|
||||
<span title="expire time">{expire}</span>
|
||||
</Box>
|
||||
</>
|
||||
<Typography
|
||||
noWrap
|
||||
flex="1 0 auto"
|
||||
fontSize={14}
|
||||
textAlign="right"
|
||||
title="updated time"
|
||||
>
|
||||
{fromnow}
|
||||
</Typography>
|
||||
</Box>
|
||||
) : (
|
||||
<>
|
||||
<Box sx={boxStyle}>
|
||||
<Typography noWrap title={itemData.desc}>
|
||||
{itemData.desc}
|
||||
</Typography>
|
||||
</Box>
|
||||
<Box sx={boxStyle}>
|
||||
<Typography noWrap title={itemData.desc}>
|
||||
{itemData.desc}
|
||||
</Typography>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
<Box sx={{ ...boxStyle, fontSize: 14, justifyContent: "flex-end" }}>
|
||||
<span title="updated time">{parseExpire(updated)}</span>
|
||||
</Box>
|
||||
</>
|
||||
{/* the third line show extra info or last updated time */}
|
||||
{hasExtra ? (
|
||||
<Box sx={{ ...boxStyle, fontSize: 14 }}>
|
||||
<span title="used / total">
|
||||
{parseTraffic(upload + download)} / {parseTraffic(total)}
|
||||
</span>
|
||||
<span title="expire time">{expire}</span>
|
||||
</Box>
|
||||
) : (
|
||||
<Box sx={{ ...boxStyle, fontSize: 14, justifyContent: "flex-end" }}>
|
||||
<span title="updated time">{parseExpire(updated)}</span>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
<LinearProgress
|
||||
@@ -250,8 +254,12 @@ const ProfileItem: React.FC<Props> = (props) => {
|
||||
anchorPosition={position}
|
||||
anchorReference="anchorPosition"
|
||||
>
|
||||
{(isUrlMode ? urlModeMenu : fileModeMenu).map((item) => (
|
||||
<MenuItem key={item.label} onClick={item.handler}>
|
||||
{(hasUrl ? urlModeMenu : fileModeMenu).map((item) => (
|
||||
<MenuItem
|
||||
key={item.label}
|
||||
onClick={item.handler}
|
||||
sx={{ minWidth: 133 }}
|
||||
>
|
||||
{item.label}
|
||||
</MenuItem>
|
||||
))}
|
||||
|
||||
@@ -29,27 +29,33 @@ interface Props {
|
||||
|
||||
const ProxyGroup = ({ group }: Props) => {
|
||||
const { mutate } = useSWRConfig();
|
||||
|
||||
const listRef = useRef<any>();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [now, setNow] = useState(group.now);
|
||||
|
||||
const virtuosoRef = useRef<any>();
|
||||
const proxies = group.all ?? [];
|
||||
|
||||
const selectLockRef = useRef(false);
|
||||
const onSelect = async (name: string) => {
|
||||
// can not call update
|
||||
if (group.type !== "Selector") {
|
||||
// Todo
|
||||
// error Tips
|
||||
return;
|
||||
}
|
||||
// Todo: support another proxy group type
|
||||
if (group.type !== "Selector") return;
|
||||
|
||||
if (selectLockRef.current) return;
|
||||
selectLockRef.current = true;
|
||||
|
||||
const oldValue = now;
|
||||
try {
|
||||
setNow(name);
|
||||
await updateProxy(group.name, name);
|
||||
} catch {
|
||||
setNow(oldValue);
|
||||
return; // do not update profile
|
||||
} finally {
|
||||
selectLockRef.current = false;
|
||||
}
|
||||
|
||||
const profiles = await getProfiles().catch(console.error);
|
||||
if (!profiles) return;
|
||||
try {
|
||||
const profiles = await getProfiles();
|
||||
const profile = profiles.items![profiles.current!]!;
|
||||
if (!profile) return;
|
||||
if (!profile.selected) profile.selected = [];
|
||||
@@ -63,12 +69,9 @@ const ProxyGroup = ({ group }: Props) => {
|
||||
} else {
|
||||
profile.selected[index] = { name: group.name, now: name };
|
||||
}
|
||||
|
||||
patchProfile(profiles.current!, profile).catch(console.error);
|
||||
} catch {
|
||||
setNow(oldValue);
|
||||
// Todo
|
||||
// error tips
|
||||
await patchProfile(profiles.current!, profile);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -76,7 +79,7 @@ const ProxyGroup = ({ group }: Props) => {
|
||||
const index = proxies.findIndex((p) => p.name === now);
|
||||
|
||||
if (index >= 0) {
|
||||
listRef.current?.scrollToIndex?.({
|
||||
virtuosoRef.current?.scrollToIndex?.({
|
||||
index,
|
||||
align: "center",
|
||||
behavior: "smooth",
|
||||
@@ -84,12 +87,18 @@ const ProxyGroup = ({ group }: Props) => {
|
||||
}
|
||||
};
|
||||
|
||||
const checkLockRef = useRef(false);
|
||||
const onCheckAll = async () => {
|
||||
let names = proxies.map((p) => p.name);
|
||||
if (checkLockRef.current) return;
|
||||
checkLockRef.current = true;
|
||||
|
||||
// rerender quickly
|
||||
if (proxies.length) setTimeout(() => mutate("getProxies"), 500);
|
||||
|
||||
let names = proxies.map((p) => p.name);
|
||||
while (names.length) {
|
||||
const list = names.slice(0, 10);
|
||||
names = names.slice(10);
|
||||
const list = names.slice(0, 8);
|
||||
names = names.slice(8);
|
||||
|
||||
await Promise.all(
|
||||
list.map((n) => delayManager.checkDelay(n, group.name))
|
||||
@@ -97,6 +106,8 @@ const ProxyGroup = ({ group }: Props) => {
|
||||
|
||||
mutate("getProxies");
|
||||
}
|
||||
|
||||
checkLockRef.current = false;
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -130,7 +141,7 @@ const ProxyGroup = ({ group }: Props) => {
|
||||
|
||||
{proxies.length >= 10 ? (
|
||||
<Virtuoso
|
||||
ref={listRef}
|
||||
ref={virtuosoRef}
|
||||
style={{ height: "320px", marginBottom: "4px" }}
|
||||
totalCount={proxies.length}
|
||||
itemContent={(index) => (
|
||||
|
||||
@@ -15,9 +15,10 @@ const SettingSystem = ({ onError }: Props) => {
|
||||
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
|
||||
|
||||
const {
|
||||
enable_auto_launch: startup = false,
|
||||
enable_system_proxy: proxy = false,
|
||||
system_proxy_bypass: bypass = "",
|
||||
enable_auto_launch = false,
|
||||
enable_system_proxy = false,
|
||||
system_proxy_bypass = "",
|
||||
enable_proxy_guard = false,
|
||||
} = vergeConfig ?? {};
|
||||
|
||||
const onSwitchFormat = (_e: any, value: boolean) => value;
|
||||
@@ -30,7 +31,7 @@ const SettingSystem = ({ onError }: Props) => {
|
||||
<SettingItem>
|
||||
<ListItemText primary="Auto Launch" />
|
||||
<GuardState
|
||||
value={startup}
|
||||
value={enable_auto_launch}
|
||||
valueProps="checked"
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
@@ -51,7 +52,7 @@ const SettingSystem = ({ onError }: Props) => {
|
||||
}
|
||||
/>
|
||||
<GuardState
|
||||
value={proxy}
|
||||
value={enable_system_proxy}
|
||||
valueProps="checked"
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
@@ -65,11 +66,27 @@ const SettingSystem = ({ onError }: Props) => {
|
||||
</GuardState>
|
||||
</SettingItem>
|
||||
|
||||
{proxy && (
|
||||
{enable_system_proxy && (
|
||||
<SettingItem>
|
||||
<ListItemText primary="Proxy Guard" />
|
||||
<GuardState
|
||||
value={enable_proxy_guard}
|
||||
valueProps="checked"
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
onChange={(e) => onChangeData({ enable_proxy_guard: e })}
|
||||
onGuard={(e) => patchVergeConfig({ enable_proxy_guard: e })}
|
||||
>
|
||||
<Switch edge="end" />
|
||||
</GuardState>
|
||||
</SettingItem>
|
||||
)}
|
||||
|
||||
{enable_system_proxy && (
|
||||
<SettingItem>
|
||||
<ListItemText primary="Proxy Bypass" />
|
||||
<GuardState
|
||||
value={bypass ?? ""}
|
||||
value={system_proxy_bypass ?? ""}
|
||||
onCatch={onError}
|
||||
onFormat={(e: any) => e.target.value}
|
||||
onChange={(e) => onChangeData({ system_proxy_bypass: e })}
|
||||
|
||||
@@ -6,12 +6,12 @@ import {
|
||||
openLogsDir,
|
||||
patchVergeConfig,
|
||||
} from "../../services/cmds";
|
||||
import { ArrowForward } from "@mui/icons-material";
|
||||
import { SettingList, SettingItem } from "./setting";
|
||||
import { CmdType } from "../../services/types";
|
||||
import { version } from "../../../package.json";
|
||||
import GuardState from "./guard-state";
|
||||
import PaletteSwitch from "./palette-switch";
|
||||
import { ArrowForward } from "@mui/icons-material";
|
||||
import GuardState from "./guard-state";
|
||||
|
||||
interface Props {
|
||||
onError?: (err: Error) => void;
|
||||
@@ -21,7 +21,7 @@ const SettingVerge = ({ onError }: Props) => {
|
||||
const { mutate } = useSWRConfig();
|
||||
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
|
||||
|
||||
const { theme_mode: mode = "light", theme_blur: blur = false } =
|
||||
const { theme_mode = "light", theme_blur = false, traffic_graph } =
|
||||
vergeConfig ?? {};
|
||||
|
||||
const onSwitchFormat = (_e: any, value: boolean) => value;
|
||||
@@ -34,13 +34,13 @@ const SettingVerge = ({ onError }: Props) => {
|
||||
<SettingItem>
|
||||
<ListItemText primary="Theme Mode" />
|
||||
<GuardState
|
||||
value={mode === "dark"}
|
||||
value={theme_mode === "dark"}
|
||||
valueProps="checked"
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
onChange={(e) => onChangeData({ theme_mode: e ? "dark" : "light" })}
|
||||
onGuard={(c) =>
|
||||
patchVergeConfig({ theme_mode: c ? "dark" : "light" })
|
||||
onGuard={(e) =>
|
||||
patchVergeConfig({ theme_mode: e ? "dark" : "light" })
|
||||
}
|
||||
>
|
||||
<PaletteSwitch edge="end" />
|
||||
@@ -50,7 +50,7 @@ const SettingVerge = ({ onError }: Props) => {
|
||||
<SettingItem>
|
||||
<ListItemText primary="Theme Blur" />
|
||||
<GuardState
|
||||
value={blur}
|
||||
value={theme_blur}
|
||||
valueProps="checked"
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
@@ -62,15 +62,22 @@ const SettingVerge = ({ onError }: Props) => {
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText primary="Open App Dir" />
|
||||
<IconButton
|
||||
color="inherit"
|
||||
size="small"
|
||||
onClick={() => {
|
||||
console.log("click");
|
||||
openAppDir().then(console.log).catch(console.log);
|
||||
}}
|
||||
<ListItemText primary="Traffic Graph" />
|
||||
<GuardState
|
||||
value={traffic_graph ?? true}
|
||||
valueProps="checked"
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
onChange={(e) => onChangeData({ traffic_graph: e })}
|
||||
onGuard={(e) => patchVergeConfig({ traffic_graph: e })}
|
||||
>
|
||||
<Switch edge="end" />
|
||||
</GuardState>
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText primary="Open App Dir" />
|
||||
<IconButton color="inherit" size="small" onClick={openAppDir}>
|
||||
<ArrowForward />
|
||||
</IconButton>
|
||||
</SettingItem>
|
||||
|
||||
@@ -1,25 +1,26 @@
|
||||
import useSWR, { SWRConfig, useSWRConfig } from "swr";
|
||||
import { useEffect, useMemo } from "react";
|
||||
import { Route, Routes } from "react-router-dom";
|
||||
import { useRecoilState } from "recoil";
|
||||
import { alpha, createTheme, List, Paper, ThemeProvider } from "@mui/material";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { appWindow } from "@tauri-apps/api/window";
|
||||
import { atomPaletteMode, atomThemeBlur } from "../states/setting";
|
||||
import { getVergeConfig } from "../services/cmds";
|
||||
import { getAxios } from "../services/api";
|
||||
import { routers } from "./_routers";
|
||||
import { getAxios } from "../services/api";
|
||||
import { getVergeConfig } from "../services/cmds";
|
||||
import LogoSvg from "../assets/image/logo.svg";
|
||||
import LayoutItem from "../components/layout/layout-item";
|
||||
import LayoutControl from "../components/layout/layout-control";
|
||||
import LayoutTraffic from "../components/layout/layout-traffic";
|
||||
import UpdateButton from "../components/layout/update-button";
|
||||
|
||||
const isMacos = navigator.userAgent.includes("Mac OS X");
|
||||
|
||||
const Layout = () => {
|
||||
const { mutate } = useSWRConfig();
|
||||
const [mode, setMode] = useRecoilState(atomPaletteMode);
|
||||
const [blur, setBlur] = useRecoilState(atomThemeBlur);
|
||||
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
|
||||
const { data } = useSWR("getVergeConfig", getVergeConfig);
|
||||
|
||||
const blur = !!data?.theme_blur;
|
||||
const mode = data?.theme_mode ?? "light";
|
||||
|
||||
useEffect(() => {
|
||||
window.addEventListener("keydown", (e) => {
|
||||
@@ -36,12 +37,6 @@ const Layout = () => {
|
||||
});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!vergeConfig) return;
|
||||
setBlur(!!vergeConfig.theme_blur);
|
||||
setMode(vergeConfig.theme_mode ?? "light");
|
||||
}, [vergeConfig]);
|
||||
|
||||
const theme = useMemo(() => {
|
||||
// const background = mode === "light" ? "#f5f5f5" : "#000";
|
||||
const selectColor = mode === "light" ? "#f5f5f5" : "#d5d5d5";
|
||||
@@ -74,7 +69,7 @@ const Layout = () => {
|
||||
<Paper
|
||||
square
|
||||
elevation={0}
|
||||
className="layout"
|
||||
className={`${isMacos ? "macos " : ""}layout`}
|
||||
onPointerDown={onDragging}
|
||||
sx={[
|
||||
(theme) => ({
|
||||
@@ -103,9 +98,11 @@ const Layout = () => {
|
||||
</div>
|
||||
|
||||
<div className="layout__right" data-windrag>
|
||||
<div className="the-bar">
|
||||
<LayoutControl />
|
||||
</div>
|
||||
{!isMacos && (
|
||||
<div className="the-bar">
|
||||
<LayoutControl />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="the-content">
|
||||
<Routes>
|
||||
|
||||
@@ -64,6 +64,10 @@ export async function getSystemProxy() {
|
||||
return invoke<any>("get_sys_proxy");
|
||||
}
|
||||
|
||||
export async function killSidecars() {
|
||||
return invoke<any>("kill_sidecars");
|
||||
}
|
||||
|
||||
export async function openAppDir() {
|
||||
return invoke<void>("open_app_dir");
|
||||
}
|
||||
|
||||
@@ -112,8 +112,10 @@ export namespace CmdType {
|
||||
export interface VergeConfig {
|
||||
theme_mode?: "light" | "dark";
|
||||
theme_blur?: boolean;
|
||||
traffic_graph?: boolean;
|
||||
enable_auto_launch?: boolean;
|
||||
enable_system_proxy?: boolean;
|
||||
enable_proxy_guard?: boolean;
|
||||
system_proxy_bypass?: string;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,5 @@
|
||||
import { atom } from "recoil";
|
||||
|
||||
export const atomPaletteMode = atom<"light" | "dark">({
|
||||
key: "atomPaletteMode",
|
||||
default: "light",
|
||||
});
|
||||
|
||||
export const atomThemeBlur = atom<boolean>({
|
||||
key: "atomThemeBlur",
|
||||
default: false,
|
||||
});
|
||||
|
||||
export const atomClashPort = atom<number>({
|
||||
key: "atomClashPort",
|
||||
default: 0,
|
||||
|
||||
Reference in New Issue
Block a user