mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-10-15 05:40:47 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
73458dcd28 | ||
|
|
23ebeb1cc0 | ||
|
|
a7ba9f1886 | ||
|
|
d5192e2244 | ||
|
|
7eb595170f | ||
|
|
bd576ca808 | ||
|
|
2f8146b11f | ||
|
|
7f321c89cb | ||
|
|
fa65f606b8 | ||
|
|
7a3285adaf | ||
|
|
8bf78fef10 | ||
|
|
78f97ce4df | ||
|
|
66ccbf70f8 | ||
|
|
cb48600b40 | ||
|
|
33ce235713 | ||
|
|
f1a68ece01 | ||
|
|
dd563360af | ||
|
|
7f6dac4271 | ||
|
|
178fd8e828 | ||
|
|
1641e02a7d | ||
|
|
cfd04e9bb4 | ||
|
|
38effaf740 | ||
|
|
a68eb4a73e | ||
|
|
c02990ef98 | ||
|
|
5aa7d5ffe9 | ||
|
|
4942b0fca5 | ||
|
|
aed1bdff5a | ||
|
|
929c840006 | ||
|
|
57aef1d3c2 | ||
|
|
c1734a094c | ||
|
|
99c46685ac | ||
|
|
066b08040a | ||
|
|
35de2334fb | ||
|
|
5564c966a5 | ||
|
|
0891b5e7b7 | ||
|
|
f3341f201f | ||
|
|
bf0dafabe2 | ||
|
|
60f6587169 | ||
|
|
a9bf32919e | ||
|
|
7633f9f88b |
@@ -77,10 +77,15 @@ jobs:
|
||||
|
||||
- name: Portable Bundle
|
||||
if: matrix.os == 'windows-latest'
|
||||
# rebuild with env settings
|
||||
run: |
|
||||
yarn build
|
||||
yarn run portable
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
|
||||
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
|
||||
VITE_WIN_PORTABLE: 1
|
||||
|
||||
release-update:
|
||||
needs: release
|
||||
|
||||
@@ -1,3 +1,21 @@
|
||||
## v1.0.5
|
||||
|
||||
### Features
|
||||
|
||||
- reimplement profile enhanced mode with quick-js
|
||||
- optimize the runtime config generation process
|
||||
- support web ui management
|
||||
- support clash field management
|
||||
- support viewing the runtime config
|
||||
- adjust some pages style
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- fix silent start
|
||||
- fix incorrectly reset system proxy on exit
|
||||
|
||||
---
|
||||
|
||||
## v1.0.4
|
||||
|
||||
### Features
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "clash-verge",
|
||||
"version": "1.0.4",
|
||||
"version": "1.0.5",
|
||||
"license": "GPL-3.0",
|
||||
"scripts": {
|
||||
"dev": "tauri dev",
|
||||
@@ -66,4 +66,4 @@
|
||||
"singleQuote": false,
|
||||
"endOfLine": "lf"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+2
-8
@@ -53,18 +53,12 @@ async function resolveUpdater() {
|
||||
const { name, browser_download_url } = asset;
|
||||
|
||||
// win64 url
|
||||
if (
|
||||
name.endsWith(".msi.zip") &&
|
||||
(!updateData.platforms.win64.url || name.includes("en-US"))
|
||||
) {
|
||||
if (name.endsWith(".msi.zip") && name.includes("en-US")) {
|
||||
updateData.platforms.win64.url = browser_download_url;
|
||||
updateData.platforms["windows-x86_64"].url = browser_download_url;
|
||||
}
|
||||
// win64 signature
|
||||
if (
|
||||
name.endsWith(".msi.zip.sig") &&
|
||||
(!updateData.platforms.win64.signature || name.includes("en-US"))
|
||||
) {
|
||||
if (name.endsWith(".msi.zip.sig") && name.includes("en-US")) {
|
||||
const sig = await getSignature(browser_download_url);
|
||||
updateData.platforms.win64.signature = sig;
|
||||
updateData.platforms["windows-x86_64"].signature = sig;
|
||||
|
||||
Generated
+28
@@ -505,6 +505,7 @@ dependencies = [
|
||||
"parking_lot 0.12.1",
|
||||
"port_scanner",
|
||||
"reqwest",
|
||||
"rquickjs",
|
||||
"runas",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -3070,6 +3071,33 @@ dependencies = [
|
||||
"windows",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rquickjs"
|
||||
version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "989910af47b3f21c95205a1e1974bfb0f460e5492f469631297cc44c3340967e"
|
||||
dependencies = [
|
||||
"rquickjs-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rquickjs-core"
|
||||
version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e78ca2361848dddf910c27296d98bd62be9467d1d1d703eeead8c732adbd4e32"
|
||||
dependencies = [
|
||||
"rquickjs-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rquickjs-sys"
|
||||
version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "263a9a14fc68f2f3403c67e94e5def69af60afbcf7914d2a7fb8f9e17027fa25"
|
||||
dependencies = [
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rs-snowflake"
|
||||
version = "0.6.0"
|
||||
|
||||
@@ -33,6 +33,7 @@ tokio = { version = "1", features = ["full"] }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
reqwest = { version = "0.11", features = ["json"] }
|
||||
tauri = { version = "1.0.0", features = ["process-all", "shell-all", "system-tray", "updater", "window-all"] }
|
||||
rquickjs = { version = "0.1.6" }
|
||||
window-shadows = { version = "0.1" }
|
||||
window-vibrancy = { version = "0.1" }
|
||||
|
||||
|
||||
+45
-19
@@ -5,6 +5,7 @@ use crate::{
|
||||
use crate::{log_if_err, ret_err, wrap_err};
|
||||
use anyhow::Result;
|
||||
use serde_yaml::Mapping;
|
||||
use std::collections::HashMap;
|
||||
use tauri::{api, State};
|
||||
|
||||
type CmdResult<T = ()> = Result<T, String>;
|
||||
@@ -19,7 +20,7 @@ pub fn get_profiles(core: State<'_, Core>) -> CmdResult<Profiles> {
|
||||
/// manually exec enhanced profile
|
||||
#[tauri::command]
|
||||
pub fn enhance_profiles(core: State<'_, Core>) -> CmdResult {
|
||||
wrap_err!(core.activate_enhanced(false))
|
||||
wrap_err!(core.activate())
|
||||
}
|
||||
|
||||
/// import the profile from url
|
||||
@@ -58,7 +59,7 @@ pub async fn update_profile(
|
||||
option: Option<PrfOption>,
|
||||
core: State<'_, Core>,
|
||||
) -> CmdResult {
|
||||
wrap_err!(Core::update_profile_item(core.inner().clone(), index, option).await)
|
||||
wrap_err!(core.update_profile_item(index, option).await)
|
||||
}
|
||||
|
||||
/// change the current profile
|
||||
@@ -66,45 +67,36 @@ pub async fn update_profile(
|
||||
pub fn select_profile(index: String, core: State<'_, Core>) -> CmdResult {
|
||||
let mut profiles = core.profiles.lock();
|
||||
wrap_err!(profiles.put_current(index))?;
|
||||
|
||||
drop(profiles);
|
||||
|
||||
wrap_err!(core.activate_enhanced(false))
|
||||
wrap_err!(core.activate())
|
||||
}
|
||||
|
||||
/// change the profile chain
|
||||
#[tauri::command]
|
||||
pub fn change_profile_chain(chain: Option<Vec<String>>, core: State<'_, Core>) -> CmdResult {
|
||||
let mut profiles = core.profiles.lock();
|
||||
profiles.put_chain(chain);
|
||||
|
||||
wrap_err!(profiles.put_chain(chain))?;
|
||||
drop(profiles);
|
||||
|
||||
wrap_err!(core.activate_enhanced(false))
|
||||
wrap_err!(core.activate())
|
||||
}
|
||||
|
||||
/// change the profile valid fields
|
||||
#[tauri::command]
|
||||
pub fn change_profile_valid(valid: Option<Vec<String>>, core: State<Core>) -> CmdResult {
|
||||
let mut profiles = core.profiles.lock();
|
||||
profiles.put_valid(valid);
|
||||
|
||||
wrap_err!(profiles.put_valid(valid))?;
|
||||
drop(profiles);
|
||||
|
||||
wrap_err!(core.activate_enhanced(false))
|
||||
wrap_err!(core.activate())
|
||||
}
|
||||
|
||||
/// delete profile item
|
||||
#[tauri::command]
|
||||
pub fn delete_profile(index: String, core: State<'_, Core>) -> CmdResult {
|
||||
let mut profiles = core.profiles.lock();
|
||||
|
||||
if wrap_err!(profiles.delete_item(index))? {
|
||||
drop(profiles);
|
||||
|
||||
log_if_err!(core.activate_enhanced(false));
|
||||
log_if_err!(core.activate());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -143,10 +135,8 @@ pub fn view_profile(index: String, core: State<'_, Core>) -> CmdResult {
|
||||
#[tauri::command]
|
||||
pub fn read_profile_file(index: String, core: State<'_, Core>) -> CmdResult<String> {
|
||||
let profiles = core.profiles.lock();
|
||||
|
||||
let item = wrap_err!(profiles.get_item(&index))?;
|
||||
let data = wrap_err!(item.read_file())?;
|
||||
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
@@ -174,6 +164,36 @@ pub fn get_clash_info(core: State<'_, Core>) -> CmdResult<ClashInfo> {
|
||||
Ok(clash.info.clone())
|
||||
}
|
||||
|
||||
/// get the runtime clash config mapping
|
||||
#[tauri::command]
|
||||
pub fn get_runtime_config(core: State<'_, Core>) -> CmdResult<Option<Mapping>> {
|
||||
let rt = core.runtime.lock();
|
||||
Ok(rt.config.clone())
|
||||
}
|
||||
|
||||
/// get the runtime clash config yaml string
|
||||
#[tauri::command]
|
||||
pub fn get_runtime_yaml(core: State<'_, Core>) -> CmdResult<Option<String>> {
|
||||
let rt = core.runtime.lock();
|
||||
Ok(rt.config_yaml.clone())
|
||||
}
|
||||
|
||||
/// get the runtime config exists keys
|
||||
#[tauri::command]
|
||||
pub fn get_runtime_exists(core: State<'_, Core>) -> CmdResult<Vec<String>> {
|
||||
let rt = core.runtime.lock();
|
||||
Ok(rt.exists_keys.clone())
|
||||
}
|
||||
|
||||
/// get the runtime enhanced chain log
|
||||
#[tauri::command]
|
||||
pub fn get_runtime_logs(
|
||||
core: State<'_, Core>,
|
||||
) -> CmdResult<HashMap<String, Vec<(String, String)>>> {
|
||||
let rt = core.runtime.lock();
|
||||
Ok(rt.chain_logs.clone())
|
||||
}
|
||||
|
||||
/// update the clash core config
|
||||
/// after putting the change to the clash core
|
||||
/// then we should save the latest config
|
||||
@@ -250,6 +270,12 @@ pub fn open_logs_dir() -> Result<(), String> {
|
||||
wrap_err!(open::that(log_dir))
|
||||
}
|
||||
|
||||
/// open url
|
||||
#[tauri::command]
|
||||
pub fn open_web_url(url: String) -> Result<(), String> {
|
||||
wrap_err!(open::that(url))
|
||||
}
|
||||
|
||||
/// service mode
|
||||
#[cfg(windows)]
|
||||
pub mod service {
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
use serde_yaml::{Mapping, Value};
|
||||
|
||||
pub const HANDLE_FIELDS: [&str; 9] = [
|
||||
"port",
|
||||
"socks-port",
|
||||
"mixed-port",
|
||||
"mode",
|
||||
"ipv6",
|
||||
"log-level",
|
||||
"allow-lan",
|
||||
"external-controller",
|
||||
"secret",
|
||||
];
|
||||
|
||||
pub const DEFAULT_FIELDS: [&str; 5] = [
|
||||
"proxies",
|
||||
"proxy-groups",
|
||||
"rules",
|
||||
"proxy-providers",
|
||||
"rule-providers",
|
||||
];
|
||||
|
||||
pub const OTHERS_FIELDS: [&str; 20] = [
|
||||
"tun",
|
||||
"dns",
|
||||
"ebpf",
|
||||
"hosts",
|
||||
"script",
|
||||
"profile",
|
||||
"payload",
|
||||
"auto-redir",
|
||||
"experimental",
|
||||
"interface-name",
|
||||
"routing-mark",
|
||||
"redir-port",
|
||||
"tproxy-port",
|
||||
"iptables",
|
||||
"external-ui",
|
||||
"bind-address",
|
||||
"authentication",
|
||||
"sniffer", // meta
|
||||
"geodata-mode", // meta
|
||||
"tcp-concurrent", // meta
|
||||
];
|
||||
|
||||
pub fn use_clash_fields() -> Vec<String> {
|
||||
DEFAULT_FIELDS
|
||||
.into_iter()
|
||||
.chain(HANDLE_FIELDS)
|
||||
.chain(OTHERS_FIELDS)
|
||||
.map(|s| s.to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn use_valid_fields(mut valid: Vec<String>) -> Vec<String> {
|
||||
let others = Vec::from(OTHERS_FIELDS);
|
||||
|
||||
valid.iter_mut().for_each(|s| s.make_ascii_lowercase());
|
||||
valid
|
||||
.into_iter()
|
||||
.filter(|s| others.contains(&s.as_str()))
|
||||
.chain(DEFAULT_FIELDS.iter().map(|s| s.to_string()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn use_filter(config: Mapping, filter: &Vec<String>) -> Mapping {
|
||||
let mut ret = Mapping::new();
|
||||
|
||||
for (key, value) in config.into_iter() {
|
||||
if let Some(key) = key.as_str() {
|
||||
if filter.contains(&key.to_string()) {
|
||||
ret.insert(Value::from(key), value);
|
||||
}
|
||||
}
|
||||
}
|
||||
ret
|
||||
}
|
||||
|
||||
pub fn use_lowercase(config: Mapping) -> Mapping {
|
||||
let mut ret = Mapping::new();
|
||||
|
||||
for (key, value) in config.into_iter() {
|
||||
if let Some(key_str) = key.as_str() {
|
||||
let mut key_str = String::from(key_str);
|
||||
key_str.make_ascii_lowercase();
|
||||
ret.insert(Value::from(key_str), value);
|
||||
}
|
||||
}
|
||||
ret
|
||||
}
|
||||
|
||||
pub fn use_sort(config: Mapping) -> Mapping {
|
||||
let mut ret = Mapping::new();
|
||||
|
||||
HANDLE_FIELDS
|
||||
.into_iter()
|
||||
.chain(OTHERS_FIELDS)
|
||||
.chain(DEFAULT_FIELDS)
|
||||
.for_each(|key| {
|
||||
let key = Value::from(key);
|
||||
config.get(&key).map(|value| {
|
||||
ret.insert(key, value.clone());
|
||||
});
|
||||
});
|
||||
ret
|
||||
}
|
||||
|
||||
pub fn use_keys(config: &Mapping) -> Vec<String> {
|
||||
config
|
||||
.iter()
|
||||
.filter_map(|(key, _)| key.as_str())
|
||||
.map(|s| {
|
||||
let mut s = s.to_string();
|
||||
s.make_ascii_lowercase();
|
||||
return s;
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
use super::{use_filter, use_lowercase};
|
||||
use serde_yaml::{self, Mapping, Sequence, Value};
|
||||
|
||||
#[allow(unused)]
|
||||
const MERGE_FIELDS: [&str; 6] = [
|
||||
"prepend-rules",
|
||||
"append-rules",
|
||||
"prepend-proxies",
|
||||
"append-proxies",
|
||||
"prepend-proxy-groups",
|
||||
"append-proxy-groups",
|
||||
];
|
||||
|
||||
pub fn use_merge(merge: Mapping, mut config: Mapping) -> Mapping {
|
||||
// 直接覆盖原字段
|
||||
use_lowercase(merge.clone())
|
||||
.into_iter()
|
||||
.for_each(|(key, value)| {
|
||||
config.insert(key, value);
|
||||
});
|
||||
|
||||
let merge_list = MERGE_FIELDS.iter().map(|s| s.to_string());
|
||||
let merge = use_filter(merge, &merge_list.collect());
|
||||
|
||||
["rules", "proxies", "proxy-groups"]
|
||||
.iter()
|
||||
.for_each(|key_str| {
|
||||
let key_val = Value::from(key_str.to_string());
|
||||
|
||||
let mut list = Sequence::default();
|
||||
list = config.get(&key_val).map_or(list.clone(), |val| {
|
||||
val.as_sequence().map_or(list, |v| v.clone())
|
||||
});
|
||||
|
||||
let pre_key = Value::from(format!("prepend-{key_str}"));
|
||||
let post_key = Value::from(format!("append-{key_str}"));
|
||||
|
||||
if let Some(pre_val) = merge.get(&pre_key) {
|
||||
if pre_val.is_sequence() {
|
||||
let mut pre_val = pre_val.as_sequence().unwrap().clone();
|
||||
pre_val.extend(list);
|
||||
list = pre_val;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(post_val) = merge.get(&post_key) {
|
||||
if post_val.is_sequence() {
|
||||
list.extend(post_val.as_sequence().unwrap().clone());
|
||||
}
|
||||
}
|
||||
|
||||
config.insert(key_val, Value::from(list));
|
||||
});
|
||||
config
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_merge() -> anyhow::Result<()> {
|
||||
let merge = r"
|
||||
prepend-rules:
|
||||
- prepend
|
||||
- 1123123
|
||||
append-rules:
|
||||
- append
|
||||
prepend-proxies:
|
||||
- 9999
|
||||
append-proxies:
|
||||
- 1111
|
||||
rules:
|
||||
- replace
|
||||
proxy-groups:
|
||||
- 123781923810
|
||||
tun:
|
||||
enable: true
|
||||
dns:
|
||||
enable: true
|
||||
";
|
||||
|
||||
let config = r"
|
||||
rules:
|
||||
- aaaaa
|
||||
script1: test
|
||||
";
|
||||
|
||||
let merge = serde_yaml::from_str::<Mapping>(merge)?;
|
||||
let config = serde_yaml::from_str::<Mapping>(config)?;
|
||||
|
||||
let result = serde_yaml::to_string(&use_merge(merge, config))?;
|
||||
|
||||
println!("{result}");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
mod field;
|
||||
mod merge;
|
||||
mod script;
|
||||
mod tun;
|
||||
|
||||
pub(self) use self::field::*;
|
||||
use self::merge::*;
|
||||
use self::script::*;
|
||||
use self::tun::*;
|
||||
use crate::core::ChainItem;
|
||||
use crate::core::ChainType;
|
||||
use serde_yaml::Mapping;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
|
||||
type ResultLog = Vec<(String, String)>;
|
||||
|
||||
pub fn enhance_config(
|
||||
clash_config: Mapping,
|
||||
profile_config: Mapping,
|
||||
chain: Vec<ChainItem>,
|
||||
valid: Vec<String>,
|
||||
tun_mode: bool,
|
||||
) -> (Mapping, Vec<String>, HashMap<String, ResultLog>) {
|
||||
let mut config = profile_config;
|
||||
let mut result_map = HashMap::new();
|
||||
let mut exists_keys = use_keys(&config);
|
||||
|
||||
let valid = use_valid_fields(valid);
|
||||
|
||||
chain.into_iter().for_each(|item| match item.data {
|
||||
ChainType::Merge(merge) => {
|
||||
exists_keys.extend(use_keys(&merge));
|
||||
config = use_merge(merge, config.to_owned());
|
||||
config = use_filter(config.to_owned(), &valid);
|
||||
}
|
||||
ChainType::Script(script) => {
|
||||
let mut logs = vec![];
|
||||
|
||||
match use_script(script, config.to_owned()) {
|
||||
Ok((res_config, res_logs)) => {
|
||||
exists_keys.extend(use_keys(&res_config));
|
||||
config = use_filter(res_config, &valid);
|
||||
logs.extend(res_logs);
|
||||
}
|
||||
Err(err) => logs.push(("exception".into(), err.to_string())),
|
||||
}
|
||||
|
||||
result_map.insert(item.uid, logs);
|
||||
}
|
||||
});
|
||||
|
||||
config = use_filter(config, &valid);
|
||||
|
||||
for (key, value) in clash_config.into_iter() {
|
||||
config.insert(key, value);
|
||||
}
|
||||
|
||||
let clash_fields = use_clash_fields();
|
||||
config = use_filter(config, &clash_fields);
|
||||
config = use_tun(config, tun_mode);
|
||||
config = use_sort(config);
|
||||
|
||||
let mut exists_set = HashSet::new();
|
||||
exists_set.extend(exists_keys.into_iter().filter(|s| clash_fields.contains(s)));
|
||||
exists_keys = exists_set.into_iter().collect();
|
||||
|
||||
(config, exists_keys, result_map)
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
use super::use_lowercase;
|
||||
use anyhow::Result;
|
||||
use serde_yaml::Mapping;
|
||||
|
||||
pub fn use_script(script: String, config: Mapping) -> Result<(Mapping, Vec<(String, String)>)> {
|
||||
use rquickjs::{Context, Func, Runtime};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
let runtime = Runtime::new().unwrap();
|
||||
let context = Context::full(&runtime).unwrap();
|
||||
let outputs = Arc::new(Mutex::new(vec![]));
|
||||
|
||||
let copy_outputs = outputs.clone();
|
||||
let result = context.with(|ctx| -> Result<Mapping> {
|
||||
ctx.globals().set(
|
||||
"__verge_log__",
|
||||
Func::from(move |level: String, data: String| {
|
||||
let mut out = copy_outputs.lock().unwrap();
|
||||
out.push((level, data));
|
||||
}),
|
||||
)?;
|
||||
|
||||
ctx.eval(
|
||||
r#"var console = Object.freeze({
|
||||
log(data){__verge_log__("log",JSON.stringify(data))},
|
||||
info(data){__verge_log__("info",JSON.stringify(data))},
|
||||
error(data){__verge_log__("error",JSON.stringify(data))},
|
||||
debug(data){__verge_log__("debug",JSON.stringify(data))},
|
||||
});"#,
|
||||
)?;
|
||||
|
||||
let config = use_lowercase(config.clone());
|
||||
let config_str = serde_json::to_string(&config)?;
|
||||
|
||||
let code = format!(
|
||||
r#"try{{
|
||||
{script};
|
||||
JSON.stringify(main({config_str})||'')
|
||||
}} catch(err) {{
|
||||
`__error_flag__ ${{err.toString()}}`
|
||||
}}"#
|
||||
);
|
||||
let result: String = ctx.eval(code.as_str())?;
|
||||
if result.starts_with("__error_flag__") {
|
||||
anyhow::bail!(result[15..].to_owned());
|
||||
}
|
||||
if result == "\"\"" {
|
||||
anyhow::bail!("main function should return object");
|
||||
}
|
||||
return Ok(serde_json::from_str::<Mapping>(result.as_str())?);
|
||||
});
|
||||
|
||||
let mut out = outputs.lock().unwrap();
|
||||
match result {
|
||||
Ok(config) => Ok((use_lowercase(config), out.to_vec())),
|
||||
Err(err) => {
|
||||
out.push(("exception".into(), err.to_string()));
|
||||
Ok((config, out.to_vec()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_script() {
|
||||
let script = r#"
|
||||
function main(config) {
|
||||
if (Array.isArray(config.rules)) {
|
||||
config.rules = [...config.rules, "add"];
|
||||
}
|
||||
console.log(config);
|
||||
config.proxies = ["111"];
|
||||
return config;
|
||||
}
|
||||
"#;
|
||||
|
||||
let config = r#"
|
||||
rules:
|
||||
- 111
|
||||
- 222
|
||||
tun:
|
||||
enable: false
|
||||
dns:
|
||||
enable: false
|
||||
"#;
|
||||
|
||||
let config = serde_yaml::from_str(config).unwrap();
|
||||
let (config, results) = use_script(script.into(), config).unwrap();
|
||||
|
||||
let config_str = serde_yaml::to_string(&config).unwrap();
|
||||
|
||||
println!("{config_str}");
|
||||
|
||||
dbg!(results);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
use serde_yaml::{Mapping, Value};
|
||||
|
||||
macro_rules! revise {
|
||||
($map: expr, $key: expr, $val: expr) => {
|
||||
let ret_key = Value::String($key.into());
|
||||
$map.insert(ret_key, Value::from($val));
|
||||
};
|
||||
}
|
||||
|
||||
// if key not exists then append value
|
||||
macro_rules! append {
|
||||
($map: expr, $key: expr, $val: expr) => {
|
||||
let ret_key = Value::String($key.into());
|
||||
if !$map.contains_key(&ret_key) {
|
||||
$map.insert(ret_key, Value::from($val));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub fn use_tun(mut config: Mapping, enable: bool) -> Mapping {
|
||||
let tun_key = Value::from("tun");
|
||||
let tun_val = config.get(&tun_key);
|
||||
|
||||
if !enable && tun_val.is_none() {
|
||||
return config;
|
||||
}
|
||||
|
||||
let mut tun_val = tun_val.map_or(Mapping::new(), |val| {
|
||||
val.as_mapping().cloned().unwrap_or(Mapping::new())
|
||||
});
|
||||
|
||||
revise!(tun_val, "enable", enable);
|
||||
if enable {
|
||||
append!(tun_val, "stack", "gvisor");
|
||||
append!(tun_val, "dns-hijack", vec!["198.18.0.2:53"]);
|
||||
append!(tun_val, "auto-route", true);
|
||||
append!(tun_val, "auto-detect-interface", true);
|
||||
}
|
||||
|
||||
revise!(config, "tun", tun_val);
|
||||
|
||||
if enable {
|
||||
use_dns_for_tun(config)
|
||||
} else {
|
||||
config
|
||||
}
|
||||
}
|
||||
|
||||
fn use_dns_for_tun(mut config: Mapping) -> Mapping {
|
||||
let dns_key = Value::from("dns");
|
||||
let dns_val = config.get(&dns_key);
|
||||
|
||||
let mut dns_val = dns_val.map_or(Mapping::new(), |val| {
|
||||
val.as_mapping().cloned().unwrap_or(Mapping::new())
|
||||
});
|
||||
|
||||
// 开启tun将同时开启dns
|
||||
revise!(dns_val, "enable", true);
|
||||
|
||||
// 借鉴cfw的默认配置
|
||||
append!(dns_val, "enhanced-mode", "fake-ip");
|
||||
append!(
|
||||
dns_val,
|
||||
"nameserver",
|
||||
vec!["114.114.114.114", "223.5.5.5", "8.8.8.8"]
|
||||
);
|
||||
append!(dns_val, "fallback", vec![] as Vec<&str>);
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
append!(
|
||||
dns_val,
|
||||
"fake-ip-filter",
|
||||
vec![
|
||||
"dns.msftncsi.com",
|
||||
"www.msftncsi.com",
|
||||
"www.msftconnecttest.com"
|
||||
]
|
||||
);
|
||||
revise!(config, "dns", dns_val);
|
||||
config
|
||||
}
|
||||
+41
-174
@@ -22,18 +22,26 @@ impl ClashInfo {
|
||||
/// parse the clash's config.yaml
|
||||
/// get some information
|
||||
pub fn from(config: &Mapping) -> ClashInfo {
|
||||
let key_port_1 = Value::from("port");
|
||||
let key_port_2 = Value::from("mixed-port");
|
||||
let key_port_1 = Value::from("mixed-port");
|
||||
let key_port_2 = Value::from("port");
|
||||
let key_server = Value::from("external-controller");
|
||||
let key_secret = Value::from("secret");
|
||||
|
||||
let mut status: u32 = 0;
|
||||
|
||||
let port = match config.get(&key_port_1) {
|
||||
Some(value) => match value {
|
||||
Value::String(val_str) => Some(val_str.clone()),
|
||||
Value::Number(val_num) => Some(val_num.to_string()),
|
||||
_ => None,
|
||||
_ => {
|
||||
status |= 0b1;
|
||||
None
|
||||
}
|
||||
},
|
||||
_ => None,
|
||||
_ => {
|
||||
status |= 0b10;
|
||||
None
|
||||
}
|
||||
};
|
||||
let port = match port {
|
||||
Some(_) => port,
|
||||
@@ -41,25 +49,38 @@ impl ClashInfo {
|
||||
Some(value) => match value {
|
||||
Value::String(val_str) => Some(val_str.clone()),
|
||||
Value::Number(val_num) => Some(val_num.to_string()),
|
||||
_ => None,
|
||||
_ => {
|
||||
status |= 0b100;
|
||||
None
|
||||
}
|
||||
},
|
||||
_ => None,
|
||||
_ => {
|
||||
status |= 0b1000;
|
||||
None
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
// `external-controller` could be
|
||||
// "127.0.0.1:9090" or ":9090"
|
||||
let server = match config.get(&key_server) {
|
||||
Some(value) => {
|
||||
let val_str = value.as_str().unwrap_or("");
|
||||
|
||||
if val_str.starts_with(":") {
|
||||
Some(format!("127.0.0.1{val_str}"))
|
||||
} else {
|
||||
Some(val_str.into())
|
||||
Some(value) => match value.as_str() {
|
||||
Some(val_str) => {
|
||||
if val_str.starts_with(":") {
|
||||
Some(format!("127.0.0.1{val_str}"))
|
||||
} else {
|
||||
Some(val_str.into())
|
||||
}
|
||||
}
|
||||
None => {
|
||||
status |= 0b10000;
|
||||
None
|
||||
}
|
||||
},
|
||||
None => {
|
||||
status |= 0b100000;
|
||||
None
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let secret = match config.get(&key_secret) {
|
||||
@@ -73,7 +94,7 @@ impl ClashInfo {
|
||||
};
|
||||
|
||||
ClashInfo {
|
||||
status: "init".into(),
|
||||
status: format!("{status}"),
|
||||
port,
|
||||
server,
|
||||
secret,
|
||||
@@ -113,29 +134,16 @@ impl Clash {
|
||||
|
||||
/// patch update the clash config
|
||||
/// if the port is changed then return true
|
||||
pub fn patch_config(&mut self, patch: Mapping) -> Result<(bool, bool)> {
|
||||
pub fn patch_config(&mut self, patch: Mapping) -> Result<()> {
|
||||
let port_key = Value::from("mixed-port");
|
||||
let server_key = Value::from("external-controller");
|
||||
let secret_key = Value::from("secret");
|
||||
let mode_key = Value::from("mode");
|
||||
|
||||
let mut change_port = false;
|
||||
let mut change_info = false;
|
||||
let mut change_mode = false;
|
||||
let change_info = patch.contains_key(&port_key)
|
||||
|| patch.contains_key(&server_key)
|
||||
|| patch.contains_key(&secret_key);
|
||||
|
||||
for (key, value) in patch.into_iter() {
|
||||
if key == port_key {
|
||||
change_port = true;
|
||||
}
|
||||
|
||||
if key == mode_key {
|
||||
change_mode = true;
|
||||
}
|
||||
|
||||
if key == port_key || key == server_key || key == secret_key || key == mode_key {
|
||||
change_info = true;
|
||||
}
|
||||
|
||||
self.config.insert(key, value);
|
||||
}
|
||||
|
||||
@@ -143,148 +151,7 @@ impl Clash {
|
||||
self.info = ClashInfo::from(&self.config);
|
||||
}
|
||||
|
||||
self.save_config()?;
|
||||
|
||||
Ok((change_port, change_mode))
|
||||
}
|
||||
|
||||
/// revise the `tun` and `dns` config
|
||||
pub fn _tun_mode(mut config: Mapping, enable: bool) -> Mapping {
|
||||
macro_rules! revise {
|
||||
($map: expr, $key: expr, $val: expr) => {
|
||||
let ret_key = Value::String($key.into());
|
||||
$map.insert(ret_key, Value::from($val));
|
||||
};
|
||||
}
|
||||
|
||||
// if key not exists then append value
|
||||
macro_rules! append {
|
||||
($map: expr, $key: expr, $val: expr) => {
|
||||
let ret_key = Value::String($key.into());
|
||||
if !$map.contains_key(&ret_key) {
|
||||
$map.insert(ret_key, Value::from($val));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// tun config
|
||||
let tun_val = config.get(&Value::from("tun"));
|
||||
let mut new_tun = Mapping::new();
|
||||
|
||||
if tun_val.is_some() && tun_val.as_ref().unwrap().is_mapping() {
|
||||
new_tun = tun_val.as_ref().unwrap().as_mapping().unwrap().clone();
|
||||
}
|
||||
|
||||
revise!(new_tun, "enable", enable);
|
||||
|
||||
if enable {
|
||||
append!(new_tun, "stack", "gvisor");
|
||||
append!(new_tun, "dns-hijack", vec!["198.18.0.2:53"]);
|
||||
append!(new_tun, "auto-route", true);
|
||||
append!(new_tun, "auto-detect-interface", true);
|
||||
}
|
||||
|
||||
revise!(config, "tun", new_tun);
|
||||
|
||||
if enable {
|
||||
// dns config
|
||||
let dns_val = config.get(&Value::from("dns"));
|
||||
let mut new_dns = Mapping::new();
|
||||
|
||||
if dns_val.is_some() && dns_val.as_ref().unwrap().is_mapping() {
|
||||
new_dns = dns_val.as_ref().unwrap().as_mapping().unwrap().clone();
|
||||
}
|
||||
revise!(new_dns, "enable", enable);
|
||||
|
||||
// 借鉴cfw的默认配置
|
||||
append!(new_dns, "enhanced-mode", "fake-ip");
|
||||
append!(
|
||||
new_dns,
|
||||
"nameserver",
|
||||
vec!["114.114.114.114", "223.5.5.5", "8.8.8.8"]
|
||||
);
|
||||
append!(new_dns, "fallback", vec![] as Vec<&str>);
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
append!(
|
||||
new_dns,
|
||||
"fake-ip-filter",
|
||||
vec![
|
||||
"dns.msftncsi.com",
|
||||
"www.msftncsi.com",
|
||||
"www.msftconnecttest.com"
|
||||
]
|
||||
);
|
||||
|
||||
revise!(config, "dns", new_dns);
|
||||
}
|
||||
|
||||
config
|
||||
}
|
||||
|
||||
/// only 5 default fields available (clash config fields)
|
||||
/// convert to lowercase
|
||||
pub fn strict_filter(config: Mapping) -> Mapping {
|
||||
// Only the following fields are allowed:
|
||||
// proxies/proxy-providers/proxy-groups/rule-providers/rules
|
||||
let valid_keys = vec![
|
||||
"proxies",
|
||||
"proxy-providers",
|
||||
"proxy-groups",
|
||||
"rules",
|
||||
"rule-providers",
|
||||
];
|
||||
|
||||
let mut new_config = Mapping::new();
|
||||
|
||||
for (key, value) in config.into_iter() {
|
||||
key.as_str().map(|key_str| {
|
||||
// change to lowercase
|
||||
let mut key_str = String::from(key_str);
|
||||
key_str.make_ascii_lowercase();
|
||||
|
||||
// filter
|
||||
if valid_keys.contains(&&*key_str) {
|
||||
new_config.insert(Value::String(key_str), value);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
new_config
|
||||
}
|
||||
|
||||
/// more clash config fields available
|
||||
/// convert to lowercase
|
||||
pub fn loose_filter(config: Mapping) -> Mapping {
|
||||
// all of these can not be revised by script or merge
|
||||
// http/https/socks port should be under control
|
||||
let not_allow = vec![
|
||||
"port",
|
||||
"socks-port",
|
||||
"mixed-port",
|
||||
"allow-lan",
|
||||
"mode",
|
||||
"external-controller",
|
||||
"secret",
|
||||
"log-level",
|
||||
];
|
||||
|
||||
let mut new_config = Mapping::new();
|
||||
|
||||
for (key, value) in config.into_iter() {
|
||||
key.as_str().map(|key_str| {
|
||||
// change to lowercase
|
||||
let mut key_str = String::from(key_str);
|
||||
key_str.make_ascii_lowercase();
|
||||
|
||||
// filter
|
||||
if !not_allow.contains(&&*key_str) {
|
||||
new_config.insert(Value::String(key_str), value);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
new_config
|
||||
self.save_config()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
use super::prfitem::PrfItem;
|
||||
use crate::utils::{config, dirs};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_yaml::Mapping;
|
||||
use std::fs;
|
||||
|
||||
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PrfEnhanced {
|
||||
pub current: Mapping,
|
||||
|
||||
pub chain: Vec<PrfData>,
|
||||
|
||||
pub valid: Vec<String>,
|
||||
|
||||
pub callback: String,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PrfEnhancedResult {
|
||||
pub data: Option<Mapping>,
|
||||
|
||||
pub status: String,
|
||||
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PrfData {
|
||||
item: PrfItem,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
merge: Option<Mapping>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
script: Option<String>,
|
||||
}
|
||||
|
||||
impl PrfData {
|
||||
pub fn from_item(item: &PrfItem) -> Option<PrfData> {
|
||||
match item.itype.as_ref() {
|
||||
Some(itype) => {
|
||||
let file = item.file.clone()?;
|
||||
let path = dirs::app_profiles_dir().join(file);
|
||||
|
||||
if !path.exists() {
|
||||
return None;
|
||||
}
|
||||
|
||||
match itype.as_str() {
|
||||
"script" => Some(PrfData {
|
||||
item: item.clone(),
|
||||
script: Some(fs::read_to_string(path).unwrap_or("".into())),
|
||||
merge: None,
|
||||
}),
|
||||
"merge" => Some(PrfData {
|
||||
item: item.clone(),
|
||||
merge: Some(config::read_yaml::<Mapping>(path)),
|
||||
script: None,
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
+47
-172
@@ -1,20 +1,16 @@
|
||||
use self::notice::Notice;
|
||||
use self::sysopt::Sysopt;
|
||||
use self::timer::Timer;
|
||||
use crate::core::enhance::PrfEnhancedResult;
|
||||
use crate::config::enhance_config;
|
||||
use crate::log_if_err;
|
||||
use crate::utils::help;
|
||||
use anyhow::{bail, Result};
|
||||
use parking_lot::Mutex;
|
||||
use serde_yaml::Mapping;
|
||||
use serde_yaml::Value;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tauri::{AppHandle, Manager, Window};
|
||||
use tokio::time::sleep;
|
||||
|
||||
mod clash;
|
||||
mod enhance;
|
||||
mod notice;
|
||||
mod prfitem;
|
||||
mod profiles;
|
||||
@@ -29,41 +25,28 @@ pub use self::profiles::*;
|
||||
pub use self::service::*;
|
||||
pub use self::verge::*;
|
||||
|
||||
/// close the window for slient start
|
||||
/// after enhance mode
|
||||
static mut WINDOW_CLOSABLE: bool = true;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Core {
|
||||
pub clash: Arc<Mutex<Clash>>,
|
||||
|
||||
pub verge: Arc<Mutex<Verge>>,
|
||||
|
||||
pub profiles: Arc<Mutex<Profiles>>,
|
||||
|
||||
pub service: Arc<Mutex<Service>>,
|
||||
|
||||
pub sysopt: Arc<Mutex<Sysopt>>,
|
||||
|
||||
pub timer: Arc<Mutex<Timer>>,
|
||||
|
||||
pub runtime: Arc<Mutex<RuntimeResult>>,
|
||||
pub window: Arc<Mutex<Option<Window>>>,
|
||||
}
|
||||
|
||||
impl Core {
|
||||
pub fn new() -> Core {
|
||||
let clash = Clash::new();
|
||||
let verge = Verge::new();
|
||||
let profiles = Profiles::new();
|
||||
let service = Service::new();
|
||||
|
||||
Core {
|
||||
clash: Arc::new(Mutex::new(clash)),
|
||||
verge: Arc::new(Mutex::new(verge)),
|
||||
profiles: Arc::new(Mutex::new(profiles)),
|
||||
service: Arc::new(Mutex::new(service)),
|
||||
clash: Arc::new(Mutex::new(Clash::new())),
|
||||
verge: Arc::new(Mutex::new(Verge::new())),
|
||||
profiles: Arc::new(Mutex::new(Profiles::new())),
|
||||
service: Arc::new(Mutex::new(Service::new())),
|
||||
sysopt: Arc::new(Mutex::new(Sysopt::new())),
|
||||
timer: Arc::new(Mutex::new(Timer::new())),
|
||||
runtime: Arc::new(Mutex::new(RuntimeResult::default())),
|
||||
window: Arc::new(Mutex::new(None)),
|
||||
}
|
||||
}
|
||||
@@ -91,17 +74,8 @@ impl Core {
|
||||
let clash = self.clash.lock();
|
||||
let verge = self.verge.lock();
|
||||
|
||||
let silent_start = verge.enable_silent_start.clone();
|
||||
// let silent_start = verge.enable_silent_start.clone();
|
||||
let auto_launch = verge.enable_auto_launch.clone();
|
||||
|
||||
// silent start
|
||||
if silent_start.unwrap_or(false) {
|
||||
let window = self.window.lock();
|
||||
window.as_ref().map(|win| {
|
||||
win.hide().unwrap();
|
||||
});
|
||||
}
|
||||
|
||||
let mut sysopt = self.sysopt.lock();
|
||||
|
||||
sysopt.init_sysproxy(clash.info.port.clone(), &verge);
|
||||
@@ -114,13 +88,6 @@ impl Core {
|
||||
log_if_err!(self.update_systray(&app_handle));
|
||||
log_if_err!(self.update_systray_clash(&app_handle));
|
||||
|
||||
// wait the window setup during resolve app
|
||||
let core = self.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
sleep(Duration::from_secs(2)).await;
|
||||
log_if_err!(core.activate_enhanced(true));
|
||||
});
|
||||
|
||||
// timer initialize
|
||||
let mut timer = self.timer.lock();
|
||||
timer.set_core(self.clone());
|
||||
@@ -138,9 +105,7 @@ impl Core {
|
||||
let mut service = self.service.lock();
|
||||
service.restart()?;
|
||||
drop(service);
|
||||
|
||||
self.activate()?;
|
||||
self.activate_enhanced(true)
|
||||
self.activate()
|
||||
}
|
||||
|
||||
/// change the clash core
|
||||
@@ -164,34 +129,35 @@ impl Core {
|
||||
service.start()?;
|
||||
drop(service);
|
||||
|
||||
self.activate()?;
|
||||
self.activate_enhanced(true)
|
||||
self.activate()
|
||||
}
|
||||
|
||||
/// Patch Clash
|
||||
/// handle the clash config changed
|
||||
pub fn patch_clash(&self, patch: Mapping, app_handle: &AppHandle) -> Result<()> {
|
||||
let ((changed_port, changed_mode), port) = {
|
||||
let has_port = patch.contains_key(&Value::from("mixed-port"));
|
||||
let has_mode = patch.contains_key(&Value::from("mode"));
|
||||
|
||||
let port = {
|
||||
let mut clash = self.clash.lock();
|
||||
(clash.patch_config(patch)?, clash.info.port.clone())
|
||||
clash.patch_config(patch)?;
|
||||
clash.info.port.clone()
|
||||
};
|
||||
|
||||
// todo: port check
|
||||
|
||||
if changed_port {
|
||||
if has_port && port.is_some() {
|
||||
let mut service = self.service.lock();
|
||||
service.restart()?;
|
||||
drop(service);
|
||||
|
||||
self.activate()?;
|
||||
self.activate_enhanced(true)?;
|
||||
|
||||
let mut sysopt = self.sysopt.lock();
|
||||
let verge = self.verge.lock();
|
||||
sysopt.init_sysproxy(port, &verge);
|
||||
}
|
||||
|
||||
if changed_mode {
|
||||
if has_mode {
|
||||
self.update_systray_clash(app_handle)?;
|
||||
}
|
||||
|
||||
@@ -219,7 +185,8 @@ impl Core {
|
||||
service.start()?;
|
||||
drop(service);
|
||||
|
||||
self.activate_enhanced(false)?;
|
||||
// self.activate_enhanced(false)?;
|
||||
self.activate()?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -257,7 +224,7 @@ impl Core {
|
||||
}
|
||||
|
||||
if tun_mode.is_some() {
|
||||
self.activate_enhanced(false)?;
|
||||
self.activate()?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -341,138 +308,49 @@ impl Core {
|
||||
/// activate the profile
|
||||
/// auto activate enhanced profile
|
||||
pub fn activate(&self) -> Result<()> {
|
||||
let data = {
|
||||
let profile_activate = {
|
||||
let profiles = self.profiles.lock();
|
||||
let data = profiles.gen_activate()?;
|
||||
Clash::strict_filter(data)
|
||||
profiles.gen_activate()?
|
||||
};
|
||||
|
||||
let (mut config, info) = {
|
||||
let (clash_config, clash_info) = {
|
||||
let clash = self.clash.lock();
|
||||
let config = clash.config.clone();
|
||||
let info = clash.info.clone();
|
||||
(config, info)
|
||||
(clash.config.clone(), clash.info.clone())
|
||||
};
|
||||
|
||||
for (key, value) in data.into_iter() {
|
||||
config.insert(key, value);
|
||||
}
|
||||
|
||||
let config = {
|
||||
let tun_mode = {
|
||||
let verge = self.verge.lock();
|
||||
let tun_mode = verge.enable_tun_mode.unwrap_or(false);
|
||||
Clash::_tun_mode(config, tun_mode)
|
||||
verge.enable_tun_mode.unwrap_or(false)
|
||||
};
|
||||
|
||||
let (config, exists_keys, logs) = enhance_config(
|
||||
clash_config,
|
||||
profile_activate.current,
|
||||
profile_activate.chain,
|
||||
profile_activate.valid,
|
||||
tun_mode,
|
||||
);
|
||||
|
||||
let mut runtime = self.runtime.lock();
|
||||
runtime.config = Some(config.clone());
|
||||
runtime.config_yaml = Some(serde_yaml::to_string(&config).unwrap_or("".into()));
|
||||
runtime.exists_keys = exists_keys;
|
||||
runtime.chain_logs = logs;
|
||||
|
||||
let notice = {
|
||||
let window = self.window.lock();
|
||||
Notice::from(window.clone())
|
||||
};
|
||||
|
||||
let service = self.service.lock();
|
||||
service.set_config(info, config, notice)
|
||||
service.set_config(clash_info, config, notice)
|
||||
}
|
||||
|
||||
/// Enhanced
|
||||
/// enhanced profiles mode
|
||||
pub fn activate_enhanced(&self, skip: bool) -> Result<()> {
|
||||
let window = self.window.lock();
|
||||
if window.is_none() {
|
||||
bail!("failed to get the main window");
|
||||
}
|
||||
|
||||
let event_name = help::get_uid("e");
|
||||
let event_name = format!("enhanced-cb-{event_name}");
|
||||
|
||||
// generate the payload
|
||||
let payload = {
|
||||
let profiles = self.profiles.lock();
|
||||
profiles.gen_enhanced(event_name.clone())?
|
||||
};
|
||||
|
||||
// do not run enhanced
|
||||
if payload.chain.len() == 0 {
|
||||
if skip {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
drop(window);
|
||||
return self.activate();
|
||||
}
|
||||
|
||||
let tun_mode = {
|
||||
let verge = self.verge.lock();
|
||||
verge.enable_tun_mode.unwrap_or(false)
|
||||
};
|
||||
|
||||
let info = {
|
||||
let clash = self.clash.lock();
|
||||
clash.info.clone()
|
||||
};
|
||||
|
||||
let notice = Notice::from(window.clone());
|
||||
let service = self.service.clone();
|
||||
|
||||
let window = window.clone().unwrap();
|
||||
window.once(&event_name, move |event| {
|
||||
let result = event.payload();
|
||||
|
||||
if result.is_none() {
|
||||
log::warn!(target: "app", "event payload result is none");
|
||||
return;
|
||||
}
|
||||
|
||||
let result = result.unwrap();
|
||||
let result: PrfEnhancedResult = serde_json::from_str(result).unwrap();
|
||||
|
||||
if let Some(data) = result.data {
|
||||
let mut config = Clash::read_config();
|
||||
let filter_data = Clash::loose_filter(data); // loose filter
|
||||
|
||||
for (key, value) in filter_data.into_iter() {
|
||||
config.insert(key, value);
|
||||
}
|
||||
|
||||
let config = Clash::_tun_mode(config, tun_mode);
|
||||
|
||||
let service = service.lock();
|
||||
log_if_err!(service.set_config(info, config, notice));
|
||||
|
||||
log::info!(target: "app", "profile enhanced status {}", result.status);
|
||||
}
|
||||
|
||||
result.error.map(|err| log::error!(target: "app", "{err}"));
|
||||
});
|
||||
|
||||
let verge = self.verge.lock();
|
||||
let silent_start = verge.enable_silent_start.clone();
|
||||
|
||||
let closable = unsafe { WINDOW_CLOSABLE };
|
||||
|
||||
if silent_start.unwrap_or(false) && closable {
|
||||
unsafe {
|
||||
WINDOW_CLOSABLE = false;
|
||||
}
|
||||
|
||||
window.emit("script-handler-close", payload).unwrap();
|
||||
} else {
|
||||
window.emit("script-handler", payload).unwrap();
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Core {
|
||||
/// Static function
|
||||
/// update profile item
|
||||
pub async fn update_profile_item(
|
||||
core: Core,
|
||||
uid: String,
|
||||
option: Option<PrfOption>,
|
||||
) -> Result<()> {
|
||||
pub async fn update_profile_item(&self, uid: String, option: Option<PrfOption>) -> Result<()> {
|
||||
let (url, opt) = {
|
||||
let profiles = core.profiles.lock();
|
||||
let profiles = self.profiles.lock();
|
||||
let item = profiles.get_item(&uid)?;
|
||||
|
||||
if let Some(typ) = item.itype.as_ref() {
|
||||
@@ -481,30 +359,27 @@ impl Core {
|
||||
// reactivate the config
|
||||
if Some(uid) == profiles.get_current() {
|
||||
drop(profiles);
|
||||
return core.activate_enhanced(false);
|
||||
return self.activate();
|
||||
}
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
if item.url.is_none() {
|
||||
bail!("failed to get the profile item url");
|
||||
}
|
||||
|
||||
(item.url.clone().unwrap(), item.option.clone())
|
||||
};
|
||||
|
||||
let merged_opt = PrfOption::merge(opt, option);
|
||||
let item = PrfItem::from_url(&url, None, None, merged_opt).await?;
|
||||
|
||||
let mut profiles = core.profiles.lock();
|
||||
let mut profiles = self.profiles.lock();
|
||||
profiles.update_item(uid.clone(), item)?;
|
||||
|
||||
// reactivate the profile
|
||||
if Some(uid) == profiles.get_current() {
|
||||
drop(profiles);
|
||||
core.activate_enhanced(false)?;
|
||||
self.activate()?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -11,6 +11,7 @@ impl Notice {
|
||||
Notice { win }
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
pub fn set_win(&mut self, win: Option<Window>) {
|
||||
self.win = win;
|
||||
}
|
||||
@@ -27,6 +28,7 @@ impl Notice {
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
pub fn refresh_profiles(&self) {
|
||||
if let Some(window) = self.win.as_ref() {
|
||||
log_if_err!(window.emit("verge://refresh-profiles-config", "yes"));
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::utils::{dirs, help, tmpl};
|
||||
use crate::utils::{config, dirs, help, tmpl};
|
||||
use anyhow::{bail, Context, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_yaml::Mapping;
|
||||
@@ -333,4 +333,40 @@ impl PrfItem {
|
||||
let path = dirs::app_profiles_dir().join(file);
|
||||
fs::write(path, data.as_bytes()).context("failed to save the file")
|
||||
}
|
||||
|
||||
/// get the data for enhanced mode
|
||||
pub fn to_enhance(&self) -> Option<ChainItem> {
|
||||
let itype = self.itype.as_ref()?.as_str();
|
||||
let file = self.file.clone()?;
|
||||
let uid = self.uid.clone().unwrap_or("".into());
|
||||
let path = dirs::app_profiles_dir().join(file);
|
||||
|
||||
if !path.exists() {
|
||||
return None;
|
||||
}
|
||||
|
||||
match itype {
|
||||
"script" => Some(ChainItem {
|
||||
uid,
|
||||
data: ChainType::Script(fs::read_to_string(path).unwrap_or("".into())),
|
||||
}),
|
||||
"merge" => Some(ChainItem {
|
||||
uid,
|
||||
data: ChainType::Merge(config::read_yaml::<Mapping>(path)),
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ChainItem {
|
||||
pub uid: String,
|
||||
pub data: ChainType,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum ChainType {
|
||||
Merge(Mapping),
|
||||
Script(String),
|
||||
}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
use super::enhance::{PrfData, PrfEnhanced};
|
||||
use super::prfitem::PrfItem;
|
||||
use super::ChainItem;
|
||||
use crate::utils::{config, dirs, help};
|
||||
use anyhow::{bail, Context, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_yaml::Mapping;
|
||||
use std::collections::HashMap;
|
||||
use std::{fs, io::Write};
|
||||
|
||||
///
|
||||
@@ -91,13 +92,15 @@ impl Profiles {
|
||||
}
|
||||
|
||||
/// just change the `chain`
|
||||
pub fn put_chain(&mut self, chain: Option<Vec<String>>) {
|
||||
pub fn put_chain(&mut self, chain: Option<Vec<String>>) -> Result<()> {
|
||||
self.chain = chain;
|
||||
self.save_file()
|
||||
}
|
||||
|
||||
/// just change the `field`
|
||||
pub fn put_valid(&mut self, valid: Option<Vec<String>>) {
|
||||
pub fn put_valid(&mut self, valid: Option<Vec<String>>) -> Result<()> {
|
||||
self.valid = valid;
|
||||
self.save_file()
|
||||
}
|
||||
|
||||
/// get items ref
|
||||
@@ -260,8 +263,8 @@ impl Profiles {
|
||||
Ok(current == uid)
|
||||
}
|
||||
|
||||
/// only generate config mapping
|
||||
pub fn gen_activate(&self) -> Result<Mapping> {
|
||||
/// generate the current Mapping data
|
||||
fn gen_current(&self) -> Result<Mapping> {
|
||||
let config = Mapping::new();
|
||||
|
||||
if self.current.is_none() || self.items.is_none() {
|
||||
@@ -269,7 +272,6 @@ impl Profiles {
|
||||
}
|
||||
|
||||
let current = self.current.clone().unwrap();
|
||||
|
||||
for item in self.items.as_ref().unwrap().iter() {
|
||||
if item.uid == Some(current.clone()) {
|
||||
let file_path = match item.file.clone() {
|
||||
@@ -284,34 +286,43 @@ impl Profiles {
|
||||
return Ok(config::read_yaml::<Mapping>(file_path.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
bail!("failed to found the uid \"{current}\"");
|
||||
}
|
||||
|
||||
/// gen the enhanced profiles
|
||||
pub fn gen_enhanced(&self, callback: String) -> Result<PrfEnhanced> {
|
||||
let current = self.gen_activate()?;
|
||||
|
||||
/// generate the data for activate clash config
|
||||
pub fn gen_activate(&self) -> Result<PrfActivate> {
|
||||
let current = self.gen_current()?;
|
||||
let chain = match self.chain.as_ref() {
|
||||
Some(chain) => chain
|
||||
.iter()
|
||||
.map(|uid| self.get_item(uid))
|
||||
.filter(|item| item.is_ok())
|
||||
.map(|item| item.unwrap())
|
||||
.map(|item| PrfData::from_item(item))
|
||||
.filter(|o| o.is_some())
|
||||
.map(|o| o.unwrap())
|
||||
.collect::<Vec<PrfData>>(),
|
||||
.filter_map(|uid| self.get_item(uid).ok())
|
||||
.filter_map(|item| item.to_enhance())
|
||||
.collect::<Vec<ChainItem>>(),
|
||||
None => vec![],
|
||||
};
|
||||
|
||||
let valid = self.valid.clone().unwrap_or(vec![]);
|
||||
|
||||
Ok(PrfEnhanced {
|
||||
Ok(PrfActivate {
|
||||
current,
|
||||
chain,
|
||||
valid,
|
||||
callback,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
pub struct PrfActivate {
|
||||
pub current: Mapping,
|
||||
pub chain: Vec<ChainItem>,
|
||||
pub valid: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct RuntimeResult {
|
||||
pub config: Option<Mapping>,
|
||||
pub config_yaml: Option<String>,
|
||||
// 记录在配置中(包括merge和script生成的)出现过的keys
|
||||
// 这些keys不一定都生效
|
||||
pub exists_keys: Vec<String>,
|
||||
pub chain_logs: HashMap<String, Vec<(String, String)>>,
|
||||
}
|
||||
|
||||
@@ -196,10 +196,11 @@ impl Service {
|
||||
/// get clash client url and headers from clash info
|
||||
fn clash_client_info(info: ClashInfo) -> Result<(String, HeaderMap)> {
|
||||
if info.server.is_none() {
|
||||
let status = &info.status;
|
||||
if info.port.is_none() {
|
||||
bail!("failed to parse config.yaml file");
|
||||
bail!("failed to parse config.yaml file with status {status}");
|
||||
} else {
|
||||
bail!("failed to parse the server");
|
||||
bail!("failed to parse the server with status {status}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -87,6 +87,14 @@ impl Sysopt {
|
||||
/// reset the sysproxy
|
||||
pub fn reset_sysproxy(&mut self) {
|
||||
if let Some(sysproxy) = self.old_sysproxy.take() {
|
||||
// 如果原代理设置是开启的,且域名端口设置和当前的一致,就不恢复原设置
|
||||
// https://github.com/zzzgydi/clash-verge/issues/157
|
||||
if let Some(cur) = self.cur_sysproxy.as_ref() {
|
||||
if sysproxy.enable && cur.server == sysproxy.server {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
match sysproxy.set_sys() {
|
||||
Ok(_) => self.cur_sysproxy = None,
|
||||
Err(_) => log::error!(target: "app", "failed to reset proxy"),
|
||||
@@ -193,7 +201,10 @@ impl Sysopt {
|
||||
|
||||
log_if_err!(sysproxy.set_sys());
|
||||
}
|
||||
None => log::error!(target: "app", "failed to parse clash port"),
|
||||
None => {
|
||||
let status = &clash.info.status;
|
||||
log::error!(target: "app", "failed to parse clash port with status {status}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -140,7 +140,7 @@ impl Timer {
|
||||
/// the task runner
|
||||
async fn async_task(core: Core, uid: String) {
|
||||
log::info!(target: "app", "running timer task `{uid}`");
|
||||
log_if_err!(Core::update_profile_item(core, uid, None).await);
|
||||
log_if_err!(core.update_profile_item(uid, None).await);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+24
-45
@@ -46,6 +46,9 @@ pub struct Verge {
|
||||
/// theme setting
|
||||
pub theme_setting: Option<VergeTheme>,
|
||||
|
||||
/// web ui list
|
||||
pub web_ui_list: Option<Vec<String>>,
|
||||
|
||||
/// clash core path
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub clash_core: Option<String>,
|
||||
@@ -84,55 +87,31 @@ impl Verge {
|
||||
/// patch verge config
|
||||
/// only save to file
|
||||
pub fn patch_config(&mut self, patch: Verge) -> Result<()> {
|
||||
// only change it
|
||||
if patch.language.is_some() {
|
||||
self.language = patch.language;
|
||||
}
|
||||
if patch.theme_mode.is_some() {
|
||||
self.theme_mode = patch.theme_mode;
|
||||
}
|
||||
if patch.theme_blur.is_some() {
|
||||
self.theme_blur = patch.theme_blur;
|
||||
}
|
||||
if patch.theme_setting.is_some() {
|
||||
self.theme_setting = patch.theme_setting;
|
||||
}
|
||||
if patch.traffic_graph.is_some() {
|
||||
self.traffic_graph = patch.traffic_graph;
|
||||
}
|
||||
if patch.clash_core.is_some() {
|
||||
self.clash_core = patch.clash_core;
|
||||
macro_rules! patch {
|
||||
($key: tt) => {
|
||||
if patch.$key.is_some() {
|
||||
self.$key = patch.$key;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// system setting
|
||||
if patch.enable_silent_start.is_some() {
|
||||
self.enable_silent_start = patch.enable_silent_start;
|
||||
}
|
||||
if patch.enable_auto_launch.is_some() {
|
||||
self.enable_auto_launch = patch.enable_auto_launch;
|
||||
}
|
||||
patch!(language);
|
||||
patch!(theme_mode);
|
||||
patch!(theme_blur);
|
||||
patch!(traffic_graph);
|
||||
|
||||
// proxy
|
||||
if patch.enable_system_proxy.is_some() {
|
||||
self.enable_system_proxy = patch.enable_system_proxy;
|
||||
}
|
||||
if patch.system_proxy_bypass.is_some() {
|
||||
self.system_proxy_bypass = patch.system_proxy_bypass;
|
||||
}
|
||||
if patch.enable_proxy_guard.is_some() {
|
||||
self.enable_proxy_guard = patch.enable_proxy_guard;
|
||||
}
|
||||
if patch.proxy_guard_duration.is_some() {
|
||||
self.proxy_guard_duration = patch.proxy_guard_duration;
|
||||
}
|
||||
patch!(enable_tun_mode);
|
||||
patch!(enable_service_mode);
|
||||
patch!(enable_auto_launch);
|
||||
patch!(enable_silent_start);
|
||||
patch!(enable_system_proxy);
|
||||
patch!(enable_proxy_guard);
|
||||
patch!(system_proxy_bypass);
|
||||
patch!(proxy_guard_duration);
|
||||
|
||||
// tun mode
|
||||
if patch.enable_tun_mode.is_some() {
|
||||
self.enable_tun_mode = patch.enable_tun_mode;
|
||||
}
|
||||
if patch.enable_service_mode.is_some() {
|
||||
self.enable_service_mode = patch.enable_service_mode;
|
||||
}
|
||||
patch!(theme_setting);
|
||||
patch!(web_ui_list);
|
||||
patch!(clash_core);
|
||||
|
||||
self.save_file()
|
||||
}
|
||||
|
||||
+18
-1
@@ -4,6 +4,7 @@
|
||||
)]
|
||||
|
||||
mod cmds;
|
||||
mod config;
|
||||
mod core;
|
||||
mod utils;
|
||||
|
||||
@@ -39,6 +40,7 @@ fn main() -> std::io::Result<()> {
|
||||
.add_item(CustomMenuItem::new("system_proxy", "System Proxy"))
|
||||
.add_item(CustomMenuItem::new("tun_mode", "Tun Mode"))
|
||||
.add_item(CustomMenuItem::new("restart_clash", "Restart Clash"))
|
||||
.add_item(CustomMenuItem::new("restart_app", "Restart App"))
|
||||
.add_native_item(SystemTrayMenuItem::Separator)
|
||||
.add_item(CustomMenuItem::new("quit", "Quit").accelerator("CmdOrControl+Q"));
|
||||
|
||||
@@ -90,6 +92,9 @@ fn main() -> std::io::Result<()> {
|
||||
let core = app_handle.state::<core::Core>();
|
||||
crate::log_if_err!(core.restart_clash());
|
||||
}
|
||||
"restart_app" => {
|
||||
api::process::restart(&app_handle.env());
|
||||
}
|
||||
"quit" => {
|
||||
resolve::resolve_reset(app_handle);
|
||||
app_handle.exit(0);
|
||||
@@ -108,12 +113,17 @@ fn main() -> std::io::Result<()> {
|
||||
cmds::get_cur_proxy,
|
||||
cmds::open_app_dir,
|
||||
cmds::open_logs_dir,
|
||||
cmds::open_web_url,
|
||||
cmds::kill_sidecar,
|
||||
cmds::restart_sidecar,
|
||||
// clash
|
||||
cmds::get_clash_info,
|
||||
cmds::patch_clash_config,
|
||||
cmds::change_clash_core,
|
||||
cmds::get_runtime_config,
|
||||
cmds::get_runtime_yaml,
|
||||
cmds::get_runtime_exists,
|
||||
cmds::get_runtime_logs,
|
||||
// verge
|
||||
cmds::get_verge_config,
|
||||
cmds::patch_verge_config,
|
||||
@@ -156,8 +166,15 @@ fn main() -> std::io::Result<()> {
|
||||
builder = builder.menu(Menu::new().add_submenu(submenu_file));
|
||||
}
|
||||
|
||||
let mut context = tauri::generate_context!();
|
||||
let verge = Verge::new();
|
||||
for win in context.config_mut().tauri.windows.iter_mut() {
|
||||
if verge.enable_silent_start.unwrap_or(false) {
|
||||
win.visible = false;
|
||||
}
|
||||
}
|
||||
builder
|
||||
.build(tauri::generate_context!())
|
||||
.build(context)
|
||||
.expect("error while running tauri application")
|
||||
.run(|app_handle, e| match e {
|
||||
tauri::RunEvent::ExitRequested { api, .. } => {
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
// use crate::core::{Clash, Profiles, Verge};
|
||||
// use std::sync::{Arc, Mutex};
|
||||
|
||||
// #[derive(Default)]
|
||||
// pub struct ProfilesState(pub Arc<Mutex<Profiles>>);
|
||||
|
||||
// #[derive(Default)]
|
||||
// pub struct ClashState(pub Arc<Mutex<Clash>>);
|
||||
|
||||
// #[derive(Default)]
|
||||
// pub struct VergeState(pub Arc<Mutex<Verge>>);
|
||||
+16
-16
@@ -1,4 +1,5 @@
|
||||
use crate::utils::{dirs, tmpl};
|
||||
use anyhow::Result;
|
||||
use chrono::Local;
|
||||
use log::LevelFilter;
|
||||
use log4rs::append::console::ConsoleAppender;
|
||||
@@ -11,7 +12,7 @@ use std::path::PathBuf;
|
||||
use tauri::PackageInfo;
|
||||
|
||||
/// initialize this instance's log file
|
||||
fn init_log(log_dir: &PathBuf) {
|
||||
fn init_log(log_dir: &PathBuf) -> Result<()> {
|
||||
let local_time = Local::now().format("%Y-%m-%d-%H%M%S").to_string();
|
||||
let log_file = format!("{}.log", local_time);
|
||||
let log_file = log_dir.join(log_file);
|
||||
@@ -22,8 +23,7 @@ fn init_log(log_dir: &PathBuf) {
|
||||
.build();
|
||||
let tofile = FileAppender::builder()
|
||||
.encoder(Box::new(PatternEncoder::new(time_format)))
|
||||
.build(log_file)
|
||||
.unwrap();
|
||||
.build(log_file)?;
|
||||
|
||||
let config = Config::builder()
|
||||
.appender(Appender::builder().build("stdout", Box::new(stdout)))
|
||||
@@ -34,14 +34,15 @@ fn init_log(log_dir: &PathBuf) {
|
||||
.additive(false)
|
||||
.build("app", LevelFilter::Info),
|
||||
)
|
||||
.build(Root::builder().appender("stdout").build(LevelFilter::Info))
|
||||
.unwrap();
|
||||
.build(Root::builder().appender("stdout").build(LevelFilter::Info))?;
|
||||
|
||||
log4rs::init_config(config).unwrap();
|
||||
log4rs::init_config(config)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Initialize all the files from resources
|
||||
fn init_config(app_dir: &PathBuf) -> std::io::Result<()> {
|
||||
fn init_config(app_dir: &PathBuf) -> Result<()> {
|
||||
// target path
|
||||
let clash_path = app_dir.join("config.yaml");
|
||||
let verge_path = app_dir.join("verge.yaml");
|
||||
@@ -69,25 +70,24 @@ pub fn init_app(package_info: &PackageInfo) {
|
||||
let res_dir = dirs::app_resources_dir(package_info);
|
||||
|
||||
if !app_dir.exists() {
|
||||
fs::create_dir_all(&app_dir).unwrap();
|
||||
let _ = fs::create_dir_all(&app_dir);
|
||||
}
|
||||
if !log_dir.exists() {
|
||||
fs::create_dir_all(&log_dir).unwrap();
|
||||
let _ = fs::create_dir_all(&log_dir);
|
||||
}
|
||||
if !profiles_dir.exists() {
|
||||
fs::create_dir_all(&profiles_dir).unwrap();
|
||||
let _ = fs::create_dir_all(&profiles_dir);
|
||||
}
|
||||
|
||||
init_log(&log_dir);
|
||||
if let Err(err) = init_config(&app_dir) {
|
||||
log::error!(target: "app", "{err}");
|
||||
}
|
||||
crate::log_if_err!(init_log(&log_dir));
|
||||
|
||||
crate::log_if_err!(init_config(&app_dir));
|
||||
|
||||
// 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();
|
||||
let _ = fs::copy(mmdb_tmpl, mmdb_path);
|
||||
}
|
||||
|
||||
// copy the wintun.dll
|
||||
@@ -96,7 +96,7 @@ pub fn init_app(package_info: &PackageInfo) {
|
||||
let wintun_path = app_dir.join("wintun.dll");
|
||||
let wintun_tmpl = res_dir.join("wintun.dll");
|
||||
if !wintun_path.exists() && wintun_tmpl.exists() {
|
||||
fs::copy(wintun_tmpl, wintun_path).unwrap();
|
||||
let _ = fs::copy(wintun_tmpl, wintun_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,6 +88,8 @@ pub fn create_window(app_handle: &AppHandle) {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
use crate::utils::winhelp;
|
||||
use std::time::Duration;
|
||||
use tokio::time::sleep;
|
||||
use window_shadows::set_shadow;
|
||||
use window_vibrancy::apply_blur;
|
||||
|
||||
@@ -101,6 +103,8 @@ pub fn create_window(app_handle: &AppHandle) {
|
||||
let app_handle = app_handle.clone();
|
||||
|
||||
tauri::async_runtime::spawn(async move {
|
||||
sleep(Duration::from_secs(1)).await;
|
||||
|
||||
if let Some(window) = app_handle.get_window("main") {
|
||||
let _ = window.show();
|
||||
let _ = set_shadow(&window, true);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"package": {
|
||||
"productName": "Clash Verge",
|
||||
"version": "1.0.4"
|
||||
"version": "1.0.5"
|
||||
},
|
||||
"build": {
|
||||
"distDir": "../dist",
|
||||
@@ -25,13 +25,8 @@
|
||||
"icons/icon-new.icns",
|
||||
"icons/icon.ico"
|
||||
],
|
||||
"resources": [
|
||||
"resources"
|
||||
],
|
||||
"externalBin": [
|
||||
"sidecar/clash",
|
||||
"sidecar/clash-meta"
|
||||
],
|
||||
"resources": ["resources"],
|
||||
"externalBin": ["sidecar/clash", "sidecar/clash-meta"],
|
||||
"copyright": "© 2022 zzzgydi All Rights Reserved",
|
||||
"category": "DeveloperTool",
|
||||
"shortDescription": "A Clash GUI based on tauri.",
|
||||
@@ -51,10 +46,7 @@
|
||||
"digestAlgorithm": "sha256",
|
||||
"timestampUrl": "",
|
||||
"wix": {
|
||||
"language": [
|
||||
"zh-CN",
|
||||
"en-US"
|
||||
]
|
||||
"language": ["zh-CN", "en-US"]
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -95,4 +87,4 @@
|
||||
"csp": "script-src 'unsafe-eval' 'self'; default-src blob: data: filesystem: ws: wss: http: https: tauri: 'unsafe-eval' 'unsafe-inline' 'self'; img-src data: 'self';"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { alpha, Box, Typography } from "@mui/material";
|
||||
import { BlurOnRounded } from "@mui/icons-material";
|
||||
|
||||
interface Props {
|
||||
text?: React.ReactNode;
|
||||
extra?: React.ReactNode;
|
||||
}
|
||||
|
||||
const BaseEmpty = (props: Props) => {
|
||||
const { text = "Empty", extra } = props;
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={({ palette }) => ({
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
color: alpha(palette.text.secondary, 0.75),
|
||||
})}
|
||||
>
|
||||
<BlurOnRounded sx={{ fontSize: "4em" }} />
|
||||
<Typography sx={{ fontSize: "1.25em" }}>{text}</Typography>
|
||||
{extra}
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export default BaseEmpty;
|
||||
@@ -2,9 +2,8 @@ import dayjs from "dayjs";
|
||||
import { useLockFn } from "ahooks";
|
||||
import { styled, ListItem, IconButton, ListItemText } from "@mui/material";
|
||||
import { CloseRounded } from "@mui/icons-material";
|
||||
import { ApiType } from "../../services/types";
|
||||
import { deleteConnection } from "../../services/api";
|
||||
import parseTraffic from "../../utils/parse-traffic";
|
||||
import { deleteConnection } from "@/services/api";
|
||||
import parseTraffic from "@/utils/parse-traffic";
|
||||
|
||||
const Tag = styled("span")(({ theme }) => ({
|
||||
display: "inline-block",
|
||||
|
||||
@@ -4,13 +4,12 @@ import { useRecoilValue } from "recoil";
|
||||
import { Box, Typography } from "@mui/material";
|
||||
import { ArrowDownward, ArrowUpward } from "@mui/icons-material";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { ApiType } from "../../services/types";
|
||||
import { getInformation } from "../../services/api";
|
||||
import { getVergeConfig } from "../../services/cmds";
|
||||
import { atomClashPort } from "../../services/states";
|
||||
import { getInformation } from "@/services/api";
|
||||
import { getVergeConfig } from "@/services/cmds";
|
||||
import { atomClashPort } from "@/services/states";
|
||||
import TrafficGraph from "./traffic-graph";
|
||||
import useLogSetup from "./use-log-setup";
|
||||
import parseTraffic from "../../utils/parse-traffic";
|
||||
import parseTraffic from "@/utils/parse-traffic";
|
||||
|
||||
// setup the traffic
|
||||
const LayoutTraffic = () => {
|
||||
|
||||
@@ -2,6 +2,7 @@ import useSWR from "swr";
|
||||
import snarkdown from "snarkdown";
|
||||
import { useMemo } from "react";
|
||||
import { useRecoilState } from "recoil";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
Box,
|
||||
Button,
|
||||
@@ -13,8 +14,8 @@ import {
|
||||
} from "@mui/material";
|
||||
import { relaunch } from "@tauri-apps/api/process";
|
||||
import { checkUpdate, installUpdate } from "@tauri-apps/api/updater";
|
||||
import { killSidecar, restartSidecar } from "../../services/cmds";
|
||||
import { atomUpdateState } from "../../services/states";
|
||||
import { killSidecar, restartSidecar } from "@/services/cmds";
|
||||
import { atomUpdateState } from "@/services/states";
|
||||
import Notice from "../base/base-notice";
|
||||
|
||||
interface Props {
|
||||
@@ -28,6 +29,7 @@ const UpdateLog = styled(Box)(() => ({
|
||||
|
||||
const UpdateDialog = (props: Props) => {
|
||||
const { open, onClose } = props;
|
||||
const { t } = useTranslation();
|
||||
const { data: updateInfo } = useSWR("checkUpdate", checkUpdate, {
|
||||
errorRetryCount: 2,
|
||||
revalidateIfStale: false,
|
||||
@@ -69,14 +71,16 @@ const UpdateDialog = (props: Props) => {
|
||||
</DialogContent>
|
||||
|
||||
<DialogActions>
|
||||
<Button onClick={onClose}>Cancel</Button>
|
||||
<Button variant="outlined" onClick={onClose}>
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
autoFocus
|
||||
variant="contained"
|
||||
disabled={updateState}
|
||||
onClick={onUpdate}
|
||||
>
|
||||
Update
|
||||
{t("Update")}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
@@ -3,9 +3,9 @@ import { useEffect, useMemo } from "react";
|
||||
import { useRecoilState } from "recoil";
|
||||
import { createTheme } from "@mui/material";
|
||||
import { appWindow } from "@tauri-apps/api/window";
|
||||
import { getVergeConfig } from "../../services/cmds";
|
||||
import { atomThemeMode } from "../../services/states";
|
||||
import { defaultTheme, defaultDarkTheme } from "../../pages/_theme";
|
||||
import { getVergeConfig } from "@/services/cmds";
|
||||
import { atomThemeMode } from "@/services/states";
|
||||
import { defaultTheme, defaultDarkTheme } from "@/pages/_theme";
|
||||
|
||||
/**
|
||||
* custome theme
|
||||
@@ -16,8 +16,12 @@ export default function useCustomTheme() {
|
||||
const [mode, setMode] = useRecoilState(atomThemeMode);
|
||||
|
||||
useEffect(() => {
|
||||
if (theme_mode !== "system") {
|
||||
setMode(theme_mode ?? "light");
|
||||
const themeMode = ["light", "dark", "system"].includes(theme_mode!)
|
||||
? theme_mode!
|
||||
: "light";
|
||||
|
||||
if (themeMode !== "system") {
|
||||
setMode(themeMode);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,9 +2,8 @@ import dayjs from "dayjs";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useSetRecoilState } from "recoil";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { ApiType } from "../../services/types";
|
||||
import { getInformation } from "../../services/api";
|
||||
import { atomLogData } from "../../services/states";
|
||||
import { getInformation } from "@/services/api";
|
||||
import { atomLogData } from "@/services/states";
|
||||
|
||||
const MAX_LOG_NUM = 1000;
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { styled, Box } from "@mui/material";
|
||||
import { ApiType } from "../../services/types";
|
||||
|
||||
const Item = styled(Box)(({ theme }) => ({
|
||||
padding: "8px 0",
|
||||
|
||||
@@ -1,31 +1,14 @@
|
||||
import useSWR from "swr";
|
||||
import { useState } from "react";
|
||||
import { useLockFn } from "ahooks";
|
||||
import {
|
||||
Box,
|
||||
Divider,
|
||||
Grid,
|
||||
IconButton,
|
||||
ListItemIcon,
|
||||
ListItemText,
|
||||
Menu,
|
||||
MenuItem,
|
||||
Stack,
|
||||
} from "@mui/material";
|
||||
import {
|
||||
AddchartRounded,
|
||||
CheckRounded,
|
||||
MenuRounded,
|
||||
RestartAltRounded,
|
||||
} from "@mui/icons-material";
|
||||
import { Box, Grid, IconButton, Stack } from "@mui/material";
|
||||
import { RestartAltRounded } from "@mui/icons-material";
|
||||
import {
|
||||
getProfiles,
|
||||
deleteProfile,
|
||||
enhanceProfiles,
|
||||
changeProfileChain,
|
||||
changeProfileValid,
|
||||
} from "../../services/cmds";
|
||||
import { CmdType } from "../../services/types";
|
||||
getRuntimeLogs,
|
||||
} from "@/services/cmds";
|
||||
import ProfileMore from "./profile-more";
|
||||
import Notice from "../base/base-notice";
|
||||
|
||||
@@ -37,15 +20,17 @@ interface Props {
|
||||
const EnhancedMode = (props: Props) => {
|
||||
const { items, chain } = props;
|
||||
|
||||
const { data, mutate } = useSWR("getProfiles", getProfiles);
|
||||
const valid = data?.valid || [];
|
||||
|
||||
const [anchorEl, setAnchorEl] = useState<any>(null);
|
||||
const { mutate: mutateProfiles } = useSWR("getProfiles", getProfiles);
|
||||
const { data: chainLogs = {}, mutate: mutateLogs } = useSWR(
|
||||
"getRuntimeLogs",
|
||||
getRuntimeLogs
|
||||
);
|
||||
|
||||
// handler
|
||||
const onEnhance = useLockFn(async () => {
|
||||
try {
|
||||
await enhanceProfiles();
|
||||
mutateLogs();
|
||||
Notice.success("Refresh clash config", 1000);
|
||||
} catch (err: any) {
|
||||
Notice.error(err.message || err.toString());
|
||||
@@ -57,7 +42,8 @@ const EnhancedMode = (props: Props) => {
|
||||
|
||||
const newChain = [...chain, uid];
|
||||
await changeProfileChain(newChain);
|
||||
mutate((conf = {}) => ({ ...conf, chain: newChain }), true);
|
||||
mutateProfiles((conf = {}) => ({ ...conf, chain: newChain }), true);
|
||||
mutateLogs();
|
||||
});
|
||||
|
||||
const onEnhanceDisable = useLockFn(async (uid: string) => {
|
||||
@@ -65,14 +51,16 @@ const EnhancedMode = (props: Props) => {
|
||||
|
||||
const newChain = chain.filter((i) => i !== uid);
|
||||
await changeProfileChain(newChain);
|
||||
mutate((conf = {}) => ({ ...conf, chain: newChain }), true);
|
||||
mutateProfiles((conf = {}) => ({ ...conf, chain: newChain }), true);
|
||||
mutateLogs();
|
||||
});
|
||||
|
||||
const onEnhanceDelete = useLockFn(async (uid: string) => {
|
||||
try {
|
||||
await onEnhanceDisable(uid);
|
||||
await deleteProfile(uid);
|
||||
mutate();
|
||||
mutateProfiles();
|
||||
mutateLogs();
|
||||
} catch (err: any) {
|
||||
Notice.error(err?.message || err.toString());
|
||||
}
|
||||
@@ -83,7 +71,8 @@ const EnhancedMode = (props: Props) => {
|
||||
|
||||
const newChain = [uid].concat(chain.filter((i) => i !== uid));
|
||||
await changeProfileChain(newChain);
|
||||
mutate((conf = {}) => ({ ...conf, chain: newChain }), true);
|
||||
mutateProfiles((conf = {}) => ({ ...conf, chain: newChain }), true);
|
||||
mutateLogs();
|
||||
});
|
||||
|
||||
const onMoveEnd = useLockFn(async (uid: string) => {
|
||||
@@ -91,24 +80,12 @@ const EnhancedMode = (props: Props) => {
|
||||
|
||||
const newChain = chain.filter((i) => i !== uid).concat([uid]);
|
||||
await changeProfileChain(newChain);
|
||||
mutate((conf = {}) => ({ ...conf, chain: newChain }), true);
|
||||
});
|
||||
|
||||
// update valid list
|
||||
const onToggleValid = useLockFn(async (key: string) => {
|
||||
try {
|
||||
const newValid = valid.includes(key)
|
||||
? valid.filter((i) => i !== key)
|
||||
: valid.concat(key);
|
||||
await changeProfileValid(newValid);
|
||||
mutate();
|
||||
} catch (err: any) {
|
||||
Notice.error(err.message || err.toString());
|
||||
}
|
||||
mutateProfiles((conf = {}) => ({ ...conf, chain: newChain }), true);
|
||||
mutateLogs();
|
||||
});
|
||||
|
||||
return (
|
||||
<Box sx={{ mt: 4 }}>
|
||||
<Box sx={{ mt: 2 }}>
|
||||
<Stack
|
||||
spacing={1}
|
||||
direction="row"
|
||||
@@ -124,72 +101,6 @@ const EnhancedMode = (props: Props) => {
|
||||
>
|
||||
<RestartAltRounded />
|
||||
</IconButton>
|
||||
|
||||
<IconButton
|
||||
size="small"
|
||||
color="inherit"
|
||||
id="profile-use-button"
|
||||
title="enable clash fields"
|
||||
aria-controls={!!anchorEl ? "profile-use-menu" : undefined}
|
||||
aria-haspopup="true"
|
||||
aria-expanded={!!anchorEl ? "true" : undefined}
|
||||
onClick={(e) => setAnchorEl(e.currentTarget)}
|
||||
>
|
||||
<MenuRounded />
|
||||
</IconButton>
|
||||
|
||||
<Menu
|
||||
id="profile-use-menu"
|
||||
open={!!anchorEl}
|
||||
anchorEl={anchorEl}
|
||||
onClose={() => setAnchorEl(null)}
|
||||
transitionDuration={225}
|
||||
MenuListProps={{
|
||||
dense: true,
|
||||
"aria-labelledby": "profile-use-button",
|
||||
}}
|
||||
onContextMenu={(e) => {
|
||||
setAnchorEl(null);
|
||||
e.preventDefault();
|
||||
}}
|
||||
>
|
||||
<MenuItem>
|
||||
<ListItemIcon color="inherit">
|
||||
<AddchartRounded />
|
||||
</ListItemIcon>
|
||||
Use Clash Fields
|
||||
</MenuItem>
|
||||
|
||||
<Divider />
|
||||
|
||||
{[
|
||||
"tun",
|
||||
"dns",
|
||||
"hosts",
|
||||
"script",
|
||||
"profile",
|
||||
"payload",
|
||||
"interface-name",
|
||||
"routing-mark",
|
||||
].map((key) => {
|
||||
const has = valid.includes(key);
|
||||
|
||||
return (
|
||||
<MenuItem
|
||||
key={key}
|
||||
sx={{ width: 180 }}
|
||||
onClick={() => onToggleValid(key)}
|
||||
>
|
||||
{has && (
|
||||
<ListItemIcon color="inherit">
|
||||
<CheckRounded />
|
||||
</ListItemIcon>
|
||||
)}
|
||||
<ListItemText inset={!has}>{key}</ListItemText>
|
||||
</MenuItem>
|
||||
);
|
||||
})}
|
||||
</Menu>
|
||||
</Stack>
|
||||
|
||||
<Grid container spacing={2}>
|
||||
@@ -199,6 +110,7 @@ const EnhancedMode = (props: Props) => {
|
||||
selected={!!chain.includes(item.uid)}
|
||||
itemData={item}
|
||||
enableNum={chain.length}
|
||||
logInfo={chainLogs[item.uid]}
|
||||
onEnable={() => onEnhanceEnable(item.uid)}
|
||||
onDisable={() => onEnhanceDisable(item.uid)}
|
||||
onDelete={() => onEnhanceDelete(item.uid)}
|
||||
|
||||
@@ -9,8 +9,8 @@ import {
|
||||
DialogContent,
|
||||
DialogTitle,
|
||||
} from "@mui/material";
|
||||
import { atomThemeMode } from "../../services/states";
|
||||
import { readProfileFile, saveProfileFile } from "../../services/cmds";
|
||||
import { atomThemeMode } from "@/services/states";
|
||||
import { readProfileFile, saveProfileFile } from "@/services/cmds";
|
||||
import Notice from "../base/base-notice";
|
||||
|
||||
import "monaco-editor/esm/vs/basic-languages/javascript/javascript.contribution.js";
|
||||
@@ -82,7 +82,9 @@ const FileEditor = (props: Props) => {
|
||||
</DialogContent>
|
||||
|
||||
<DialogActions>
|
||||
<Button onClick={onClose}>{t("Cancel")}</Button>
|
||||
<Button onClick={onClose} variant="outlined">
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button onClick={onSave} variant="contained">
|
||||
{t("Save")}
|
||||
</Button>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useRef, useState } from "react";
|
||||
import { useLockFn } from "ahooks";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Box, Button, Typography } from "@mui/material";
|
||||
|
||||
interface Props {
|
||||
@@ -9,6 +10,7 @@ interface Props {
|
||||
const FileInput = (props: Props) => {
|
||||
const { onChange } = props;
|
||||
|
||||
const { t } = useTranslation();
|
||||
// file input
|
||||
const inputRef = useRef<any>();
|
||||
const [loading, setLoading] = useState(false);
|
||||
@@ -40,7 +42,7 @@ const FileInput = (props: Props) => {
|
||||
sx={{ flex: "none" }}
|
||||
onClick={() => inputRef.current?.click()}
|
||||
>
|
||||
Choose File
|
||||
{t("Choose File")}
|
||||
</Button>
|
||||
|
||||
<input
|
||||
|
||||
@@ -12,8 +12,7 @@ import {
|
||||
TextField,
|
||||
} from "@mui/material";
|
||||
import { Settings } from "@mui/icons-material";
|
||||
import { CmdType } from "../../services/types";
|
||||
import { patchProfile } from "../../services/cmds";
|
||||
import { patchProfile } from "@/services/cmds";
|
||||
import Notice from "../base/base-notice";
|
||||
|
||||
interface Props {
|
||||
@@ -24,7 +23,7 @@ interface Props {
|
||||
|
||||
// edit the profile item
|
||||
// remote / local file / merge / script
|
||||
const ProfileEdit = (props: Props) => {
|
||||
const InfoEditor = (props: Props) => {
|
||||
const { open, itemData, onClose } = props;
|
||||
|
||||
const { t } = useTranslation();
|
||||
@@ -57,7 +56,6 @@ const ProfileEdit = (props: Props) => {
|
||||
}
|
||||
|
||||
await patchProfile(uid, { uid, name, desc, url, option: option_ });
|
||||
setShowOpt(false);
|
||||
mutate("getProfiles");
|
||||
onClose();
|
||||
} catch (err: any) {
|
||||
@@ -134,7 +132,7 @@ const ProfileEdit = (props: Props) => {
|
||||
value={option.update_interval}
|
||||
onChange={(e) => {
|
||||
const str = e.target.value?.replace(/\D/, "");
|
||||
setOption({ update_interval: str != null ? +str : str });
|
||||
setOption({ update_interval: !!str ? +str : undefined });
|
||||
}}
|
||||
onKeyDown={(e) => e.key === "Enter" && onUpdate()}
|
||||
/>
|
||||
@@ -145,6 +143,7 @@ const ProfileEdit = (props: Props) => {
|
||||
{form.type === "remote" && (
|
||||
<IconButton
|
||||
size="small"
|
||||
color="inherit"
|
||||
sx={{ position: "absolute", left: 18 }}
|
||||
onClick={() => setShowOpt((o) => !o)}
|
||||
>
|
||||
@@ -152,13 +151,15 @@ const ProfileEdit = (props: Props) => {
|
||||
</IconButton>
|
||||
)}
|
||||
|
||||
<Button onClick={onClose}>Cancel</Button>
|
||||
<Button onClick={onClose} variant="outlined">
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button onClick={onUpdate} variant="contained">
|
||||
Update
|
||||
{t("Save")}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProfileEdit;
|
||||
export default InfoEditor;
|
||||
@@ -0,0 +1,71 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
Button,
|
||||
Chip,
|
||||
Dialog,
|
||||
DialogActions,
|
||||
DialogContent,
|
||||
DialogTitle,
|
||||
Divider,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import BaseEmpty from "../base/base-empty";
|
||||
import { Fragment } from "react";
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
logInfo: [string, string][];
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
const LogViewer = (props: Props) => {
|
||||
const { open, logInfo, onClose } = props;
|
||||
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Dialog open={open} onClose={onClose}>
|
||||
<DialogTitle>{t("Script Console")}</DialogTitle>
|
||||
|
||||
<DialogContent
|
||||
sx={{
|
||||
width: 400,
|
||||
height: 300,
|
||||
overflowX: "hidden",
|
||||
userSelect: "text",
|
||||
pb: 1,
|
||||
}}
|
||||
>
|
||||
{logInfo.map(([level, log], index) => (
|
||||
<Fragment key={index.toString()}>
|
||||
<Typography color="text.secondary" component="div">
|
||||
<Chip
|
||||
label={level}
|
||||
size="small"
|
||||
variant="outlined"
|
||||
color={
|
||||
level === "error" || level === "exception"
|
||||
? "error"
|
||||
: "default"
|
||||
}
|
||||
sx={{ mr: 1 }}
|
||||
/>
|
||||
{log}
|
||||
</Typography>
|
||||
<Divider sx={{ my: 0.5 }} />
|
||||
</Fragment>
|
||||
))}
|
||||
|
||||
{logInfo.length === 0 && <BaseEmpty />}
|
||||
</DialogContent>
|
||||
|
||||
<DialogActions>
|
||||
<Button onClick={onClose} variant="outlined">
|
||||
{t("Back")}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default LogViewer;
|
||||
@@ -0,0 +1,43 @@
|
||||
import { alpha, Box, styled } from "@mui/material";
|
||||
|
||||
const ProfileBox = styled(Box)(({ theme, "aria-selected": selected }) => {
|
||||
const { mode, primary, text, grey, background } = theme.palette;
|
||||
const key = `${mode}-${!!selected}`;
|
||||
|
||||
const backgroundColor = {
|
||||
"light-true": alpha(primary.main, 0.2),
|
||||
"light-false": alpha(background.paper, 0.75),
|
||||
"dark-true": alpha(primary.main, 0.45),
|
||||
"dark-false": alpha(grey[700], 0.45),
|
||||
}[key]!;
|
||||
|
||||
const color = {
|
||||
"light-true": text.secondary,
|
||||
"light-false": text.secondary,
|
||||
"dark-true": alpha(text.secondary, 0.85),
|
||||
"dark-false": alpha(text.secondary, 0.65),
|
||||
}[key]!;
|
||||
|
||||
const h2color = {
|
||||
"light-true": primary.main,
|
||||
"light-false": text.primary,
|
||||
"dark-true": primary.light,
|
||||
"dark-false": text.primary,
|
||||
}[key]!;
|
||||
|
||||
return {
|
||||
width: "100%",
|
||||
display: "block",
|
||||
cursor: "pointer",
|
||||
textAlign: "left",
|
||||
borderRadius: theme.shape.borderRadius,
|
||||
boxShadow: theme.shadows[2],
|
||||
padding: "8px 16px",
|
||||
boxSizing: "border-box",
|
||||
backgroundColor,
|
||||
color,
|
||||
"& h2": { color: h2color },
|
||||
};
|
||||
});
|
||||
|
||||
export default ProfileBox;
|
||||
@@ -1,13 +1,11 @@
|
||||
import dayjs from "dayjs";
|
||||
import { mutate } from "swr";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useLockFn } from "ahooks";
|
||||
import { useSWRConfig } from "swr";
|
||||
import { useRecoilState } from "recoil";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
alpha,
|
||||
Box,
|
||||
styled,
|
||||
Typography,
|
||||
LinearProgress,
|
||||
IconButton,
|
||||
@@ -16,25 +14,14 @@ import {
|
||||
Menu,
|
||||
} from "@mui/material";
|
||||
import { RefreshRounded } from "@mui/icons-material";
|
||||
import { CmdType } from "../../services/types";
|
||||
import { atomLoadingCache } from "../../services/states";
|
||||
import { updateProfile, deleteProfile, viewProfile } from "../../services/cmds";
|
||||
import parseTraffic from "../../utils/parse-traffic";
|
||||
import ProfileEdit from "./profile-edit";
|
||||
import { atomLoadingCache } from "@/services/states";
|
||||
import { updateProfile, deleteProfile, viewProfile } from "@/services/cmds";
|
||||
import parseTraffic from "@/utils/parse-traffic";
|
||||
import ProfileBox from "./profile-box";
|
||||
import InfoEditor from "./info-editor";
|
||||
import FileEditor from "./file-editor";
|
||||
import Notice from "../base/base-notice";
|
||||
|
||||
const Wrapper = styled(Box)(({ theme }) => ({
|
||||
width: "100%",
|
||||
display: "block",
|
||||
cursor: "pointer",
|
||||
textAlign: "left",
|
||||
borderRadius: theme.shape.borderRadius,
|
||||
boxShadow: theme.shadows[2],
|
||||
padding: "8px 16px",
|
||||
boxSizing: "border-box",
|
||||
}));
|
||||
|
||||
const round = keyframes`
|
||||
from { transform: rotate(0deg); }
|
||||
to { transform: rotate(360deg); }
|
||||
@@ -50,7 +37,6 @@ const ProfileItem = (props: Props) => {
|
||||
const { selected, itemData, onSelect } = props;
|
||||
|
||||
const { t } = useTranslation();
|
||||
const { mutate } = useSWRConfig();
|
||||
const [anchorEl, setAnchorEl] = useState<any>(null);
|
||||
const [position, setPosition] = useState({ left: 0, top: 0 });
|
||||
const [loadingCache, setLoadingCache] = useRecoilState(atomLoadingCache);
|
||||
@@ -59,7 +45,6 @@ const ProfileItem = (props: Props) => {
|
||||
|
||||
// local file mode
|
||||
// remote file mode
|
||||
// subscription url mode
|
||||
const hasUrl = !!itemData.url;
|
||||
const hasExtra = !!extra; // only subscription url has extra info
|
||||
|
||||
@@ -80,7 +65,6 @@ const ProfileItem = (props: Props) => {
|
||||
const handler = () => {
|
||||
const now = Date.now();
|
||||
const lastUpdate = updated * 1000;
|
||||
|
||||
// 大于一天的不管
|
||||
if (now - lastUpdate >= 24 * 36e5) return;
|
||||
|
||||
@@ -153,13 +137,6 @@ const ProfileItem = (props: Props) => {
|
||||
}
|
||||
});
|
||||
|
||||
const boxStyle = {
|
||||
height: 26,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
};
|
||||
|
||||
const urlModeMenu = [
|
||||
{ label: "Select", handler: onForceSelect },
|
||||
{ label: "Edit Info", handler: onEditInfo },
|
||||
@@ -177,36 +154,17 @@ const ProfileItem = (props: Props) => {
|
||||
{ label: "Delete", handler: onDelete },
|
||||
];
|
||||
|
||||
const boxStyle = {
|
||||
height: 26,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Wrapper
|
||||
sx={({ palette }) => {
|
||||
const { mode, primary, text, grey } = palette;
|
||||
const key = `${mode}-${selected}`;
|
||||
|
||||
const bgcolor = {
|
||||
"light-true": alpha(primary.main, 0.15),
|
||||
"light-false": palette.background.paper,
|
||||
"dark-true": alpha(primary.main, 0.35),
|
||||
"dark-false": alpha(grey[700], 0.35),
|
||||
}[key]!;
|
||||
|
||||
const color = {
|
||||
"light-true": text.secondary,
|
||||
"light-false": text.secondary,
|
||||
"dark-true": alpha(text.secondary, 0.75),
|
||||
"dark-false": alpha(text.secondary, 0.75),
|
||||
}[key]!;
|
||||
|
||||
const h2color = {
|
||||
"light-true": primary.main,
|
||||
"light-false": text.primary,
|
||||
"dark-true": primary.light,
|
||||
"dark-false": text.primary,
|
||||
}[key]!;
|
||||
|
||||
return { bgcolor, color, "& h2": { color: h2color } };
|
||||
}}
|
||||
<ProfileBox
|
||||
aria-selected={selected}
|
||||
onClick={() => onSelect(false)}
|
||||
onContextMenu={(event) => {
|
||||
const { clientX, clientY } = event;
|
||||
@@ -215,9 +173,9 @@ const ProfileItem = (props: Props) => {
|
||||
event.preventDefault();
|
||||
}}
|
||||
>
|
||||
<Box display="flex" justifyContent="space-between">
|
||||
<Box position="relative">
|
||||
<Typography
|
||||
width="calc(100% - 40px)"
|
||||
width="calc(100% - 36px)"
|
||||
variant="h6"
|
||||
component="h2"
|
||||
noWrap
|
||||
@@ -230,10 +188,13 @@ const ProfileItem = (props: Props) => {
|
||||
{hasUrl && (
|
||||
<IconButton
|
||||
sx={{
|
||||
width: 26,
|
||||
height: 26,
|
||||
position: "absolute",
|
||||
p: "3px",
|
||||
top: -1,
|
||||
right: -5,
|
||||
animation: loading ? `1s linear infinite ${round}` : "none",
|
||||
}}
|
||||
size="small"
|
||||
color="inherit"
|
||||
disabled={loading}
|
||||
onClick={(e) => {
|
||||
@@ -241,47 +202,47 @@ const ProfileItem = (props: Props) => {
|
||||
onUpdate(false);
|
||||
}}
|
||||
>
|
||||
<RefreshRounded />
|
||||
<RefreshRounded color="inherit" />
|
||||
</IconButton>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
{/* the second line show url's info or description */}
|
||||
{hasUrl ? (
|
||||
<Box sx={boxStyle}>
|
||||
<Typography noWrap title={`From: ${from}`}>
|
||||
{from}
|
||||
</Typography>
|
||||
<Box sx={boxStyle}>
|
||||
{hasUrl ? (
|
||||
<>
|
||||
<Typography noWrap title={`From: ${from}`}>
|
||||
{from}
|
||||
</Typography>
|
||||
|
||||
<Typography
|
||||
noWrap
|
||||
flex="1 0 auto"
|
||||
fontSize={14}
|
||||
textAlign="right"
|
||||
title="updated time"
|
||||
>
|
||||
{updated > 0 ? dayjs(updated * 1000).fromNow() : ""}
|
||||
</Typography>
|
||||
</Box>
|
||||
) : (
|
||||
<Box sx={boxStyle}>
|
||||
<Typography
|
||||
noWrap
|
||||
flex="1 0 auto"
|
||||
fontSize={14}
|
||||
textAlign="right"
|
||||
title={`Updated Time: ${parseExpire(updated)}`}
|
||||
>
|
||||
{updated > 0 ? dayjs(updated * 1000).fromNow() : ""}
|
||||
</Typography>
|
||||
</>
|
||||
) : (
|
||||
<Typography noWrap title={itemData.desc}>
|
||||
{itemData.desc}
|
||||
</Typography>
|
||||
</Box>
|
||||
)}
|
||||
)}
|
||||
</Box>
|
||||
|
||||
{/* the third line show extra info or last updated time */}
|
||||
{hasExtra ? (
|
||||
<Box sx={{ ...boxStyle, fontSize: 14 }}>
|
||||
<span title="used / total">
|
||||
<span title="Used / Total">
|
||||
{parseTraffic(upload + download)} / {parseTraffic(total)}
|
||||
</span>
|
||||
<span title="expire time">{expire}</span>
|
||||
<span title="Expire Time">{expire}</span>
|
||||
</Box>
|
||||
) : (
|
||||
<Box sx={{ ...boxStyle, fontSize: 14, justifyContent: "flex-end" }}>
|
||||
<span title="updated time">{parseExpire(updated)}</span>
|
||||
<span title="Updated Time">{parseExpire(updated)}</span>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
@@ -290,7 +251,7 @@ const ProfileItem = (props: Props) => {
|
||||
value={progress}
|
||||
color="inherit"
|
||||
/>
|
||||
</Wrapper>
|
||||
</ProfileBox>
|
||||
|
||||
<Menu
|
||||
open={!!anchorEl}
|
||||
@@ -315,22 +276,18 @@ const ProfileItem = (props: Props) => {
|
||||
))}
|
||||
</Menu>
|
||||
|
||||
{editOpen && (
|
||||
<ProfileEdit
|
||||
open={editOpen}
|
||||
itemData={itemData}
|
||||
onClose={() => setEditOpen(false)}
|
||||
/>
|
||||
)}
|
||||
<InfoEditor
|
||||
open={editOpen}
|
||||
itemData={itemData}
|
||||
onClose={() => setEditOpen(false)}
|
||||
/>
|
||||
|
||||
{fileOpen && (
|
||||
<FileEditor
|
||||
uid={uid}
|
||||
open={fileOpen}
|
||||
mode="yaml"
|
||||
onClose={() => setFileOpen(false)}
|
||||
/>
|
||||
)}
|
||||
<FileEditor
|
||||
uid={uid}
|
||||
open={fileOpen}
|
||||
mode="yaml"
|
||||
onClose={() => setFileOpen(false)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,38 +1,29 @@
|
||||
import dayjs from "dayjs";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useLockFn } from "ahooks";
|
||||
import {
|
||||
alpha,
|
||||
Box,
|
||||
Badge,
|
||||
Chip,
|
||||
styled,
|
||||
Typography,
|
||||
MenuItem,
|
||||
Menu,
|
||||
IconButton,
|
||||
} from "@mui/material";
|
||||
import { CmdType } from "../../services/types";
|
||||
import { viewProfile } from "../../services/cmds";
|
||||
import enhance from "../../services/enhance";
|
||||
import ProfileEdit from "./profile-edit";
|
||||
import { FeaturedPlayListRounded } from "@mui/icons-material";
|
||||
import { viewProfile } from "@/services/cmds";
|
||||
import InfoEditor from "./info-editor";
|
||||
import FileEditor from "./file-editor";
|
||||
import ProfileBox from "./profile-box";
|
||||
import LogViewer from "./log-viewer";
|
||||
import Notice from "../base/base-notice";
|
||||
|
||||
const Wrapper = styled(Box)(({ theme }) => ({
|
||||
width: "100%",
|
||||
display: "block",
|
||||
cursor: "pointer",
|
||||
textAlign: "left",
|
||||
borderRadius: theme.shape.borderRadius,
|
||||
boxShadow: theme.shadows[2],
|
||||
padding: "8px 16px",
|
||||
boxSizing: "border-box",
|
||||
}));
|
||||
|
||||
interface Props {
|
||||
selected: boolean;
|
||||
itemData: CmdType.ProfileItem;
|
||||
enableNum: number;
|
||||
logInfo?: [string, string][];
|
||||
onEnable: () => void;
|
||||
onDisable: () => void;
|
||||
onMoveTop: () => void;
|
||||
@@ -46,6 +37,7 @@ const ProfileMore = (props: Props) => {
|
||||
selected,
|
||||
itemData,
|
||||
enableNum,
|
||||
logInfo = [],
|
||||
onEnable,
|
||||
onDisable,
|
||||
onMoveTop,
|
||||
@@ -55,18 +47,11 @@ const ProfileMore = (props: Props) => {
|
||||
|
||||
const { uid, type } = itemData;
|
||||
const { t } = useTranslation();
|
||||
|
||||
const [anchorEl, setAnchorEl] = useState<any>(null);
|
||||
const [position, setPosition] = useState({ left: 0, top: 0 });
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
const [fileOpen, setFileOpen] = useState(false);
|
||||
const [status, setStatus] = useState(enhance.status(uid));
|
||||
|
||||
// unlisten when unmount
|
||||
useEffect(() => enhance.listen(uid, setStatus), [uid]);
|
||||
|
||||
// error during enhanced mode
|
||||
const hasError = selected && status?.status === "error";
|
||||
const [logOpen, setLogOpen] = useState(false);
|
||||
|
||||
const onEditInfo = () => {
|
||||
setAnchorEl(null);
|
||||
@@ -92,6 +77,7 @@ const ProfileMore = (props: Props) => {
|
||||
return fn();
|
||||
};
|
||||
|
||||
const hasError = !!logInfo.find((e) => e[0] === "exception");
|
||||
const showMove = enableNum > 1 && !hasError;
|
||||
|
||||
const enableMenu = [
|
||||
@@ -122,39 +108,8 @@ const ProfileMore = (props: Props) => {
|
||||
|
||||
return (
|
||||
<>
|
||||
<Wrapper
|
||||
sx={({ palette }) => {
|
||||
// todo
|
||||
// 区分 selected 和 error 和 mode 下各种颜色的排列组合
|
||||
const { mode, primary, text, grey, error } = palette;
|
||||
const key = `${mode}-${selected}`;
|
||||
const bgkey = hasError ? `${mode}-err` : key;
|
||||
|
||||
const bgcolor = {
|
||||
"light-true": alpha(primary.main, 0.15),
|
||||
"light-false": palette.background.paper,
|
||||
"dark-true": alpha(primary.main, 0.35),
|
||||
"dark-false": alpha(grey[700], 0.35),
|
||||
"light-err": alpha(error.main, 0.12),
|
||||
"dark-err": alpha(error.main, 0.3),
|
||||
}[bgkey]!;
|
||||
|
||||
const color = {
|
||||
"light-true": text.secondary,
|
||||
"light-false": text.secondary,
|
||||
"dark-true": alpha(text.secondary, 0.6),
|
||||
"dark-false": alpha(text.secondary, 0.6),
|
||||
}[key]!;
|
||||
|
||||
const h2color = {
|
||||
"light-true": primary.main,
|
||||
"light-false": text.primary,
|
||||
"dark-true": primary.light,
|
||||
"dark-false": text.primary,
|
||||
}[key]!;
|
||||
|
||||
return { bgcolor, color, "& h2": { color: h2color } };
|
||||
}}
|
||||
<ProfileBox
|
||||
aria-selected={selected}
|
||||
// onClick={() => onSelect(false)}
|
||||
onContextMenu={(event) => {
|
||||
const { clientX, clientY } = event;
|
||||
@@ -163,7 +118,12 @@ const ProfileMore = (props: Props) => {
|
||||
event.preventDefault();
|
||||
}}
|
||||
>
|
||||
<Box display="flex" justifyContent="space-between" alignItems="center">
|
||||
<Box
|
||||
display="flex"
|
||||
justifyContent="space-between"
|
||||
alignItems="center"
|
||||
mb={0.5}
|
||||
>
|
||||
<Typography
|
||||
width="calc(100% - 52px)"
|
||||
variant="h6"
|
||||
@@ -179,20 +139,35 @@ const ProfileMore = (props: Props) => {
|
||||
color="primary"
|
||||
size="small"
|
||||
variant="outlined"
|
||||
sx={{ textTransform: "capitalize" }}
|
||||
sx={{ height: 20, textTransform: "capitalize" }}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
<Box sx={boxStyle}>
|
||||
{hasError ? (
|
||||
<Typography
|
||||
noWrap
|
||||
color="error"
|
||||
sx={{ width: "calc(100% - 75px)" }}
|
||||
title={status.message}
|
||||
>
|
||||
{status.message}
|
||||
</Typography>
|
||||
{selected ? (
|
||||
hasError ? (
|
||||
<Badge color="error" variant="dot" overlap="circular">
|
||||
<IconButton
|
||||
size="small"
|
||||
edge="start"
|
||||
color="error"
|
||||
title="Console"
|
||||
onClick={() => setLogOpen(true)}
|
||||
>
|
||||
<FeaturedPlayListRounded fontSize="inherit" />
|
||||
</IconButton>
|
||||
</Badge>
|
||||
) : (
|
||||
<IconButton
|
||||
size="small"
|
||||
edge="start"
|
||||
color="inherit"
|
||||
title="Console"
|
||||
onClick={() => setLogOpen(true)}
|
||||
>
|
||||
<FeaturedPlayListRounded fontSize="inherit" />
|
||||
</IconButton>
|
||||
)
|
||||
) : (
|
||||
<Typography
|
||||
noWrap
|
||||
@@ -205,13 +180,15 @@ const ProfileMore = (props: Props) => {
|
||||
|
||||
<Typography
|
||||
component="span"
|
||||
title="updated time"
|
||||
title={`Updated Time: ${parseExpire(itemData.updated)}`}
|
||||
style={{ fontSize: 14 }}
|
||||
>
|
||||
{parseExpire(itemData.updated)}
|
||||
{!!itemData.updated
|
||||
? dayjs(itemData.updated! * 1000).fromNow()
|
||||
: ""}
|
||||
</Typography>
|
||||
</Box>
|
||||
</Wrapper>
|
||||
</ProfileBox>
|
||||
|
||||
<Menu
|
||||
open={!!anchorEl}
|
||||
@@ -238,20 +215,24 @@ const ProfileMore = (props: Props) => {
|
||||
))}
|
||||
</Menu>
|
||||
|
||||
{editOpen && (
|
||||
<ProfileEdit
|
||||
open={editOpen}
|
||||
itemData={itemData}
|
||||
onClose={() => setEditOpen(false)}
|
||||
/>
|
||||
)}
|
||||
<InfoEditor
|
||||
open={editOpen}
|
||||
itemData={itemData}
|
||||
onClose={() => setEditOpen(false)}
|
||||
/>
|
||||
|
||||
{fileOpen && (
|
||||
<FileEditor
|
||||
uid={uid}
|
||||
open={fileOpen}
|
||||
mode={type === "merge" ? "yaml" : "javascript"}
|
||||
onClose={() => setFileOpen(false)}
|
||||
<FileEditor
|
||||
uid={uid}
|
||||
open={fileOpen}
|
||||
mode={type === "merge" ? "yaml" : "javascript"}
|
||||
onClose={() => setFileOpen(false)}
|
||||
/>
|
||||
|
||||
{selected && (
|
||||
<LogViewer
|
||||
open={logOpen}
|
||||
logInfo={logInfo}
|
||||
onClose={() => setLogOpen(false)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useRef, useState } from "react";
|
||||
import { useSWRConfig } from "swr";
|
||||
import { mutate } from "swr";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useLockFn, useSetState } from "ahooks";
|
||||
import {
|
||||
Button,
|
||||
@@ -15,7 +16,7 @@ import {
|
||||
TextField,
|
||||
} from "@mui/material";
|
||||
import { Settings } from "@mui/icons-material";
|
||||
import { createProfile } from "../../services/cmds";
|
||||
import { createProfile } from "@/services/cmds";
|
||||
import Notice from "../base/base-notice";
|
||||
import FileInput from "./file-input";
|
||||
|
||||
@@ -29,7 +30,7 @@ interface Props {
|
||||
const ProfileNew = (props: Props) => {
|
||||
const { open, onClose } = props;
|
||||
|
||||
const { mutate } = useSWRConfig();
|
||||
const { t } = useTranslation();
|
||||
const [form, setForm] = useSetState({
|
||||
type: "remote",
|
||||
name: "",
|
||||
@@ -83,7 +84,7 @@ const ProfileNew = (props: Props) => {
|
||||
|
||||
return (
|
||||
<Dialog open={open} onClose={onClose}>
|
||||
<DialogTitle sx={{ pb: 0.5 }}>Create Profile</DialogTitle>
|
||||
<DialogTitle sx={{ pb: 0.5 }}>{t("Create Profile")}</DialogTitle>
|
||||
|
||||
<DialogContent sx={{ width: 336, pb: 1 }}>
|
||||
<FormControl size="small" fullWidth sx={{ mt: 2, mb: 1 }}>
|
||||
@@ -120,7 +121,7 @@ const ProfileNew = (props: Props) => {
|
||||
{form.type === "remote" && (
|
||||
<TextField
|
||||
{...textFieldProps}
|
||||
label="Subscription Url"
|
||||
label="Subscription URL"
|
||||
autoComplete="off"
|
||||
value={form.url}
|
||||
onChange={(e) => setForm({ url: e.target.value })}
|
||||
@@ -146,6 +147,7 @@ const ProfileNew = (props: Props) => {
|
||||
{form.type === "remote" && (
|
||||
<IconButton
|
||||
size="small"
|
||||
color="inherit"
|
||||
sx={{ position: "absolute", left: 18 }}
|
||||
onClick={() => setShowOpt((o) => !o)}
|
||||
>
|
||||
@@ -153,9 +155,11 @@ const ProfileNew = (props: Props) => {
|
||||
</IconButton>
|
||||
)}
|
||||
|
||||
<Button onClick={onClose}>Cancel</Button>
|
||||
<Button onClick={onClose} variant="outlined">
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button onClick={onCreate} variant="contained">
|
||||
Create
|
||||
{t("Save")}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
@@ -2,13 +2,12 @@ import useSWR, { useSWRConfig } from "swr";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useLockFn } from "ahooks";
|
||||
import { Virtuoso } from "react-virtuoso";
|
||||
import { ApiType } from "../../services/types";
|
||||
import { updateProxy } from "../../services/api";
|
||||
import { getProfiles, patchProfile } from "../../services/cmds";
|
||||
import { updateProxy } from "@/services/api";
|
||||
import { getProfiles, patchProfile } from "@/services/cmds";
|
||||
import delayManager from "@/services/delay";
|
||||
import useSortProxy from "./use-sort-proxy";
|
||||
import useHeadState from "./use-head-state";
|
||||
import useFilterProxy from "./use-filter-proxy";
|
||||
import delayManager from "../../services/delay";
|
||||
import ProxyHead from "./proxy-head";
|
||||
import ProxyItem from "./proxy-item";
|
||||
|
||||
|
||||
@@ -15,13 +15,12 @@ import {
|
||||
ExpandLessRounded,
|
||||
ExpandMoreRounded,
|
||||
} from "@mui/icons-material";
|
||||
import { ApiType } from "../../services/types";
|
||||
import { updateProxy } from "../../services/api";
|
||||
import { getProfiles, patchProfile } from "../../services/cmds";
|
||||
import { updateProxy } from "@/services/api";
|
||||
import { getProfiles, patchProfile } from "@/services/cmds";
|
||||
import delayManager from "@/services/delay";
|
||||
import useSortProxy from "./use-sort-proxy";
|
||||
import useHeadState from "./use-head-state";
|
||||
import useFilterProxy from "./use-filter-proxy";
|
||||
import delayManager from "../../services/delay";
|
||||
import ProxyHead from "./proxy-head";
|
||||
import ProxyItem from "./proxy-item";
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
SortByAlphaRounded,
|
||||
SortRounded,
|
||||
} from "@mui/icons-material";
|
||||
import delayManager from "../../services/delay";
|
||||
import delayManager from "@/services/delay";
|
||||
import type { HeadState } from "./use-head-state";
|
||||
import type { ProxySortType } from "./use-sort-proxy";
|
||||
|
||||
|
||||
@@ -12,8 +12,7 @@ import {
|
||||
SxProps,
|
||||
Theme,
|
||||
} from "@mui/material";
|
||||
import { ApiType } from "../../services/types";
|
||||
import delayManager from "../../services/delay";
|
||||
import delayManager from "@/services/delay";
|
||||
|
||||
interface Props {
|
||||
groupName: string;
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useMemo } from "react";
|
||||
import { ApiType } from "../../services/types";
|
||||
import delayManager from "../../services/delay";
|
||||
import delayManager from "@/services/delay";
|
||||
|
||||
const regex1 = /delay([=<>])(\d+|timeout|error)/i;
|
||||
const regex2 = /type=(.*)/i;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useRecoilValue } from "recoil";
|
||||
import { atomCurrentProfile } from "../../services/states";
|
||||
import { atomCurrentProfile } from "@/services/states";
|
||||
import { ProxySortType } from "./use-sort-proxy";
|
||||
|
||||
export interface HeadState {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useMemo } from "react";
|
||||
import { ApiType } from "../../services/types";
|
||||
import delayManager from "../../services/delay";
|
||||
import delayManager from "@/services/delay";
|
||||
|
||||
// default | delay | alpha
|
||||
export type ProxySortType = 0 | 1 | 2;
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
import useSWR from "swr";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
Button,
|
||||
Checkbox,
|
||||
Dialog,
|
||||
DialogActions,
|
||||
DialogContent,
|
||||
DialogTitle,
|
||||
Divider,
|
||||
Stack,
|
||||
Tooltip,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import { InfoRounded } from "@mui/icons-material";
|
||||
import {
|
||||
changeProfileValid,
|
||||
getProfiles,
|
||||
getRuntimeExists,
|
||||
} from "@/services/cmds";
|
||||
import { ModalHandler } from "@/hooks/use-modal-handler";
|
||||
import {
|
||||
HANDLE_FIELDS,
|
||||
DEFAULT_FIELDS,
|
||||
OTHERS_FIELDS,
|
||||
} from "@/utils/clash-fields";
|
||||
import Notice from "@/components/base/base-notice";
|
||||
|
||||
interface Props {
|
||||
handler: ModalHandler;
|
||||
}
|
||||
|
||||
const fieldSorter = (a: string, b: string) => {
|
||||
if (a.includes("-") === a.includes("-")) {
|
||||
if (a.length === b.length) return a.localeCompare(b);
|
||||
return a.length - b.length;
|
||||
} else if (a.includes("-")) return 1;
|
||||
else if (b.includes("-")) return -1;
|
||||
return 0;
|
||||
};
|
||||
|
||||
const otherFields = [...OTHERS_FIELDS].sort(fieldSorter);
|
||||
const handleFields = [...HANDLE_FIELDS, ...DEFAULT_FIELDS].sort(fieldSorter);
|
||||
|
||||
const ClashFieldViewer = ({ handler }: Props) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const { data: profiles = {}, mutate: mutateProfile } = useSWR(
|
||||
"getProfiles",
|
||||
getProfiles
|
||||
);
|
||||
const { data: existsKeys = [], mutate: mutateExists } = useSWR(
|
||||
"getRuntimeExists",
|
||||
getRuntimeExists
|
||||
);
|
||||
|
||||
const [open, setOpen] = useState(false);
|
||||
const [selected, setSelected] = useState<string[]>([]);
|
||||
|
||||
if (handler) {
|
||||
handler.current = {
|
||||
open: () => setOpen(true),
|
||||
close: () => setOpen(false),
|
||||
};
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
mutateProfile();
|
||||
mutateExists();
|
||||
setSelected(profiles.valid || []);
|
||||
}
|
||||
}, [open, profiles.valid]);
|
||||
|
||||
const handleChange = (item: string) => {
|
||||
if (!item) return;
|
||||
|
||||
setSelected((old) =>
|
||||
old.includes(item) ? old.filter((e) => e !== item) : [...old, item]
|
||||
);
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
setOpen(false);
|
||||
|
||||
const oldSet = new Set(profiles.valid || []);
|
||||
const curSet = new Set(selected);
|
||||
const joinSet = new Set(selected.concat([...oldSet]));
|
||||
|
||||
if (curSet.size === oldSet.size && curSet.size === joinSet.size) return;
|
||||
|
||||
try {
|
||||
await changeProfileValid([...curSet]);
|
||||
mutateProfile();
|
||||
Notice.success("Refresh clash config", 1000);
|
||||
} catch (err: any) {
|
||||
Notice.error(err?.message || err.toString());
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onClose={() => setOpen(false)}>
|
||||
<DialogTitle>{t("Clash Field")}</DialogTitle>
|
||||
|
||||
<DialogContent
|
||||
sx={{
|
||||
pb: 0,
|
||||
width: 320,
|
||||
height: 300,
|
||||
overflowY: "auto",
|
||||
userSelect: "text",
|
||||
}}
|
||||
>
|
||||
{otherFields.map((item) => {
|
||||
const inSelect = selected.includes(item);
|
||||
const inConfig = existsKeys.includes(item);
|
||||
|
||||
return (
|
||||
<Stack key={item} mb={0.5} direction="row" alignItems="center">
|
||||
<Checkbox
|
||||
checked={inSelect}
|
||||
size="small"
|
||||
sx={{ p: 0.5 }}
|
||||
onChange={() => handleChange(item)}
|
||||
/>
|
||||
<Typography width="100%">{item}</Typography>
|
||||
|
||||
{!inSelect && inConfig && <WarnIcon />}
|
||||
</Stack>
|
||||
);
|
||||
})}
|
||||
|
||||
<Divider sx={{ my: 1 }}>
|
||||
<Typography color="text.secondary" fontSize={14}>
|
||||
Clash Verge Control Fields
|
||||
</Typography>
|
||||
</Divider>
|
||||
|
||||
{handleFields.map((item) => (
|
||||
<Stack key={item} mb={0.5} direction="row" alignItems="center">
|
||||
<Checkbox defaultChecked disabled size="small" sx={{ p: 0.5 }} />
|
||||
<Typography>{item}</Typography>
|
||||
</Stack>
|
||||
))}
|
||||
</DialogContent>
|
||||
|
||||
<DialogActions>
|
||||
<Button variant="outlined" onClick={() => setOpen(false)}>
|
||||
{t("Back")}
|
||||
</Button>
|
||||
<Button variant="contained" onClick={handleSave}>
|
||||
{t("Save")}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
function WarnIcon() {
|
||||
return (
|
||||
<Tooltip title="The field exists in the config but not enabled.">
|
||||
<InfoRounded color="warning" sx={{ cursor: "pointer", opacity: 0.5 }} />
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
export default ClashFieldViewer;
|
||||
@@ -0,0 +1,78 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useRecoilValue } from "recoil";
|
||||
import {
|
||||
Button,
|
||||
Chip,
|
||||
Dialog,
|
||||
DialogActions,
|
||||
DialogContent,
|
||||
DialogTitle,
|
||||
} from "@mui/material";
|
||||
import { atomThemeMode } from "@/services/states";
|
||||
import { getRuntimeYaml } from "@/services/cmds";
|
||||
|
||||
import "monaco-editor/esm/vs/basic-languages/javascript/javascript.contribution.js";
|
||||
import "monaco-editor/esm/vs/basic-languages/yaml/yaml.contribution.js";
|
||||
import "monaco-editor/esm/vs/editor/contrib/folding/browser/folding.js";
|
||||
import { editor } from "monaco-editor/esm/vs/editor/editor.api";
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
const ConfigViewer = (props: Props) => {
|
||||
const { open, onClose } = props;
|
||||
|
||||
const { t } = useTranslation();
|
||||
|
||||
const editorRef = useRef<any>();
|
||||
const instanceRef = useRef<editor.IStandaloneCodeEditor | null>(null);
|
||||
const themeMode = useRecoilValue(atomThemeMode);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
|
||||
getRuntimeYaml().then((data) => {
|
||||
const dom = editorRef.current;
|
||||
|
||||
if (!dom) return;
|
||||
if (instanceRef.current) instanceRef.current.dispose();
|
||||
|
||||
instanceRef.current = editor.create(editorRef.current, {
|
||||
value: data ?? "# Error\n",
|
||||
language: "yaml",
|
||||
theme: themeMode === "light" ? "vs" : "vs-dark",
|
||||
minimap: { enabled: false },
|
||||
readOnly: true,
|
||||
});
|
||||
});
|
||||
|
||||
return () => {
|
||||
if (instanceRef.current) {
|
||||
instanceRef.current.dispose();
|
||||
instanceRef.current = null;
|
||||
}
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onClose={onClose}>
|
||||
<DialogTitle>
|
||||
{t("Runtime Config")} <Chip label={t("ReadOnly")} size="small" />
|
||||
</DialogTitle>
|
||||
|
||||
<DialogContent sx={{ width: 520, pb: 1 }}>
|
||||
<div style={{ width: "100%", height: "420px" }} ref={editorRef} />
|
||||
</DialogContent>
|
||||
|
||||
<DialogActions>
|
||||
<Button variant="outlined" onClick={onClose}>
|
||||
{t("Back")}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
export default ConfigViewer;
|
||||
+4
-4
@@ -3,9 +3,9 @@ import { useState } from "react";
|
||||
import { useLockFn } from "ahooks";
|
||||
import { Menu, MenuItem } from "@mui/material";
|
||||
import { Settings } from "@mui/icons-material";
|
||||
import { changeClashCore, getVergeConfig } from "../../services/cmds";
|
||||
import { getVersion } from "../../services/api";
|
||||
import Notice from "../base/base-notice";
|
||||
import { changeClashCore, getVergeConfig } from "@/services/cmds";
|
||||
import { getVersion } from "@/services/api";
|
||||
import Notice from "@/components/base/base-notice";
|
||||
|
||||
const VALID_CORE = [
|
||||
{ name: "Clash", core: "clash" },
|
||||
@@ -41,7 +41,7 @@ const CoreSwitch = () => {
|
||||
<>
|
||||
<Settings
|
||||
fontSize="small"
|
||||
style={{ cursor: "pointer" }}
|
||||
style={{ cursor: "pointer", opacity: 0.75 }}
|
||||
onClick={(event) => {
|
||||
const { clientX, clientY } = event;
|
||||
setPosition({ top: clientY, left: clientX });
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
import { cloneElement, isValidElement, ReactNode, useRef } from "react";
|
||||
import noop from "../../utils/noop";
|
||||
import noop from "@/utils/noop";
|
||||
|
||||
interface Props<Value> {
|
||||
value?: Value;
|
||||
+3
-3
@@ -14,9 +14,9 @@ import {
|
||||
installService,
|
||||
uninstallService,
|
||||
patchVergeConfig,
|
||||
} from "../../services/cmds";
|
||||
import Notice from "../base/base-notice";
|
||||
import noop from "../../utils/noop";
|
||||
} from "@/services/cmds";
|
||||
import Notice from "@/components/base/base-notice";
|
||||
import noop from "@/utils/noop";
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
+6
-2
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { InfoRounded } from "@mui/icons-material";
|
||||
import { ClickAwayListener, Tooltip } from "@mui/material";
|
||||
import { getSystemProxy } from "../../services/cmds";
|
||||
import { getSystemProxy } from "@/services/cmds";
|
||||
|
||||
const SysproxyTooltip = () => {
|
||||
const [open, setOpen] = useState(false);
|
||||
@@ -43,7 +43,11 @@ const SysproxyTooltip = () => {
|
||||
title={showTitle}
|
||||
arrow
|
||||
>
|
||||
<InfoRounded fontSize="small" onClick={onShow} />
|
||||
<InfoRounded
|
||||
fontSize="small"
|
||||
style={{ cursor: "pointer", opacity: 0.75 }}
|
||||
onClick={onShow}
|
||||
/>
|
||||
</Tooltip>
|
||||
</ClickAwayListener>
|
||||
);
|
||||
+1
-2
@@ -1,6 +1,5 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Button, ButtonGroup } from "@mui/material";
|
||||
import { CmdType } from "../../services/types";
|
||||
|
||||
type ThemeValue = CmdType.VergeConfig["theme_mode"];
|
||||
|
||||
@@ -16,7 +15,7 @@ const ThemeModeSwitch = (props: Props) => {
|
||||
const modes = ["light", "dark", "system"] as const;
|
||||
|
||||
return (
|
||||
<ButtonGroup size="small">
|
||||
<ButtonGroup size="small" sx={{ my: "4px" }}>
|
||||
{modes.map((mode) => (
|
||||
<Button
|
||||
key={mode}
|
||||
@@ -0,0 +1,132 @@
|
||||
import { useState } from "react";
|
||||
import {
|
||||
Divider,
|
||||
IconButton,
|
||||
Stack,
|
||||
TextField,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import {
|
||||
CheckRounded,
|
||||
CloseRounded,
|
||||
DeleteRounded,
|
||||
EditRounded,
|
||||
OpenInNewRounded,
|
||||
} from "@mui/icons-material";
|
||||
|
||||
interface Props {
|
||||
value?: string;
|
||||
onlyEdit?: boolean;
|
||||
onChange: (value?: string) => void;
|
||||
onOpenUrl?: (value?: string) => void;
|
||||
onDelete?: () => void;
|
||||
onCancel?: () => void;
|
||||
}
|
||||
|
||||
const WebUIItem = (props: Props) => {
|
||||
const {
|
||||
value,
|
||||
onlyEdit = false,
|
||||
onChange,
|
||||
onDelete,
|
||||
onOpenUrl,
|
||||
onCancel,
|
||||
} = props;
|
||||
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [editValue, setEditValue] = useState(value);
|
||||
|
||||
if (editing || onlyEdit) {
|
||||
return (
|
||||
<>
|
||||
<Stack spacing={0.75} direction="row" mt={1} mb={1} alignItems="center">
|
||||
<TextField
|
||||
fullWidth
|
||||
size="small"
|
||||
value={editValue}
|
||||
onChange={(e) => setEditValue(e.target.value)}
|
||||
placeholder={`Support %host %port %secret`}
|
||||
autoComplete="off"
|
||||
/>
|
||||
<IconButton
|
||||
size="small"
|
||||
title="Save"
|
||||
color="inherit"
|
||||
onClick={() => {
|
||||
onChange(editValue);
|
||||
setEditing(false);
|
||||
}}
|
||||
>
|
||||
<CheckRounded fontSize="inherit" />
|
||||
</IconButton>
|
||||
<IconButton
|
||||
size="small"
|
||||
title="Cancel"
|
||||
color="inherit"
|
||||
onClick={() => {
|
||||
onCancel?.();
|
||||
setEditing(false);
|
||||
}}
|
||||
>
|
||||
<CloseRounded fontSize="inherit" />
|
||||
</IconButton>
|
||||
</Stack>
|
||||
<Divider />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const html = value
|
||||
?.replace("%host", "<span>%host</span>")
|
||||
.replace("%port", "<span>%port</span>")
|
||||
.replace("%secret", "<span>%secret</span>");
|
||||
|
||||
return (
|
||||
<>
|
||||
<Stack spacing={0.75} direction="row" alignItems="center" mt={1} mb={1}>
|
||||
<Typography
|
||||
component="div"
|
||||
width="100%"
|
||||
title={value}
|
||||
color={value ? "text.primary" : "text.secondary"}
|
||||
sx={({ palette }) => ({
|
||||
"> span": {
|
||||
color: palette.primary.main,
|
||||
},
|
||||
})}
|
||||
dangerouslySetInnerHTML={{ __html: html || "NULL" }}
|
||||
/>
|
||||
<IconButton
|
||||
size="small"
|
||||
title="Open URL"
|
||||
color="inherit"
|
||||
onClick={() => onOpenUrl?.(value)}
|
||||
>
|
||||
<OpenInNewRounded fontSize="inherit" />
|
||||
</IconButton>
|
||||
<IconButton
|
||||
size="small"
|
||||
title="Edit"
|
||||
color="inherit"
|
||||
onClick={() => {
|
||||
setEditing(true);
|
||||
setEditValue(value);
|
||||
}}
|
||||
>
|
||||
<EditRounded fontSize="inherit" />
|
||||
</IconButton>
|
||||
<IconButton
|
||||
size="small"
|
||||
title="Delete"
|
||||
color="inherit"
|
||||
onClick={onDelete}
|
||||
>
|
||||
<DeleteRounded fontSize="inherit" />
|
||||
</IconButton>
|
||||
</Stack>
|
||||
<Divider />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default WebUIItem;
|
||||
@@ -0,0 +1,165 @@
|
||||
import useSWR from "swr";
|
||||
import { useState } from "react";
|
||||
import { useLockFn } from "ahooks";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
Button,
|
||||
Dialog,
|
||||
DialogActions,
|
||||
DialogContent,
|
||||
DialogTitle,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import {
|
||||
getClashInfo,
|
||||
getVergeConfig,
|
||||
openWebUrl,
|
||||
patchVergeConfig,
|
||||
} from "@/services/cmds";
|
||||
import { ModalHandler } from "@/hooks/use-modal-handler";
|
||||
import BaseEmpty from "@/components/base/base-empty";
|
||||
import WebUIItem from "./web-ui-item";
|
||||
|
||||
interface Props {
|
||||
handler: ModalHandler;
|
||||
onError: (err: Error) => void;
|
||||
}
|
||||
|
||||
const WebUIViewer = ({ handler, onError }: Props) => {
|
||||
const { t } = useTranslation();
|
||||
const { data: vergeConfig, mutate: mutateVerge } = useSWR(
|
||||
"getVergeConfig",
|
||||
getVergeConfig
|
||||
);
|
||||
|
||||
const webUIList = vergeConfig?.web_ui_list || [];
|
||||
|
||||
const [open, setOpen] = useState(false);
|
||||
const [editing, setEditing] = useState(false);
|
||||
|
||||
if (handler) {
|
||||
handler.current = {
|
||||
open: () => setOpen(true),
|
||||
close: () => setOpen(false),
|
||||
};
|
||||
}
|
||||
|
||||
const handleAdd = useLockFn(async (value: string) => {
|
||||
const newList = [value, ...webUIList];
|
||||
mutateVerge((old) => (old ? { ...old, web_ui_list: newList } : old), false);
|
||||
await patchVergeConfig({ web_ui_list: newList });
|
||||
await mutateVerge();
|
||||
});
|
||||
|
||||
const handleChange = useLockFn(async (index: number, value?: string) => {
|
||||
const newList = [...webUIList];
|
||||
newList[index] = value ?? "";
|
||||
mutateVerge((old) => (old ? { ...old, web_ui_list: newList } : old), false);
|
||||
await patchVergeConfig({ web_ui_list: newList });
|
||||
await mutateVerge();
|
||||
});
|
||||
|
||||
const handleDelete = useLockFn(async (index: number) => {
|
||||
const newList = [...webUIList];
|
||||
newList.splice(index, 1);
|
||||
mutateVerge((old) => (old ? { ...old, web_ui_list: newList } : old), false);
|
||||
await patchVergeConfig({ web_ui_list: newList });
|
||||
await mutateVerge();
|
||||
});
|
||||
|
||||
const { data: clashInfo } = useSWR("getClashInfo", getClashInfo);
|
||||
|
||||
const handleOpenUrl = useLockFn(async (value?: string) => {
|
||||
if (!value) return;
|
||||
try {
|
||||
let url = value.trim().replaceAll("%host", "127.0.0.1");
|
||||
|
||||
if (url.includes("%port") || url.includes("%secret")) {
|
||||
if (!clashInfo) throw new Error("failed to get clash info");
|
||||
if (!clashInfo.server?.includes(":")) {
|
||||
throw new Error(
|
||||
`failed to parse server with status ${clashInfo.status}`
|
||||
);
|
||||
}
|
||||
|
||||
const port = clashInfo.server
|
||||
.slice(clashInfo.server.indexOf(":") + 1)
|
||||
.trim();
|
||||
|
||||
url = url.replaceAll("%port", port || "9090");
|
||||
url = url.replaceAll("%secret", clashInfo.secret || "");
|
||||
}
|
||||
|
||||
await openWebUrl(url);
|
||||
} catch (e: any) {
|
||||
onError(e);
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<Dialog open={open} onClose={() => setOpen(false)}>
|
||||
<DialogTitle display="flex" justifyContent="space-between">
|
||||
{t("Web UI")}
|
||||
<Button
|
||||
variant="contained"
|
||||
size="small"
|
||||
disabled={editing}
|
||||
onClick={() => setEditing(true)}
|
||||
>
|
||||
{t("New")}
|
||||
</Button>
|
||||
</DialogTitle>
|
||||
|
||||
<DialogContent
|
||||
sx={{
|
||||
width: 450,
|
||||
height: 300,
|
||||
pb: 1,
|
||||
overflowY: "auto",
|
||||
userSelect: "text",
|
||||
}}
|
||||
>
|
||||
{editing && (
|
||||
<WebUIItem
|
||||
value=""
|
||||
onlyEdit
|
||||
onChange={(v) => {
|
||||
setEditing(false);
|
||||
handleAdd(v || "");
|
||||
}}
|
||||
onCancel={() => setEditing(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{!editing && webUIList.length === 0 && (
|
||||
<BaseEmpty
|
||||
text="Empty List"
|
||||
extra={
|
||||
<Typography mt={2} sx={{ fontSize: "12px" }}>
|
||||
Replace host, port, secret with "%host" "%port" "%secret"
|
||||
</Typography>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
{webUIList.map((item, index) => (
|
||||
<WebUIItem
|
||||
key={index}
|
||||
value={item}
|
||||
onChange={(v) => handleChange(index, v)}
|
||||
onDelete={() => handleDelete(index)}
|
||||
onOpenUrl={handleOpenUrl}
|
||||
/>
|
||||
))}
|
||||
</DialogContent>
|
||||
|
||||
<DialogActions>
|
||||
<Button variant="outlined" onClick={() => setOpen(false)}>
|
||||
{t("Back")}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default WebUIViewer;
|
||||
@@ -1,52 +0,0 @@
|
||||
import { styled, Switch } from "@mui/material";
|
||||
|
||||
// todo: deprecated
|
||||
// From: https://mui.com/components/switches/
|
||||
const PaletteSwitch = styled(Switch)(({ theme }) => ({
|
||||
width: 62,
|
||||
height: 34,
|
||||
padding: 7,
|
||||
"& .MuiSwitch-switchBase": {
|
||||
margin: 1,
|
||||
padding: 0,
|
||||
transform: "translateX(6px)",
|
||||
"&.Mui-checked": {
|
||||
color: "#fff",
|
||||
transform: "translateX(22px)",
|
||||
"& .MuiSwitch-thumb:before": {
|
||||
backgroundImage: `url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" height="20" width="20" viewBox="0 0 20 20"><path fill="${encodeURIComponent(
|
||||
"#fff"
|
||||
)}" d="M4.2 2.5l-.7 1.8-1.8.7 1.8.7.7 1.8.6-1.8L6.7 5l-1.9-.7-.6-1.8zm15 8.3a6.7 6.7 0 11-6.6-6.6 5.8 5.8 0 006.6 6.6z"/></svg>')`,
|
||||
},
|
||||
"& + .MuiSwitch-track": {
|
||||
opacity: 1,
|
||||
backgroundColor: theme.palette.mode === "dark" ? "#8796A5" : "#aab4be",
|
||||
},
|
||||
},
|
||||
},
|
||||
"& .MuiSwitch-thumb": {
|
||||
backgroundColor: theme.palette.mode === "dark" ? "#003892" : "#001e3c",
|
||||
width: 32,
|
||||
height: 32,
|
||||
"&:before": {
|
||||
content: "''",
|
||||
position: "absolute",
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
left: 0,
|
||||
top: 0,
|
||||
backgroundRepeat: "no-repeat",
|
||||
backgroundPosition: "center",
|
||||
backgroundImage: `url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" height="20" width="20" viewBox="0 0 20 20"><path fill="${encodeURIComponent(
|
||||
"#fff"
|
||||
)}" d="M9.305 1.667V3.75h1.389V1.667h-1.39zm-4.707 1.95l-.982.982L5.09 6.072l.982-.982-1.473-1.473zm10.802 0L13.927 5.09l.982.982 1.473-1.473-.982-.982zM10 5.139a4.872 4.872 0 00-4.862 4.86A4.872 4.872 0 0010 14.862 4.872 4.872 0 0014.86 10 4.872 4.872 0 0010 5.139zm0 1.389A3.462 3.462 0 0113.471 10a3.462 3.462 0 01-3.473 3.472A3.462 3.462 0 016.527 10 3.462 3.462 0 0110 6.528zM1.665 9.305v1.39h2.083v-1.39H1.666zm14.583 0v1.39h2.084v-1.39h-2.084zM5.09 13.928L3.616 15.4l.982.982 1.473-1.473-.982-.982zm9.82 0l-.982.982 1.473 1.473.982-.982-1.473-1.473zM9.305 16.25v2.083h1.389V16.25h-1.39z"/></svg>')`,
|
||||
},
|
||||
},
|
||||
"& .MuiSwitch-track": {
|
||||
opacity: 1,
|
||||
backgroundColor: theme.palette.mode === "dark" ? "#8796A5" : "#aab4be",
|
||||
borderRadius: 20 / 2,
|
||||
},
|
||||
}));
|
||||
|
||||
export default PaletteSwitch;
|
||||
@@ -1,35 +1,37 @@
|
||||
import useSWR, { useSWRConfig } from "swr";
|
||||
import useSWR from "swr";
|
||||
import { useSetRecoilState } from "recoil";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
ListItemText,
|
||||
TextField,
|
||||
Switch,
|
||||
Select,
|
||||
MenuItem,
|
||||
Typography,
|
||||
Box,
|
||||
IconButton,
|
||||
} from "@mui/material";
|
||||
import { ApiType } from "../../services/types";
|
||||
import { atomClashPort } from "../../services/states";
|
||||
import { patchClashConfig } from "../../services/cmds";
|
||||
import { atomClashPort } from "@/services/states";
|
||||
import { ArrowForward } from "@mui/icons-material";
|
||||
import { patchClashConfig } from "@/services/cmds";
|
||||
import { SettingList, SettingItem } from "./setting";
|
||||
import { getClashConfig, getVersion, updateConfigs } from "../../services/api";
|
||||
import { getClashConfig, getVersion, updateConfigs } from "@/services/api";
|
||||
import useModalHandler from "@/hooks/use-modal-handler";
|
||||
import Notice from "../base/base-notice";
|
||||
import GuardState from "./guard-state";
|
||||
import CoreSwitch from "./core-switch";
|
||||
import GuardState from "./mods/guard-state";
|
||||
import CoreSwitch from "./mods/core-switch";
|
||||
import WebUIViewer from "./mods/web-ui-viewer";
|
||||
import ClashFieldViewer from "./mods/clash-field-viewer";
|
||||
|
||||
interface Props {
|
||||
onError: (err: Error) => void;
|
||||
}
|
||||
|
||||
// const MULTI_CORE = !!import.meta.env.VITE_MULTI_CORE;
|
||||
const MULTI_CORE = true;
|
||||
|
||||
const SettingClash = ({ onError }: Props) => {
|
||||
const { t } = useTranslation();
|
||||
const { mutate } = useSWRConfig();
|
||||
const { data: clashConfig } = useSWR("getClashConfig", getClashConfig);
|
||||
|
||||
const { data: clashConfig, mutate: mutateClash } = useSWR(
|
||||
"getClashConfig",
|
||||
getClashConfig
|
||||
);
|
||||
const { data: versionData } = useSWR("getVersion", getVersion);
|
||||
|
||||
const {
|
||||
@@ -41,9 +43,12 @@ const SettingClash = ({ onError }: Props) => {
|
||||
|
||||
const setGlobalClashPort = useSetRecoilState(atomClashPort);
|
||||
|
||||
const webUIHandler = useModalHandler();
|
||||
const fieldHandler = useModalHandler();
|
||||
|
||||
const onSwitchFormat = (_e: any, value: boolean) => value;
|
||||
const onChangeData = (patch: Partial<ApiType.ConfigData>) => {
|
||||
mutate("getClashConfig", { ...clashConfig, ...patch }, false);
|
||||
mutateClash((old) => ({ ...(old! || {}), ...patch }), false);
|
||||
};
|
||||
const onUpdateData = async (patch: Partial<ApiType.ConfigData>) => {
|
||||
await updateConfigs(patch);
|
||||
@@ -62,7 +67,7 @@ const SettingClash = ({ onError }: Props) => {
|
||||
Notice.success("Change Clash port successfully!", 1000);
|
||||
|
||||
// update the config
|
||||
mutate("getClashConfig");
|
||||
mutateClash();
|
||||
};
|
||||
|
||||
// get clash core version
|
||||
@@ -72,8 +77,10 @@ const SettingClash = ({ onError }: Props) => {
|
||||
|
||||
return (
|
||||
<SettingList title={t("Clash Setting")}>
|
||||
<SettingItem>
|
||||
<ListItemText primary={t("Allow Lan")} />
|
||||
<WebUIViewer handler={webUIHandler} onError={onError} />
|
||||
<ClashFieldViewer handler={fieldHandler} />
|
||||
|
||||
<SettingItem label={t("Allow Lan")}>
|
||||
<GuardState
|
||||
value={allowLan ?? false}
|
||||
valueProps="checked"
|
||||
@@ -86,8 +93,7 @@ const SettingClash = ({ onError }: Props) => {
|
||||
</GuardState>
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText primary={t("IPv6")} />
|
||||
<SettingItem label={t("IPv6")}>
|
||||
<GuardState
|
||||
value={ipv6 ?? false}
|
||||
valueProps="checked"
|
||||
@@ -100,8 +106,7 @@ const SettingClash = ({ onError }: Props) => {
|
||||
</GuardState>
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText primary={t("Log Level")} />
|
||||
<SettingItem label={t("Log Level")}>
|
||||
<GuardState
|
||||
value={logLevel ?? "info"}
|
||||
onCatch={onError}
|
||||
@@ -109,7 +114,7 @@ const SettingClash = ({ onError }: Props) => {
|
||||
onChange={(e) => onChangeData({ "log-level": e })}
|
||||
onGuard={(e) => onUpdateData({ "log-level": e })}
|
||||
>
|
||||
<Select size="small" sx={{ width: 120 }}>
|
||||
<Select size="small" sx={{ width: 120, "> div": { py: "7.5px" } }}>
|
||||
<MenuItem value="debug">Debug</MenuItem>
|
||||
<MenuItem value="info">Info</MenuItem>
|
||||
<MenuItem value="warning">Warning</MenuItem>
|
||||
@@ -119,8 +124,7 @@ const SettingClash = ({ onError }: Props) => {
|
||||
</GuardState>
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText primary={t("Mixed Port")} />
|
||||
<SettingItem label={t("Mixed Port")}>
|
||||
<GuardState
|
||||
value={mixedPort ?? 0}
|
||||
onCatch={onError}
|
||||
@@ -129,24 +133,38 @@ const SettingClash = ({ onError }: Props) => {
|
||||
onGuard={onUpdatePort}
|
||||
waitTime={1000}
|
||||
>
|
||||
<TextField autoComplete="off" size="small" sx={{ width: 120 }} />
|
||||
<TextField
|
||||
autoComplete="off"
|
||||
size="small"
|
||||
sx={{ width: 120, input: { py: "7.5px" } }}
|
||||
/>
|
||||
</GuardState>
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText
|
||||
primary={
|
||||
MULTI_CORE ? (
|
||||
<Box sx={{ display: "flex", alignItems: "center" }}>
|
||||
<span style={{ marginRight: 4 }}>{t("Clash Core")}</span>
|
||||
<CoreSwitch />
|
||||
</Box>
|
||||
) : (
|
||||
t("Clash Core")
|
||||
)
|
||||
}
|
||||
/>
|
||||
<Typography sx={{ py: 1 }}>{clashVer}</Typography>
|
||||
<SettingItem label={t("Web UI")}>
|
||||
<IconButton
|
||||
color="inherit"
|
||||
size="small"
|
||||
sx={{ my: "2px" }}
|
||||
onClick={() => webUIHandler.current.open()}
|
||||
>
|
||||
<ArrowForward />
|
||||
</IconButton>
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem label={t("Clash Field")}>
|
||||
<IconButton
|
||||
color="inherit"
|
||||
size="small"
|
||||
sx={{ my: "2px" }}
|
||||
onClick={() => fieldHandler.current.open()}
|
||||
>
|
||||
<ArrowForward />
|
||||
</IconButton>
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem label={t("Clash Core")} extra={<CoreSwitch />}>
|
||||
<Typography sx={{ py: "7px" }}>{clashVer}</Typography>
|
||||
</SettingItem>
|
||||
</SettingList>
|
||||
);
|
||||
|
||||
@@ -1,25 +1,18 @@
|
||||
import useSWR, { useSWRConfig } from "swr";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
Box,
|
||||
IconButton,
|
||||
ListItemText,
|
||||
Switch,
|
||||
TextField,
|
||||
} from "@mui/material";
|
||||
import { IconButton, Switch, TextField } from "@mui/material";
|
||||
import { ArrowForward, PrivacyTipRounded } from "@mui/icons-material";
|
||||
import {
|
||||
checkService,
|
||||
getVergeConfig,
|
||||
patchVergeConfig,
|
||||
} from "../../services/cmds";
|
||||
} from "@/services/cmds";
|
||||
import { SettingList, SettingItem } from "./setting";
|
||||
import { CmdType } from "../../services/types";
|
||||
import GuardState from "./guard-state";
|
||||
import ServiceMode from "./service-mode";
|
||||
import SysproxyTooltip from "./sysproxy-tooltip";
|
||||
import getSystem from "../../utils/get-system";
|
||||
import getSystem from "@/utils/get-system";
|
||||
import GuardState from "./mods/guard-state";
|
||||
import ServiceMode from "./mods/service-mode";
|
||||
import SysproxyTooltip from "./mods/sysproxy-tooltip";
|
||||
|
||||
interface Props {
|
||||
onError?: (err: Error) => void;
|
||||
@@ -57,8 +50,7 @@ const SettingSystem = ({ onError }: Props) => {
|
||||
|
||||
return (
|
||||
<SettingList title={t("System Setting")}>
|
||||
<SettingItem>
|
||||
<ListItemText primary={t("Tun Mode")} />
|
||||
<SettingItem label={t("Tun Mode")}>
|
||||
<GuardState
|
||||
value={enable_tun_mode ?? false}
|
||||
valueProps="checked"
|
||||
@@ -72,23 +64,18 @@ const SettingSystem = ({ onError }: Props) => {
|
||||
</SettingItem>
|
||||
|
||||
{isWIN && (
|
||||
<SettingItem>
|
||||
<ListItemText
|
||||
primary={
|
||||
<Box sx={{ display: "flex", alignItems: "center" }}>
|
||||
<span style={{ marginRight: 4 }}>{t("Service Mode")}</span>
|
||||
|
||||
{(serviceStatus === "active" ||
|
||||
serviceStatus === "installed") && (
|
||||
<PrivacyTipRounded
|
||||
fontSize="small"
|
||||
onClick={() => setServiceOpen(true)}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
}
|
||||
/>
|
||||
|
||||
<SettingItem
|
||||
label={t("Service Mode")}
|
||||
extra={
|
||||
(serviceStatus === "active" || serviceStatus === "installed") && (
|
||||
<PrivacyTipRounded
|
||||
fontSize="small"
|
||||
style={{ cursor: "pointer", opacity: 0.75 }}
|
||||
onClick={() => setServiceOpen(true)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
>
|
||||
{serviceStatus === "active" || serviceStatus === "installed" ? (
|
||||
<GuardState
|
||||
value={enable_service_mode ?? false}
|
||||
@@ -109,20 +96,19 @@ const SettingSystem = ({ onError }: Props) => {
|
||||
<ArrowForward />
|
||||
</IconButton>
|
||||
)}
|
||||
|
||||
{serviceOpen && (
|
||||
<ServiceMode
|
||||
open={serviceOpen}
|
||||
enable={!!enable_service_mode}
|
||||
onError={onError}
|
||||
onClose={() => setServiceOpen(false)}
|
||||
/>
|
||||
)}
|
||||
</SettingItem>
|
||||
)}
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText primary={t("Auto Launch")} />
|
||||
{isWIN && (
|
||||
<ServiceMode
|
||||
open={serviceOpen}
|
||||
enable={!!enable_service_mode}
|
||||
onError={onError}
|
||||
onClose={() => setServiceOpen(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<SettingItem label={t("Auto Launch")}>
|
||||
<GuardState
|
||||
value={enable_auto_launch ?? false}
|
||||
valueProps="checked"
|
||||
@@ -135,8 +121,7 @@ const SettingSystem = ({ onError }: Props) => {
|
||||
</GuardState>
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText primary={t("Silent Start")} />
|
||||
<SettingItem label={t("Silent Start")}>
|
||||
<GuardState
|
||||
value={enable_silent_start ?? false}
|
||||
valueProps="checked"
|
||||
@@ -149,15 +134,7 @@ const SettingSystem = ({ onError }: Props) => {
|
||||
</GuardState>
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText
|
||||
primary={
|
||||
<Box sx={{ display: "flex", alignItems: "center" }}>
|
||||
<span style={{ marginRight: 4 }}>{t("System Proxy")}</span>
|
||||
<SysproxyTooltip />
|
||||
</Box>
|
||||
}
|
||||
/>
|
||||
<SettingItem label={t("System Proxy")} extra={<SysproxyTooltip />}>
|
||||
<GuardState
|
||||
value={enable_system_proxy ?? false}
|
||||
valueProps="checked"
|
||||
@@ -174,8 +151,7 @@ const SettingSystem = ({ onError }: Props) => {
|
||||
</SettingItem>
|
||||
|
||||
{enable_system_proxy && (
|
||||
<SettingItem>
|
||||
<ListItemText primary={t("Proxy Guard")} />
|
||||
<SettingItem label={t("Proxy Guard")}>
|
||||
<GuardState
|
||||
value={enable_proxy_guard ?? false}
|
||||
valueProps="checked"
|
||||
@@ -190,8 +166,7 @@ const SettingSystem = ({ onError }: Props) => {
|
||||
)}
|
||||
|
||||
{enable_system_proxy && (
|
||||
<SettingItem>
|
||||
<ListItemText primary={t("Proxy Bypass")} />
|
||||
<SettingItem label={t("Proxy Bypass")}>
|
||||
<GuardState
|
||||
value={system_proxy_bypass ?? ""}
|
||||
onCatch={onError}
|
||||
@@ -200,7 +175,11 @@ const SettingSystem = ({ onError }: Props) => {
|
||||
onGuard={(e) => patchVergeConfig({ system_proxy_bypass: e })}
|
||||
waitTime={1000}
|
||||
>
|
||||
<TextField autoComplete="off" size="small" sx={{ width: 120 }} />
|
||||
<TextField
|
||||
autoComplete="off"
|
||||
size="small"
|
||||
sx={{ width: 120, input: { py: "7.5px" } }}
|
||||
/>
|
||||
</GuardState>
|
||||
</SettingItem>
|
||||
)}
|
||||
|
||||
@@ -15,8 +15,8 @@ import {
|
||||
TextField,
|
||||
useTheme,
|
||||
} from "@mui/material";
|
||||
import { getVergeConfig, patchVergeConfig } from "../../services/cmds";
|
||||
import { defaultTheme, defaultDarkTheme } from "../../pages/_theme";
|
||||
import { getVergeConfig, patchVergeConfig } from "@/services/cmds";
|
||||
import { defaultTheme, defaultDarkTheme } from "@/pages/_theme";
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
@@ -142,7 +142,9 @@ const SettingTheme = (props: Props) => {
|
||||
</DialogContent>
|
||||
|
||||
<DialogActions>
|
||||
<Button onClick={onClose}>{t("Cancel")}</Button>
|
||||
<Button variant="outlined" onClick={onClose}>
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button onClick={onSave} variant="contained">
|
||||
{t("Save")}
|
||||
</Button>
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import useSWR, { useSWRConfig } from "swr";
|
||||
import useSWR from "swr";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
IconButton,
|
||||
ListItemText,
|
||||
MenuItem,
|
||||
Select,
|
||||
Switch,
|
||||
@@ -14,13 +13,13 @@ import {
|
||||
openAppDir,
|
||||
openLogsDir,
|
||||
patchVergeConfig,
|
||||
} from "../../services/cmds";
|
||||
} 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 ThemeModeSwitch from "./theme-mode-switch";
|
||||
import GuardState from "./guard-state";
|
||||
import { version } from "@root/package.json";
|
||||
import ThemeModeSwitch from "./mods/theme-mode-switch";
|
||||
import ConfigViewer from "./mods/config-viewer";
|
||||
import GuardState from "./mods/guard-state";
|
||||
import SettingTheme from "./setting-theme";
|
||||
|
||||
interface Props {
|
||||
@@ -29,22 +28,24 @@ interface Props {
|
||||
|
||||
const SettingVerge = ({ onError }: Props) => {
|
||||
const { t } = useTranslation();
|
||||
const { mutate } = useSWRConfig();
|
||||
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
|
||||
const { data: vergeConfig, mutate: mutateVerge } = useSWR(
|
||||
"getVergeConfig",
|
||||
getVergeConfig
|
||||
);
|
||||
|
||||
const { theme_mode, theme_blur, traffic_graph, language } = vergeConfig ?? {};
|
||||
|
||||
const [themeOpen, setThemeOpen] = useState(false);
|
||||
const [configOpen, setConfigOpen] = useState(false);
|
||||
|
||||
const onSwitchFormat = (_e: any, value: boolean) => value;
|
||||
const onChangeData = (patch: Partial<CmdType.VergeConfig>) => {
|
||||
mutate("getVergeConfig", { ...vergeConfig, ...patch }, false);
|
||||
mutateVerge({ ...vergeConfig, ...patch }, false);
|
||||
};
|
||||
|
||||
return (
|
||||
<SettingList title={t("Verge Setting")}>
|
||||
<SettingItem>
|
||||
<ListItemText primary={t("Language")} />
|
||||
<SettingItem label={t("Language")}>
|
||||
<GuardState
|
||||
value={language ?? "en"}
|
||||
onCatch={onError}
|
||||
@@ -52,15 +53,14 @@ const SettingVerge = ({ onError }: Props) => {
|
||||
onChange={(e) => onChangeData({ language: e })}
|
||||
onGuard={(e) => patchVergeConfig({ language: e })}
|
||||
>
|
||||
<Select size="small" sx={{ width: 100 }}>
|
||||
<Select size="small" sx={{ width: 100, "> div": { py: "7.5px" } }}>
|
||||
<MenuItem value="zh">中文</MenuItem>
|
||||
<MenuItem value="en">English</MenuItem>
|
||||
</Select>
|
||||
</GuardState>
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText primary={t("Theme Mode")} />
|
||||
<SettingItem label={t("Theme Mode")}>
|
||||
<GuardState
|
||||
value={theme_mode}
|
||||
onCatch={onError}
|
||||
@@ -71,8 +71,7 @@ const SettingVerge = ({ onError }: Props) => {
|
||||
</GuardState>
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText primary={t("Theme Blur")} />
|
||||
<SettingItem label={t("Theme Blur")}>
|
||||
<GuardState
|
||||
value={theme_blur ?? false}
|
||||
valueProps="checked"
|
||||
@@ -85,8 +84,7 @@ const SettingVerge = ({ onError }: Props) => {
|
||||
</GuardState>
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText primary={t("Traffic Graph")} />
|
||||
<SettingItem label={t("Traffic Graph")}>
|
||||
<GuardState
|
||||
value={traffic_graph ?? true}
|
||||
valueProps="checked"
|
||||
@@ -99,37 +97,56 @@ const SettingVerge = ({ onError }: Props) => {
|
||||
</GuardState>
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText primary={t("Theme Setting")} />
|
||||
<SettingItem label={t("Theme Setting")}>
|
||||
<IconButton
|
||||
color="inherit"
|
||||
size="small"
|
||||
sx={{ my: "2px" }}
|
||||
onClick={() => setThemeOpen(true)}
|
||||
>
|
||||
<ArrowForward />
|
||||
</IconButton>
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText primary={t("Open App Dir")} />
|
||||
<IconButton color="inherit" size="small" onClick={openAppDir}>
|
||||
<SettingItem label={t("Runtime Config")}>
|
||||
<IconButton
|
||||
color="inherit"
|
||||
size="small"
|
||||
sx={{ my: "2px" }}
|
||||
onClick={() => setConfigOpen(true)}
|
||||
>
|
||||
<ArrowForward />
|
||||
</IconButton>
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText primary={t("Open Logs Dir")} />
|
||||
<IconButton color="inherit" size="small" onClick={openLogsDir}>
|
||||
<SettingItem label={t("Open App Dir")}>
|
||||
<IconButton
|
||||
color="inherit"
|
||||
size="small"
|
||||
sx={{ my: "2px" }}
|
||||
onClick={openAppDir}
|
||||
>
|
||||
<ArrowForward />
|
||||
</IconButton>
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText primary={t("Verge Version")} />
|
||||
<Typography sx={{ py: "6px" }}>v{version}</Typography>
|
||||
<SettingItem label={t("Open Logs Dir")}>
|
||||
<IconButton
|
||||
color="inherit"
|
||||
size="small"
|
||||
sx={{ my: "2px" }}
|
||||
onClick={openLogsDir}
|
||||
>
|
||||
<ArrowForward />
|
||||
</IconButton>
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem label={t("Verge Version")}>
|
||||
<Typography sx={{ py: "7px" }}>v{version}</Typography>
|
||||
</SettingItem>
|
||||
|
||||
<SettingTheme open={themeOpen} onClose={() => setThemeOpen(false)} />
|
||||
<ConfigViewer open={configOpen} onClose={() => setConfigOpen(false)} />
|
||||
</SettingList>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,10 +1,36 @@
|
||||
import React from "react";
|
||||
import { List, ListItem, ListSubheader, styled } from "@mui/material";
|
||||
import {
|
||||
Box,
|
||||
List,
|
||||
ListItem,
|
||||
ListItemText,
|
||||
ListSubheader,
|
||||
} from "@mui/material";
|
||||
|
||||
export const SettingItem = styled(ListItem)(() => ({
|
||||
paddingTop: 5,
|
||||
paddingBottom: 5,
|
||||
}));
|
||||
interface ItemProps {
|
||||
label: React.ReactNode;
|
||||
extra?: React.ReactNode;
|
||||
}
|
||||
|
||||
export const SettingItem: React.FC<ItemProps> = (props) => {
|
||||
const { label, extra, children } = props;
|
||||
|
||||
const primary = !extra ? (
|
||||
label
|
||||
) : (
|
||||
<Box sx={{ display: "flex", alignItems: "center" }}>
|
||||
<span style={{ marginRight: 4 }}>{label}</span>
|
||||
{extra}
|
||||
</Box>
|
||||
);
|
||||
|
||||
return (
|
||||
<ListItem sx={{ pt: "5px", pb: "5px" }}>
|
||||
<ListItemText primary={primary} />
|
||||
{children}
|
||||
</ListItem>
|
||||
);
|
||||
};
|
||||
|
||||
export const SettingList: React.FC<{ title: string }> = (props) => (
|
||||
<List>
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { MutableRefObject, useRef } from "react";
|
||||
|
||||
interface Handler {
|
||||
open: () => void;
|
||||
close: () => void;
|
||||
}
|
||||
|
||||
export type ModalHandler = MutableRefObject<Handler>;
|
||||
|
||||
const useModalHandler = (): ModalHandler => {
|
||||
return useRef({ open: () => {}, close: () => {} });
|
||||
};
|
||||
|
||||
export default useModalHandler;
|
||||
@@ -18,6 +18,8 @@
|
||||
"Profile URL": "Profile URL",
|
||||
"Import": "Import",
|
||||
"New": "New",
|
||||
"Create Profile": "Create Profile",
|
||||
"Choose File": "Choose File",
|
||||
"Close All": "Close All",
|
||||
"Select": "Select",
|
||||
"Edit Info": "Edit Info",
|
||||
@@ -59,7 +61,11 @@
|
||||
"theme.light": "Light",
|
||||
"theme.dark": "Dark",
|
||||
"theme.system": "System",
|
||||
"Clash Field": "Clash Field",
|
||||
"Runtime Config": "Runtime Config",
|
||||
"ReadOnly": "ReadOnly",
|
||||
|
||||
"Back": "Back",
|
||||
"Save": "Save",
|
||||
"Cancel": "Cancel"
|
||||
}
|
||||
|
||||
@@ -18,6 +18,8 @@
|
||||
"Profile URL": "配置文件链接",
|
||||
"Import": "导入",
|
||||
"New": "新建",
|
||||
"Create Profile": "新建配置",
|
||||
"Choose File": "选择文件",
|
||||
"Close All": "关闭全部",
|
||||
"Select": "使用",
|
||||
"Edit Info": "编辑信息",
|
||||
@@ -59,7 +61,11 @@
|
||||
"theme.light": "浅色",
|
||||
"theme.dark": "深色",
|
||||
"theme.system": "系统",
|
||||
"Clash Field": "Clash 字段",
|
||||
"Runtime Config": "运行配置",
|
||||
"ReadOnly": "只读",
|
||||
|
||||
"Back": "返回",
|
||||
"Save": "保存",
|
||||
"Cancel": "取消"
|
||||
}
|
||||
|
||||
@@ -7,11 +7,8 @@ import ReactDOM from "react-dom";
|
||||
import { RecoilRoot } from "recoil";
|
||||
import { BrowserRouter } from "react-router-dom";
|
||||
import Layout from "./pages/_layout";
|
||||
import enhance from "./services/enhance";
|
||||
import "./services/i18n";
|
||||
|
||||
enhance.setup();
|
||||
|
||||
ReactDOM.render(
|
||||
<React.StrictMode>
|
||||
<RecoilRoot>
|
||||
|
||||
+17
-11
@@ -10,18 +10,22 @@ import { alpha, List, Paper, ThemeProvider } from "@mui/material";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { appWindow } from "@tauri-apps/api/window";
|
||||
import { routers } from "./_routers";
|
||||
import { getAxios } from "../services/api";
|
||||
import { atomCurrentProfile } from "../services/states";
|
||||
import { getVergeConfig, getProfiles } from "../services/cmds";
|
||||
import { ReactComponent as 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";
|
||||
import useCustomTheme from "../components/layout/use-custom-theme";
|
||||
import getSystem from "../utils/get-system";
|
||||
import { getAxios } from "@/services/api";
|
||||
import { atomCurrentProfile } from "@/services/states";
|
||||
import { getVergeConfig, getProfiles } from "@/services/cmds";
|
||||
import { ReactComponent as 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";
|
||||
import useCustomTheme from "@/components/layout/use-custom-theme";
|
||||
import getSystem from "@/utils/get-system";
|
||||
import "dayjs/locale/zh-cn";
|
||||
|
||||
declare global {
|
||||
const WIN_PORTABLE: boolean;
|
||||
}
|
||||
|
||||
dayjs.extend(relativeTime);
|
||||
|
||||
const OS = getSystem();
|
||||
@@ -87,7 +91,9 @@ const Layout = () => {
|
||||
<div className="the-logo" data-windrag>
|
||||
<LogoSvg />
|
||||
|
||||
<UpdateButton className="the-newbtn" />
|
||||
{!(OS === "windows" && WIN_PORTABLE) && (
|
||||
<UpdateButton className="the-newbtn" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<List className="the-menu">
|
||||
|
||||
@@ -3,10 +3,9 @@ import { useLockFn } from "ahooks";
|
||||
import { Box, Button, Paper, TextField } from "@mui/material";
|
||||
import { Virtuoso } from "react-virtuoso";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ApiType } from "../services/types";
|
||||
import { closeAllConnections, getInformation } from "../services/api";
|
||||
import BasePage from "../components/base/base-page";
|
||||
import ConnectionItem from "../components/connection/connection-item";
|
||||
import { closeAllConnections, getInformation } from "@/services/api";
|
||||
import BasePage from "@/components/base/base-page";
|
||||
import ConnectionItem from "@/components/connection/connection-item";
|
||||
|
||||
const initConn = { uploadTotal: 0, downloadTotal: 0, connections: [] };
|
||||
|
||||
|
||||
+3
-3
@@ -3,9 +3,9 @@ import { useRecoilState } from "recoil";
|
||||
import { Box, Button, MenuItem, Paper, Select, TextField } from "@mui/material";
|
||||
import { Virtuoso } from "react-virtuoso";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { atomLogData } from "../services/states";
|
||||
import BasePage from "../components/base/base-page";
|
||||
import LogItem from "../components/log/log-item";
|
||||
import { atomLogData } from "@/services/states";
|
||||
import BasePage from "@/components/base/base-page";
|
||||
import LogItem from "@/components/log/log-item";
|
||||
|
||||
const LogPage = () => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
+30
-22
@@ -1,26 +1,25 @@
|
||||
import useSWR, { useSWRConfig } from "swr";
|
||||
import useSWR, { mutate } from "swr";
|
||||
import { useLockFn } from "ahooks";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useSetRecoilState } from "recoil";
|
||||
import { Box, Button, Grid, TextField } from "@mui/material";
|
||||
import { Button, Grid, Stack, TextField } from "@mui/material";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
getProfiles,
|
||||
patchProfile,
|
||||
selectProfile,
|
||||
importProfile,
|
||||
} from "../services/cmds";
|
||||
import { getProxies, updateProxy } from "../services/api";
|
||||
import { atomCurrentProfile } from "../services/states";
|
||||
import Notice from "../components/base/base-notice";
|
||||
import BasePage from "../components/base/base-page";
|
||||
import ProfileNew from "../components/profile/profile-new";
|
||||
import ProfileItem from "../components/profile/profile-item";
|
||||
import EnhancedMode from "../components/profile/enhanced";
|
||||
} from "@/services/cmds";
|
||||
import { getProxies, updateProxy } from "@/services/api";
|
||||
import { atomCurrentProfile } from "@/services/states";
|
||||
import Notice from "@/components/base/base-notice";
|
||||
import BasePage from "@/components/base/base-page";
|
||||
import ProfileNew from "@/components/profile/profile-new";
|
||||
import ProfileItem from "@/components/profile/profile-item";
|
||||
import EnhancedMode from "@/components/profile/enhanced";
|
||||
|
||||
const ProfilePage = () => {
|
||||
const { t } = useTranslation();
|
||||
const { mutate } = useSWRConfig();
|
||||
|
||||
const [url, setUrl] = useState("");
|
||||
const [disabled, setDisabled] = useState(false);
|
||||
@@ -110,10 +109,13 @@ const ProfilePage = () => {
|
||||
getProfiles().then((newProfiles) => {
|
||||
mutate("getProfiles", newProfiles);
|
||||
|
||||
if (!newProfiles.current && newProfiles.items?.length) {
|
||||
const current = newProfiles.items[0].uid;
|
||||
const remoteItem = newProfiles.items?.find((e) => e.type === "remote");
|
||||
|
||||
if (!newProfiles.current && remoteItem) {
|
||||
const current = remoteItem.uid;
|
||||
selectProfile(current);
|
||||
mutate("getProfiles", { ...newProfiles, current }, true);
|
||||
mutate("getRuntimeLogs");
|
||||
}
|
||||
});
|
||||
} catch {
|
||||
@@ -130,6 +132,7 @@ const ProfilePage = () => {
|
||||
await selectProfile(uid);
|
||||
setCurrentProfile(uid);
|
||||
mutate("getProfiles", { ...profiles, current: uid }, true);
|
||||
mutate("getRuntimeLogs");
|
||||
if (force) Notice.success("Refresh clash config", 1000);
|
||||
} catch (err: any) {
|
||||
Notice.error(err?.message || err.toString());
|
||||
@@ -138,29 +141,34 @@ const ProfilePage = () => {
|
||||
|
||||
return (
|
||||
<BasePage title={t("Profiles")}>
|
||||
<Box sx={{ display: "flex", mb: 2.5 }}>
|
||||
<Stack direction="row" spacing={1} sx={{ mb: 2 }}>
|
||||
<TextField
|
||||
id="clas_verge_profile_url"
|
||||
name="profile_url"
|
||||
label={t("Profile URL")}
|
||||
size="small"
|
||||
hiddenLabel
|
||||
fullWidth
|
||||
size="small"
|
||||
value={url}
|
||||
variant="outlined"
|
||||
autoComplete="off"
|
||||
onChange={(e) => setUrl(e.target.value)}
|
||||
sx={{ mr: 1 }}
|
||||
sx={{ input: { py: 0.65, px: 1.25 } }}
|
||||
placeholder={t("Profile URL")}
|
||||
/>
|
||||
<Button
|
||||
disabled={!url || disabled}
|
||||
variant="contained"
|
||||
size="small"
|
||||
onClick={onImport}
|
||||
sx={{ mr: 1 }}
|
||||
>
|
||||
{t("Import")}
|
||||
</Button>
|
||||
<Button variant="contained" onClick={() => setDialogOpen(true)}>
|
||||
<Button
|
||||
variant="contained"
|
||||
size="small"
|
||||
onClick={() => setDialogOpen(true)}
|
||||
>
|
||||
{t("New")}
|
||||
</Button>
|
||||
</Box>
|
||||
</Stack>
|
||||
|
||||
<Grid container spacing={2}>
|
||||
{regularItems.map((item) => (
|
||||
|
||||
@@ -3,12 +3,12 @@ import { useEffect } from "react";
|
||||
import { useLockFn } from "ahooks";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Button, ButtonGroup, List, Paper } from "@mui/material";
|
||||
import { getClashConfig, updateConfigs } from "../services/api";
|
||||
import { patchClashConfig } from "../services/cmds";
|
||||
import { getProxies } from "../services/api";
|
||||
import BasePage from "../components/base/base-page";
|
||||
import ProxyGroup from "../components/proxy/proxy-group";
|
||||
import ProxyGlobal from "../components/proxy/proxy-global";
|
||||
import { getClashConfig, updateConfigs } from "@/services/api";
|
||||
import { patchClashConfig } from "@/services/cmds";
|
||||
import { getProxies } from "@/services/api";
|
||||
import BasePage from "@/components/base/base-page";
|
||||
import ProxyGroup from "@/components/proxy/proxy-group";
|
||||
import ProxyGlobal from "@/components/proxy/proxy-global";
|
||||
|
||||
const ProxyPage = () => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { Paper } from "@mui/material";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import Notice from "../components/base/base-notice";
|
||||
import BasePage from "../components/base/base-page";
|
||||
import SettingVerge from "../components/setting/setting-verge";
|
||||
import SettingClash from "../components/setting/setting-clash";
|
||||
import SettingSystem from "../components/setting/setting-system";
|
||||
import Notice from "@/components/base/base-notice";
|
||||
import BasePage from "@/components/base/base-page";
|
||||
import SettingVerge from "@/components/setting/setting-verge";
|
||||
import SettingClash from "@/components/setting/setting-clash";
|
||||
import SettingSystem from "@/components/setting/setting-system";
|
||||
|
||||
const SettingPage = () => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import axios, { AxiosInstance } from "axios";
|
||||
import { getClashInfo } from "./cmds";
|
||||
import { ApiType } from "./types";
|
||||
|
||||
let axiosIns: AxiosInstance = null!;
|
||||
let server = "";
|
||||
|
||||
+21
-2
@@ -1,6 +1,5 @@
|
||||
import { invoke } from "@tauri-apps/api/tauri";
|
||||
import { ApiType, CmdType } from "./types";
|
||||
import Notice from "../components/base/base-notice";
|
||||
import Notice from "@/components/base/base-notice";
|
||||
|
||||
export async function getProfiles() {
|
||||
return invoke<CmdType.ProfilesConfig>("get_profiles");
|
||||
@@ -70,6 +69,22 @@ export async function getClashInfo() {
|
||||
return invoke<CmdType.ClashInfo | null>("get_clash_info");
|
||||
}
|
||||
|
||||
export async function getRuntimeConfig() {
|
||||
return invoke<any | null>("get_runtime_config");
|
||||
}
|
||||
|
||||
export async function getRuntimeYaml() {
|
||||
return invoke<string | null>("get_runtime_yaml");
|
||||
}
|
||||
|
||||
export async function getRuntimeExists() {
|
||||
return invoke<string[]>("get_runtime_exists");
|
||||
}
|
||||
|
||||
export async function getRuntimeLogs() {
|
||||
return invoke<Record<string, [string, string][]>>("get_runtime_logs");
|
||||
}
|
||||
|
||||
export async function patchClashConfig(payload: Partial<ApiType.ConfigData>) {
|
||||
return invoke<void>("patch_clash_config", { payload });
|
||||
}
|
||||
@@ -110,6 +125,10 @@ export async function openLogsDir() {
|
||||
);
|
||||
}
|
||||
|
||||
export async function openWebUrl(url: string) {
|
||||
return invoke<void>("open_web_url", { url });
|
||||
}
|
||||
|
||||
/// service mode
|
||||
|
||||
export async function startService() {
|
||||
|
||||
@@ -1,221 +0,0 @@
|
||||
import { emit, listen, Event } from "@tauri-apps/api/event";
|
||||
import { appWindow } from "@tauri-apps/api/window";
|
||||
import { CmdType } from "./types";
|
||||
import ignoreCase from "../utils/ignore-case";
|
||||
|
||||
const DEFAULT_FIELDS = [
|
||||
"rules",
|
||||
"proxies",
|
||||
"proxy-groups",
|
||||
"proxy-providers",
|
||||
"rule-providers",
|
||||
] as const;
|
||||
|
||||
const USE_FLAG_FIELDS = [
|
||||
"tun",
|
||||
"dns",
|
||||
"hosts",
|
||||
"script",
|
||||
"profile",
|
||||
"payload",
|
||||
"interface-name",
|
||||
"routing-mark",
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* process the merge mode
|
||||
*/
|
||||
function toMerge(merge: CmdType.ProfileMerge, data: CmdType.ProfileData) {
|
||||
if (!merge) return { data, use: [] };
|
||||
|
||||
const {
|
||||
use,
|
||||
"prepend-rules": preRules,
|
||||
"append-rules": postRules,
|
||||
"prepend-proxies": preProxies,
|
||||
"append-proxies": postProxies,
|
||||
"prepend-proxy-groups": preProxyGroups,
|
||||
"append-proxy-groups": postProxyGroups,
|
||||
...mergeConfig
|
||||
} = merge;
|
||||
|
||||
[...DEFAULT_FIELDS, ...USE_FLAG_FIELDS].forEach((key) => {
|
||||
// the value should not be null
|
||||
if (mergeConfig[key] != null) {
|
||||
data[key] = mergeConfig[key];
|
||||
}
|
||||
});
|
||||
|
||||
// init
|
||||
if (!data.rules) data.rules = [];
|
||||
if (!data.proxies) data.proxies = [];
|
||||
if (!data["proxy-groups"]) data["proxy-groups"] = [];
|
||||
|
||||
// rules
|
||||
if (Array.isArray(preRules)) {
|
||||
data.rules.unshift(...preRules);
|
||||
}
|
||||
if (Array.isArray(postRules)) {
|
||||
data.rules.push(...postRules);
|
||||
}
|
||||
|
||||
// proxies
|
||||
if (Array.isArray(preProxies)) {
|
||||
data.proxies.unshift(...preProxies);
|
||||
}
|
||||
if (Array.isArray(postProxies)) {
|
||||
data.proxies.push(...postProxies);
|
||||
}
|
||||
|
||||
// proxy-groups
|
||||
if (Array.isArray(preProxyGroups)) {
|
||||
data["proxy-groups"].unshift(...preProxyGroups);
|
||||
}
|
||||
if (Array.isArray(postProxyGroups)) {
|
||||
data["proxy-groups"].push(...postProxyGroups);
|
||||
}
|
||||
|
||||
return { data, use: Array.isArray(use) ? use : [] };
|
||||
}
|
||||
|
||||
/**
|
||||
* process the script mode
|
||||
*/
|
||||
function toScript(
|
||||
script: string,
|
||||
data: CmdType.ProfileData
|
||||
): Promise<CmdType.ProfileData> {
|
||||
if (!script) {
|
||||
throw new Error("miss the main function");
|
||||
}
|
||||
|
||||
const paramsName = `__verge${Math.floor(Math.random() * 1000)}`;
|
||||
const code = `'use strict';${script};return main(${paramsName});`;
|
||||
const func = new Function(paramsName, code);
|
||||
return func(data);
|
||||
}
|
||||
|
||||
export type EStatus = { status: "ok" | "error"; message?: string };
|
||||
export type EListener = (status: EStatus) => void;
|
||||
export type EUnlistener = () => void;
|
||||
|
||||
/**
|
||||
* The service helps to
|
||||
* implement enhanced profiles
|
||||
*/
|
||||
class Enhance {
|
||||
private isSetup = false;
|
||||
private listenMap: Map<string, EListener>;
|
||||
private resultMap: Map<string, EStatus>;
|
||||
|
||||
constructor() {
|
||||
this.listenMap = new Map();
|
||||
this.resultMap = new Map();
|
||||
}
|
||||
|
||||
// setup some listener
|
||||
// for the enhanced running status
|
||||
listen(uid: string, cb: EListener): EUnlistener {
|
||||
this.listenMap.set(uid, cb);
|
||||
return () => this.listenMap.delete(uid);
|
||||
}
|
||||
|
||||
// get the running status
|
||||
status(uid: string): EStatus | undefined {
|
||||
return this.resultMap.get(uid);
|
||||
}
|
||||
|
||||
async enhanceHandler(event: Event<unknown>) {
|
||||
const payload = event.payload as CmdType.EnhancedPayload;
|
||||
|
||||
const result = await this.runner(payload).catch((err: any) => ({
|
||||
data: null,
|
||||
status: "error",
|
||||
error: err.message,
|
||||
}));
|
||||
|
||||
emit(payload.callback, JSON.stringify(result)).catch(console.error);
|
||||
}
|
||||
|
||||
// setup the handler
|
||||
setup() {
|
||||
if (this.isSetup) return;
|
||||
this.isSetup = true;
|
||||
|
||||
listen("script-handler", async (event) => {
|
||||
await this.enhanceHandler(event);
|
||||
});
|
||||
|
||||
listen("script-handler-close", async (event) => {
|
||||
await this.enhanceHandler(event);
|
||||
appWindow.close();
|
||||
});
|
||||
}
|
||||
|
||||
// enhanced mode runner
|
||||
private async runner(payload: CmdType.EnhancedPayload) {
|
||||
const chain = payload.chain || [];
|
||||
const valid = payload.valid || [];
|
||||
|
||||
if (!Array.isArray(chain)) throw new Error("unhandle error");
|
||||
|
||||
let pdata = payload.current || {};
|
||||
let useList = valid;
|
||||
|
||||
for (const each of chain) {
|
||||
const { uid, type = "" } = each.item;
|
||||
|
||||
try {
|
||||
// process script
|
||||
if (type === "script") {
|
||||
// support async main function
|
||||
pdata = await toScript(each.script!, ignoreCase(pdata));
|
||||
}
|
||||
|
||||
// process merge
|
||||
else if (type === "merge") {
|
||||
const temp = toMerge(each.merge!, ignoreCase(pdata));
|
||||
pdata = temp.data;
|
||||
useList = useList.concat(temp.use || []);
|
||||
}
|
||||
|
||||
// invalid type
|
||||
else {
|
||||
throw new Error(`invalid enhanced profile type "${type}"`);
|
||||
}
|
||||
|
||||
this.exec(uid, { status: "ok" });
|
||||
} catch (err: any) {
|
||||
console.error(err);
|
||||
|
||||
this.exec(uid, {
|
||||
status: "error",
|
||||
message: err.message || err.toString(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pdata = ignoreCase(pdata);
|
||||
|
||||
// filter the data
|
||||
const filterData: typeof pdata = {};
|
||||
Object.keys(pdata).forEach((key: any) => {
|
||||
if (
|
||||
DEFAULT_FIELDS.includes(key) ||
|
||||
(USE_FLAG_FIELDS.includes(key) && useList.includes(key))
|
||||
) {
|
||||
filterData[key] = pdata[key];
|
||||
}
|
||||
});
|
||||
|
||||
return { data: filterData, status: "ok" };
|
||||
}
|
||||
|
||||
// exec the listener
|
||||
private exec(uid: string, status: EStatus) {
|
||||
this.resultMap.set(uid, status);
|
||||
this.listenMap.get(uid)?.(status);
|
||||
}
|
||||
}
|
||||
|
||||
export default new Enhance();
|
||||
@@ -1,7 +1,7 @@
|
||||
import i18n from "i18next";
|
||||
import { initReactI18next } from "react-i18next";
|
||||
import en from "../locales/en.json";
|
||||
import zh from "../locales/zh.json";
|
||||
import en from "@/locales/en.json";
|
||||
import zh from "@/locales/zh.json";
|
||||
|
||||
const resources = {
|
||||
en: { translation: en },
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { atom } from "recoil";
|
||||
import { ApiType } from "./types";
|
||||
|
||||
export const atomThemeMode = atom<"light" | "dark">({
|
||||
key: "atomThemeMode",
|
||||
|
||||
+36
-21
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* Some interface for clash api
|
||||
*/
|
||||
export namespace ApiType {
|
||||
export interface ConfigData {
|
||||
declare namespace ApiType {
|
||||
interface ConfigData {
|
||||
port: number;
|
||||
mode: string;
|
||||
ipv6: boolean;
|
||||
@@ -15,13 +15,13 @@ export namespace ApiType {
|
||||
"tproxy-port": number;
|
||||
}
|
||||
|
||||
export interface RuleItem {
|
||||
interface RuleItem {
|
||||
type: string;
|
||||
payload: string;
|
||||
proxy: string;
|
||||
}
|
||||
|
||||
export interface ProxyItem {
|
||||
interface ProxyItem {
|
||||
name: string;
|
||||
type: string;
|
||||
udp: boolean;
|
||||
@@ -33,22 +33,22 @@ export namespace ApiType {
|
||||
now?: string;
|
||||
}
|
||||
|
||||
export type ProxyGroupItem = Omit<ProxyItem, "all"> & {
|
||||
type ProxyGroupItem = Omit<ProxyItem, "all"> & {
|
||||
all: ProxyItem[];
|
||||
};
|
||||
|
||||
export interface TrafficItem {
|
||||
interface TrafficItem {
|
||||
up: number;
|
||||
down: number;
|
||||
}
|
||||
|
||||
export interface LogItem {
|
||||
interface LogItem {
|
||||
type: string;
|
||||
time?: string;
|
||||
payload: string;
|
||||
}
|
||||
|
||||
export interface ConnectionsItem {
|
||||
interface ConnectionsItem {
|
||||
id: string;
|
||||
metadata: {
|
||||
network: string;
|
||||
@@ -69,7 +69,7 @@ export namespace ApiType {
|
||||
curDownload?: number; // calculate
|
||||
}
|
||||
|
||||
export interface Connections {
|
||||
interface Connections {
|
||||
downloadTotal: number;
|
||||
uploadTotal: number;
|
||||
connections: ConnectionsItem[];
|
||||
@@ -79,17 +79,17 @@ export namespace ApiType {
|
||||
/**
|
||||
* Some interface for command
|
||||
*/
|
||||
export namespace CmdType {
|
||||
export type ProfileType = "local" | "remote" | "merge" | "script";
|
||||
declare namespace CmdType {
|
||||
type ProfileType = "local" | "remote" | "merge" | "script";
|
||||
|
||||
export interface ClashInfo {
|
||||
interface ClashInfo {
|
||||
status: string;
|
||||
port?: string;
|
||||
server?: string;
|
||||
secret?: string;
|
||||
}
|
||||
|
||||
export interface ProfileItem {
|
||||
interface ProfileItem {
|
||||
uid: string;
|
||||
type?: ProfileType | string;
|
||||
name?: string;
|
||||
@@ -110,20 +110,20 @@ export namespace CmdType {
|
||||
option?: ProfileOption;
|
||||
}
|
||||
|
||||
export interface ProfileOption {
|
||||
interface ProfileOption {
|
||||
user_agent?: string;
|
||||
with_proxy?: boolean;
|
||||
update_interval?: number;
|
||||
}
|
||||
|
||||
export interface ProfilesConfig {
|
||||
interface ProfilesConfig {
|
||||
current?: string;
|
||||
chain?: string[];
|
||||
valid?: string[];
|
||||
items?: ProfileItem[];
|
||||
}
|
||||
|
||||
export interface VergeConfig {
|
||||
interface VergeConfig {
|
||||
language?: string;
|
||||
clash_core?: string;
|
||||
theme_mode?: "light" | "dark" | "system";
|
||||
@@ -136,6 +136,7 @@ export namespace CmdType {
|
||||
enable_system_proxy?: boolean;
|
||||
enable_proxy_guard?: boolean;
|
||||
system_proxy_bypass?: string;
|
||||
web_ui_list?: string[];
|
||||
theme_setting?: {
|
||||
primary_color?: string;
|
||||
secondary_color?: string;
|
||||
@@ -152,7 +153,7 @@ export namespace CmdType {
|
||||
|
||||
type ClashConfigValue = any;
|
||||
|
||||
export interface ProfileMerge {
|
||||
interface ProfileMerge {
|
||||
// clash config fields (default supports)
|
||||
rules?: ClashConfigValue;
|
||||
proxies?: ClashConfigValue;
|
||||
@@ -176,10 +177,24 @@ export namespace CmdType {
|
||||
"append-proxies"?: any[];
|
||||
"prepend-proxy-groups"?: any[];
|
||||
"append-proxy-groups"?: any[];
|
||||
// fix
|
||||
ebpf?: any;
|
||||
experimental?: any;
|
||||
iptables?: any;
|
||||
sniffer?: any;
|
||||
authentication?: any;
|
||||
"bind-address"?: any;
|
||||
"external-ui"?: any;
|
||||
"auto-redir"?: any;
|
||||
"socks-port"?: any;
|
||||
"redir-port"?: any;
|
||||
"tproxy-port"?: any;
|
||||
"geodata-mode"?: any;
|
||||
"tcp-concurrent"?: any;
|
||||
}
|
||||
|
||||
// partial of the clash config
|
||||
export type ProfileData = Partial<{
|
||||
type ProfileData = Partial<{
|
||||
rules: any[];
|
||||
proxies: any[];
|
||||
"proxy-groups": any[];
|
||||
@@ -189,20 +204,20 @@ export namespace CmdType {
|
||||
[k: string]: any;
|
||||
}>;
|
||||
|
||||
export interface ChainItem {
|
||||
interface ChainItem {
|
||||
item: ProfileItem;
|
||||
merge?: ProfileMerge;
|
||||
script?: string;
|
||||
}
|
||||
|
||||
export interface EnhancedPayload {
|
||||
interface EnhancedPayload {
|
||||
chain: ChainItem[];
|
||||
valid: string[];
|
||||
current: ProfileData;
|
||||
callback: string;
|
||||
}
|
||||
|
||||
export interface EnhancedResult {
|
||||
interface EnhancedResult {
|
||||
data: ProfileData;
|
||||
status: string;
|
||||
error?: string;
|
||||
@@ -0,0 +1,42 @@
|
||||
export const HANDLE_FIELDS = [
|
||||
"port",
|
||||
"socks-port",
|
||||
"mixed-port",
|
||||
"allow-lan",
|
||||
"mode",
|
||||
"log-level",
|
||||
"ipv6",
|
||||
"secret",
|
||||
"external-controller",
|
||||
];
|
||||
|
||||
export const DEFAULT_FIELDS = [
|
||||
"rules",
|
||||
"proxies",
|
||||
"proxy-groups",
|
||||
"proxy-providers",
|
||||
"rule-providers",
|
||||
] as const;
|
||||
|
||||
export const OTHERS_FIELDS = [
|
||||
"tun",
|
||||
"dns",
|
||||
"ebpf",
|
||||
"hosts",
|
||||
"script",
|
||||
"profile",
|
||||
"payload",
|
||||
"auto-redir",
|
||||
"experimental",
|
||||
"interface-name",
|
||||
"routing-mark",
|
||||
"redir-port",
|
||||
"tproxy-port",
|
||||
"iptables",
|
||||
"external-ui",
|
||||
"bind-address",
|
||||
"authentication",
|
||||
"sniffer", // meta
|
||||
"geodata-mode", // meta
|
||||
"tcp-concurrent", // meta
|
||||
] as const;
|
||||
@@ -2,7 +2,7 @@
|
||||
type TData = Record<string, any>;
|
||||
|
||||
export default function ignoreCase(data: TData): TData {
|
||||
if (!data) return data;
|
||||
if (!data) return {};
|
||||
|
||||
const newData = {} as TData;
|
||||
|
||||
|
||||
+6
-1
@@ -1,5 +1,6 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"baseUrl": ".",
|
||||
"target": "ESNext",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["DOM", "DOM.Iterable", "ESNext"],
|
||||
@@ -14,7 +15,11 @@
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx"
|
||||
"jsx": "react-jsx",
|
||||
"paths": {
|
||||
"@/*": ["src/*"],
|
||||
"@root/*": ["./*"]
|
||||
}
|
||||
},
|
||||
"include": ["./src"]
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { defineConfig } from "vite";
|
||||
import path from "path";
|
||||
import svgr from "vite-plugin-svgr";
|
||||
import react from "@vitejs/plugin-react";
|
||||
import monaco from "vite-plugin-monaco-editor";
|
||||
@@ -15,4 +16,13 @@ export default defineConfig({
|
||||
outDir: "../dist",
|
||||
emptyOutDir: true,
|
||||
},
|
||||
resolve: {
|
||||
alias: {
|
||||
"@": path.resolve("./src"),
|
||||
"@root": path.resolve("."),
|
||||
},
|
||||
},
|
||||
define: {
|
||||
WIN_PORTABLE: !!process.env.VITE_WIN_PORTABLE,
|
||||
},
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user