86 Commits

Author SHA1 Message Date
GyDi
74bbd3c3a2 chore: tauri updater env 2022-02-16 11:02:00 +08:00
GyDi
2e82eaf59a chore: add pubkey 2022-02-16 10:59:31 +08:00
GyDi
7f1df1f1bd v0.0.15 2022-02-16 03:22:25 +08:00
GyDi
3c79238a44 feat: support open dir 2022-02-16 03:21:34 +08:00
GyDi
0aa2565df3 fix: spawn command 2022-02-16 02:43:52 +08:00
GyDi
22b11db16e feat: change allow list 2022-02-16 02:42:56 +08:00
GyDi
d0e678b5e9 feat: support check delay 2022-02-16 02:22:01 +08:00
GyDi
e7bba968b3 fix: import error 2022-02-15 01:36:19 +08:00
GyDi
4934a24293 feat: scroll to proxy item 2022-02-15 01:34:10 +08:00
GyDi
ccb68bcda9 chore: update deps 2022-02-15 00:33:58 +08:00
GyDi
66bf4ba3ad fix: not open file when new profile 2022-02-15 00:21:34 +08:00
GyDi
78a0cfd052 feat: edit system proxy bypass 2022-02-14 01:26:24 +08:00
GyDi
8548373742 feat: disable user select 2022-02-13 19:52:35 +08:00
GyDi
2dfd725ee0 fix: reset value correctly 2022-02-13 19:40:31 +08:00
GyDi
5b779b4f14 feat: new profile able to edit name and desc 2022-02-13 19:33:24 +08:00
GyDi
fc48aa7155 chore: adjust files 2022-02-13 19:27:24 +08:00
GyDi
6193a842f4 feat: update tauri version 2022-02-13 18:45:03 +08:00
GyDi
eb86b471fe fix: something 2022-02-12 21:12:39 +08:00
GyDi
2b52584547 fix: menu without fragment 2022-02-10 01:42:52 +08:00
GyDi
6e3cc57f48 feat: display clash core version 2022-02-10 01:35:55 +08:00
GyDi
f2c04621a5 feat: adjust profile item menu 2022-02-10 01:14:57 +08:00
GyDi
3ed6938d4a v0.0.14 2022-02-09 02:11:01 +08:00
GyDi
99fec25ed5 feat: profile item ui 2022-02-09 02:08:27 +08:00
GyDi
73758ad1fd fix: proxy list error 2022-02-09 02:02:29 +08:00
GyDi
c53fe0ed1f feat: support new profile 2022-02-07 17:26:05 +08:00
GyDi
6082c2bcac feat: support open command for viewing 2022-02-07 16:45:20 +08:00
GyDi
069abed784 chore: add item template yaml 2022-02-02 20:56:06 +08:00
GyDi
7d8fa4d78a fix: something 2022-01-31 23:34:58 +08:00
GyDi
76081f8d89 fix: macos auto launch fail 2022-01-31 23:32:41 +08:00
GyDi
5ef4285558 chore: update deps and app name 2022-01-31 23:27:11 +08:00
GyDi
aa7df4282e chore: cargo update 2022-01-28 22:02:17 +08:00
GyDi
0ef1d5d0de chore: update clash version 2022-01-28 22:00:15 +08:00
GyDi
cceb4bb81f v0.0.13 2022-01-25 02:11:00 +08:00
GyDi
f0f45e007d feat: global proxies use virtual list 2022-01-25 02:08:10 +08:00
GyDi
6a8ffe1642 feat: enable change proxy mode 2022-01-25 01:51:44 +08:00
GyDi
3a73868c10 feat: update styles 2022-01-25 01:48:26 +08:00
GyDi
ab1b5897a6 feat: manage clash mode 2022-01-24 23:13:13 +08:00
GyDi
f94734a5c8 chore: update readme 2022-01-22 23:57:39 +08:00
GyDi
61b86c9584 v0.0.12 2022-01-21 03:09:21 +08:00
GyDi
1ac1d6e903 chore: update ci 2022-01-21 03:08:40 +08:00
GyDi
b6c58f74c0 fix: type error 2022-01-21 03:08:20 +08:00
GyDi
c88e99d87c v0.0.12 2022-01-21 02:59:33 +08:00
GyDi
8d7ab9d05e refactor: rename profiles & command state 2022-01-21 02:57:15 +08:00
GyDi
47155a4a29 feat: change system porxy when changed port 2022-01-21 02:50:13 +08:00
GyDi
d0b87fd7c3 feat: enable change mixed port 2022-01-21 02:32:23 +08:00
GyDi
d49fd37656 feat: manage clash config 2022-01-21 02:31:44 +08:00
GyDi
0bd29d71be chore: add ahooks 2022-01-21 02:29:45 +08:00
GyDi
4b5b62c8ae fix: restart clash should update something 2022-01-21 00:29:33 +08:00
GyDi
65fb2ca2d5 feat: enable update clash info 2022-01-20 23:41:08 +08:00
GyDi
0d5bfc0997 feat: rename edit as view 2022-01-19 23:58:34 +08:00
GyDi
4f02c373c2 chore: adjust ci 2022-01-19 23:55:05 +08:00
GyDi
209a5b1207 fix: script error... 2022-01-19 00:49:23 +08:00
GyDi
95349eacab fix: tag error 2022-01-19 00:46:43 +08:00
GyDi
82ba604b99 fix: script error 2022-01-19 00:42:37 +08:00
GyDi
46a8dec655 feat: test auto gen update.json ci 2022-01-19 00:37:59 +08:00
GyDi
b5af234524 v0.0.11 2022-01-17 02:53:07 +08:00
GyDi
b5c41750f7 fix: remove cargo test 2022-01-17 02:50:19 +08:00
GyDi
6083824eec v0.0.11 2022-01-17 02:44:08 +08:00
GyDi
40977785c3 feat: adjust setting typography 2022-01-17 02:42:52 +08:00
GyDi
5eddf4f1aa feat: enable force select profile 2022-01-17 02:28:23 +08:00
GyDi
99a8e25411 feat: support edit profile item 2022-01-17 02:16:17 +08:00
GyDi
08587d8f2f fix: reduce proxy item height 2022-01-17 02:15:54 +08:00
GyDi
3480d50f61 feat: adjust control ui 2022-01-17 02:15:06 +08:00
GyDi
43af55252d feat: update profile supports noproxy 2022-01-16 22:57:42 +08:00
GyDi
9c43b31fc0 refactor: something 2022-01-16 18:30:25 +08:00
GyDi
9ec7184aa1 fix: put profile request with no proxy 2022-01-16 18:20:01 +08:00
GyDi
4e2cb30db7 refactor: notice caller 2022-01-16 17:56:43 +08:00
GyDi
9ca83d3291 chore: change ci 2022-01-16 16:03:53 +08:00
GyDi
6b2172d873 fix: ci strategy 2022-01-16 14:30:49 +08:00
GyDi
1a5d9f7dad chore: enhance ci 2022-01-16 14:27:41 +08:00
GyDi
a8425862f0 feat: rename page 2022-01-16 03:25:50 +08:00
GyDi
a3a3db6abb refactor: setting page 2022-01-16 03:22:37 +08:00
GyDi
d6c3bc57c0 feat: refactor and adjust ui 2022-01-16 03:11:07 +08:00
GyDi
59c09f90f9 feat: rm some commands 2022-01-16 03:09:36 +08:00
GyDi
d982b83e14 feat: change type 2022-01-15 21:58:13 +08:00
GyDi
cc0e930d34 feat: supports auto launch on macos and windows 2022-01-15 21:55:05 +08:00
GyDi
3c3d77fbea chore: add auto-launch 2022-01-15 21:00:19 +08:00
GyDi
da7453fdbf v0.0.10 2022-01-13 02:53:29 +08:00
GyDi
5fcd25506e feat: adjust proxy page 2022-01-13 02:51:30 +08:00
GyDi
4979a472de feat: press esc hide the window 2022-01-13 02:11:50 +08:00
GyDi
4e8d4f4591 fix: version update error 2022-01-12 22:19:44 +08:00
GyDi
0f5d2b15e0 v0.0.9 2022-01-12 02:55:07 +08:00
GyDi
7fc9631434 feat: show system proxy info 2022-01-12 02:54:50 +08:00
GyDi
df5953dd7b feat: support blur window 2022-01-12 02:27:29 +08:00
GyDi
8f5b2b4a0e chore: add macos startup todo 2022-01-11 23:14:43 +08:00
GyDi
43c63ffa70 chore: cargo update 2022-01-11 23:13:02 +08:00
64 changed files with 3673 additions and 4591 deletions

100
.github/workflows/ci.yml vendored Normal file
View File

@@ -0,0 +1,100 @@
name: CI
on: [push]
env:
CARGO_INCREMENTAL: 0
RUST_BACKTRACE: short
jobs:
release:
strategy:
matrix:
os: [windows-latest, macos-11]
runs-on: ${{ matrix.os }}
if: |
startsWith(github.repository, 'zzzgydi') &&
startsWith(github.ref, 'refs/tags/v')
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
profile: minimal
override: true
- name: Rust Cache
uses: Swatinem/rust-cache@ce325b60658c1b38465c06cc965b79baf32c1e72
- name: Install Node
uses: actions/setup-node@v1
with:
node-version: 14
- name: Get yarn cache dir path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- name: Yarn Cache
uses: actions/cache@v2
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: Yarn install and check
run: |
yarn install --network-timeout 1000000
yarn run check
- name: Tauri build
uses: tauri-apps/tauri-action@v0
# enable cache even though failed
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__"
releaseBody: "Clash Verge now supports Windows and macos(intel)."
releaseDraft: false
prerelease: true
release-update:
needs: release
runs-on: macos-11
if: |
startsWith(github.repository, 'zzzgydi') &&
startsWith(github.ref, 'refs/tags/v')
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Get yarn cache dir path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- name: Yarn Cache
uses: actions/cache@v2
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: Yarn install
run: yarn
- name: Release update.json
run: yarn run release
continue-on-error: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -1,59 +0,0 @@
name: Release Project
on:
push:
tags:
- v*
jobs:
build-tauri:
strategy:
fail-fast: false
matrix:
platform: [windows-latest, macos-latest]
runs-on: ${{ matrix.platform }}
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Install Node
uses: actions/setup-node@v1
with:
node-version: 14
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
profile: minimal
override: true
- name: Get yarn cache dir path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- name: Yarn Cache
uses: actions/cache@v2
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: Rust Cache
uses: Swatinem/rust-cache@ce325b60658c1b38465c06cc965b79baf32c1e72
- name: Yarn install and check
run: yarn && yarn run check
- name: Tauri build
uses: tauri-apps/tauri-action@v0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tagName: v__VERSION__
releaseName: "Clash Verge v__VERSION__"
releaseBody: "Clash Verge now supports Windows and macos(intel)."
releaseDraft: false
prerelease: true

View File

@@ -58,6 +58,15 @@ This is a learning project for Rust practice.
PR welcome! 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 ## License
GPL-3.0 License GPL-3.0 License. See [License here](./LICENSE) for details.

View File

