Compare commits
38 Commits
2
.github/workflows/ci.yml
vendored
2
.github/workflows/ci.yml
vendored
@@ -58,6 +58,8 @@ jobs:
|
||||
continue-on-error: true
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
|
||||
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
|
||||
with:
|
||||
tagName: v__VERSION__
|
||||
releaseName: "Clash Verge v__VERSION__"
|
||||
|
||||
11
README.md
11
README.md
@@ -58,6 +58,15 @@ This is a learning project for Rust practice.
|
||||
|
||||
PR welcome!
|
||||
|
||||
## Acknowledgement
|
||||
|
||||
Clash Verge was based on or inspired by these projects and so on:
|
||||
|
||||
- [tauri-apps/tauri](https://github.com/tauri-apps/tauri): Build smaller, faster, and more secure desktop applications with a web frontend.
|
||||
- [Dreamacro/clash](https://github.com/Dreamacro/clash): A rule-based tunnel in Go.
|
||||
- [Fndroid/clash_for_windows_pkg](https://github.com/Fndroid/clash_for_windows_pkg): A Windows/macOS GUI based on Clash.
|
||||
- [vitejs/vite](https://github.com/vitejs/vite): Next generation frontend tooling. It's fast!
|
||||
|
||||
## License
|
||||
|
||||
GPL-3.0 License
|
||||
GPL-3.0 License. See [License here](./LICENSE) for details.
|
||||
|
||||
36
package.json
36
package.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "clash-verge",
|
||||
"version": "0.0.12",
|
||||
"version": "0.0.15",
|
||||
"license": "GPL-3.0",
|
||||
"scripts": {
|
||||
"dev": "cargo tauri dev",
|
||||
@@ -17,35 +17,35 @@
|
||||
"dependencies": {
|
||||
"@emotion/react": "^11.7.0",
|
||||
"@emotion/styled": "^11.6.0",
|
||||
"@mui/icons-material": "^5.2.1",
|
||||
"@mui/material": "^5.2.3",
|
||||
"@tauri-apps/api": "^1.0.0-beta.8",
|
||||
"ahooks": "^3.1.7",
|
||||
"axios": "^0.24.0",
|
||||
"@mui/icons-material": "^5.4.1",
|
||||
"@mui/material": "^5.4.1",
|
||||
"@tauri-apps/api": "^1.0.0-rc.1",
|
||||
"ahooks": "^3.1.9",
|
||||
"axios": "^0.26.0",
|
||||
"dayjs": "^1.10.7",
|
||||
"react": "^17.0.0",
|
||||
"react-dom": "^17.0.0",
|
||||
"react-router-dom": "^6.0.2",
|
||||
"react-virtuoso": "^2.3.1",
|
||||
"recoil": "^0.5.2",
|
||||
"swr": "^1.1.2-beta.0"
|
||||
"react": "^17.0.2",
|
||||
"react-dom": "^17.0.2",
|
||||
"react-router-dom": "^6.2.1",
|
||||
"react-virtuoso": "^2.7.0",
|
||||
"recoil": "^0.6.1",
|
||||
"swr": "^1.2.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@actions/github": "^5.0.0",
|
||||
"@tauri-apps/cli": "^1.0.0-beta.10",
|
||||
"@tauri-apps/cli": "^1.0.0-rc.4",
|
||||
"@types/fs-extra": "^9.0.13",
|
||||
"@types/js-cookie": "^3.0.1",
|
||||
"@types/react": "^17.0.0",
|
||||
"@types/react-dom": "^17.0.0",
|
||||
"@vitejs/plugin-react": "^1.1.1",
|
||||
"@vitejs/plugin-react": "^1.2.0",
|
||||
"adm-zip": "^0.5.9",
|
||||
"fs-extra": "^10.0.0",
|
||||
"husky": "^7.0.0",
|
||||
"node-fetch": "^3.1.0",
|
||||
"node-fetch": "^3.2.0",
|
||||
"pretty-quick": "^3.1.3",
|
||||
"sass": "^1.44.0",
|
||||
"typescript": "^4.5.2",
|
||||
"vite": "^2.7.1"
|
||||
"sass": "^1.49.7",
|
||||
"typescript": "^4.5.5",
|
||||
"vite": "^2.8.0"
|
||||
},
|
||||
"prettier": {
|
||||
"tabWidth": 2,
|
||||
|
||||
@@ -9,7 +9,7 @@ const cwd = process.cwd();
|
||||
|
||||
const CLASH_URL_PREFIX =
|
||||
"https://github.com/Dreamacro/clash/releases/download/premium/";
|
||||
const CLASH_LATEST_DATE = "2022.01.03";
|
||||
const CLASH_LATEST_DATE = "2022.01.27";
|
||||
|
||||
/**
|
||||
* get the correct clash release infomation
|
||||
|
||||
1390
src-tauri/Cargo.lock
generated
1390
src-tauri/Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -1,16 +1,16 @@
|
||||
[package]
|
||||
name = "app"
|
||||
name = "clash-verge"
|
||||
version = "0.1.0"
|
||||
description = "clash verge"
|
||||
authors = ["zzzgydi"]
|
||||
license = "GPL-3.0"
|
||||
repository = "https://github.com/zzzgydi/clash-verge.git"
|
||||
default-run = "app"
|
||||
default-run = "clash-verge"
|
||||
edition = "2021"
|
||||
build = "build.rs"
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "1.0.0-beta.4" }
|
||||
tauri-build = { version = "1.0.0-rc.1", features = [] }
|
||||
|
||||
[dependencies]
|
||||
dirs = "4.0.0"
|
||||
@@ -18,9 +18,7 @@ chrono = "0.4.19"
|
||||
serde_json = "1.0"
|
||||
serde_yaml = "0.8"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
# tauri = { version = "1.0.0-beta.8", features = ["api-all", "system-tray"] }
|
||||
# tauri = { git = "https://github.com/tauri-apps/tauri", rev = "5e0d59ec", features = ["api-all", "system-tray"] }
|
||||
tauri = { git = "https://github.com/tauri-apps/tauri", branch = "next", features = ["api-all", "system-tray", "updater"] }
|
||||
tauri = { version = "1.0.0-rc.2", features = ["shell-all", "system-tray", "updater", "window-all"] }
|
||||
tauri-plugin-shadows = { git = "https://github.com/tauri-apps/tauri-plugin-shadows", features = ["tauri-impl"] }
|
||||
tauri-plugin-vibrancy = { git = "https://github.com/tauri-apps/tauri-plugin-vibrancy", features = ["tauri-impl"] }
|
||||
|
||||
|
||||
@@ -4,4 +4,5 @@ mixed-port: 7890
|
||||
log-level: info
|
||||
allow-lan: false
|
||||
external-controller: 127.0.0.1:9090
|
||||
mode: rule
|
||||
secret: ""
|
||||
|
||||
16
src-tauri/resources/item_tmp.yaml
Normal file
16
src-tauri/resources/item_tmp.yaml
Normal file
@@ -0,0 +1,16 @@
|
||||
# Profile Template for clash verge
|
||||
|
||||
# the profile's name
|
||||
name: New Profile
|
||||
|
||||
# the description of this profile(optional)
|
||||
description:
|
||||
|
||||
# proxies defination (optional, the same as clash)
|
||||
proxies:
|
||||
|
||||
# proxy-groups (optional, the same as clash)
|
||||
proxy-groups:
|
||||
|
||||
# rules (optional, the same as clash)
|
||||
rules:
|
||||
@@ -43,6 +43,20 @@ pub async fn import_profile(
|
||||
}
|
||||
}
|
||||
|
||||
/// new a profile
|
||||
/// append a temp profile item file to the `profiles` dir
|
||||
/// view the temp profile file by using vscode or other editor
|
||||
#[tauri::command]
|
||||
pub async fn new_profile(
|
||||
name: String,
|
||||
desc: String,
|
||||
profiles_state: State<'_, ProfilesState>,
|
||||
) -> Result<(), String> {
|
||||
let mut profiles = profiles_state.0.lock().unwrap();
|
||||
profiles.append_item(name, desc)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Update the profile
|
||||
#[tauri::command]
|
||||
pub async fn update_profile(
|
||||
@@ -155,15 +169,20 @@ pub fn view_profile(index: usize, profiles_state: State<'_, ProfilesState>) -> R
|
||||
|
||||
let path = app_home_dir().join("profiles").join(file);
|
||||
if !path.exists() {
|
||||
return Err("failed to open the file".into());
|
||||
return Err("the file not found".into());
|
||||
}
|
||||
|
||||
match which::which("code") {
|
||||
Ok(code) => match Command::new(code).arg(path).status() {
|
||||
// use vscode first
|
||||
if let Ok(code) = which::which("code") {
|
||||
return match Command::new(code).arg(path).spawn() {
|
||||
Ok(_) => Ok(()),
|
||||
Err(_) => Err("failed to open file by VScode".into()),
|
||||
},
|
||||
Err(_) => Err("please install VScode for edit".into()),
|
||||
};
|
||||
}
|
||||
|
||||
match open_command().arg(path).spawn() {
|
||||
Ok(_) => Ok(()),
|
||||
Err(_) => Err("failed to open file by `open`".into()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -233,10 +252,14 @@ pub fn get_cur_proxy(verge_state: State<'_, VergeState>) -> Result<Option<SysPro
|
||||
/// get the verge config
|
||||
#[tauri::command]
|
||||
pub fn get_verge_config(verge_state: State<'_, VergeState>) -> Result<VergeConfig, String> {
|
||||
match verge_state.0.lock() {
|
||||
Ok(arc) => Ok(arc.config.clone()),
|
||||
Err(_) => Err("failed to get verge lock".into()),
|
||||
let verge = verge_state.0.lock().unwrap();
|
||||
let mut config = verge.config.clone();
|
||||
|
||||
if config.system_proxy_bypass.is_none() && verge.cur_sysproxy.is_some() {
|
||||
config.system_proxy_bypass = Some(verge.cur_sysproxy.clone().unwrap().bypass)
|
||||
}
|
||||
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
/// patch the verge config
|
||||
@@ -249,3 +272,35 @@ pub async fn patch_verge_config(
|
||||
let mut verge = verge_state.0.lock().unwrap();
|
||||
verge.patch_config(payload)
|
||||
}
|
||||
|
||||
/// open app config dir
|
||||
#[tauri::command]
|
||||
pub fn open_app_dir() -> Result<(), String> {
|
||||
let app_dir = app_home_dir();
|
||||
|
||||
match open_command().arg(app_dir).spawn() {
|
||||
Ok(_) => Ok(()),
|
||||
Err(_) => Err("failed to open logs dir".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// open logs dir
|
||||
#[tauri::command]
|
||||
pub fn open_logs_dir() -> Result<(), String> {
|
||||
let log_dir = app_home_dir().join("logs");
|
||||
|
||||
match open_command().arg(log_dir).spawn() {
|
||||
Ok(_) => Ok(()),
|
||||
Err(_) => Err("failed to open logs dir".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// get open/explorer command
|
||||
fn open_command() -> Command {
|
||||
let open = if cfg!(target_os = "windows") {
|
||||
"explorer"
|
||||
} else {
|
||||
"open"
|
||||
};
|
||||
Command::new(open)
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ use std::collections::HashMap;
|
||||
use std::env::temp_dir;
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
/// Define the `profiles.yaml` schema
|
||||
@@ -23,6 +24,8 @@ pub struct Profiles {
|
||||
pub struct ProfileItem {
|
||||
/// profile name
|
||||
pub name: Option<String>,
|
||||
/// profile description
|
||||
pub desc: Option<String>,
|
||||
/// profile file
|
||||
pub file: Option<String>,
|
||||
/// current mode
|
||||
@@ -109,6 +112,7 @@ impl Profiles {
|
||||
|
||||
items.push(ProfileItem {
|
||||
name: Some(result.name),
|
||||
desc: Some("imported url".into()),
|
||||
file: Some(result.file),
|
||||
mode: Some(format!("rule")),
|
||||
url: Some(url),
|
||||
@@ -138,6 +142,49 @@ impl Profiles {
|
||||
self.save_file()
|
||||
}
|
||||
|
||||
/// append new item
|
||||
/// return the new item's index
|
||||
pub fn append_item(&mut self, name: String, desc: String) -> Result<(usize, PathBuf), String> {
|
||||
let mut items = self.items.take().unwrap_or(vec![]);
|
||||
|
||||
// create a new profile file
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs();
|
||||
let file = format!("{}.yaml", now);
|
||||
let path = dirs::app_home_dir().join("profiles").join(&file);
|
||||
|
||||
let file_data = b"# Profile Template for clash verge\n
|
||||
# proxies defination (optional, the same as clash)
|
||||
proxies:\n
|
||||
# proxy-groups (optional, the same as clash)
|
||||
proxy-groups:\n
|
||||
# rules (optional, the same as clash)
|
||||
rules:\n\n
|
||||
";
|
||||
|
||||
match File::create(&path).unwrap().write(file_data) {
|
||||
Ok(_) => {
|
||||
items.push(ProfileItem {
|
||||
name: Some(name),
|
||||
desc: Some(desc),
|
||||
file: Some(file),
|
||||
mode: None,
|
||||
url: None,
|
||||
selected: Some(vec![]),
|
||||
extra: None,
|
||||
updated: Some(now as usize),
|
||||
});
|
||||
|
||||
let index = items.len();
|
||||
self.items = Some(items);
|
||||
Ok((index, path))
|
||||
}
|
||||
Err(_) => Err("failed to create file".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// update the target profile
|
||||
/// and save to config file
|
||||
/// only support the url item
|
||||
@@ -306,6 +353,7 @@ pub async fn activate_profile(
|
||||
"allow-lan",
|
||||
"external-controller",
|
||||
"secret",
|
||||
"mode",
|
||||
"ipv6",
|
||||
];
|
||||
valid_keys.iter().for_each(|key| {
|
||||
|
||||
@@ -105,7 +105,9 @@ impl Verge {
|
||||
pub fn init_launch(&mut self, package_info: &tauri::PackageInfo) {
|
||||
let app_name = "clash-verge";
|
||||
let app_path = get_app_path(app_name);
|
||||
let app_path = resource_dir(package_info).unwrap().join(app_path);
|
||||
let app_path = resource_dir(package_info, &tauri::Env::default())
|
||||
.unwrap()
|
||||
.join(app_path);
|
||||
let app_path = app_path.as_os_str().to_str().unwrap();
|
||||
|
||||
let auto = AutoLaunchBuilder::new()
|
||||
@@ -157,7 +159,10 @@ impl Verge {
|
||||
|
||||
match result {
|
||||
Ok(_) => Ok(()),
|
||||
Err(_) => Err("failed to set system startup info".into()),
|
||||
Err(err) => {
|
||||
log::error!("{err}");
|
||||
Err("failed to set system startup info".into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -227,7 +232,7 @@ fn get_app_path(app_name: &str) -> String {
|
||||
#[cfg(target_os = "linux")]
|
||||
let ext = "";
|
||||
#[cfg(target_os = "macos")]
|
||||
let ext = ".app";
|
||||
let ext = "";
|
||||
#[cfg(target_os = "windows")]
|
||||
let ext = ".exe";
|
||||
String::from(app_name) + ext
|
||||
|
||||
@@ -53,17 +53,19 @@ fn main() -> std::io::Result<()> {
|
||||
}
|
||||
}
|
||||
"quit" => {
|
||||
api::process::kill_children();
|
||||
resolve::resolve_reset(app_handle);
|
||||
app_handle.exit(0);
|
||||
api::process::kill_children();
|
||||
std::process::exit(0);
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
SystemTrayEvent::LeftClick { .. } => {
|
||||
let window = app_handle.get_window("main").unwrap();
|
||||
window.unminimize().unwrap();
|
||||
window.show().unwrap();
|
||||
window.set_focus().unwrap();
|
||||
if cfg![target_os = "windows"] {
|
||||
let window = app_handle.get_window("main").unwrap();
|
||||
window.unminimize().unwrap();
|
||||
window.show().unwrap();
|
||||
window.set_focus().unwrap();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
})
|
||||
@@ -72,6 +74,8 @@ fn main() -> std::io::Result<()> {
|
||||
cmds::restart_sidecar,
|
||||
cmds::get_sys_proxy,
|
||||
cmds::get_cur_proxy,
|
||||
cmds::open_app_dir,
|
||||
cmds::open_logs_dir,
|
||||
// clash
|
||||
cmds::get_clash_info,
|
||||
cmds::patch_clash_config,
|
||||
@@ -79,6 +83,7 @@ fn main() -> std::io::Result<()> {
|
||||
cmds::get_verge_config,
|
||||
cmds::patch_verge_config,
|
||||
// profile
|
||||
cmds::new_profile,
|
||||
cmds::view_profile,
|
||||
cmds::patch_profile,
|
||||
cmds::import_profile,
|
||||
@@ -91,12 +96,12 @@ fn main() -> std::io::Result<()> {
|
||||
.build(tauri::generate_context!())
|
||||
.expect("error while running tauri application")
|
||||
.run(|app_handle, e| match e {
|
||||
tauri::Event::CloseRequested { label, api, .. } => {
|
||||
tauri::RunEvent::CloseRequested { label, api, .. } => {
|
||||
let app_handle = app_handle.clone();
|
||||
api.prevent_close();
|
||||
app_handle.get_window(&label).unwrap().hide().unwrap();
|
||||
}
|
||||
tauri::Event::ExitRequested { .. } => {
|
||||
tauri::RunEvent::ExitRequested { .. } => {
|
||||
resolve::resolve_reset(app_handle);
|
||||
api::process::kill_children();
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
use tauri::{
|
||||
api::path::{home_dir, resource_dir},
|
||||
PackageInfo,
|
||||
Env, PackageInfo,
|
||||
};
|
||||
|
||||
/// get the verge app home dir
|
||||
@@ -14,5 +14,7 @@ pub fn app_home_dir() -> PathBuf {
|
||||
|
||||
/// get the resources dir
|
||||
pub fn app_resources_dir(package_info: &PackageInfo) -> PathBuf {
|
||||
resource_dir(package_info).unwrap().join("resources")
|
||||
resource_dir(package_info, &Env::default())
|
||||
.unwrap()
|
||||
.join("resources")
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ pub fn resolve_setup(app: &App) {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
use tauri_plugin_vibrancy::MacOSVibrancy;
|
||||
#[allow(deprecated)]
|
||||
window.apply_vibrancy(MacOSVibrancy::AppearanceBased);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"package": {
|
||||
"productName": "clash-verge",
|
||||
"version": "0.0.12"
|
||||
"version": "0.0.15"
|
||||
},
|
||||
"build": {
|
||||
"distDir": "../dist",
|
||||
@@ -54,10 +54,16 @@
|
||||
"endpoints": [
|
||||
"https://github.com/zzzgydi/clash-verge/releases/download/updater/update.json"
|
||||
],
|
||||
"dialog": false
|
||||
"dialog": false,
|
||||
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDExNUFBNTBBN0FDNEFBRTUKUldUbHFzUjZDcVZhRVRJM25NS3NkSFlFVElxUkNZMzZ6bHUwRVJjb2F3alJXVzRaeDdSaTA2YWYK"
|
||||
},
|
||||
"allowlist": {
|
||||
"all": true
|
||||
"shell": {
|
||||
"all": true
|
||||
},
|
||||
"window": {
|
||||
"all": true
|
||||
}
|
||||
},
|
||||
"windows": [
|
||||
{
|
||||
|
||||
@@ -72,9 +72,9 @@
|
||||
|
||||
.the-content {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
top: 30px;
|
||||
left: 0;
|
||||
right: 2px;
|
||||
bottom: 10px;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
width: 90%;
|
||||
max-width: 850px;
|
||||
margin: 0 auto;
|
||||
padding-right: 4px;
|
||||
box-sizing: border-box;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
|
||||
@@ -12,15 +12,15 @@ const BasePage: React.FC<Props> = (props) => {
|
||||
|
||||
return (
|
||||
<div className="base-page" data-windrag>
|
||||
<header data-windrag>
|
||||
<Typography variant="h4" component="h1">
|
||||
<header data-windrag style={{ userSelect: "none" }}>
|
||||
<Typography variant="h4" component="h1" data-windrag>
|
||||
{title}
|
||||
</Typography>
|
||||
|
||||
{header}
|
||||
</header>
|
||||
|
||||
<section data-windrag>
|
||||
<section>
|
||||
<div className="base-content" style={contentStyle} data-windrag>
|
||||
{children}
|
||||
</div>
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ApiType } from "../services/types";
|
||||
import { ApiType } from "../../services/types";
|
||||
|
||||
interface Props {
|
||||
value: ApiType.ConnectionsItem;
|
||||
@@ -2,12 +2,12 @@ import { useEffect, useState } from "react";
|
||||
import { useRecoilValue } from "recoil";
|
||||
import { Box, Typography } from "@mui/material";
|
||||
import { ArrowDownward, ArrowUpward } from "@mui/icons-material";
|
||||
import { getInfomation } from "../services/api";
|
||||
import { ApiType } from "../services/types";
|
||||
import { atomClashPort } from "../states/setting";
|
||||
import parseTraffic from "../utils/parse-traffic";
|
||||
import { getInfomation } from "../../services/api";
|
||||
import { ApiType } from "../../services/types";
|
||||
import { atomClashPort } from "../../states/setting";
|
||||
import parseTraffic from "../../utils/parse-traffic";
|
||||
|
||||
const Traffic = () => {
|
||||
const LayoutTraffic = () => {
|
||||
const portValue = useRecoilValue(atomClashPort);
|
||||
const [traffic, setTraffic] = useState({ up: 0, down: 0 });
|
||||
|
||||
@@ -66,4 +66,4 @@ const Traffic = () => {
|
||||
);
|
||||
};
|
||||
|
||||
export default Traffic;
|
||||
export default LayoutTraffic;
|
||||
@@ -1,5 +1,5 @@
|
||||
import { styled, Box } from "@mui/material";
|
||||
import { ApiType } from "../services/types";
|
||||
import { ApiType } from "../../services/types";
|
||||
|
||||
const Item = styled(Box)(({ theme }) => ({
|
||||
padding: "8px 0",
|
||||
@@ -13,10 +13,10 @@ import {
|
||||
} from "@mui/material";
|
||||
import { useSWRConfig } from "swr";
|
||||
import { RefreshRounded } from "@mui/icons-material";
|
||||
import { CmdType } from "../services/types";
|
||||
import { updateProfile, deleteProfile, viewProfile } from "../services/cmds";
|
||||
import Notice from "./notice";
|
||||
import parseTraffic from "../utils/parse-traffic";
|
||||
import { CmdType } from "../../services/types";
|
||||
import { updateProfile, deleteProfile, viewProfile } from "../../services/cmds";
|
||||
import Notice from "../base/base-notice";
|
||||
import parseTraffic from "../../utils/parse-traffic";
|
||||
import relativeTime from "dayjs/plugin/relativeTime";
|
||||
|
||||
dayjs.extend(relativeTime);
|
||||
@@ -59,6 +59,9 @@ const ProfileItem: React.FC<Props> = (props) => {
|
||||
const progress = Math.round(((download + upload) * 100) / (total + 0.1));
|
||||
const fromnow = updated > 0 ? dayjs(updated * 1000).fromNow() : "";
|
||||
|
||||
// url or file mode
|
||||
const isUrlMode = itemData.url && extra;
|
||||
|
||||
const onView = async () => {
|
||||
setAnchorEl(null);
|
||||
try {
|
||||
@@ -111,6 +114,26 @@ const ProfileItem: React.FC<Props> = (props) => {
|
||||
event.preventDefault();
|
||||
};
|
||||
|
||||
const boxStyle = {
|
||||
height: 26,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
};
|
||||
|
||||
const urlModeMenu = [
|
||||
{ label: "Select", handler: onForceSelect },
|
||||
{ label: "View", handler: onView },
|
||||
{ label: "Update", handler: onUpdateWrapper(false) },
|
||||
{ label: "Update(Proxy)", handler: onUpdateWrapper(true) },
|
||||
{ label: "Delete", handler: onDelete },
|
||||
];
|
||||
const fileModeMenu = [
|
||||
{ label: "Select", handler: onForceSelect },
|
||||
{ label: "Edit", handler: onView },
|
||||
{ label: "Delete", handler: onDelete },
|
||||
];
|
||||
|
||||
return (
|
||||
<>
|
||||
<Wrapper
|
||||
@@ -155,52 +178,63 @@ const ProfileItem: React.FC<Props> = (props) => {
|
||||
{name}
|
||||
</Typography>
|
||||
|
||||
<IconButton
|
||||
sx={{
|
||||
width: 30,
|
||||
height: 30,
|
||||
animation: loading ? `1s linear infinite ${round}` : "none",
|
||||
}}
|
||||
color="inherit"
|
||||
disabled={loading}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onUpdateWrapper(false)();
|
||||
}}
|
||||
>
|
||||
<RefreshRounded />
|
||||
</IconButton>
|
||||
{isUrlMode && (
|
||||
<IconButton
|
||||
sx={{
|
||||
width: 26,
|
||||
height: 26,
|
||||
animation: loading ? `1s linear infinite ${round}` : "none",
|
||||
}}
|
||||
color="inherit"
|
||||
disabled={loading}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onUpdateWrapper(false)();
|
||||
}}
|
||||
>
|
||||
<RefreshRounded />
|
||||
</IconButton>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<Box display="flex" justifyContent="space-between" alignItems="center">
|
||||
<Typography noWrap title={`From: ${from}`}>
|
||||
{from}
|
||||
</Typography>
|
||||
{isUrlMode ? (
|
||||
<>
|
||||
<Box sx={boxStyle}>
|
||||
<Typography noWrap title={`From: ${from}`}>
|
||||
{from}
|
||||
</Typography>
|
||||
|
||||
<Typography
|
||||
noWrap
|
||||
flex="1 0 auto"
|
||||
fontSize={14}
|
||||
textAlign="right"
|
||||
title="updated time"
|
||||
>
|
||||
{fromnow}
|
||||
</Typography>
|
||||
</Box>
|
||||
<Typography
|
||||
noWrap
|
||||
flex="1 0 auto"
|
||||
fontSize={14}
|
||||
textAlign="right"
|
||||
title="updated time"
|
||||
>
|
||||
{fromnow}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
my: 0.5,
|
||||
fontSize: 14,
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
}}
|
||||
>
|
||||
<span title="used / total">
|
||||
{parseTraffic(upload + download)} / {parseTraffic(total)}
|
||||
</span>
|
||||
<span title="expire time">{expire}</span>
|
||||
</Box>
|
||||
<Box sx={{ ...boxStyle, fontSize: 14 }}>
|
||||
<span title="used / total">
|
||||
{parseTraffic(upload + download)} / {parseTraffic(total)}
|
||||
</span>
|
||||
<span title="expire time">{expire}</span>
|
||||
</Box>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Box sx={boxStyle}>
|
||||
<Typography noWrap title={itemData.desc}>
|
||||
{itemData.desc}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ ...boxStyle, fontSize: 14, justifyContent: "flex-end" }}>
|
||||
<span title="updated time">{parseExpire(updated)}</span>
|
||||
</Box>
|
||||
</>
|
||||
)}
|
||||
|
||||
<LinearProgress
|
||||
variant="determinate"
|
||||
@@ -216,11 +250,11 @@ const ProfileItem: React.FC<Props> = (props) => {
|
||||
anchorPosition={position}
|
||||
anchorReference="anchorPosition"
|
||||
>
|
||||
<MenuItem onClick={onForceSelect}>Select</MenuItem>
|
||||
<MenuItem onClick={onView}>View</MenuItem>
|
||||
<MenuItem onClick={onUpdateWrapper(false)}>Update</MenuItem>
|
||||
<MenuItem onClick={onUpdateWrapper(true)}>Update(Proxy)</MenuItem>
|
||||
<MenuItem onClick={onDelete}>Delete</MenuItem>
|
||||
{(isUrlMode ? urlModeMenu : fileModeMenu).map((item) => (
|
||||
<MenuItem key={item.label} onClick={item.handler}>
|
||||
{item.label}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Menu>
|
||||
</>
|
||||
);
|
||||
71
src/components/profile/profile-new.tsx
Normal file
71
src/components/profile/profile-new.tsx
Normal file
@@ -0,0 +1,71 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import {
|
||||
Button,
|
||||
Dialog,
|
||||
DialogActions,
|
||||
DialogContent,
|
||||
DialogTitle,
|
||||
TextField,
|
||||
} from "@mui/material";
|
||||
import Notice from "../base/base-notice";
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onSubmit: (name: string, desc: string) => void;
|
||||
}
|
||||
|
||||
const ProfileNew = (props: Props) => {
|
||||
const { open, onClose, onSubmit } = props;
|
||||
const [name, setName] = useState("");
|
||||
const [desc, setDesc] = useState("");
|
||||
|
||||
const onCreate = () => {
|
||||
if (!name.trim()) {
|
||||
Notice.error("`Name` should not be null");
|
||||
return;
|
||||
}
|
||||
onSubmit(name, desc);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setName("");
|
||||
setDesc("");
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onClose={onClose}>
|
||||
<DialogTitle>Create Profile</DialogTitle>
|
||||
<DialogContent sx={{ width: 320, pb: 0.5 }}>
|
||||
<TextField
|
||||
autoFocus
|
||||
fullWidth
|
||||
label="Name"
|
||||
margin="dense"
|
||||
variant="outlined"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
/>
|
||||
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Descriptions"
|
||||
margin="normal"
|
||||
variant="outlined"
|
||||
value={desc}
|
||||
onChange={(e) => setDesc(e.target.value)}
|
||||
/>
|
||||
</DialogContent>
|
||||
<DialogActions sx={{ px: 2, pb: 2 }}>
|
||||
<Button onClick={onClose}>Cancel</Button>
|
||||
<Button onClick={onCreate} variant="contained">
|
||||
Create
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProfileNew;
|
||||
@@ -1,58 +0,0 @@
|
||||
import { CheckCircleOutlineRounded } from "@mui/icons-material";
|
||||
import {
|
||||
alpha,
|
||||
ListItem,
|
||||
ListItemButton,
|
||||
ListItemIcon,
|
||||
ListItemText,
|
||||
SxProps,
|
||||
Theme,
|
||||
} from "@mui/material";
|
||||
import { ApiType } from "../services/types";
|
||||
|
||||
interface Props {
|
||||
proxy: ApiType.ProxyItem;
|
||||
selected: boolean;
|
||||
sx?: SxProps<Theme>;
|
||||
onClick?: (name: string) => void;
|
||||
}
|
||||
|
||||
const ProxyItem = (props: Props) => {
|
||||
const { proxy, selected, sx, onClick } = props;
|
||||
|
||||
return (
|
||||
<ListItem sx={sx}>
|
||||
<ListItemButton
|
||||
dense
|
||||
selected={selected}
|
||||
onClick={() => onClick?.(proxy.name)}
|
||||
sx={[
|
||||
{
|
||||
borderRadius: 1,
|
||||
},
|
||||
({ palette: { mode, primary } }) => {
|
||||
const bgcolor =
|
||||
mode === "light"
|
||||
? alpha(primary.main, 0.15)
|
||||
: alpha(primary.main, 0.35);
|
||||
const color = mode === "light" ? primary.main : primary.light;
|
||||
|
||||
return {
|
||||
"&.Mui-selected": { bgcolor },
|
||||
"&.Mui-selected .MuiListItemText-secondary": { color },
|
||||
};
|
||||
},
|
||||
]}
|
||||
>
|
||||
<ListItemText title={proxy.name} secondary={proxy.name} />
|
||||
<ListItemIcon
|
||||
sx={{ justifyContent: "flex-end", color: "primary.main" }}
|
||||
>
|
||||
{selected && <CheckCircleOutlineRounded sx={{ fontSize: 16 }} />}
|
||||
</ListItemIcon>
|
||||
</ListItemButton>
|
||||
</ListItem>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProxyItem;
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useState } from "react";
|
||||
import { useRef, useState } from "react";
|
||||
import { useSWRConfig } from "swr";
|
||||
import { Virtuoso } from "react-virtuoso";
|
||||
import {
|
||||
Box,
|
||||
@@ -16,9 +17,10 @@ import {
|
||||
MyLocationRounded,
|
||||
NetworkCheckRounded,
|
||||
} from "@mui/icons-material";
|
||||
import { updateProxy } from "../services/api";
|
||||
import { ApiType } from "../services/types";
|
||||
import { getProfiles, patchProfile } from "../services/cmds";
|
||||
import { ApiType } from "../../services/types";
|
||||
import { updateProxy } from "../../services/api";
|
||||
import { getProfiles, patchProfile } from "../../services/cmds";
|
||||
import delayManager from "../../services/delay";
|
||||
import ProxyItem from "./proxy-item";
|
||||
|
||||
interface Props {
|
||||
@@ -26,12 +28,15 @@ interface Props {
|
||||
}
|
||||
|
||||
const ProxyGroup = ({ group }: Props) => {
|
||||
const { mutate } = useSWRConfig();
|
||||
|
||||
const listRef = useRef<any>();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [now, setNow] = useState(group.now);
|
||||
|
||||
const proxies = group.all ?? [];
|
||||
|
||||
const onUpdate = async (name: string) => {
|
||||
const onSelect = async (name: string) => {
|
||||
// can not call update
|
||||
if (group.type !== "Selector") {
|
||||
// Todo
|
||||
@@ -67,6 +72,33 @@ const ProxyGroup = ({ group }: Props) => {
|
||||
}
|
||||
};
|
||||
|
||||
const onLocation = () => {
|
||||
const index = proxies.findIndex((p) => p.name === now);
|
||||
|
||||
if (index >= 0) {
|
||||
listRef.current?.scrollToIndex?.({
|
||||
index,
|
||||
align: "center",
|
||||
behavior: "smooth",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const onCheckAll = async () => {
|
||||
let names = proxies.map((p) => p.name);
|
||||
|
||||
while (names.length) {
|
||||
const list = names.slice(0, 10);
|
||||
names = names.slice(10);
|
||||
|
||||
await Promise.all(
|
||||
list.map((n) => delayManager.checkDelay(n, group.name))
|
||||
);
|
||||
|
||||
mutate("getProxies");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<ListItem button onClick={() => setOpen(!open)} dense>
|
||||
@@ -88,24 +120,26 @@ const ProxyGroup = ({ group }: Props) => {
|
||||
|
||||
<Collapse in={open} timeout="auto" unmountOnExit>
|
||||
<Box sx={{ pl: 4, pr: 3, my: 0.5 }}>
|
||||
<IconButton size="small" title="location">
|
||||
<IconButton size="small" title="location" onClick={onLocation}>
|
||||
<MyLocationRounded />
|
||||
</IconButton>
|
||||
<IconButton size="small" title="check">
|
||||
<IconButton size="small" title="check" onClick={onCheckAll}>
|
||||
<NetworkCheckRounded />
|
||||
</IconButton>
|
||||
</Box>
|
||||
|
||||
{proxies.length >= 10 ? (
|
||||
<Virtuoso
|
||||
ref={listRef}
|
||||
style={{ height: "320px", marginBottom: "4px" }}
|
||||
totalCount={proxies.length}
|
||||
itemContent={(index) => (
|
||||
<ProxyItem
|
||||
groupName={group.name}
|
||||
proxy={proxies[index]}
|
||||
selected={proxies[index].name === now}
|
||||
sx={{ py: 0, pl: 4 }}
|
||||
onClick={onUpdate}
|
||||
onClick={onSelect}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
@@ -118,10 +152,11 @@ const ProxyGroup = ({ group }: Props) => {
|
||||
{proxies.map((proxy) => (
|
||||
<ProxyItem
|
||||
key={proxy.name}
|
||||
groupName={group.name}
|
||||
proxy={proxy}
|
||||
selected={proxy.name === now}
|
||||
sx={{ py: 0, pl: 4 }}
|
||||
onClick={onUpdate}
|
||||
onClick={onSelect}
|
||||
/>
|
||||
))}
|
||||
</List>
|
||||
114
src/components/proxy/proxy-item.tsx
Normal file
114
src/components/proxy/proxy-item.tsx
Normal file
@@ -0,0 +1,114 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { CheckCircleOutlineRounded } from "@mui/icons-material";
|
||||
import {
|
||||
alpha,
|
||||
Box,
|
||||
ListItem,
|
||||
ListItemButton,
|
||||
ListItemIcon,
|
||||
ListItemText,
|
||||
styled,
|
||||
SxProps,
|
||||
Theme,
|
||||
} from "@mui/material";
|
||||
import { ApiType } from "../../services/types";
|
||||
import delayManager from "../../services/delay";
|
||||
|
||||
interface Props {
|
||||
groupName: string;
|
||||
proxy: ApiType.ProxyItem;
|
||||
selected: boolean;
|
||||
sx?: SxProps<Theme>;
|
||||
onClick?: (name: string) => void;
|
||||
}
|
||||
|
||||
const Widget = styled(Box)(() => ({
|
||||
padding: "4px 6px",
|
||||
fontSize: 14,
|
||||
}));
|
||||
|
||||
const ProxyItem = (props: Props) => {
|
||||
const { groupName, proxy, selected, sx, onClick } = props;
|
||||
const [delay, setDelay] = useState(-1);
|
||||
|
||||
useEffect(() => {
|
||||
if (proxy) {
|
||||
setDelay(delayManager.getDelay(proxy.name, groupName));
|
||||
}
|
||||
}, [proxy]);
|
||||
|
||||
const onDelay = (e: any) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
delayManager
|
||||
.checkDelay(proxy.name, groupName)
|
||||
.then((result) => setDelay(result))
|
||||
.catch(() => setDelay(1e6));
|
||||
};
|
||||
|
||||
return (
|
||||
<ListItem sx={sx}>
|
||||
<ListItemButton
|
||||
dense
|
||||
selected={selected}
|
||||
onClick={() => onClick?.(proxy.name)}
|
||||
sx={[
|
||||
{ borderRadius: 1 },
|
||||
({ palette: { mode, primary } }) => {
|
||||
const bgcolor =
|
||||
mode === "light"
|
||||
? alpha(primary.main, 0.15)
|
||||
: alpha(primary.main, 0.35);
|
||||
const color = mode === "light" ? primary.main : primary.light;
|
||||
|
||||
const showDelay = delay > 0;
|
||||
const showIcon = !showDelay && selected;
|
||||
|
||||
return {
|
||||
".the-check": { display: "none" },
|
||||
".the-delay": { display: showDelay ? "block" : "none" },
|
||||
".the-icon": { display: showIcon ? "block" : "none" },
|
||||
"&:hover .the-check": { display: !showDelay ? "block" : "none" },
|
||||
"&:hover .the-delay": { display: showDelay ? "block" : "none" },
|
||||
"&:hover .the-icon": { display: "none" },
|
||||
"&.Mui-selected": { bgcolor },
|
||||
"&.Mui-selected .MuiListItemText-secondary": { color },
|
||||
};
|
||||
},
|
||||
]}
|
||||
>
|
||||
<ListItemText title={proxy.name} secondary={proxy.name} />
|
||||
|
||||
<ListItemIcon
|
||||
sx={{ justifyContent: "flex-end", color: "primary.main" }}
|
||||
>
|
||||
<Widget className="the-check" onClick={onDelay}>
|
||||
Check
|
||||
</Widget>
|
||||
|
||||
<Widget
|
||||
className="the-delay"
|
||||
onClick={onDelay}
|
||||
color={
|
||||
delay > 500
|
||||
? "error.main"
|
||||
: delay < 100
|
||||
? "success.main"
|
||||
: "text.secondary"
|
||||
}
|
||||
>
|
||||
{delay > 1e5 ? "Error" : delay > 3000 ? "Timeout" : `${delay}ms`}
|
||||
</Widget>
|
||||
|
||||
<CheckCircleOutlineRounded
|
||||
className="the-icon"
|
||||
sx={{ fontSize: 16 }}
|
||||
/>
|
||||
</ListItemIcon>
|
||||
</ListItemButton>
|
||||
</ListItem>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProxyItem;
|
||||
@@ -8,14 +8,15 @@ import {
|
||||
Switch,
|
||||
Select,
|
||||
MenuItem,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import { getClashConfig, updateConfigs } from "../../services/api";
|
||||
import { SettingList, SettingItem } from "./setting";
|
||||
import { patchClashConfig } from "../../services/cmds";
|
||||
import { atomClashPort } from "../../states/setting";
|
||||
import { ApiType } from "../../services/types";
|
||||
import { atomClashPort } from "../../states/setting";
|
||||
import { patchClashConfig } from "../../services/cmds";
|
||||
import { SettingList, SettingItem } from "./setting";
|
||||
import { getClashConfig, getVersion, updateConfigs } from "../../services/api";
|
||||
import Notice from "../base/base-notice";
|
||||
import GuardState from "./guard-state";
|
||||
import Notice from "../notice";
|
||||
|
||||
interface Props {
|
||||
onError: (err: Error) => void;
|
||||
@@ -49,7 +50,7 @@ const SettingClash = ({ onError }: Props) => {
|
||||
// restart clash when port is changed
|
||||
const { run: onUpdatePort } = useDebounceFn(
|
||||
async (port: number) => {
|
||||
(async () => {
|
||||
try {
|
||||
if (port < 1000) {
|
||||
throw new Error("The port should not < 1000");
|
||||
}
|
||||
@@ -60,14 +61,22 @@ const SettingClash = ({ onError }: Props) => {
|
||||
onChangeData({ "mixed-port": port });
|
||||
setPort(port);
|
||||
Notice.success("Change Clash port successfully!");
|
||||
})().catch((err: any) => {
|
||||
} catch (err: any) {
|
||||
setMixedPort(thePort); // back to old port value
|
||||
Notice.error(err.message ?? err.toString());
|
||||
});
|
||||
}
|
||||
},
|
||||
{ wait: 1000 }
|
||||
);
|
||||
|
||||
// get clash core version
|
||||
const [clashVer, setClashVer] = useState("");
|
||||
useEffect(() => {
|
||||
getVersion().then(({ premium, version }) => {
|
||||
setClashVer(premium ? `${version} Premium` : version);
|
||||
});
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<SettingList title="Clash Setting">
|
||||
<SettingItem>
|
||||
@@ -128,6 +137,11 @@ const SettingClash = ({ onError }: Props) => {
|
||||
<TextField autoComplete="off" size="small" sx={{ width: 120 }} />
|
||||
</GuardState>
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText primary="Clash core" />
|
||||
<Typography sx={{ py: 1 }}>{clashVer}</Typography>
|
||||
</SettingItem>
|
||||
</SettingList>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import useSWR, { useSWRConfig } from "swr";
|
||||
import { Box, ListItemText, Switch } from "@mui/material";
|
||||
import { Box, ListItemText, Switch, TextField } from "@mui/material";
|
||||
import { getVergeConfig, patchVergeConfig } from "../../services/cmds";
|
||||
import { SettingList, SettingItem } from "./setting";
|
||||
import { CmdType } from "../../services/types";
|
||||
@@ -17,6 +17,7 @@ const SettingSystem = ({ onError }: Props) => {
|
||||
const {
|
||||
enable_auto_launch: startup = false,
|
||||
enable_system_proxy: proxy = false,
|
||||
system_proxy_bypass: bypass = "",
|
||||
} = vergeConfig ?? {};
|
||||
|
||||
const onSwitchFormat = (_e: any, value: boolean) => value;
|
||||
@@ -55,11 +56,29 @@ const SettingSystem = ({ onError }: Props) => {
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
onChange={(e) => onChangeData({ enable_system_proxy: e })}
|
||||
onGuard={(e) => patchVergeConfig({ enable_system_proxy: e })}
|
||||
onGuard={async (e) => {
|
||||
await patchVergeConfig({ enable_system_proxy: e });
|
||||
mutate("getVergeConfig"); // update bypass value
|
||||
}}
|
||||
>
|
||||
<Switch edge="end" />
|
||||
</GuardState>
|
||||
</SettingItem>
|
||||
|
||||
{proxy && (
|
||||
<SettingItem>
|
||||
<ListItemText primary="Proxy Bypass" />
|
||||
<GuardState
|
||||
value={bypass ?? ""}
|
||||
onCatch={onError}
|
||||
onFormat={(e: any) => e.target.value}
|
||||
onChange={(e) => onChangeData({ system_proxy_bypass: e })}
|
||||
onGuard={(e) => patchVergeConfig({ system_proxy_bypass: e })}
|
||||
>
|
||||
<TextField autoComplete="off" size="small" sx={{ width: 120 }} />
|
||||
</GuardState>
|
||||
</SettingItem>
|
||||
)}
|
||||
</SettingList>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
import useSWR, { useSWRConfig } from "swr";
|
||||
import { ListItemText, Switch, Typography } from "@mui/material";
|
||||
import { getVergeConfig, patchVergeConfig } from "../../services/cmds";
|
||||
import { IconButton, ListItemText, Switch, Typography } from "@mui/material";
|
||||
import {
|
||||
getVergeConfig,
|
||||
openAppDir,
|
||||
openLogsDir,
|
||||
patchVergeConfig,
|
||||
} from "../../services/cmds";
|
||||
import { SettingList, SettingItem } from "./setting";
|
||||
import { CmdType } from "../../services/types";
|
||||
import { version } from "../../../package.json";
|
||||
import GuardState from "./guard-state";
|
||||
import PaletteSwitch from "./palette-switch";
|
||||
import { ArrowForward } from "@mui/icons-material";
|
||||
|
||||
interface Props {
|
||||
onError?: (err: Error) => void;
|
||||
@@ -55,6 +61,27 @@ const SettingVerge = ({ onError }: Props) => {
|
||||
</GuardState>
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText primary="Open App Dir" />
|
||||
<IconButton
|
||||
color="inherit"
|
||||
size="small"
|
||||
onClick={() => {
|
||||
console.log("click");
|
||||
openAppDir().then(console.log).catch(console.log);
|
||||
}}
|
||||
>
|
||||
<ArrowForward />
|
||||
</IconButton>
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText primary="Open Logs Dir" />
|
||||
<IconButton color="inherit" size="small" onClick={openLogsDir}>
|
||||
<ArrowForward />
|
||||
</IconButton>
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText primary="Version" />
|
||||
<Typography sx={{ py: "6px" }}>v{version}</Typography>
|
||||
|
||||
@@ -10,10 +10,10 @@ import { getVergeConfig } from "../services/cmds";
|
||||
import { getAxios } from "../services/api";
|
||||
import { routers } from "./_routers";
|
||||
import LogoSvg from "../assets/image/logo.svg";
|
||||
import Traffic from "../components/traffic";
|
||||
import LayoutItem from "../components/layout-item";
|
||||
import UpdateButton from "../components/update-button";
|
||||
import LayoutControl from "../components/layout-control";
|
||||
import LayoutItem from "../components/layout/layout-item";
|
||||
import LayoutControl from "../components/layout/layout-control";
|
||||
import LayoutTraffic from "../components/layout/layout-traffic";
|
||||
import UpdateButton from "../components/layout/update-button";
|
||||
|
||||
const Layout = () => {
|
||||
const { mutate } = useSWRConfig();
|
||||
@@ -98,7 +98,7 @@ const Layout = () => {
|
||||
</List>
|
||||
|
||||
<div className="the-traffic" data-windrag>
|
||||
<Traffic />
|
||||
<LayoutTraffic />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -107,7 +107,7 @@ const Layout = () => {
|
||||
<LayoutControl />
|
||||
</div>
|
||||
|
||||
<div className="the-content" data-windrag>
|
||||
<div className="the-content">
|
||||
<Routes>
|
||||
{routers.map(({ label, link, ele: Ele }) => (
|
||||
<Route key={label} path={link} element={<Ele />} />
|
||||
|
||||
@@ -3,8 +3,8 @@ import { Paper } from "@mui/material";
|
||||
import { Virtuoso } from "react-virtuoso";
|
||||
import { ApiType } from "../services/types";
|
||||
import { getInfomation } from "../services/api";
|
||||
import BasePage from "../components/base-page";
|
||||
import ConnectionItem from "../components/connection-item";
|
||||
import BasePage from "../components/base/base-page";
|
||||
import ConnectionItem from "../components/connection/connection-item";
|
||||
|
||||
const ConnectionsPage = () => {
|
||||
const initConn = { uploadTotal: 0, downloadTotal: 0, connections: [] };
|
||||
|
||||
@@ -4,8 +4,8 @@ import { Button, Paper } from "@mui/material";
|
||||
import { Virtuoso } from "react-virtuoso";
|
||||
import { ApiType } from "../services/types";
|
||||
import { getInfomation } from "../services/api";
|
||||
import BasePage from "../components/base-page";
|
||||
import LogItem from "../components/log-item";
|
||||
import BasePage from "../components/base/base-page";
|
||||
import LogItem from "../components/log/log-item";
|
||||
|
||||
let logCache: ApiType.LogItem[] = [];
|
||||
|
||||
|
||||
@@ -6,12 +6,14 @@ import {
|
||||
selectProfile,
|
||||
patchProfile,
|
||||
importProfile,
|
||||
newProfile,
|
||||
} from "../services/cmds";
|
||||
import { getProxies, updateProxy } from "../services/api";
|
||||
import noop from "../utils/noop";
|
||||
import Notice from "../components/notice";
|
||||
import BasePage from "../components/base-page";
|
||||
import ProfileItem from "../components/profile-item";
|
||||
import Notice from "../components/base/base-notice";
|
||||
import BasePage from "../components/base/base-page";
|
||||
import ProfileItem from "../components/profile/profile-item";
|
||||
import ProfileNew from "../components/profile/profile-new";
|
||||
|
||||
const ProfilePage = () => {
|
||||
const [url, setUrl] = useState("");
|
||||
@@ -94,6 +96,23 @@ const ProfilePage = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const lockNewRef = useRef(false);
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const onNew = async (name: string, desc: string) => {
|
||||
if (lockNewRef.current) return;
|
||||
lockNewRef.current = true;
|
||||
|
||||
try {
|
||||
await newProfile(name, desc);
|
||||
setDialogOpen(false);
|
||||
mutate("getProfiles");
|
||||
} catch (err: any) {
|
||||
err && Notice.error(err.toString());
|
||||
} finally {
|
||||
lockNewRef.current = false;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<BasePage title="Profiles">
|
||||
<Box sx={{ display: "flex", mb: 3 }}>
|
||||
@@ -105,15 +124,19 @@ const ProfilePage = () => {
|
||||
fullWidth
|
||||
value={url}
|
||||
onChange={(e) => setUrl(e.target.value)}
|
||||
sx={{ mr: 2 }}
|
||||
sx={{ mr: 1 }}
|
||||
/>
|
||||
<Button
|
||||
disabled={!url || disabled}
|
||||
variant="contained"
|
||||
onClick={onImport}
|
||||
sx={{ mr: 1 }}
|
||||
>
|
||||
Import
|
||||
</Button>
|
||||
<Button variant="contained" onClick={() => setDialogOpen(true)}>
|
||||
New
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
<Grid container spacing={3}>
|
||||
@@ -128,6 +151,12 @@ const ProfilePage = () => {
|
||||
</Grid>
|
||||
))}
|
||||
</Grid>
|
||||
|
||||
<ProfileNew
|
||||
open={dialogOpen}
|
||||
onClose={() => setDialogOpen(false)}
|
||||
onSubmit={onNew}
|
||||
/>
|
||||
</BasePage>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,46 +1,127 @@
|
||||
import useSWR, { useSWRConfig } from "swr";
|
||||
import { useEffect } from "react";
|
||||
import { List, Paper } from "@mui/material";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Virtuoso } from "react-virtuoso";
|
||||
import { Button, ButtonGroup, List, Paper } from "@mui/material";
|
||||
import { getClashConfig, updateConfigs, updateProxy } from "../services/api";
|
||||
import { patchClashConfig } from "../services/cmds";
|
||||
import { getProxies } from "../services/api";
|
||||
import BasePage from "../components/base-page";
|
||||
import ProxyItem from "../components/proxy-item";
|
||||
import ProxyGroup from "../components/proxy-group";
|
||||
import BasePage from "../components/base/base-page";
|
||||
import ProxyItem from "../components/proxy/proxy-item";
|
||||
import ProxyGroup from "../components/proxy/proxy-group";
|
||||
|
||||
const ProxyPage = () => {
|
||||
const { mutate } = useSWRConfig();
|
||||
const { data: proxiesData } = useSWR("getProxies", getProxies);
|
||||
const { groups = [], proxies = [] } = proxiesData ?? {};
|
||||
const { data: clashConfig } = useSWR("getClashConfig", getClashConfig);
|
||||
const [curProxy, setCurProxy] = useState<string>("DIRECT");
|
||||
const curMode = clashConfig?.mode.toLowerCase();
|
||||
|
||||
// proxy groups
|
||||
const { groups = [] } = proxiesData ?? {};
|
||||
// proxies and sorted
|
||||
const filterProxies = useMemo(() => {
|
||||
if (!proxiesData?.proxies) return [];
|
||||
|
||||
const list = Object.values(proxiesData.proxies);
|
||||
const retList = list.filter(
|
||||
(p) => !p.all?.length && p.name !== "DIRECT" && p.name !== "REJECT"
|
||||
);
|
||||
const direct = list.filter((p) => p.name === "DIRECT");
|
||||
const reject = list.filter((p) => p.name === "REJECT");
|
||||
|
||||
return direct.concat(retList).concat(reject);
|
||||
}, [proxiesData]);
|
||||
|
||||
const modeList = ["rule", "global", "direct"];
|
||||
const asGroup = curMode === "rule" && groups.length;
|
||||
|
||||
// make sure that fetch the proxies successfully
|
||||
useEffect(() => {
|
||||
// fix the empty proxies on the first sight
|
||||
// this bud only show on the build version
|
||||
// call twice to avoid something unknown or the delay of the clash startup
|
||||
setTimeout(() => mutate("getProxies"), 250);
|
||||
setTimeout(() => mutate("getProxies"), 1000);
|
||||
}, []);
|
||||
if (
|
||||
(curMode === "rule" && !groups.length) ||
|
||||
(curMode === "global" && filterProxies.length < 4)
|
||||
) {
|
||||
setTimeout(() => mutate("getProxies"), 500);
|
||||
}
|
||||
}, [groups, filterProxies, curMode]);
|
||||
|
||||
// update the current proxy
|
||||
useEffect(() => {
|
||||
if (curMode === "direct") setCurProxy("DIRECT");
|
||||
if (curMode === "global") {
|
||||
const globalNow = proxiesData?.proxies?.GLOBAL?.now;
|
||||
setCurProxy(globalNow || "DIRECT");
|
||||
}
|
||||
}, [curMode, proxiesData]);
|
||||
|
||||
const changeLockRef = useRef(false);
|
||||
const onChangeMode = async (mode: string) => {
|
||||
if (changeLockRef.current) return;
|
||||
changeLockRef.current = true;
|
||||
|
||||
try {
|
||||
// switch rapidly
|
||||
await updateConfigs({ mode });
|
||||
await patchClashConfig({ mode });
|
||||
mutate("getClashConfig");
|
||||
} finally {
|
||||
changeLockRef.current = false;
|
||||
}
|
||||
};
|
||||
|
||||
const onChangeProxy = async (name: string) => {
|
||||
if (curMode !== "global") return;
|
||||
await updateProxy("GLOBAL", name);
|
||||
setCurProxy(name);
|
||||
};
|
||||
|
||||
// difference style
|
||||
const pageStyle = asGroup ? {} : { height: "100%" };
|
||||
const paperStyle: any = asGroup
|
||||
? { mb: 0.5 }
|
||||
: { py: 1, height: "100%", boxSizing: "border-box" };
|
||||
|
||||
return (
|
||||
<BasePage title={groups.length ? "Proxy Groups" : "Proxies"}>
|
||||
<Paper sx={{ borderRadius: 1, boxShadow: 2, mb: 1 }}>
|
||||
{groups.length > 0 && (
|
||||
<BasePage
|
||||
contentStyle={pageStyle}
|
||||
title={asGroup ? "Proxy Groups" : "Proxies"}
|
||||
header={
|
||||
<ButtonGroup size="small">
|
||||
{modeList.map((mode) => (
|
||||
<Button
|
||||
key={mode}
|
||||
variant={mode === curMode ? "contained" : "outlined"}
|
||||
onClick={() => onChangeMode(mode)}
|
||||
sx={{ textTransform: "capitalize" }}
|
||||
>
|
||||
{mode}
|
||||
</Button>
|
||||
))}
|
||||
</ButtonGroup>
|
||||
}
|
||||
>
|
||||
<Paper sx={{ borderRadius: 1, boxShadow: 2, ...paperStyle }}>
|
||||
{asGroup ? (
|
||||
<List>
|
||||
{groups.map((group) => (
|
||||
<ProxyGroup key={group.name} group={group} />
|
||||
))}
|
||||
</List>
|
||||
)}
|
||||
|
||||
{!groups.length && (
|
||||
<List>
|
||||
{Object.values(proxies).map((proxy) => (
|
||||
) : (
|
||||
// virtual list
|
||||
<Virtuoso
|
||||
style={{ height: "100%" }}
|
||||
totalCount={filterProxies.length}
|
||||
itemContent={(index) => (
|
||||
<ProxyItem
|
||||
key={proxy.name}
|
||||
proxy={proxy}
|
||||
selected={false}
|
||||
groupName="GLOBAL"
|
||||
proxy={filterProxies[index]}
|
||||
selected={filterProxies[index].name === curProxy}
|
||||
onClick={onChangeProxy}
|
||||
sx={{ py: 0, px: 2 }}
|
||||
/>
|
||||
))}
|
||||
</List>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</Paper>
|
||||
</BasePage>
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { Paper } from "@mui/material";
|
||||
import BasePage from "../components/base-page";
|
||||
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/notice";
|
||||
|
||||
const SettingPage = () => {
|
||||
const onError = (error: any) => {
|
||||
|
||||
@@ -60,10 +60,24 @@ export async function getRules() {
|
||||
return instance.get("/rules") as Promise<ApiType.RuleItem[]>;
|
||||
}
|
||||
|
||||
/// Get Proxy delay
|
||||
export async function getProxyDelay(
|
||||
name: string,
|
||||
url?: string
|
||||
): Promise<{ delay: number }> {
|
||||
const params = {
|
||||
timeout: 3000,
|
||||
url: url || "http://www.gstatic.com/generate_204",
|
||||
};
|
||||
|
||||
const instance = await getAxios();
|
||||
return instance.get(`/proxies/${encodeURIComponent(name)}/delay`, { params });
|
||||
}
|
||||
|
||||
/// Update the Proxy Choose
|
||||
export async function updateProxy(group: string, proxy: string) {
|
||||
const instance = await getAxios();
|
||||
return instance.put(`/proxies/${group}`, { name: proxy });
|
||||
return instance.put(`/proxies/${encodeURIComponent(group)}`, { name: proxy });
|
||||
}
|
||||
|
||||
/// Get the Proxy infomation
|
||||
|
||||
@@ -9,6 +9,10 @@ export async function syncProfiles() {
|
||||
return invoke<void>("sync_profiles");
|
||||
}
|
||||
|
||||
export async function newProfile(name: string, desc: string) {
|
||||
return invoke<void>("new_profile", { name, desc });
|
||||
}
|
||||
|
||||
export async function viewProfile(index: number) {
|
||||
return invoke<void>("view_profile", { index });
|
||||
}
|
||||
@@ -59,3 +63,11 @@ export async function patchVergeConfig(payload: CmdType.VergeConfig) {
|
||||
export async function getSystemProxy() {
|
||||
return invoke<any>("get_sys_proxy");
|
||||
}
|
||||
|
||||
export async function openAppDir() {
|
||||
return invoke<void>("open_app_dir");
|
||||
}
|
||||
|
||||
export async function openLogsDir() {
|
||||
return invoke<void>("open_logs_dir");
|
||||
}
|
||||
|
||||
37
src/services/delay.ts
Normal file
37
src/services/delay.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { getProxyDelay } from "./api";
|
||||
|
||||
const hashKey = (name: string, group: string) => `${group ?? ""}::${name}`;
|
||||
|
||||
class DelayManager {
|
||||
private cache = new Map<string, [number, number]>();
|
||||
|
||||
setDelay(name: string, group: string, delay: number) {
|
||||
this.cache.set(hashKey(name, group), [Date.now(), delay]);
|
||||
}
|
||||
|
||||
getDelay(name: string, group: string) {
|
||||
if (!name) return -1;
|
||||
|
||||
const result = this.cache.get(hashKey(name, group));
|
||||
if (result && Date.now() - result[0] <= 18e5) {
|
||||
return result[1];
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
async checkDelay(name: string, group: string) {
|
||||
let delay = -1;
|
||||
|
||||
try {
|
||||
const result = await getProxyDelay(name);
|
||||
delay = result.delay;
|
||||
} catch {
|
||||
delay = 1e6; // error
|
||||
}
|
||||
|
||||
this.setDelay(name, group, delay);
|
||||
return delay;
|
||||
}
|
||||
}
|
||||
|
||||
export default new DelayManager();
|
||||
@@ -87,6 +87,7 @@ export namespace CmdType {
|
||||
|
||||
export interface ProfileItem {
|
||||
name?: string;
|
||||
desc?: string;
|
||||
file?: string;
|
||||
mode?: string;
|
||||
url?: string;
|
||||
@@ -113,5 +114,6 @@ export namespace CmdType {
|
||||
theme_blur?: boolean;
|
||||
enable_auto_launch?: boolean;
|
||||
enable_system_proxy?: boolean;
|
||||
system_proxy_bypass?: string;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user