@@ -1,6 +1,6 @@
{ {
"name": "clash-verge", "name": "clash-verge",
"version": "0.0.8", "version": "0.0.15",
"license": "GPL-3.0", "license": "GPL-3.0",
"scripts": { "scripts": {
"dev": "cargo tauri dev", "dev": "cargo tauri dev",
@@ -11,37 +11,41 @@
"web:serve": "vite preview", "web:serve": "vite preview",
"check": "node scripts/check.mjs", "check": "node scripts/check.mjs",
"publish": "node scripts/publish.mjs", "publish": "node scripts/publish.mjs",
"release": "node scripts/release.mjs",
"prepare": "husky install" "prepare": "husky install"
}, },
"dependencies": { "dependencies": {
"@emotion/react": "^11.7.0", "@emotion/react": "^11.7.0",
"@emotion/styled": "^11.6.0", "@emotion/styled": "^11.6.0",
"@mui/icons-material": "^5.2.1", "@mui/icons-material": "^5.4.1",
"@mui/material": "^5.2.3", "@mui/material": "^5.4.1",
"@tauri-apps/api": "^1.0.0-beta.8", "@tauri-apps/api": "^1.0.0-rc.1",
"axios": "^0.24.0", "ahooks": "^3.1.9",
"axios": "^0.26.0",
"dayjs": "^1.10.7", "dayjs": "^1.10.7",
"react": "^17.0.0", "react": "^17.0.2",
"react-dom": "^17.0.0", "react-dom": "^17.0.2",
"react-router-dom": "^6.0.2", "react-router-dom": "^6.2.1",
"react-virtuoso": "^2.3.1", "react-virtuoso": "^2.7.0",
"recoil": "^0.5.2", "recoil": "^0.6.1",
"swr": "^1.1.2-beta.0" "swr": "^1.2.1"
}, },
"devDependencies": { "devDependencies": {
"@tauri-apps/cli": "^1.0.0-beta.10", "@actions/github": "^5.0.0",
"@tauri-apps/cli": "^1.0.0-rc.4",
"@types/fs-extra": "^9.0.13", "@types/fs-extra": "^9.0.13",
"@types/js-cookie": "^3.0.1",
"@types/react": "^17.0.0", "@types/react": "^17.0.0",
"@types/react-dom": "^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", "adm-zip": "^0.5.9",
"fs-extra": "^10.0.0", "fs-extra": "^10.0.0",
"husky": "^7.0.0", "husky": "^7.0.0",
"node-fetch": "^3.1.0", "node-fetch": "^3.2.0",
"pretty-quick": "^3.1.3", "pretty-quick": "^3.1.3",
"sass": "^1.44.0", "sass": "^1.49.7",
"typescript": "^4.5.2", "typescript": "^4.5.5",
"vite": "^2.7.1" "vite": "^2.8.0"
}, },
"prettier": { "prettier": {
"tabWidth": 2, "tabWidth": 2,

View File

@@ -9,7 +9,7 @@ const cwd = process.cwd();
const CLASH_URL_PREFIX = const CLASH_URL_PREFIX =
"https://github.com/Dreamacro/clash/releases/download/premium/"; "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 * get the correct clash release infomation

View File

@@ -11,10 +11,16 @@ async function resolvePublish() {
let [a, b, c] = packageJson.version.split(".").map(Number); let [a, b, c] = packageJson.version.split(".").map(Number);
if (flag === "major") a += 1; if (flag === "major") {
else if (flag === "minor") b += 1; a += 1;
else if (flag === "patch") c += 1; b = 0;
else throw new Error(`invalid flag "${flag}"`); c = 0;
} else if (flag === "minor") {
b += 1;
c = 0;
} else if (flag === "patch") {
c += 1;
} else throw new Error(`invalid flag "${flag}"`);
const nextVersion = `${a}.${b}.${c}`; const nextVersion = `${a}.${b}.${c}`;
packageJson.version = nextVersion; packageJson.version = nextVersion;

68
scripts/release.mjs Normal file
View File

@@ -0,0 +1,68 @@
import { createRequire } from "module";
import { getOctokit, context } from "@actions/github";
const require = createRequire(import.meta.url);
/// generate update.json
/// upload to update tag's release asset
async function resolveRelease() {
if (process.env.GITHUB_TOKEN === undefined) {
throw new Error("GITHUB_TOKEN is required");
}
const packageJson = require("../package.json");
const { version } = packageJson;
const urlPrefix = "https://github.com/zzzgydi/clash-verge/releases/download";
const updateData = {
name: `v${version}`,
notes: `Version ${version} is available now!!!`,
pub_date: new Date().toISOString(),
platforms: {
win64: {
signature: "",
url: `${urlPrefix}/v${version}/clash-verge_${version}_x64.msi.zip`,
},
darwin: {
signature: "",
url: `${urlPrefix}/v${version}/clash-verge.app.tar.gz`,
},
},
};
console.log(`Generating Version "${version}" update.json`);
const github = getOctokit(process.env.GITHUB_TOKEN);
const { data: release } = await github.rest.repos.getReleaseByTag({
owner: context.repo.owner,
repo: context.repo.repo,
tag: "updater",
});
const { data: assets } = await github.rest.repos.listReleaseAssets({
owner: context.repo.owner,
repo: context.repo.repo,
release_id: release.id,
});
for (let asset of assets) {
if (asset.name === "update.json") {
await github.rest.repos.deleteReleaseAsset({
owner: context.repo.owner,
repo: context.repo.repo,
asset_id: asset.id,
});
break;
}
}
await github.rest.repos.uploadReleaseAsset({
owner: context.repo.owner,
repo: context.repo.repo,
release_id: release.id,
name: "update.json",
data: JSON.stringify(updateData, null, 2),
});
}
resolveRelease();

1527
src-tauri/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,16 +1,16 @@
[package] [package]
name = "app" name = "clash-verge"
version = "0.1.0" version = "0.1.0"
description = "clash verge" description = "clash verge"
authors = ["zzzgydi"] authors = ["zzzgydi"]
license = "GPL-3.0" license = "GPL-3.0"
repository = "https://github.com/zzzgydi/clash-verge.git" repository = "https://github.com/zzzgydi/clash-verge.git"
default-run = "app" default-run = "clash-verge"
edition = "2021" edition = "2021"
build = "build.rs" build = "build.rs"
[build-dependencies] [build-dependencies]
tauri-build = { version = "1.0.0-beta.4" } tauri-build = { version = "1.0.0-rc.1", features = [] }
[dependencies] [dependencies]
dirs = "4.0.0" dirs = "4.0.0"
@@ -18,16 +18,17 @@ chrono = "0.4.19"
serde_json = "1.0" serde_json = "1.0"
serde_yaml = "0.8" serde_yaml = "0.8"
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
# tauri = { version = "1.0.0-beta.8", features = ["api-all", "system-tray"] } tauri = { version = "1.0.0-rc.2", features = ["shell-all", "system-tray", "updater", "window-all"] }
# 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-plugin-shadows = { git = "https://github.com/tauri-apps/tauri-plugin-shadows", features = ["tauri-impl"] } 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"] }
reqwest = { version = "0.11", features = ["json"] } reqwest = { version = "0.11", features = ["json"] }
tokio = { version = "1", features = ["full"] } tokio = { version = "1", features = ["full"] }
log = "0.4.14" log = "0.4.14"
log4rs = "1.0.0" log4rs = "1.0.0"
warp = "0.3" warp = "0.3"
which = "4.2.2"
auto-launch = "0.2"
port_scanner = "0.1.5" port_scanner = "0.1.5"
[target.'cfg(windows)'.dependencies] [target.'cfg(windows)'.dependencies]

View File

@@ -4,4 +4,5 @@ mixed-port: 7890
log-level: info log-level: info
allow-lan: false allow-lan: false
external-controller: 127.0.0.1:9090 external-controller: 127.0.0.1:9090
mode: rule
secret: "" secret: ""

View 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:

View File

@@ -1,20 +1,17 @@
use crate::{ use crate::{
core::{ClashInfo, ProfileItem, ProfilesConfig, VergeConfig}, core::{ClashInfo, ProfileItem, Profiles, VergeConfig},
states::{ClashState, ProfilesState, VergeState}, states::{ClashState, ProfilesState, VergeState},
utils::{ utils::{dirs::app_home_dir, fetch::fetch_profile, sysopt::SysProxyConfig},
config::{read_clash, save_clash},
fetch::fetch_profile,
sysopt::SysProxyConfig,
},
}; };
use serde_yaml::Mapping; use serde_yaml::Mapping;
use tauri::{AppHandle, Manager, State}; use std::process::Command;
use tauri::State;
/// get all profiles from `profiles.yaml` /// get all profiles from `profiles.yaml`
/// do not acquire the lock of ProfileLock /// do not acquire the lock of ProfileLock
#[tauri::command] #[tauri::command]
pub fn get_profiles(profiles: State<'_, ProfilesState>) -> Result<ProfilesConfig, String> { pub fn get_profiles(profiles_state: State<'_, ProfilesState>) -> Result<Profiles, String> {
match profiles.0.lock() { match profiles_state.0.lock() {
Ok(profiles) => Ok(profiles.clone()), Ok(profiles) => Ok(profiles.clone()),
Err(_) => Err("failed to get profiles lock".into()), Err(_) => Err("failed to get profiles lock".into()),
} }
@@ -22,38 +19,54 @@ pub fn get_profiles(profiles: State<'_, ProfilesState>) -> Result<ProfilesConfig
/// synchronize data irregularly /// synchronize data irregularly
#[tauri::command] #[tauri::command]
pub fn sync_profiles(profiles: State<'_, ProfilesState>) -> Result<(), String> { pub fn sync_profiles(profiles_state: State<'_, ProfilesState>) -> Result<(), String> {
match profiles.0.lock() { match profiles_state.0.lock() {
Ok(mut profiles) => profiles.sync_file(), Ok(mut profiles) => profiles.sync_file(),
Err(_) => Err("failed to get profiles lock".into()), Err(_) => Err("failed to get profiles lock".into()),
} }
} }
/// Import the profile from url /// import the profile from url
/// and save to `profiles.yaml` /// and save to `profiles.yaml`
#[tauri::command] #[tauri::command]
pub async fn import_profile(url: String, profiles: State<'_, ProfilesState>) -> Result<(), String> { pub async fn import_profile(
match fetch_profile(&url).await { url: String,
with_proxy: bool,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
match fetch_profile(&url, with_proxy).await {
Some(result) => { Some(result) => {
let mut profiles = profiles.0.lock().unwrap(); let mut profiles = profiles_state.0.lock().unwrap();
profiles.import_from_url(url, result) profiles.import_from_url(url, result)
} }
None => Err(format!("failed to fetch profile from `{}`", url)), None => Err(format!("failed to fetch profile from `{}`", url)),
} }
} }
/// 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 /// Update the profile
/// and save to `profiles.yaml`
/// http request firstly
/// then acquire the lock of `profiles.yaml`
#[tauri::command] #[tauri::command]
pub async fn update_profile( pub async fn update_profile(
index: usize, index: usize,
clash: State<'_, ClashState>, with_proxy: bool,
profiles: State<'_, ProfilesState>, clash_state: State<'_, ClashState>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> { ) -> Result<(), String> {
// maybe we can get the url from the web app directly // maybe we can get the url from the web app directly
let url = match profiles.0.lock() { let url = match profiles_state.0.lock() {
Ok(mut profile) => { Ok(mut profile) => {
let items = profile.items.take().unwrap_or(vec![]); let items = profile.items.take().unwrap_or(vec![]);
if index >= items.len() { if index >= items.len() {
@@ -69,16 +82,16 @@ pub async fn update_profile(
Err(_) => return Err("failed to get profiles lock".into()), Err(_) => return Err("failed to get profiles lock".into()),
}; };
match fetch_profile(&url).await { match fetch_profile(&url, with_proxy).await {
Some(result) => match profiles.0.lock() { Some(result) => match profiles_state.0.lock() {
Ok(mut profiles) => { Ok(mut profiles) => {
profiles.update_item(index, result)?; profiles.update_item(index, result)?;
// reactivate the profile // reactivate the profile
let current = profiles.current.clone().unwrap_or(0); let current = profiles.current.clone().unwrap_or(0);
if current == index { if current == index {
let clash = clash.0.lock().unwrap(); let clash = clash_state.0.lock().unwrap();
profiles.activate(clash.info.clone()) profiles.activate(&clash)
} else { } else {
Ok(()) Ok(())
} }
@@ -93,15 +106,15 @@ pub async fn update_profile(
#[tauri::command] #[tauri::command]
pub fn select_profile( pub fn select_profile(
index: usize, index: usize,
clash: State<'_, ClashState>, clash_state: State<'_, ClashState>,
profiles: State<'_, ProfilesState>, profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> { ) -> Result<(), String> {
let mut profiles = profiles.0.lock().unwrap(); let mut profiles = profiles_state.0.lock().unwrap();
match profiles.put_current(index) { match profiles.put_current(index) {
Ok(()) => { Ok(()) => {
let clash = clash.0.lock().unwrap(); let clash = clash_state.0.lock().unwrap();
profiles.activate(clash.info.clone()) profiles.activate(&clash)
} }
Err(err) => Err(err), Err(err) => Err(err),
} }
@@ -119,7 +132,7 @@ pub fn delete_profile(
Ok(change) => match change { Ok(change) => match change {
true => { true => {
let clash = clash_state.0.lock().unwrap(); let clash = clash_state.0.lock().unwrap();
profiles.activate(clash.info.clone()) profiles.activate(&clash)
} }
false => Ok(()), false => Ok(()),
}, },
@@ -132,14 +145,47 @@ pub fn delete_profile(
pub fn patch_profile( pub fn patch_profile(
index: usize, index: usize,
profile: ProfileItem, profile: ProfileItem,
profiles: State<'_, ProfilesState>, profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> { ) -> Result<(), String> {
match profiles.0.lock() { match profiles_state.0.lock() {
Ok(mut profiles) => profiles.patch_item(index, profile), Ok(mut profiles) => profiles.patch_item(index, profile),
Err(_) => Err("can not get profiles lock".into()), Err(_) => Err("can not get profiles lock".into()),
} }
} }
/// run vscode command to edit the profile
#[tauri::command]
pub fn view_profile(index: usize, profiles_state: State<'_, ProfilesState>) -> Result<(), String> {
let mut profiles = profiles_state.0.lock().unwrap();
let items = profiles.items.take().unwrap_or(vec![]);
if index >= items.len() {
profiles.items = Some(items);
return Err("the index out of bound".into());
}
let file = items[index].file.clone().unwrap_or("".into());
profiles.items = Some(items);
let path = app_home_dir().join("profiles").join(file);
if !path.exists() {
return Err("the file not found".into());
}
// 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()),
};
}
match open_command().arg(path).spawn() {
Ok(_) => Ok(()),
Err(_) => Err("failed to open file by `open`".into()),
}
}
/// restart the sidecar /// restart the sidecar
#[tauri::command] #[tauri::command]
pub fn restart_sidecar( pub fn restart_sidecar(
@@ -147,18 +193,10 @@ pub fn restart_sidecar(
profiles_state: State<'_, ProfilesState>, profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> { ) -> Result<(), String> {
let mut clash = clash_state.0.lock().unwrap(); let mut clash = clash_state.0.lock().unwrap();
let mut profiles = profiles_state.0.lock().unwrap();
match clash.restart_sidecar() { match clash.restart_sidecar(&mut profiles) {
Ok(_) => { Ok(_) => Ok(()),
let profiles = profiles_state.0.lock().unwrap();
match profiles.activate(clash.info.clone()) {
Ok(()) => Ok(()),
Err(err) => {
log::error!("{}", err);
Err(err)
}
}
}
Err(err) => { Err(err) => {
log::error!("{}", err); log::error!("{}", err);
Err(err) Err(err)
@@ -171,26 +209,25 @@ pub fn restart_sidecar(
#[tauri::command] #[tauri::command]
pub fn get_clash_info(clash_state: State<'_, ClashState>) -> Result<ClashInfo, String> { pub fn get_clash_info(clash_state: State<'_, ClashState>) -> Result<ClashInfo, String> {
match clash_state.0.lock() { match clash_state.0.lock() {
Ok(arc) => Ok(arc.info.clone()), Ok(clash) => Ok(clash.info.clone()),
Err(_) => Err("failed to get clash lock".into()), Err(_) => Err("failed to get clash lock".into()),
} }
} }
/// todo: need refactor
/// update the clash core config /// update the clash core config
/// after putting the change to the clash core /// after putting the change to the clash core
/// then we should save the latest config /// then we should save the latest config
#[tauri::command] #[tauri::command]
pub fn patch_clash_config(payload: Mapping) -> Result<(), String> { pub fn patch_clash_config(
let mut config = read_clash(); payload: Mapping,
for (key, value) in payload.iter() { clash_state: State<'_, ClashState>,
if config.contains_key(key) { verge_state: State<'_, VergeState>,
config[key] = value.clone(); profiles_state: State<'_, ProfilesState>,
} else { ) -> Result<(), String> {
config.insert(key.clone(), value.clone()); let mut clash = clash_state.0.lock().unwrap();
} let mut verge = verge_state.0.lock().unwrap();
} let mut profiles = profiles_state.0.lock().unwrap();
save_clash(&config) clash.patch_config(payload, &mut verge, &mut profiles)
} }
/// get the system proxy /// get the system proxy
@@ -215,10 +252,14 @@ pub fn get_cur_proxy(verge_state: State<'_, VergeState>) -> Result<Option<SysPro
/// get the verge config /// get the verge config
#[tauri::command] #[tauri::command]
pub fn get_verge_config(verge_state: State<'_, VergeState>) -> Result<VergeConfig, String> { pub fn get_verge_config(verge_state: State<'_, VergeState>) -> Result<VergeConfig, String> {
match verge_state.0.lock() { let verge = verge_state.0.lock().unwrap();
Ok(arc) => Ok(arc.config.clone()), let mut config = verge.config.clone();
Err(_) => Err("failed to get verge lock".into()),
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 /// patch the verge config
@@ -232,24 +273,34 @@ pub async fn patch_verge_config(
verge.patch_config(payload) verge.patch_config(payload)
} }
/// start dragging window /// open app config dir
#[tauri::command] #[tauri::command]
pub fn win_drag(app_handle: AppHandle) { pub fn open_app_dir() -> Result<(), String> {
let window = app_handle.get_window("main").unwrap(); let app_dir = app_home_dir();
window.start_dragging().unwrap();
match open_command().arg(app_dir).spawn() {
Ok(_) => Ok(()),
Err(_) => Err("failed to open logs dir".into()),
}
} }
/// hide the window /// open logs dir
#[tauri::command] #[tauri::command]
pub fn win_hide(app_handle: AppHandle) { pub fn open_logs_dir() -> Result<(), String> {
let window = app_handle.get_window("main").unwrap(); let log_dir = app_home_dir().join("logs");
window.hide().unwrap();
match open_command().arg(log_dir).spawn() {
Ok(_) => Ok(()),
Err(_) => Err("failed to open logs dir".into()),
}
} }
/// mini the window /// get open/explorer command
#[tauri::command] fn open_command() -> Command {
pub fn win_mini(app_handle: AppHandle) { let open = if cfg!(target_os = "windows") {
let window = app_handle.get_window("main").unwrap(); "explorer"
// todo: these methods still has bug on Windows } else {
window.minimize().unwrap(); "open"
};
Command::new(open)
} }

View File

@@ -1,3 +1,4 @@
use super::{Profiles, Verge};
use crate::utils::{config, dirs}; use crate::utils::{config, dirs};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_yaml::{Mapping, Value}; use serde_yaml::{Mapping, Value};
@@ -20,6 +21,9 @@ pub struct ClashInfo {
#[derive(Debug)] #[derive(Debug)]
pub struct Clash { pub struct Clash {
/// maintain the clash config
pub config: Mapping,
/// some info /// some info
pub info: ClashInfo, pub info: ClashInfo,
@@ -32,8 +36,19 @@ static CLASH_CONFIG: &str = "config.yaml";
// todo: be able to change config field // todo: be able to change config field
impl Clash { impl Clash {
pub fn new() -> Clash { pub fn new() -> Clash {
let clash_config = config::read_yaml::<Mapping>(dirs::app_home_dir().join(CLASH_CONFIG)); let config = Clash::get_config();
let info = Clash::get_info(&config);
Clash {
config,
info,
sidecar: None,
}
}
/// parse the clash's config.yaml
/// get some information
fn get_info(clash_config: &Mapping) -> ClashInfo {
let key_port_1 = Value::String("port".to_string()); let key_port_1 = Value::String("port".to_string());
let key_port_2 = Value::String("mixed-port".to_string()); let key_port_2 = Value::String("mixed-port".to_string());
let key_server = Value::String("external-controller".to_string()); let key_server = Value::String("external-controller".to_string());
@@ -76,14 +91,11 @@ impl Clash {
_ => None, _ => None,
}; };
Clash { ClashInfo {
info: ClashInfo { status: "init".into(),
status: "init".into(), port,
port, server,
server, secret,
secret,
},
sidecar: None,
} }
} }
@@ -126,9 +138,70 @@ impl Clash {
} }
/// restart clash sidecar /// restart clash sidecar
pub fn restart_sidecar(&mut self) -> Result<(), String> { /// should reactivate profile after restart
pub fn restart_sidecar(&mut self, profiles: &mut Profiles) -> Result<(), String> {
self.update_config();
self.drop_sidecar()?; self.drop_sidecar()?;
self.run_sidecar() self.run_sidecar()?;
profiles.activate(&self)
}
/// update the clash info
pub fn update_config(&mut self) {
self.config = Clash::get_config();
self.info = Clash::get_info(&self.config);
}
/// get clash config
fn get_config() -> Mapping {
config::read_yaml::<Mapping>(dirs::app_home_dir().join(CLASH_CONFIG))
}
/// save the clash config
fn save_config(&self) -> Result<(), String> {
config::save_yaml(
dirs::app_home_dir().join(CLASH_CONFIG),
&self.config,
Some("# Default Config For Clash Core\n\n"),
)
}
/// patch update the clash config
pub fn patch_config(
&mut self,
patch: Mapping,
verge: &mut Verge,
profiles: &mut Profiles,
) -> Result<(), String> {
for (key, value) in patch.iter() {
let value = value.clone();
let key_str = key.as_str().clone().unwrap_or("");
// restart the clash
if key_str == "mixed-port" {
self.restart_sidecar(profiles)?;
let port = if value.is_number() {
match value.as_i64().clone() {
Some(num) => Some(format!("{num}")),
None => None,
}
} else {
match value.as_str().clone() {
Some(num) => Some(num.into()),
None => None,
}
};
verge.init_sysproxy(port);
}
if self.config.contains_key(key) {
self.config[key] = value;
} else {
self.config.insert(key.clone(), value);
}
}
self.save_config()
} }
} }

View File

@@ -1,3 +1,4 @@
use super::{Clash, ClashInfo};
use crate::utils::{config, dirs}; use crate::utils::{config, dirs};
use reqwest::header::HeaderMap; use reqwest::header::HeaderMap;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -6,13 +7,12 @@ use std::collections::HashMap;
use std::env::temp_dir; use std::env::temp_dir;
use std::fs::File; use std::fs::File;
use std::io::Write; use std::io::Write;
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH}; use std::time::{SystemTime, UNIX_EPOCH};
use super::ClashInfo;
/// Define the `profiles.yaml` schema /// Define the `profiles.yaml` schema
#[derive(Default, Debug, Clone, Deserialize, Serialize)] #[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct ProfilesConfig { pub struct Profiles {
/// current profile's name /// current profile's name
pub current: Option<usize>, pub current: Option<usize>,
@@ -24,6 +24,8 @@ pub struct ProfilesConfig {
pub struct ProfileItem { pub struct ProfileItem {
/// profile name /// profile name
pub name: Option<String>, pub name: Option<String>,
/// profile description
pub desc: Option<String>,
/// profile file /// profile file
pub file: Option<String>, pub file: Option<String>,
/// current mode /// current mode
@@ -64,10 +66,10 @@ pub struct ProfileResponse {
static PROFILE_YAML: &str = "profiles.yaml"; static PROFILE_YAML: &str = "profiles.yaml";
static PROFILE_TEMP: &str = "clash-verge-runtime.yaml"; static PROFILE_TEMP: &str = "clash-verge-runtime.yaml";
impl ProfilesConfig { impl Profiles {
/// read the config from the file /// read the config from the file
pub fn read_file() -> Self { pub fn read_file() -> Self {
config::read_yaml::<ProfilesConfig>(dirs::app_home_dir().join(PROFILE_YAML)) config::read_yaml::<Profiles>(dirs::app_home_dir().join(PROFILE_YAML))
} }
/// save the config to the file /// save the config to the file
@@ -100,7 +102,7 @@ impl ProfilesConfig {
File::create(path).unwrap().write(file_data).unwrap(); File::create(path).unwrap().write(file_data).unwrap();
// update `profiles.yaml` // update `profiles.yaml`
let data = ProfilesConfig::read_file(); let data = Profiles::read_file();
let mut items = data.items.unwrap_or(vec![]); let mut items = data.items.unwrap_or(vec![]);
let now = SystemTime::now() let now = SystemTime::now()
@@ -110,6 +112,7 @@ impl ProfilesConfig {
items.push(ProfileItem { items.push(ProfileItem {
name: Some(result.name), name: Some(result.name),
desc: Some("imported url".into()),
file: Some(result.file), file: Some(result.file),
mode: Some(format!("rule")), mode: Some(format!("rule")),
url: Some(url), url: Some(url),
@@ -139,6 +142,49 @@ impl ProfilesConfig {
self.save_file() 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 /// update the target profile
/// and save to config file /// and save to config file
/// only support the url item /// only support the url item
@@ -224,7 +270,7 @@ impl ProfilesConfig {
} }
/// activate current profile /// activate current profile
pub fn activate(&self, clash_config: ClashInfo) -> Result<(), String> { pub fn activate(&self, clash: &Clash) -> Result<(), String> {
let current = self.current.unwrap_or(0); let current = self.current.unwrap_or(0);
match self.items.clone() { match self.items.clone() {
Some(items) => { Some(items) => {
@@ -233,11 +279,13 @@ impl ProfilesConfig {
} }
let profile = items[current].clone(); let profile = items[current].clone();
let clash_config = clash.config.clone();
let clash_info = clash.info.clone();
tauri::async_runtime::spawn(async move { tauri::async_runtime::spawn(async move {
let mut count = 5; // retry times let mut count = 5; // retry times
let mut err = String::from(""); let mut err = String::from("");
while count > 0 { while count > 0 {
match activate_profile(&profile, &clash_config).await { match activate_profile(&profile, &clash_config, &clash_info).await {
Ok(_) => return, Ok(_) => return,
Err(e) => err = e, Err(e) => err = e,
} }
@@ -254,7 +302,11 @@ impl ProfilesConfig {
} }
/// put the profile to clash /// put the profile to clash
pub async fn activate_profile(profile_item: &ProfileItem, info: &ClashInfo) -> Result<(), String> { pub async fn activate_profile(
profile_item: &ProfileItem,
clash_config: &Mapping,
clash_info: &ClashInfo,
) -> Result<(), String> {
// temp profile's path // temp profile's path
let temp_path = temp_dir().join(PROFILE_TEMP); let temp_path = temp_dir().join(PROFILE_TEMP);
@@ -267,25 +319,47 @@ pub async fn activate_profile(profile_item: &ProfileItem, info: &ClashInfo) -> R
let file_path = dirs::app_home_dir().join("profiles").join(file_name); let file_path = dirs::app_home_dir().join("profiles").join(file_name);
if !file_path.exists() { if !file_path.exists() {
return Err(format!("profile `{:?}` not exists", file_path)); return Err(format!(
"profile `{}` not exists",
file_path.as_os_str().to_str().unwrap()
));
} }
// begin to generate the new profile config
let def_config = config::read_yaml::<Mapping>(file_path.clone());
let mut new_config = Mapping::new();
// Only the following fields are allowed: // Only the following fields are allowed:
// proxies/proxy-providers/proxy-groups/rule-providers/rules // proxies/proxy-providers/proxy-groups/rule-providers/rules
let config = config::read_yaml::<Mapping>(file_path.clone()); let valid_keys = vec![
let mut new_config = Mapping::new();
vec![
"proxies", "proxies",
"proxy-providers", "proxy-providers",
"proxy-groups", "proxy-groups",
"rule-providers", "rule-providers",
"rules", "rules",
] ];
.iter() valid_keys.iter().for_each(|key| {
.map(|item| Value::String(item.to_string())) let key = Value::String(key.to_string());
.for_each(|key| { if def_config.contains_key(&key) {
if config.contains_key(&key) { let value = def_config[&key].clone();
let value = config[&key].clone(); new_config.insert(key, value);
}
});
// add some of the clash `config.yaml` config to it
let valid_keys = vec![
"mixed-port",
"log-level",
"allow-lan",
"external-controller",
"secret",
"mode",
"ipv6",
];
valid_keys.iter().for_each(|key| {
let key = Value::String(key.to_string());
if clash_config.contains_key(&key) {
let value = clash_config[&key].clone();
new_config.insert(key, value); new_config.insert(key, value);
} }
}); });
@@ -297,12 +371,12 @@ pub async fn activate_profile(profile_item: &ProfileItem, info: &ClashInfo) -> R
)? )?
}; };
let server = format!("http://{}/configs", info.server.clone().unwrap()); let server = format!("http://{}/configs", clash_info.server.clone().unwrap());
let mut headers = HeaderMap::new(); let mut headers = HeaderMap::new();
headers.insert("Content-Type", "application/json".parse().unwrap()); headers.insert("Content-Type", "application/json".parse().unwrap());
if let Some(secret) = info.secret.clone() { if let Some(secret) = clash_info.secret.clone() {
headers.insert( headers.insert(
"Authorization", "Authorization",
format!("Bearer {}", secret).parse().unwrap(), format!("Bearer {}", secret).parse().unwrap(),
@@ -312,7 +386,10 @@ pub async fn activate_profile(profile_item: &ProfileItem, info: &ClashInfo) -> R
let mut data = HashMap::new(); let mut data = HashMap::new();
data.insert("path", temp_path.as_os_str().to_str().unwrap()); data.insert("path", temp_path.as_os_str().to_str().unwrap());
let client = reqwest::Client::new(); let client = match reqwest::ClientBuilder::new().no_proxy().build() {
Ok(c) => c,
Err(_) => return Err("failed to create http::put".into()),
};
match client.put(server).headers(headers).json(&data).send().await { match client.put(server).headers(headers).json(&data).send().await {
Ok(_) => Ok(()), Ok(_) => Ok(()),
Err(err) => Err(format!("request failed `{}`", err.to_string())), Err(err) => Err(format!("request failed `{}`", err.to_string())),

View File

@@ -1,6 +1,6 @@
use crate::utils::{config, dirs, startup, sysopt::SysProxyConfig}; use crate::utils::{config, dirs, sysopt::SysProxyConfig};
use auto_launch::{AutoLaunch, AutoLaunchBuilder};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use tauri::api::path::resource_dir; use tauri::api::path::resource_dir;
/// ### `verge.yaml` schema /// ### `verge.yaml` schema
@@ -9,8 +9,12 @@ pub struct VergeConfig {
/// `light` or `dark` /// `light` or `dark`
pub theme_mode: Option<String>, pub theme_mode: Option<String>,
/// enable blur mode
/// maybe be able to set the alpha
pub theme_blur: Option<bool>,
/// can the app auto startup /// can the app auto startup
pub enable_self_startup: Option<bool>, pub enable_auto_launch: Option<bool>,
/// set system proxy /// set system proxy
pub enable_system_proxy: Option<bool>, pub enable_system_proxy: Option<bool>,
@@ -45,7 +49,7 @@ pub struct Verge {
pub cur_sysproxy: Option<SysProxyConfig>, pub cur_sysproxy: Option<SysProxyConfig>,
pub exe_path: Option<PathBuf>, pub auto_launch: Option<AutoLaunch>,
} }
impl Default for Verge { impl Default for Verge {
@@ -60,7 +64,7 @@ impl Verge {
config: VergeConfig::new(), config: VergeConfig::new(),
old_sysproxy: None, old_sysproxy: None,
cur_sysproxy: None, cur_sysproxy: None,
exe_path: None, auto_launch: None,
} }
} }
@@ -97,58 +101,89 @@ impl Verge {
} }
} }
/// set the exe_path /// init the auto launch
pub fn set_exe_path(&mut self, package_info: &tauri::PackageInfo) { pub fn init_launch(&mut self, package_info: &tauri::PackageInfo) {
let exe = if cfg!(target_os = "windows") { let app_name = "clash-verge";
"clash-verge.exe" let app_path = get_app_path(app_name);
} else { let app_path = resource_dir(package_info, &tauri::Env::default())
"clash-verge" .unwrap()
}; .join(app_path);
let path = resource_dir(package_info).unwrap().join(exe); let app_path = app_path.as_os_str().to_str().unwrap();
self.exe_path = Some(path);
let auto = AutoLaunchBuilder::new()
.set_app_name(app_name)
.set_app_path(app_path)
.build();
self.auto_launch = Some(auto);
} }
/// sync the startup when run the app /// sync the startup when run the app
pub fn sync_startup(&self) -> Result<(), String> { pub fn sync_launch(&self) -> Result<(), String> {
let enable = self.config.enable_self_startup.clone().unwrap_or(false); let enable = self.config.enable_auto_launch.clone().unwrap_or(false);
if !enable { if !enable {
return Ok(()); return Ok(());
} }
if self.exe_path.is_none() {
return Err("should init the exe_path first".into()); if self.auto_launch.is_none() {
return Err("should init the auto launch first".into());
} }
let exe_path = self.exe_path.clone().unwrap(); let auto_launch = self.auto_launch.clone().unwrap();
match startup::get_startup(&exe_path) {
Ok(sys_enable) => { let is_enabled = auto_launch.is_enabled().unwrap_or(false);
if sys_enable || (!sys_enable && startup::set_startup(true, &exe_path).is_ok()) { if !is_enabled {
Ok(()) if let Err(_) = auto_launch.enable() {
} else { return Err("failed to enable auto-launch".into());
Err("failed to sync startup".into())
}
} }
Err(_) => Err("failed to get system startup info".into()),
} }
Ok(())
} }
/// update the startup /// update the startup
fn update_startup(&mut self, enable: bool) -> Result<(), String> { fn update_launch(&mut self, enable: bool) -> Result<(), String> {
let conf_enable = self.config.enable_self_startup.clone().unwrap_or(false); let conf_enable = self.config.enable_auto_launch.clone().unwrap_or(false);
if enable == conf_enable { if enable == conf_enable {
return Ok(()); return Ok(());
} }
if self.exe_path.is_none() {
return Err("should init the exe_path first".into()); let auto_launch = self.auto_launch.clone().unwrap();
}
let exe_path = self.exe_path.clone().unwrap(); let result = if enable {
match startup::set_startup(enable, &exe_path) { auto_launch.enable()
} else {
auto_launch.disable()
};
match result {
Ok(_) => Ok(()), Ok(_) => Ok(()),
Err(_) => Err("failed to set system startup info".into()), Err(err) => {
log::error!("{err}");
Err("failed to set system startup info".into())
}
} }
} }
// fn guard_thread(&mut self) -> Result<(), String> {
// let sysproxy = self.cur_sysproxy.clone();
// use std::{thread, time};
// tauri::async_runtime::spawn(async move {
// if let Some(sysproxy) = sysproxy {
// sysproxy.set_sys();
// }
// let ten_millis = time::Duration::from_millis(10);
// let now = time::Instant::now();
// thread::sleep(ten_millis);
// });
// Ok(())
// }
/// patch verge config /// patch verge config
/// There should be only one update at a time here /// There should be only one update at a time here
/// so call the save_file at the end is savely /// so call the save_file at the end is savely
@@ -157,12 +192,15 @@ impl Verge {
if patch.theme_mode.is_some() { if patch.theme_mode.is_some() {
self.config.theme_mode = patch.theme_mode; self.config.theme_mode = patch.theme_mode;
} }
if patch.theme_blur.is_some() {
self.config.theme_blur = patch.theme_blur;
}
// should update system startup // should update system startup
if patch.enable_self_startup.is_some() { if patch.enable_auto_launch.is_some() {
let enable = patch.enable_self_startup.unwrap(); let enable = patch.enable_auto_launch.unwrap();
self.update_startup(enable)?; self.update_launch(enable)?;
self.config.enable_self_startup = Some(enable); self.config.enable_auto_launch = Some(enable);
} }
// should update system proxy // should update system proxy
@@ -180,7 +218,7 @@ impl Verge {
} }
// todo // todo
// should update system proxt too // should update system proxy too
if patch.system_proxy_bypass.is_some() { if patch.system_proxy_bypass.is_some() {
self.config.system_proxy_bypass = patch.system_proxy_bypass; self.config.system_proxy_bypass = patch.system_proxy_bypass;
} }
@@ -188,3 +226,14 @@ impl Verge {
self.config.save_file() self.config.save_file()
} }
} }
// Get the target app_path
fn get_app_path(app_name: &str) -> String {
#[cfg(target_os = "linux")]
let ext = "";
#[cfg(target_os = "macos")]
let ext = "";
#[cfg(target_os = "windows")]
let ext = ".exe";
String::from(app_name) + ext
}

View File

@@ -3,8 +3,6 @@
windows_subsystem = "windows" windows_subsystem = "windows"
)] )]
extern crate tauri;
mod cmds; mod cmds;
mod core; mod core;
mod states; mod states;
@@ -37,34 +35,37 @@ fn main() -> std::io::Result<()> {
SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() { SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() {
"open_window" => { "open_window" => {
let window = app_handle.get_window("main").unwrap(); let window = app_handle.get_window("main").unwrap();
window.unminimize().unwrap();
window.show().unwrap(); window.show().unwrap();
window.set_focus().unwrap(); window.set_focus().unwrap();
} }
"restart_clash" => { "restart_clash" => {
let clash_state = app_handle.state::<states::ClashState>(); let clash_state = app_handle.state::<states::ClashState>();
let profiles_state = app_handle.state::<states::ProfilesState>();
let mut clash = clash_state.0.lock().unwrap(); let mut clash = clash_state.0.lock().unwrap();
match clash.restart_sidecar() { let mut profiles = profiles_state.0.lock().unwrap();
match clash.restart_sidecar(&mut profiles) {
Ok(_) => { Ok(_) => {
let profiles = app_handle.state::<states::ProfilesState>(); let window = app_handle.get_window("main").unwrap();
let profiles = profiles.0.lock().unwrap(); window.emit("restart_clash", "yes").unwrap();
if let Err(err) = profiles.activate(clash.info.clone()) {
log::error!("{}", err);
}
} }
Err(err) => log::error!("{}", err), Err(err) => log::error!("{}", err),
} }
} }
"quit" => { "quit" => {
api::process::kill_children();
resolve::resolve_reset(app_handle); resolve::resolve_reset(app_handle);
app_handle.exit(0); api::process::kill_children();
std::process::exit(0);
} }
_ => {} _ => {}
}, },
SystemTrayEvent::LeftClick { .. } => { SystemTrayEvent::LeftClick { .. } => {
let window = app_handle.get_window("main").unwrap(); if cfg![target_os = "windows"] {
window.show().unwrap(); let window = app_handle.get_window("main").unwrap();
window.set_focus().unwrap(); window.unminimize().unwrap();
window.show().unwrap();
window.set_focus().unwrap();
}
} }
_ => {} _ => {}
}) })
@@ -73,9 +74,8 @@ fn main() -> std::io::Result<()> {
cmds::restart_sidecar, cmds::restart_sidecar,
cmds::get_sys_proxy, cmds::get_sys_proxy,
cmds::get_cur_proxy, cmds::get_cur_proxy,
cmds::win_drag, cmds::open_app_dir,
cmds::win_hide, cmds::open_logs_dir,
cmds::win_mini,
// clash // clash
cmds::get_clash_info, cmds::get_clash_info,
cmds::patch_clash_config, cmds::patch_clash_config,
@@ -83,23 +83,25 @@ fn main() -> std::io::Result<()> {
cmds::get_verge_config, cmds::get_verge_config,
cmds::patch_verge_config, cmds::patch_verge_config,
// profile // profile
cmds::new_profile,
cmds::view_profile,
cmds::patch_profile,
cmds::import_profile, cmds::import_profile,
cmds::update_profile, cmds::update_profile,
cmds::delete_profile, cmds::delete_profile,
cmds::select_profile, cmds::select_profile,
cmds::patch_profile,
cmds::sync_profiles,
cmds::get_profiles, cmds::get_profiles,
cmds::sync_profiles,
]) ])
.build(tauri::generate_context!()) .build(tauri::generate_context!())
.expect("error while running tauri application") .expect("error while running tauri application")
.run(|app_handle, e| match e { .run(|app_handle, e| match e {
tauri::Event::CloseRequested { label, api, .. } => { tauri::RunEvent::CloseRequested { label, api, .. } => {
let app_handle = app_handle.clone(); let app_handle = app_handle.clone();
api.prevent_close(); api.prevent_close();
app_handle.get_window(&label).unwrap().hide().unwrap(); app_handle.get_window(&label).unwrap().hide().unwrap();
} }
tauri::Event::ExitRequested { .. } => { tauri::RunEvent::ExitRequested { .. } => {
resolve::resolve_reset(app_handle); resolve::resolve_reset(app_handle);
api::process::kill_children(); api::process::kill_children();
} }

View File

@@ -1,8 +1,8 @@
use crate::core::{Clash, ProfilesConfig, Verge}; use crate::core::{Clash, Profiles, Verge};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
#[derive(Default)] #[derive(Default)]
pub struct ProfilesState(pub Arc<Mutex<ProfilesConfig>>); pub struct ProfilesState(pub Arc<Mutex<Profiles>>);
#[derive(Default)] #[derive(Default)]
pub struct ClashState(pub Arc<Mutex<Clash>>); pub struct ClashState(pub Arc<Mutex<Clash>>);

View File

@@ -1,6 +1,4 @@
use crate::utils::dirs;
use serde::{de::DeserializeOwned, Serialize}; use serde::{de::DeserializeOwned, Serialize};
use serde_yaml::Mapping;
use std::{fs, path::PathBuf}; use std::{fs, path::PathBuf};
/// read data from yaml as struct T /// read data from yaml as struct T
@@ -32,17 +30,3 @@ pub fn save_yaml<T: Serialize>(
Err(_) => Err("can not convert the data to yaml".into()), Err(_) => Err("can not convert the data to yaml".into()),
} }
} }
/// Get Clash Core Config `config.yaml`
pub fn read_clash() -> Mapping {
read_yaml::<Mapping>(dirs::app_home_dir().join("config.yaml"))
}
/// Save the clash core Config `config.yaml`
pub fn save_clash(config: &Mapping) -> Result<(), String> {
save_yaml(
dirs::app_home_dir().join("config.yaml"),
config,
Some("# Default Config For Clash Core\n\n"),
)
}

View File

@@ -1,7 +1,7 @@
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use tauri::{ use tauri::{
api::path::{home_dir, resource_dir}, api::path::{home_dir, resource_dir},
PackageInfo, Env, PackageInfo,
}; };
/// get the verge app home dir /// get the verge app home dir
@@ -14,5 +14,7 @@ pub fn app_home_dir() -> PathBuf {
/// get the resources dir /// get the resources dir
pub fn app_resources_dir(package_info: &PackageInfo) -> PathBuf { 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")
} }

View File

@@ -23,11 +23,20 @@ fn parse_string<T: FromStr>(target: &str, key: &str) -> Option<T> {
} }
/// fetch and parse the profile /// fetch and parse the profile
pub async fn fetch_profile(url: &str) -> Option<ProfileResponse> { pub async fn fetch_profile(url: &str, with_proxy: bool) -> Option<ProfileResponse> {
let resp = match reqwest::get(url).await { let builder = reqwest::ClientBuilder::new();
Ok(res) => res, let client = match with_proxy {
true => builder.build(),
false => builder.no_proxy().build(),
};
let resp = match client {
Ok(client) => match client.get(url).send().await {
Ok(res) => res,
Err(_) => return None,
},
Err(_) => return None, Err(_) => return None,
}; };
let header = resp.headers(); let header = resp.headers();
// parse the Subscription Userinfo // parse the Subscription Userinfo

View File

@@ -4,5 +4,4 @@ pub mod fetch;
pub mod init; pub mod init;
pub mod resolve; pub mod resolve;
pub mod server; pub mod server;
pub mod startup;
pub mod sysopt; pub mod sysopt;

View File

@@ -1,5 +1,5 @@
use super::{init, server}; use super::{init, server};
use crate::{core::ProfilesConfig, states}; use crate::{core::Profiles, states};
use tauri::{App, AppHandle, Manager}; use tauri::{App, AppHandle, Manager};
use tauri_plugin_shadows::Shadows; use tauri_plugin_shadows::Shadows;
@@ -9,6 +9,17 @@ pub fn resolve_setup(app: &App) {
let window = app.get_window("main").unwrap(); let window = app.get_window("main").unwrap();
window.set_shadow(true); window.set_shadow(true);
// enable system blur
use tauri_plugin_vibrancy::Vibrancy;
#[cfg(target_os = "windows")]
window.apply_blur();
#[cfg(target_os = "macos")]
{
use tauri_plugin_vibrancy::MacOSVibrancy;
#[allow(deprecated)]
window.apply_vibrancy(MacOSVibrancy::AppearanceBased);
}
// setup a simple http server for singleton // setup a simple http server for singleton
server::embed_server(&app.handle()); server::embed_server(&app.handle());
@@ -28,14 +39,14 @@ pub fn resolve_setup(app: &App) {
log::error!("{}", err); log::error!("{}", err);
} }
*profiles = ProfilesConfig::read_file(); *profiles = Profiles::read_file();
if let Err(err) = profiles.activate(clash.info.clone()) { if let Err(err) = profiles.activate(&clash) {
log::error!("{}", err); log::error!("{}", err);
} }
verge.set_exe_path(app.package_info());
verge.init_sysproxy(clash.info.port.clone()); verge.init_sysproxy(clash.info.port.clone());
if let Err(err) = verge.sync_startup() { verge.init_launch(app.package_info());
if let Err(err) = verge.sync_launch() {
log::error!("{}", err); log::error!("{}", err);
} }
} }

View File

@@ -1,62 +0,0 @@
use std::io;
use std::path::PathBuf;
static APP_KEY: &str = "ClashVerge";
#[cfg(target_os = "windows")]
/// get the startup value
/// whether as same as the exe_path
pub fn get_startup(exe_path: &PathBuf) -> io::Result<bool> {
use winreg::enums::*;
use winreg::RegKey;
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
let cur_var = hkcu.open_subkey_with_flags(
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",
KEY_READ,
)?;
match cur_var.get_value::<String, _>(APP_KEY) {
Ok(path) => {
let exe_path = exe_path.clone();
let exe_path = exe_path.as_os_str().to_str().unwrap();
Ok(path == exe_path)
}
Err(_) => Ok(false),
}
}
#[cfg(target_os = "windows")]
/// set the startup on windows
/// delete the reg key if disabled
pub fn set_startup(enable: bool, exe_path: &PathBuf) -> io::Result<()> {
use winreg::enums::*;
use winreg::RegKey;
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
let cur_var = hkcu.open_subkey_with_flags(
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",
KEY_SET_VALUE,
)?;
match enable {
true => {
let exe_path = exe_path.clone();
let exe_path = exe_path.as_os_str().to_str().unwrap();
cur_var.set_value::<&str, _>(APP_KEY, &exe_path)
}
false => cur_var.delete_value(APP_KEY),
}
}
#[cfg(target_os = "windows")]
#[test]
fn test() {
let path = PathBuf::from(r"D:\Software\Clash Verge\clash-verge.exe");
assert!(set_startup(true, &path).is_ok());
assert_eq!(get_startup(&path).unwrap(), true);
assert!(set_startup(false, &path).is_ok());
assert_eq!(get_startup(&path).unwrap(), false);
}

View File

@@ -1,7 +1,7 @@
{ {
"package": { "package": {
"productName": "clash-verge", "productName": "clash-verge",
"version": "0.0.8" "version": "0.0.15"
}, },
"build": { "build": {
"distDir": "../dist", "distDir": "../dist",
@@ -54,10 +54,16 @@
"endpoints": [ "endpoints": [
"https://github.com/zzzgydi/clash-verge/releases/download/updater/update.json" "https://github.com/zzzgydi/clash-verge/releases/download/updater/update.json"
], ],
"dialog": false "dialog": false,
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDExNUFBNTBBN0FDNEFBRTUKUldUbHFzUjZDcVZhRVRJM25NS3NkSFlFVElxUkNZMzZ6bHUwRVJjb2F3alJXVzRaeDdSaTA2YWYK"
}, },
"allowlist": { "allowlist": {
"all": true "shell": {
"all": true
},
"window": {
"all": true
}
}, },
"windows": [ "windows": [
{ {
@@ -67,7 +73,7 @@
"resizable": true, "resizable": true,
"fullscreen": false, "fullscreen": false,
"decorations": false, "decorations": false,
"transparent": false, "transparent": true,
"minWidth": 600, "minWidth": 600,
"minHeight": 520 "minHeight": 520
} }

View File

@@ -28,3 +28,4 @@ body {
} }
@import "./layout.scss"; @import "./layout.scss";
@import "./page.scss";

View File

@@ -27,6 +27,10 @@
text-align: center; text-align: center;
box-sizing: border-box; box-sizing: border-box;
img {
width: 100%;
}
.the-newbtn { .the-newbtn {
position: absolute; position: absolute;
right: 20px; right: 20px;
@@ -54,27 +58,24 @@
position: relative; position: relative;
flex: 1 1 75%; flex: 1 1 75%;
height: 100%; height: 100%;
display: flex;
flex-direction: column;
padding: 2px 0;
box-sizing: border-box;
.the-bar { .the-bar {
flex: 0 0 30px; position: absolute;
width: 100%; top: 2px;
height: 30px; right: 8px;
padding: 0 16px; height: 36px;
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: flex-end;
box-sizing: border-box; box-sizing: border-box;
z-index: 2;
} }
.the-content { .the-content {
flex: 1 1 100%; position: absolute;
overflow: auto; top: 30px;
box-sizing: border-box; left: 0;
scrollbar-gutter: stable; right: 2px;
bottom: 10px;
} }
} }
} }

View File

@@ -0,0 +1,35 @@
.base-page {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
> header {
flex: 0 0 58px;
width: 90%;
max-width: 850px;
margin: 0 auto;
padding-right: 4px;
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: space-between;
}
> section {
position: relative;
flex: 1 1 100%;
width: 100%;
height: 100%;
overflow: auto;
padding: 8px 0;
box-sizing: border-box;
scrollbar-gutter: stable;
.base-content {
width: 90%;
max-width: 850px;
margin: 0 auto;
}
}
}

View File

@@ -0,0 +1,92 @@
import ReactDOM from "react-dom";
import { ReactNode, useState } from "react";
import { Box, IconButton, Slide, Snackbar, Typography } from "@mui/material";
import { Close, CheckCircleRounded, ErrorRounded } from "@mui/icons-material";
interface InnerProps {
type: string;
duration?: number;
message: ReactNode;
onClose: () => void;
}
const NoticeInner = (props: InnerProps) => {
const { type, message, duration = 2000, onClose } = props;
const [visible, setVisible] = useState(true);
const onBtnClose = () => {
setVisible(false);
onClose();
};
const onAutoClose = (_e: any, reason: string) => {
if (reason !== "clickaway") onBtnClose();
};
const msgElement =
type === "info" ? (
message
) : (
<Box sx={{ display: "flex", alignItems: "center" }}>
{type === "error" && <ErrorRounded color="error" />}
{type === "success" && <CheckCircleRounded color="success" />}
<Typography
sx={{ ml: 1, wordWrap: "break-word", wordBreak: "break-all" }}
>
{message}
</Typography>
</Box>
);
return (
<Snackbar
open={visible}
anchorOrigin={{ vertical: "top", horizontal: "right" }}
autoHideDuration={duration}
onClose={onAutoClose}
message={msgElement}
sx={{ maxWidth: 360 }}
TransitionComponent={(p) => <Slide {...p} direction="left" />}
transitionDuration={200}
action={
<IconButton size="small" color="inherit" onClick={onBtnClose}>
<Close fontSize="inherit" />
</IconButton>
}
/>
);
};
interface NoticeInstance {
(props: Omit<InnerProps, "onClose">): void;
info(message: ReactNode, duration?: number): void;
error(message: ReactNode, duration?: number): void;
success(message: ReactNode, duration?: number): void;
}
let parent: HTMLDivElement = null!;
// @ts-ignore
const Notice: NoticeInstance = (props) => {
if (!parent) {
parent = document.createElement("div");
document.body.appendChild(parent);
}
const container = document.createElement("div");
parent.appendChild(container);
const onUnmount = () => {
const result = ReactDOM.unmountComponentAtNode(container);
if (result && parent) parent.removeChild(container);
};
ReactDOM.render(<NoticeInner {...props} onClose={onUnmount} />, container);
};
(["info", "error", "success"] as const).forEach((type) => {
Notice[type] = (message, duration) => Notice({ type, message, duration });
});
export default Notice;

View File

@@ -0,0 +1,32 @@
import { Typography } from "@mui/material";
import React from "react";
interface Props {
title?: React.ReactNode; // the page title
header?: React.ReactNode; // something behind title
contentStyle?: React.CSSProperties;
}
const BasePage: React.FC<Props> = (props) => {
const { title, header, contentStyle, children } = props;
return (
<div className="base-page" data-windrag>
<header data-windrag style={{ userSelect: "none" }}>
<Typography variant="h4" component="h1" data-windrag>
{title}
</Typography>
{header}
</header>
<section>
<div className="base-content" style={contentStyle} data-windrag>
{children}
</div>
</section>
</div>
);
};
export default BasePage;

View File

@@ -1,4 +1,4 @@
import { ApiType } from "../services/types"; import { ApiType } from "../../services/types";
interface Props { interface Props {
value: ApiType.ConnectionsItem; value: ApiType.ConnectionsItem;

View File

@@ -0,0 +1,41 @@
import { Button } from "@mui/material";
import { appWindow } from "@tauri-apps/api/window";
import {
CloseRounded,
CropSquareRounded,
HorizontalRuleRounded,
} from "@mui/icons-material";
const LayoutControl = () => {
const minWidth = 40;
return (
<>
<Button
size="small"
sx={{ minWidth, svg: { transform: "scale(0.9)" } }}
onClick={() => appWindow.minimize()}
>
<HorizontalRuleRounded fontSize="small" />
</Button>
<Button
size="small"
sx={{ minWidth, svg: { transform: "scale(0.9)" } }}
onClick={() => appWindow.toggleMaximize()}
>
<CropSquareRounded fontSize="small" />
</Button>
<Button
size="small"
sx={{ minWidth, svg: { transform: "scale(1.05)" } }}
onClick={() => appWindow.hide()}
>
<CloseRounded fontSize="small" />
</Button>
</>
);
};
export default LayoutControl;

View File

@@ -1,11 +1,14 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { useRecoilValue } from "recoil";
import { Box, Typography } from "@mui/material"; import { Box, Typography } from "@mui/material";
import { ArrowDownward, ArrowUpward } from "@mui/icons-material"; import { ArrowDownward, ArrowUpward } from "@mui/icons-material";
import { getInfomation } from "../services/api"; import { getInfomation } from "../../services/api";
import { ApiType } from "../services/types"; import { ApiType } from "../../services/types";
import parseTraffic from "../utils/parse-traffic"; 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 }); const [traffic, setTraffic] = useState({ up: 0, down: 0 });
useEffect(() => { useEffect(() => {
@@ -21,7 +24,7 @@ const Traffic = () => {
}); });
return () => ws?.close(); return () => ws?.close();
}, []); }, [portValue]);
const [up, upUnit] = parseTraffic(traffic.up); const [up, upUnit] = parseTraffic(traffic.up);
const [down, downUnit] = parseTraffic(traffic.down); const [down, downUnit] = parseTraffic(traffic.down);
@@ -63,4 +66,4 @@ const Traffic = () => {
); );
}; };
export default Traffic; export default LayoutTraffic;

View File

@@ -0,0 +1,40 @@
import useSWR from "swr";
import { useState } from "react";
import { Button } from "@mui/material";
import { checkUpdate } from "@tauri-apps/api/updater";
import UpdateDialog from "./update-dialog";
interface Props {
className?: string;
}
const UpdateButton = (props: Props) => {
const { className } = props;
const [dialogOpen, setDialogOpen] = useState(false);
const { data: updateInfo } = useSWR("checkUpdate", checkUpdate, {
errorRetryCount: 2,
revalidateIfStale: false,
focusThrottleInterval: 36e5, // 1 hour
});
if (!updateInfo?.shouldUpdate) return null;
return (
<>
<Button
color="error"
variant="contained"
size="small"
className={className}
onClick={() => setDialogOpen(true)}
>
New
</Button>
<UpdateDialog open={dialogOpen} onClose={() => setDialogOpen(false)} />
</>
);
};
export default UpdateButton;

View File

@@ -1,5 +1,5 @@
import { styled, Box } from "@mui/material"; import { styled, Box } from "@mui/material";
import { ApiType } from "../services/types"; import { ApiType } from "../../services/types";
const Item = styled(Box)(({ theme }) => ({ const Item = styled(Box)(({ theme }) => ({
padding: "8px 0", padding: "8px 0",

View File

@@ -1,4 +1,4 @@
import React, { useState } from "react"; import React, { useRef, useState } from "react";
import dayjs from "dayjs"; import dayjs from "dayjs";
import { import {
alpha, alpha,
@@ -13,9 +13,10 @@ import {
} from "@mui/material"; } from "@mui/material";
import { useSWRConfig } from "swr"; import { useSWRConfig } from "swr";
import { RefreshRounded } from "@mui/icons-material"; import { RefreshRounded } from "@mui/icons-material";
import { CmdType } from "../services/types"; import { CmdType } from "../../services/types";
import { updateProfile, deleteProfile } from "../services/cmds"; import { updateProfile, deleteProfile, viewProfile } from "../../services/cmds";
import parseTraffic from "../utils/parse-traffic"; import Notice from "../base/base-notice";
import parseTraffic from "../../utils/parse-traffic";
import relativeTime from "dayjs/plugin/relativeTime"; import relativeTime from "dayjs/plugin/relativeTime";
dayjs.extend(relativeTime); dayjs.extend(relativeTime);
@@ -32,19 +33,19 @@ const Wrapper = styled(Box)(({ theme }) => ({
})); }));
const round = keyframes` const round = keyframes`
from { transform: rotate(0deg); } from { transform: rotate(0deg); }
to { transform: rotate(360deg); } to { transform: rotate(360deg); }
`; `;
interface Props { interface Props {
index: number; index: number;
selected: boolean; selected: boolean;
itemData: CmdType.ProfileItem; itemData: CmdType.ProfileItem;
onClick: () => void; onSelect: (force: boolean) => void;
} }
const ProfileItemComp: React.FC<Props> = (props) => { const ProfileItem: React.FC<Props> = (props) => {
const { index, selected, itemData, onClick } = props; const { index, selected, itemData, onSelect } = props;
const { mutate } = useSWRConfig(); const { mutate } = useSWRConfig();
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@@ -58,27 +59,49 @@ const ProfileItemComp: React.FC<Props> = (props) => {
const progress = Math.round(((download + upload) * 100) / (total + 0.1)); const progress = Math.round(((download + upload) * 100) / (total + 0.1));
const fromnow = updated > 0 ? dayjs(updated * 1000).fromNow() : ""; const fromnow = updated > 0 ? dayjs(updated * 1000).fromNow() : "";
const onUpdate = async () => { // url or file mode
const isUrlMode = itemData.url && extra;
const onView = async () => {
setAnchorEl(null);
try {
await viewProfile(index);
} catch (err: any) {
Notice.error(err.toString());
}
};
const onForceSelect = () => {
setAnchorEl(null);
onSelect(true);
};
const onUpdateWrapper = (withProxy: boolean) => async () => {
setAnchorEl(null); setAnchorEl(null);
if (loading) return; if (loading) return;
setLoading(true); setLoading(true);
try { try {
await updateProfile(index); await updateProfile(index, withProxy);
mutate("getProfiles"); mutate("getProfiles");
} catch (err) { } catch (err: any) {
console.error(err); Notice.error(err.toString());
} finally { } finally {
setLoading(false); setLoading(false);
} }
}; };
const deleteRef = useRef(false);
const onDelete = async () => { const onDelete = async () => {
setAnchorEl(null); setAnchorEl(null);
if (deleteRef.current) return;
deleteRef.current = true;
try { try {
await deleteProfile(index); await deleteProfile(index);
mutate("getProfiles"); mutate("getProfiles");
} catch (err) { } catch (err: any) {
console.error(err); Notice.error(err.toString());
} finally {
deleteRef.current = false;
} }
}; };
@@ -91,6 +114,26 @@ const ProfileItemComp: React.FC<Props> = (props) => {
event.preventDefault(); 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 ( return (
<> <>
<Wrapper <Wrapper
@@ -121,7 +164,7 @@ const ProfileItemComp: React.FC<Props> = (props) => {
return { bgcolor, color, "& h2": { color: h2color } }; return { bgcolor, color, "& h2": { color: h2color } };
}} }}
onClick={onClick} onClick={() => onSelect(false)}
onContextMenu={handleContextMenu} onContextMenu={handleContextMenu}
> >
<Box display="flex" justifyContent="space-between"> <Box display="flex" justifyContent="space-between">
@@ -135,52 +178,63 @@ const ProfileItemComp: React.FC<Props> = (props) => {
{name} {name}
</Typography> </Typography>
<IconButton {isUrlMode && (
sx={{ <IconButton
width: 30, sx={{
height: 30, width: 26,
animation: loading ? `1s linear infinite ${round}` : "none", height: 26,
}} animation: loading ? `1s linear infinite ${round}` : "none",
color="inherit" }}
disabled={loading} color="inherit"
onClick={(e) => { disabled={loading}
e.stopPropagation(); onClick={(e) => {
onUpdate(); e.stopPropagation();
}} onUpdateWrapper(false)();
> }}
<RefreshRounded /> >
</IconButton> <RefreshRounded />
</IconButton>
)}
</Box> </Box>
<Box display="flex" justifyContent="space-between" alignItems="center"> {isUrlMode ? (
<Typography noWrap title={`From: ${from}`}> <>
{from} <Box sx={boxStyle}>
</Typography> <Typography noWrap title={`From: ${from}`}>
{from}
</Typography>
<Typography <Typography
noWrap noWrap
flex="1 0 auto" flex="1 0 auto"
fontSize={14} fontSize={14}
textAlign="right" textAlign="right"
title="updated time" title="updated time"
> >
{fromnow} {fromnow}
</Typography> </Typography>
</Box> </Box>
<Box <Box sx={{ ...boxStyle, fontSize: 14 }}>
sx={{ <span title="used / total">
my: 0.5, {parseTraffic(upload + download)} / {parseTraffic(total)}
fontSize: 14, </span>
display: "flex", <span title="expire time">{expire}</span>
justifyContent: "space-between", </Box>
}} </>
> ) : (
<span title="used / total"> <>
{parseTraffic(upload + download)} / {parseTraffic(total)} <Box sx={boxStyle}>
</span> <Typography noWrap title={itemData.desc}>
<span title="expire time">{expire}</span> {itemData.desc}
</Box> </Typography>
</Box>
<Box sx={{ ...boxStyle, fontSize: 14, justifyContent: "flex-end" }}>
<span title="updated time">{parseExpire(updated)}</span>
</Box>
</>
)}
<LinearProgress <LinearProgress
variant="determinate" variant="determinate"
@@ -196,9 +250,11 @@ const ProfileItemComp: React.FC<Props> = (props) => {
anchorPosition={position} anchorPosition={position}
anchorReference="anchorPosition" anchorReference="anchorPosition"
> >
<MenuItem onClick={onUpdate}>Update</MenuItem> {(isUrlMode ? urlModeMenu : fileModeMenu).map((item) => (
<MenuItem onClick={onDelete}>Delete</MenuItem> <MenuItem key={item.label} onClick={item.handler}>
{/* <MenuItem>Update(proxy)</MenuItem> */} {item.label}
</MenuItem>
))}
</Menu> </Menu>
</> </>
); );
@@ -216,4 +272,4 @@ function parseExpire(expire?: number) {
return dayjs(expire * 1000).format("YYYY-MM-DD"); return dayjs(expire * 1000).format("YYYY-MM-DD");
} }
export default ProfileItemComp; export default ProfileItem;

View 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;

View File

@@ -1,15 +1,13 @@
import { useState } from "react"; import { useRef, useState } from "react";
import { useSWRConfig } from "swr";
import { Virtuoso } from "react-virtuoso"; import { Virtuoso } from "react-virtuoso";
import { import {
alpha,
Box, Box,
Collapse, Collapse,
Divider, Divider,
IconButton, IconButton,
List, List,
ListItem, ListItem,
ListItemButton,
ListItemIcon,
ListItemText, ListItemText,
} from "@mui/material"; } from "@mui/material";
import { import {
@@ -18,65 +16,27 @@ import {
ExpandMoreRounded, ExpandMoreRounded,
MyLocationRounded, MyLocationRounded,
NetworkCheckRounded, NetworkCheckRounded,
CheckCircleOutlineRounded,
} from "@mui/icons-material"; } from "@mui/icons-material";
import { updateProxy } from "../services/api"; import { ApiType } from "../../services/types";
import { ApiType } from "../services/types"; import { updateProxy } from "../../services/api";
import { getProfiles, patchProfile } from "../services/cmds"; import { getProfiles, patchProfile } from "../../services/cmds";
import delayManager from "../../services/delay";
interface ItemProps { import ProxyItem from "./proxy-item";
proxy: ApiType.ProxyItem;
selected: boolean;
onClick?: (name: string) => void;
}
const Item = ({ proxy, selected, onClick }: ItemProps) => {
return (
<ListItem sx={{ py: 0, pl: 4 }}>
<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>
);
};
interface Props { interface Props {
group: ApiType.ProxyGroupItem; group: ApiType.ProxyGroupItem;
} }
const ProxyGroup = ({ group }: Props) => { const ProxyGroup = ({ group }: Props) => {
const { mutate } = useSWRConfig();
const listRef = useRef<any>();
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [now, setNow] = useState(group.now); const [now, setNow] = useState(group.now);
const proxies = group.all ?? []; const proxies = group.all ?? [];
const onUpdate = async (name: string) => { const onSelect = async (name: string) => {
// can not call update // can not call update
if (group.type !== "Selector") { if (group.type !== "Selector") {
// Todo // Todo
@@ -112,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 ( return (
<> <>
<ListItem button onClick={() => setOpen(!open)} dense> <ListItem button onClick={() => setOpen(!open)} dense>
@@ -133,23 +120,26 @@ const ProxyGroup = ({ group }: Props) => {
<Collapse in={open} timeout="auto" unmountOnExit> <Collapse in={open} timeout="auto" unmountOnExit>
<Box sx={{ pl: 4, pr: 3, my: 0.5 }}> <Box sx={{ pl: 4, pr: 3, my: 0.5 }}>
<IconButton size="small" title="location"> <IconButton size="small" title="location" onClick={onLocation}>
<MyLocationRounded /> <MyLocationRounded />
</IconButton> </IconButton>
<IconButton size="small" title="check"> <IconButton size="small" title="check" onClick={onCheckAll}>
<NetworkCheckRounded /> <NetworkCheckRounded />
</IconButton> </IconButton>
</Box> </Box>
{proxies.length >= 10 ? ( {proxies.length >= 10 ? (
<Virtuoso <Virtuoso
style={{ height: "400px", marginBottom: "4px" }} ref={listRef}
style={{ height: "320px", marginBottom: "4px" }}
totalCount={proxies.length} totalCount={proxies.length}
itemContent={(index) => ( itemContent={(index) => (
<Item <ProxyItem
groupName={group.name}
proxy={proxies[index]} proxy={proxies[index]}
selected={proxies[index].name === now} selected={proxies[index].name === now}
onClick={onUpdate} sx={{ py: 0, pl: 4 }}
onClick={onSelect}
/> />
)} )}
/> />
@@ -157,14 +147,16 @@ const ProxyGroup = ({ group }: Props) => {
<List <List
component="div" component="div"
disablePadding disablePadding
sx={{ maxHeight: "400px", overflow: "auto", mb: "4px" }} sx={{ maxHeight: "320px", overflow: "auto", mb: "4px" }}
> >
{proxies.map((proxy) => ( {proxies.map((proxy) => (
<Item <ProxyItem
key={proxy.name} key={proxy.name}
groupName={group.name}
proxy={proxy} proxy={proxy}
selected={proxy.name === now} selected={proxy.name === now}
onClick={onUpdate} sx={{ py: 0, pl: 4 }}
onClick={onSelect}
/> />
))} ))}
</List> </List>

View 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;

View File

@@ -1,8 +0,0 @@
import { ListItem, styled } from "@mui/material";
const SettingItem = styled(ListItem)(() => ({
paddingTop: 5,
paddingBottom: 5,
}));
export default SettingItem;

View File

@@ -1,5 +1,5 @@
import { cloneElement, isValidElement, ReactNode, useRef } from "react"; import { cloneElement, isValidElement, ReactNode, useRef } from "react";
import noop from "../utils/noop"; import noop from "../../utils/noop";
interface Props<Value> { interface Props<Value> {
value?: Value; value?: Value;
@@ -7,7 +7,7 @@ interface Props<Value> {
onChangeProps?: string; onChangeProps?: string;
onChange?: (value: Value) => void; onChange?: (value: Value) => void;
onFormat?: (...args: any[]) => Value; onFormat?: (...args: any[]) => Value;
onGuard?: (value: Value) => Promise<void>; onGuard?: (value: Value, oldValue: Value) => Promise<void>;
onCatch?: (error: Error) => void; onCatch?: (error: Error) => void;
children: ReactNode; children: ReactNode;
} }
@@ -41,7 +41,7 @@ function GuardState<T>(props: Props<T>) {
const newValue = (onFormat as any)(...args); const newValue = (onFormat as any)(...args);
// 先在ui上响应操作 // 先在ui上响应操作
onChange(newValue); onChange(newValue);
await onGuard(newValue); await onGuard(newValue, oldValue!);
} catch (err: any) { } catch (err: any) {
// 状态回退 // 状态回退
onChange(oldValue!); onChange(oldValue!);

View File

@@ -1,21 +1,25 @@
import { useEffect, useState } from "react";
import { useDebounceFn } from "ahooks";
import { useSetRecoilState } from "recoil";
import useSWR, { useSWRConfig } from "swr"; import useSWR, { useSWRConfig } from "swr";
import { import {
List,
ListItemText, ListItemText,
ListSubheader,
TextField, TextField,
Switch, Switch,
Select, Select,
MenuItem, MenuItem,
Typography,
} from "@mui/material"; } from "@mui/material";
import { getClashConfig, updateConfigs } from "../services/api"; import { ApiType } from "../../services/types";
import { patchClashConfig } from "../services/cmds"; import { atomClashPort } from "../../states/setting";
import { ApiType } from "../services/types"; 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 GuardState from "./guard-state";
import SettingItem from "./setting-item";
interface Props { interface Props {
onError?: (err: Error) => void; onError: (err: Error) => void;
} }
const SettingClash = ({ onError }: Props) => { const SettingClash = ({ onError }: Props) => {
@@ -26,26 +30,55 @@ const SettingClash = ({ onError }: Props) => {
ipv6 = false, ipv6 = false,
"allow-lan": allowLan = false, "allow-lan": allowLan = false,
"log-level": logLevel = "silent", "log-level": logLevel = "silent",
"mixed-port": mixedPort = 7890, "mixed-port": thePort = 0,
} = clashConfig ?? {}; } = clashConfig ?? {};
const onSwitchFormat = (_e: any, value: boolean) => value; const setPort = useSetRecoilState(atomClashPort);
const [mixedPort, setMixedPort] = useState(thePort);
useEffect(() => setMixedPort(thePort), [thePort]);
const onSwitchFormat = (_e: any, value: boolean) => value;
const onChangeData = (patch: Partial<ApiType.ConfigData>) => { const onChangeData = (patch: Partial<ApiType.ConfigData>) => {
mutate("getClashConfig", { ...clashConfig, ...patch }, false); mutate("getClashConfig", { ...clashConfig, ...patch }, false);
}; };
const onUpdateData = async (patch: Partial<ApiType.ConfigData>) => { const onUpdateData = async (patch: Partial<ApiType.ConfigData>) => {
await updateConfigs(patch); await updateConfigs(patch);
await patchClashConfig(patch); await patchClashConfig(patch);
}; };
return ( // restart clash when port is changed
<List> const { run: onUpdatePort } = useDebounceFn(
<ListSubheader sx={{ background: "transparent" }}> async (port: number) => {
Clash Setting try {
</ListSubheader> if (port < 1000) {
throw new Error("The port should not < 1000");
}
if (port > 65536) {
throw new Error("The port should not > 65536");
}
await patchClashConfig({ "mixed-port": port });
onChangeData({ "mixed-port": port });
setPort(port);
Notice.success("Change Clash port successfully!");
} 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> <SettingItem>
<ListItemText primary="Allow Lan" /> <ListItemText primary="Allow Lan" />
<GuardState <GuardState
@@ -95,14 +128,21 @@ const SettingClash = ({ onError }: Props) => {
<SettingItem> <SettingItem>
<ListItemText primary="Mixed Port" /> <ListItemText primary="Mixed Port" />
<TextField <GuardState
size="small"
value={mixedPort!} value={mixedPort!}
sx={{ width: 120 }} onFormat={(e: any) => +e.target.value?.replace(/\D+/, "")}
disabled onChange={setMixedPort}
/> onGuard={onUpdatePort}
>
<TextField autoComplete="off" size="small" sx={{ width: 120 }} />
</GuardState>
</SettingItem> </SettingItem>
</List>
<SettingItem>
<ListItemText primary="Clash core" />
<Typography sx={{ py: 1 }}>{clashVer}</Typography>
</SettingItem>
</SettingList>
); );
}; };

View File

@@ -0,0 +1,86 @@
import useSWR, { useSWRConfig } from "swr";
import { Box, ListItemText, Switch, TextField } from "@mui/material";
import { getVergeConfig, patchVergeConfig } from "../../services/cmds";
import { SettingList, SettingItem } from "./setting";
import { CmdType } from "../../services/types";
import GuardState from "./guard-state";
import SysproxyTooltip from "./sysproxy-tooltip";
interface Props {
onError?: (err: Error) => void;
}
const SettingSystem = ({ onError }: Props) => {
const { mutate } = useSWRConfig();
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
const {
enable_auto_launch: startup = false,
enable_system_proxy: proxy = false,
system_proxy_bypass: bypass = "",
} = vergeConfig ?? {};
const onSwitchFormat = (_e: any, value: boolean) => value;
const onChangeData = (patch: Partial<CmdType.VergeConfig>) => {
mutate("getVergeConfig", { ...vergeConfig, ...patch }, false);
};
return (
<SettingList title="System Setting">
<SettingItem>
<ListItemText primary="Auto Launch" />
<GuardState
value={startup}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_auto_launch: e })}
onGuard={(e) => patchVergeConfig({ enable_auto_launch: e })}
>
<Switch edge="end" />
</GuardState>
</SettingItem>
<SettingItem>
<ListItemText
primary={
<Box sx={{ display: "flex", alignItems: "center" }}>
System Proxy
<SysproxyTooltip />
</Box>
}
/>
<GuardState
value={proxy}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ 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>
);
};
export default SettingSystem;

View File

@@ -1,17 +1,17 @@
import useSWR, { useSWRConfig } from "swr"; import useSWR, { useSWRConfig } from "swr";
import { IconButton, ListItemText, Switch, Typography } from "@mui/material";
import { import {
List, getVergeConfig,
ListItemText, openAppDir,
ListSubheader, openLogsDir,
Switch, patchVergeConfig,
Typography, } from "../../services/cmds";
} from "@mui/material"; import { SettingList, SettingItem } from "./setting";
import { getVergeConfig, patchVergeConfig } from "../services/cmds"; import { CmdType } from "../../services/types";
import { CmdType } from "../services/types"; import { version } from "../../../package.json";
import { version } from "../../package.json";
import GuardState from "./guard-state"; import GuardState from "./guard-state";
import SettingItem from "./setting-item";
import PaletteSwitch from "./palette-switch"; import PaletteSwitch from "./palette-switch";
import { ArrowForward } from "@mui/icons-material";
interface Props { interface Props {
onError?: (err: Error) => void; onError?: (err: Error) => void;
@@ -21,11 +21,8 @@ const SettingVerge = ({ onError }: Props) => {
const { mutate } = useSWRConfig(); const { mutate } = useSWRConfig();
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig); const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
const { const { theme_mode: mode = "light", theme_blur: blur = false } =
theme_mode: mode = "light", vergeConfig ?? {};
enable_self_startup: startup = false,
enable_system_proxy: proxy = false,
} = vergeConfig ?? {};
const onSwitchFormat = (_e: any, value: boolean) => value; const onSwitchFormat = (_e: any, value: boolean) => value;
const onChangeData = (patch: Partial<CmdType.VergeConfig>) => { const onChangeData = (patch: Partial<CmdType.VergeConfig>) => {
@@ -33,11 +30,7 @@ const SettingVerge = ({ onError }: Props) => {
}; };
return ( return (
<List> <SettingList title="Verge Setting">
<ListSubheader sx={{ background: "transparent" }}>
Common Setting
</ListSubheader>
<SettingItem> <SettingItem>
<ListItemText primary="Theme Mode" /> <ListItemText primary="Theme Mode" />
<GuardState <GuardState
@@ -55,38 +48,45 @@ const SettingVerge = ({ onError }: Props) => {
</SettingItem> </SettingItem>
<SettingItem> <SettingItem>
<ListItemText primary="Self Startup" /> <ListItemText primary="Theme Blur" />
<GuardState <GuardState
value={startup} value={blur}
valueProps="checked" valueProps="checked"
onCatch={onError} onCatch={onError}
onFormat={onSwitchFormat} onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_self_startup: e })} onChange={(e) => onChangeData({ theme_blur: e })}
onGuard={(e) => patchVergeConfig({ enable_self_startup: e })} onGuard={(e) => patchVergeConfig({ theme_blur: e })}
> >
<Switch edge="end" /> <Switch edge="end" />
</GuardState> </GuardState>
</SettingItem> </SettingItem>
<SettingItem> <SettingItem>
<ListItemText primary="System Proxy" /> <ListItemText primary="Open App Dir" />
<GuardState <IconButton
value={proxy} color="inherit"
valueProps="checked" size="small"
onCatch={onError} onClick={() => {
onFormat={onSwitchFormat} console.log("click");
onChange={(e) => onChangeData({ enable_system_proxy: e })} openAppDir().then(console.log).catch(console.log);
onGuard={(e) => patchVergeConfig({ enable_system_proxy: e })} }}
> >
<Switch edge="end" /> <ArrowForward />
</GuardState> </IconButton>
</SettingItem>
<SettingItem>
<ListItemText primary="Open Logs Dir" />
<IconButton color="inherit" size="small" onClick={openLogsDir}>
<ArrowForward />
</IconButton>
</SettingItem> </SettingItem>
<SettingItem> <SettingItem>
<ListItemText primary="Version" /> <ListItemText primary="Version" />
<Typography sx={{ py: "6px" }}>v{version}</Typography> <Typography sx={{ py: "6px" }}>v{version}</Typography>
</SettingItem> </SettingItem>
</List> </SettingList>
); );
}; };

View File

@@ -0,0 +1,17 @@
import React from "react";
import { List, ListItem, ListSubheader, styled } from "@mui/material";
export const SettingItem = styled(ListItem)(() => ({
paddingTop: 5,
paddingBottom: 5,
}));
export const SettingList: React.FC<{ title: string }> = (props) => (
<List>
<ListSubheader sx={{ background: "transparent" }} disableSticky>
{props.title}
</ListSubheader>
{props.children}
</List>
);

View File

@@ -0,0 +1,52 @@
import { useEffect, useState } from "react";
import { InfoRounded } from "@mui/icons-material";
import { ClickAwayListener, Tooltip } from "@mui/material";
import { getSystemProxy } from "../../services/cmds";
const SysproxyTooltip = () => {
const [open, setOpen] = useState(false);
const [info, setInfo] = useState<any>({});
const onShow = async () => {
const data = await getSystemProxy();
setInfo(data ?? {});
setOpen(true);
};
useEffect(() => {
if (!open) return;
const timer = setTimeout(() => setOpen(false), 2000);
return () => clearTimeout(timer);
}, [open]);
// todo: add error info
const showTitle = (
<div>
<div>Enable: {(!!info.enable).toString()}</div>
<div>Server: {info.server}</div>
<div>Bypass: {info.bypass}</div>
</div>
);
return (
<ClickAwayListener onClickAway={() => setOpen(false)}>
<Tooltip
PopperProps={{
disablePortal: true,
}}
onClose={() => setOpen(false)}
open={open}
disableFocusListener
disableHoverListener
disableTouchListener
placement="top"
title={showTitle}
arrow
>
<InfoRounded fontSize="small" onClick={onShow} />
</Tooltip>
</ClickAwayListener>
);
};
export default SysproxyTooltip;

View File

@@ -1,70 +1,46 @@
import { useEffect, useMemo, useState } from "react"; import useSWR, { SWRConfig, useSWRConfig } from "swr";
import useSWR, { SWRConfig } from "swr"; import { useEffect, useMemo } from "react";
import { Route, Routes } from "react-router-dom"; import { Route, Routes } from "react-router-dom";
import { useRecoilState } from "recoil"; import { useRecoilState } from "recoil";
import { import { alpha, createTheme, List, Paper, ThemeProvider } from "@mui/material";
Button, import { listen } from "@tauri-apps/api/event";
createTheme, import { appWindow } from "@tauri-apps/api/window";
IconButton, import { atomPaletteMode, atomThemeBlur } from "../states/setting";
List, import { getVergeConfig } from "../services/cmds";
Paper, import { getAxios } from "../services/api";
ThemeProvider, import { routers } from "./_routers";
} from "@mui/material";
import { HorizontalRuleRounded, CloseRounded } from "@mui/icons-material";
import { checkUpdate } from "@tauri-apps/api/updater";
import { atomPaletteMode } from "../states/setting";
import { getVergeConfig, windowDrag, windowHide } from "../services/cmds";
import LogoSvg from "../assets/image/logo.svg"; import LogoSvg from "../assets/image/logo.svg";
import LogPage from "./log"; import LayoutItem from "../components/layout/layout-item";
import ProfilePage from "./profile"; import LayoutControl from "../components/layout/layout-control";
import ProxyPage from "./proxy"; import LayoutTraffic from "../components/layout/layout-traffic";
import SettingPage from "./setting"; import UpdateButton from "../components/layout/update-button";
import ConnectionsPage from "./connections";
import LayoutItem from "../components/layout-item";
import Traffic from "../components/traffic";
import UpdateDialog from "../components/update-dialog";
const routers = [
{
label: "Proxy",
link: "/",
ele: ProxyPage,
},
{
label: "Profile",
link: "/profile",
ele: ProfilePage,
},
{
label: "Connections",
link: "/connections",
ele: ConnectionsPage,
},
{
label: "Log",
link: "/log",
ele: LogPage,
},
{
label: "Setting",
link: "/setting",
ele: SettingPage,
},
];
const Layout = () => { const Layout = () => {
const { mutate } = useSWRConfig();
const [mode, setMode] = useRecoilState(atomPaletteMode); const [mode, setMode] = useRecoilState(atomPaletteMode);
const [blur, setBlur] = useRecoilState(atomThemeBlur);
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig); const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
const { data: updateInfo } = useSWR("checkUpdate", checkUpdate, {
errorRetryCount: 2,
revalidateIfStale: false,
focusThrottleInterval: 36e5, // 1 hour
});
const [dialogOpen, setDialogOpen] = useState(false);
useEffect(() => { useEffect(() => {
setMode(vergeConfig?.theme_mode ?? "light"); window.addEventListener("keydown", (e) => {
}, [vergeConfig?.theme_mode]); if (e.key === "Escape") appWindow.hide();
});
listen("restart_clash", async () => {
// the clash info may be updated
await getAxios(true);
// make sure that the clash is ok
setTimeout(() => mutate("getProxies"), 1000);
setTimeout(() => mutate("getProxies"), 2000);
mutate("getClashConfig");
});
}, []);
useEffect(() => {
if (!vergeConfig) return;
setBlur(!!vergeConfig.theme_blur);
setMode(vergeConfig.theme_mode ?? "light");
}, [vergeConfig]);
const theme = useMemo(() => { const theme = useMemo(() => {
// const background = mode === "light" ? "#f5f5f5" : "#000"; // const background = mode === "light" ? "#f5f5f5" : "#000";
@@ -86,36 +62,34 @@ const Layout = () => {
}); });
}, [mode]); }, [mode]);
const onDragging = (e: any) => {
if (e?.target?.dataset?.windrag) {
appWindow.startDragging();
}
};
return ( return (
<SWRConfig value={{}}> <SWRConfig value={{}}>
<ThemeProvider theme={theme}> <ThemeProvider theme={theme}>
<Paper square elevation={0} className="layout"> <Paper
<div className="layout__left"> square
<div className="the-logo"> elevation={0}
<img className="layout"
src={LogoSvg} onPointerDown={onDragging}
width="100%" sx={[
alt="" (theme) => ({
onPointerDown={(e) => { bgcolor: alpha(theme.palette.background.paper, blur ? 0.85 : 1),
windowDrag(); }),
e.preventDefault(); ]}
}} >
/> <div className="layout__left" data-windrag>
<div className="the-logo" data-windrag>
<img src={LogoSvg} alt="" data-windrag />
{updateInfo?.shouldUpdate && ( <UpdateButton className="the-newbtn" />
<Button
color="error"
variant="contained"
size="small"
className="the-newbtn"
onClick={() => setDialogOpen(true)}
>
New
</Button>
)}
</div> </div>
<List className="the-menu"> <List className="the-menu" data-windrag>
{routers.map((router) => ( {routers.map((router) => (
<LayoutItem key={router.label} to={router.link}> <LayoutItem key={router.label} to={router.link}>
{router.label} {router.label}
@@ -123,26 +97,14 @@ const Layout = () => {
))} ))}
</List> </List>
<div className="the-traffic"> <div className="the-traffic" data-windrag>
<Traffic /> <LayoutTraffic />
</div> </div>
</div> </div>
<div className="layout__right"> <div className="layout__right" data-windrag>
<div <div className="the-bar">
className="the-bar" <LayoutControl />
onPointerDown={(e) =>
e.target === e.currentTarget && windowDrag()
}
>
{/* todo: onClick = windowMini */}
<IconButton size="small" sx={{ mx: 1 }} onClick={windowHide}>
<HorizontalRuleRounded fontSize="inherit" />
</IconButton>
<IconButton size="small" onClick={windowHide}>
<CloseRounded fontSize="inherit" />
</IconButton>
</div> </div>
<div className="the-content"> <div className="the-content">
@@ -154,7 +116,6 @@ const Layout = () => {
</div> </div>
</div> </div>
</Paper> </Paper>
<UpdateDialog open={dialogOpen} onClose={() => setDialogOpen(false)} />
</ThemeProvider> </ThemeProvider>
</SWRConfig> </SWRConfig>
); );

33
src/pages/_routers.tsx Normal file
View File

@@ -0,0 +1,33 @@
import LogsPage from "./logs";
import ProxiesPage from "./proxies";
import ProfilesPage from "./profiles";
import SettingsPage from "./settings";
import ConnectionsPage from "./connections";
export const routers = [
{
label: "Proxies",
link: "/",
ele: ProxiesPage,
},
{
label: "Profiles",
link: "/profile",
ele: ProfilesPage,
},
{
label: "Connections",
link: "/connections",
ele: ConnectionsPage,
},
{
label: "Logs",
link: "/logs",
ele: LogsPage,
},
{
label: "Settings",
link: "/settings",
ele: SettingsPage,
},
];

View File

@@ -1,9 +1,10 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { Box, Paper, Typography } from "@mui/material"; import { Paper } from "@mui/material";
import { Virtuoso } from "react-virtuoso"; import { Virtuoso } from "react-virtuoso";
import { getInfomation } from "../services/api";
import { ApiType } from "../services/types"; import { ApiType } from "../services/types";
import ConnectionItem from "../components/connection-item"; import { getInfomation } from "../services/api";
import BasePage from "../components/base/base-page";
import ConnectionItem from "../components/connection/connection-item";
const ConnectionsPage = () => { const ConnectionsPage = () => {
const initConn = { uploadTotal: 0, downloadTotal: 0, connections: [] }; const initConn = { uploadTotal: 0, downloadTotal: 0, connections: [] };
@@ -26,25 +27,14 @@ const ConnectionsPage = () => {
}, []); }, []);
return ( return (
<Box <BasePage title="Connections" contentStyle={{ height: "100%" }}>
sx={{ <Paper sx={{ boxShadow: 2, height: "100%" }}>
width: 0.9,
maxWidth: "850px",
height: "100%",
mx: "auto",
}}
>
<Typography variant="h4" component="h1" sx={{ py: 2 }}>
Connections
</Typography>
<Paper sx={{ boxShadow: 2, height: "calc(100% - 100px)" }}>
<Virtuoso <Virtuoso
data={conn.connections} data={conn.connections}
itemContent={(index, item) => <ConnectionItem value={item} />} itemContent={(index, item) => <ConnectionItem value={item} />}
/> />
</Paper> </Paper>
</Box> </BasePage>
); );
}; };

View File

@@ -1,10 +1,11 @@
import dayjs from "dayjs"; import dayjs from "dayjs";
import { useEffect, useRef, useState } from "react"; import { useEffect, useState } from "react";
import { Box, Button, Paper, Typography } from "@mui/material"; import { Button, Paper } from "@mui/material";
import { Virtuoso } from "react-virtuoso"; import { Virtuoso } from "react-virtuoso";
import { ApiType } from "../services/types"; import { ApiType } from "../services/types";
import { getInfomation } from "../services/api"; import { getInfomation } from "../services/api";
import LogItem from "../components/log-item"; import BasePage from "../components/base/base-page";
import LogItem from "../components/log/log-item";
let logCache: ApiType.LogItem[] = []; let logCache: ApiType.LogItem[] = [];
@@ -28,33 +29,27 @@ const LogPage = () => {
return () => ws?.close(); return () => ws?.close();
}, []); }, []);
const onClear = () => {
setLogData([]);
logCache = [];
};
return ( return (
<Box <BasePage
sx={{ title="Logs"
position: "relative", contentStyle={{ height: "100%" }}
width: 0.9, header={
maxWidth: "850px", <Button
height: "100%", size="small"
mx: "auto", sx={{ mt: 1 }}
}} variant="contained"
onClick={onClear}
>
Clear
</Button>
}
> >
<Typography variant="h4" component="h1" sx={{ py: 2 }}> <Paper sx={{ boxShadow: 2, height: "100%" }}>
Logs
</Typography>
<Button
size="small"
variant="contained"
sx={{ position: "absolute", top: 22, right: 0 }}
onClick={() => {
setLogData([]);
logCache = [];
}}
>
Clear
</Button>
<Paper sx={{ boxShadow: 2, height: "calc(100% - 100px)" }}>
<Virtuoso <Virtuoso
initialTopMostItemIndex={999} initialTopMostItemIndex={999}
data={logData} data={logData}
@@ -62,7 +57,7 @@ const LogPage = () => {
followOutput={"smooth"} followOutput={"smooth"}
/> />
</Paper> </Paper>
</Box> </BasePage>
); );
}; };

View File

@@ -1,21 +1,23 @@
import { useEffect, useRef, useState } from "react";
import useSWR, { useSWRConfig } from "swr"; import useSWR, { useSWRConfig } from "swr";
import { Box, Button, Grid, TextField, Typography } from "@mui/material"; import { useEffect, useRef, useState } from "react";
import { Box, Button, Grid, TextField } from "@mui/material";
import { import {
getProfiles, getProfiles,
selectProfile, selectProfile,
patchProfile, patchProfile,
importProfile, importProfile,
newProfile,
} from "../services/cmds"; } from "../services/cmds";
import { getProxies, updateProxy } from "../services/api"; import { getProxies, updateProxy } from "../services/api";
import ProfileItemComp from "../components/profile-item";
import useNotice from "../utils/use-notice";
import noop from "../utils/noop"; import noop from "../utils/noop";
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 ProfilePage = () => {
const [url, setUrl] = useState(""); const [url, setUrl] = useState("");
const [disabled, setDisabled] = useState(false); const [disabled, setDisabled] = useState(false);
const [notice, noticeElement] = useNotice();
const { mutate } = useSWRConfig(); const { mutate } = useSWRConfig();
const { data: profiles = {} } = useSWR("getProfiles", getProfiles); const { data: profiles = {} } = useSWR("getProfiles", getProfiles);
@@ -71,37 +73,48 @@ const ProfilePage = () => {
await importProfile(url); await importProfile(url);
mutate("getProfiles", getProfiles()); mutate("getProfiles", getProfiles());
if (!profiles.items?.length) selectProfile(0).catch(noop); if (!profiles.items?.length) selectProfile(0).catch(noop);
notice.success("Successfully import profile."); Notice.success("Successfully import profile.");
} catch { } catch {
notice.error("Failed to import profile."); Notice.error("Failed to import profile.");
} finally { } finally {
setDisabled(false); setDisabled(false);
} }
}; };
const lockRef = useRef(false); const lockRef = useRef(false);
const onProfileChange = (index: number) => { const onSelect = async (index: number, force: boolean) => {
if (index === profiles.current || lockRef.current) return;
if (lockRef.current) return; if (lockRef.current) return;
if (!force && index === profiles.current) return;
lockRef.current = true; lockRef.current = true;
selectProfile(index) try {
.then(() => { await selectProfile(index);
mutate("getProfiles", { ...profiles, current: index }, true); mutate("getProfiles", { ...profiles, current: index }, true);
}) } catch (err: any) {
.catch((err) => { err && Notice.error(err.toString());
console.error(err); } finally {
}) lockRef.current = false;
.finally(() => { }
lockRef.current = false; };
});
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 ( return (
<Box sx={{ width: 0.9, maxWidth: "850px", mx: "auto", mb: 2 }}> <BasePage title="Profiles">
<Typography variant="h4" component="h1" sx={{ py: 2, mb: 1 }}>
Profiles
</Typography>
<Box sx={{ display: "flex", mb: 3 }}> <Box sx={{ display: "flex", mb: 3 }}>
<TextField <TextField
id="profile_url" id="profile_url"
@@ -111,32 +124,40 @@ const ProfilePage = () => {
fullWidth fullWidth
value={url} value={url}
onChange={(e) => setUrl(e.target.value)} onChange={(e) => setUrl(e.target.value)}
sx={{ mr: 4 }} sx={{ mr: 1 }}
/> />
<Button <Button
disabled={!url || disabled} disabled={!url || disabled}
variant="contained" variant="contained"
onClick={onImport} onClick={onImport}
sx={{ mr: 1 }}
> >
Import Import
</Button> </Button>
<Button variant="contained" onClick={() => setDialogOpen(true)}>
New
</Button>
</Box> </Box>
<Grid container spacing={3}> <Grid container spacing={3}>
{profiles?.items?.map((item, idx) => ( {profiles?.items?.map((item, idx) => (
<Grid item xs={12} sm={6} key={item.file}> <Grid item xs={12} sm={6} key={item.file}>
<ProfileItemComp <ProfileItem
index={idx} index={idx}
selected={profiles.current === idx} selected={profiles.current === idx}
itemData={item} itemData={item}
onClick={() => onProfileChange(idx)} onSelect={(f) => onSelect(idx, f)}
/> />
</Grid> </Grid>
))} ))}
</Grid> </Grid>
{noticeElement} <ProfileNew
</Box> open={dialogOpen}
onClose={() => setDialogOpen(false)}
onSubmit={onNew}
/>
</BasePage>
); );
}; };

131
src/pages/proxies.tsx Normal file
View File

@@ -0,0 +1,131 @@
import useSWR, { useSWRConfig } from "swr";
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/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 { 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(() => {
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
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>
) : (
// virtual list
<Virtuoso
style={{ height: "100%" }}
totalCount={filterProxies.length}
itemContent={(index) => (
<ProxyItem
groupName="GLOBAL"
proxy={filterProxies[index]}
selected={filterProxies[index].name === curProxy}
onClick={onChangeProxy}
sx={{ py: 0, px: 2 }}
/>
)}
/>
)}
</Paper>
</BasePage>
);
};
export default ProxyPage;

View File

@@ -1,39 +0,0 @@
import useSWR, { useSWRConfig } from "swr";
import { useEffect } from "react";
import { Box, List, Paper, Typography } from "@mui/material";
import { getProxies } from "../services/api";
import ProxyGroup from "../components/proxy-group";
const ProxyPage = () => {
const { mutate } = useSWRConfig();
const { data: proxiesData } = useSWR("getProxies", getProxies);
const { groups = [] } = proxiesData ?? {};
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);
}, []);
return (
<Box sx={{ width: 0.9, maxWidth: "850px", mx: "auto", mb: 2 }}>
<Typography variant="h4" component="h1" sx={{ py: 2 }}>
Proxy Groups
</Typography>
{groups.length > 0 && (
<Paper sx={{ borderRadius: 1, boxShadow: 2 }}>
<List>
{groups.map((group) => (
<ProxyGroup key={group.name} group={group} />
))}
</List>
</Paper>
)}
</Box>
);
};
export default ProxyPage;

View File

@@ -1,23 +0,0 @@
import { Box, Paper, Typography } from "@mui/material";
import SettingVerge from "../components/setting-verge";
import SettingClash from "../components/setting-clash";
const SettingPage = () => {
return (
<Box sx={{ width: 0.9, maxWidth: 850, mx: "auto", mb: 2 }}>
<Typography variant="h4" component="h1" sx={{ py: 2 }}>
Setting
</Typography>
<Paper sx={{ borderRadius: 1, boxShadow: 2 }}>
<SettingVerge />
</Paper>
<Paper sx={{ borderRadius: 1, boxShadow: 2, mt: 3 }}>
<SettingClash />
</Paper>
</Box>
);
};
export default SettingPage;

30
src/pages/settings.tsx Normal file
View File

@@ -0,0 +1,30 @@
import { Paper } from "@mui/material";
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 onError = (error: any) => {
error && Notice.error(error.toString());
};
return (
<BasePage title="Settings">
<Paper sx={{ borderRadius: 1, boxShadow: 2, mb: 3 }}>
<SettingClash onError={onError} />
</Paper>
<Paper sx={{ borderRadius: 1, boxShadow: 2, mb: 3 }}>
<SettingSystem onError={onError} />
</Paper>
<Paper sx={{ borderRadius: 1, boxShadow: 2 }}>
<SettingVerge onError={onError} />
</Paper>
</BasePage>
);
};
export default SettingPage;

View File

@@ -7,8 +7,9 @@ let server = "";
let secret = ""; let secret = "";
/// initialize some infomation /// initialize some infomation
export async function getAxios() { /// enable force update axiosIns
if (axiosIns) return axiosIns; export async function getAxios(force: boolean = false) {
if (axiosIns && !force) return axiosIns;
try { try {
const info = await getClashInfo(); const info = await getClashInfo();
@@ -59,10 +60,24 @@ export async function getRules() {
return instance.get("/rules") as Promise<ApiType.RuleItem[]>; 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 /// Update the Proxy Choose
export async function updateProxy(group: string, proxy: string) { export async function updateProxy(group: string, proxy: string) {
const instance = await getAxios(); const instance = await getAxios();
return instance.put(`/proxies/${group}`, { name: proxy }); return instance.put(`/proxies/${encodeURIComponent(group)}`, { name: proxy });
} }
/// Get the Proxy infomation /// Get the Proxy infomation

View File

@@ -9,12 +9,20 @@ export async function syncProfiles() {
return invoke<void>("sync_profiles"); return invoke<void>("sync_profiles");
} }
export async function importProfile(url: string) { export async function newProfile(name: string, desc: string) {
return invoke<void>("import_profile", { url }); return invoke<void>("new_profile", { name, desc });
} }
export async function updateProfile(index: number) { export async function viewProfile(index: number) {
return invoke<void>("update_profile", { index }); return invoke<void>("view_profile", { index });
}
export async function importProfile(url: string) {
return invoke<void>("import_profile", { url, withProxy: true });
}
export async function updateProfile(index: number, withProxy: boolean) {
return invoke<void>("update_profile", { index, withProxy });
} }
export async function deleteProfile(index: number) { export async function deleteProfile(index: number) {
@@ -36,18 +44,6 @@ export async function restartSidecar() {
return invoke<void>("restart_sidecar"); return invoke<void>("restart_sidecar");
} }
export async function windowDrag() {
return invoke<void>("win_drag");
}
export async function windowHide() {
return invoke<void>("win_hide");
}
export async function windowMini() {
return invoke<void>("win_mini");
}
export async function getClashInfo() { export async function getClashInfo() {
return invoke<CmdType.ClashInfo | null>("get_clash_info"); return invoke<CmdType.ClashInfo | null>("get_clash_info");
} }
@@ -63,3 +59,15 @@ export async function getVergeConfig() {
export async function patchVergeConfig(payload: CmdType.VergeConfig) { export async function patchVergeConfig(payload: CmdType.VergeConfig) {
return invoke<void>("patch_verge_config", { payload }); return invoke<void>("patch_verge_config", { payload });
} }
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
View 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();

View File

@@ -87,6 +87,7 @@ export namespace CmdType {
export interface ProfileItem { export interface ProfileItem {
name?: string; name?: string;
desc?: string;
file?: string; file?: string;
mode?: string; mode?: string;
url?: string; url?: string;
@@ -110,7 +111,9 @@ export namespace CmdType {
export interface VergeConfig { export interface VergeConfig {
theme_mode?: "light" | "dark"; theme_mode?: "light" | "dark";
enable_self_startup?: boolean; theme_blur?: boolean;
enable_auto_launch?: boolean;
enable_system_proxy?: boolean; enable_system_proxy?: boolean;
system_proxy_bypass?: string;
} }
} }

View File

@@ -4,3 +4,13 @@ export const atomPaletteMode = atom<"light" | "dark">({
key: "atomPaletteMode", key: "atomPaletteMode",
default: "light", default: "light",
}); });
export const atomThemeBlur = atom<boolean>({
key: "atomThemeBlur",
default: false,
});
export const atomClashPort = atom<number>({
key: "atomClashPort",
default: 0,
});

View File

@@ -1,68 +0,0 @@
import { useMemo, useState } from "react";
import { Box, IconButton, Slide, Snackbar } from "@mui/material";
import { Close, CheckCircleRounded, ErrorRounded } from "@mui/icons-material";
interface NoticeInstance {
info: (msg: string) => void;
error: (msg: string) => void;
success: (msg: string) => void;
}
const useNotice = () => {
const [message, setMessage] = useState("");
const [level, setLevel] = useState<"info" | "error" | "success">("info");
const handleClose = (_e: any, reason: string) => {
if (reason !== "clickaway") setMessage("");
};
const msgElement =
level === "info" ? (
message
) : (
<Box sx={{ display: "flex", alignItems: "center" }}>
{level === "error" && <ErrorRounded color="error" />}
{level === "success" && <CheckCircleRounded color="success" />}
<span style={{ marginLeft: 4 }}>{message}</span>
</Box>
);
const element = useMemo(
() => (
<Snackbar
open={!!message}
anchorOrigin={{ vertical: "top", horizontal: "right" }}
autoHideDuration={3000}
onClose={handleClose}
message={msgElement}
sx={{ maxWidth: 360 }}
TransitionComponent={(p) => <Slide {...p} direction="left" />}
transitionDuration={200}
action={
<IconButton
size="small"
color="inherit"
onClick={() => setMessage("")}
>
<Close fontSize="small" />
</IconButton>
}
/>
),
[message]
);
const instance = (Object.fromEntries(
(["info", "error", "success"] as const).map((item) => [
item,
(msg: string) => {
setLevel(item);
setMessage(msg);
},
])
) as unknown) as NoticeInstance;
return [instance, element] as const;
};
export default useNotice;

3853
yarn.lock

File diff suppressed because it is too large Load Diff