114 Commits

Author SHA1 Message Date
GyDi
f4f1a0fbc6 v0.0.29 2022-04-13 01:30:08 +08:00
GyDi
74e10dc012 chore: update log 2022-04-13 01:29:48 +08:00
GyDi
359812b7ed chore: update dep 2022-04-13 01:21:49 +08:00
GyDi
c2449e53c4 chore: rename green to portable 2022-04-13 01:17:40 +08:00
GyDi
1a91249da2 feat: system tray add tun mode 2022-04-13 01:09:51 +08:00
GyDi
b9162f9576 fix: adjust log 2022-04-13 00:49:30 +08:00
GyDi
f726e8a7b3 feat: supports change config dir 2022-04-12 23:09:32 +08:00
GyDi
2f284cfdc9 chore: update clash version 2022-04-12 23:04:19 +08:00
GyDi
b74696adba feat: add default user agent 2022-04-12 01:05:51 +08:00
GyDi
c8ccba0192 chore: rm console 2022-04-11 02:26:09 +08:00
GyDi
41b0e05f62 feat: connections page supports filter 2022-04-11 02:25:34 +08:00
GyDi
847d5f1b3b feat: log page supports filter 2022-04-11 01:46:33 +08:00
GyDi
0445f9dfc2 fix: check button hover style 2022-04-10 03:33:17 +08:00
GyDi
3001c780bd feat: optimize delay checker concurrency strategy 2022-04-10 02:58:48 +08:00
GyDi
68ad5e2320 feat: support sort proxy node and custom test url 2022-04-10 02:09:36 +08:00
GyDi
b5e229b19c chore: update deps 2022-04-10 01:31:05 +08:00
GyDi
453d798fcf refactor: proxy head 2022-04-08 01:35:18 +08:00
GyDi
451afdb660 v0.0.28 2022-04-07 01:28:30 +08:00
GyDi
d298bda92c chore: update log 2022-04-07 01:27:48 +08:00
GyDi
fd99ba6255 feat: handle remote clash config fields 2022-04-07 01:20:44 +08:00
GyDi
6ade0b2b1a fix: icon button color inherit 2022-04-06 22:52:00 +08:00
GyDi
9902003da9 fix: remove the lonely zero 2022-04-06 22:48:10 +08:00
GyDi
0ff2fcac11 chore: readme 2022-04-06 01:52:20 +08:00
GyDi
e80be8e7b6 v0.0.27 2022-04-06 01:21:33 +08:00
GyDi
fe0ad0f5cb chore: update log 2022-04-06 01:19:13 +08:00
GyDi
cb8e162f4e refactor: update profile menu 2022-04-06 01:13:06 +08:00
GyDi
ae8c30fe57 chore: add updater script 2022-04-05 23:24:52 +08:00
GyDi
ab82db9e22 chore: updater json supports arch field 2022-04-05 23:19:54 +08:00
GyDi
cb9d3098de chore: add ci 2022-04-05 20:21:53 +08:00
GyDi
c927419c99 refactor: enhanced mode ui component 2022-04-03 01:41:48 +08:00
GyDi
c009026961 feat: add text color 2022-04-02 17:18:38 +08:00
GyDi
51cf442fa5 fix: i18n add value 2022-04-02 13:49:48 +08:00
GyDi
954e3553ee fix: proxy page first render 2022-04-02 01:23:31 +08:00
GyDi
cde17385b4 feat: control final tun config 2022-04-01 23:55:44 +08:00
GyDi
5b9e078061 chore: add debug feature 2022-04-01 23:43:35 +08:00
GyDi
0290d9ddfc feat: support css injection 2022-04-01 02:08:42 +08:00
GyDi
eab671d102 fix: console warning 2022-04-01 01:16:23 +08:00
GyDi
f9a96ff914 feat: support theme setting 2022-03-31 23:38:00 +08:00
GyDi
3ec2b46d28 feat: add text color 2022-03-31 23:34:36 +08:00
GyDi
aec30b89e0 feat: add theme setting 2022-03-31 23:11:50 +08:00
GyDi
309c33e190 refactor: ui theme 2022-03-30 12:36:39 +08:00
GyDi
9c0276f97b chore: add api 2022-03-30 01:30:22 +08:00
GyDi
0a3402ff43 fix: icon button title 2022-03-30 01:29:25 +08:00
GyDi
bd82308024 chore: update tauri 2022-03-29 23:05:32 +08:00
GyDi
db3b634e62 fix: macOS transition flickers close #47 2022-03-29 01:39:54 +08:00
GyDi
40bcb22977 chore: update deps 2022-03-29 01:33:14 +08:00
GyDi
4bd94092f1 fix: csp image data 2022-03-28 23:17:11 +08:00
GyDi
cac1ce6895 chore: readme 2022-03-28 01:33:58 +08:00
GyDi
5c3696123a v0.0.26 2022-03-28 01:30:54 +08:00
GyDi
4140fc86ee chore: update log 2022-03-28 01:18:18 +08:00
GyDi
2ad771e7fd fix: close dialog after save 2022-03-28 01:09:34 +08:00
GyDi
5a38468144 refactor: optimize enhance mode strategy 2022-03-28 01:07:14 +08:00
GyDi
0a9c81772f fix: change to deep copy 2022-03-28 00:56:48 +08:00
GyDi
c9649ac501 feat: enhanced mode supports more fields 2022-03-27 20:36:13 +08:00
GyDi
6ea567742b chore: profile release 2022-03-27 01:38:40 +08:00
GyDi
f31349eaa0 feat: supports edit profile file 2022-03-27 00:58:17 +08:00
GyDi
9d44668d5f feat: supports silent start 2022-03-26 18:56:16 +08:00
GyDi
a12f58c1c7 feat: use crate open 2022-03-23 23:00:14 +08:00
GyDi
b5283eaaed fix: window style close #45 2022-03-23 21:43:13 +08:00
GyDi
4b6189af5f feat: enhance connections display order 2022-03-23 14:02:08 +08:00
GyDi
5d0ffbe453 chore: adjust style 2022-03-23 13:58:57 +08:00
GyDi
502706931e fix: manage global proxy correctly 2022-03-23 12:49:34 +08:00
GyDi
57c411288f fix: tauri csp 2022-03-23 01:47:35 +08:00
GyDi
b09b7b11a1 feat: save global selected 2022-03-22 12:38:59 +08:00
GyDi
1a7b3c7294 v0.0.25 2022-03-22 01:51:06 +08:00
GyDi
4678fc7dde chore: update log 2022-03-22 01:50:24 +08:00
GyDi
9f492fad49 chore: update clash core 2022-03-22 01:50:15 +08:00
GyDi
bd0a959e18 fix: windows style 2022-03-22 01:36:06 +08:00
GyDi
dd605e2610 fix: update state 2022-03-22 01:27:22 +08:00
inRm3D
9910f6b817 chore: readme (#43) 2022-03-21 21:55:45 +08:00
GyDi
991897aff4 chore: tauri feature 2022-03-21 11:40:52 +08:00
GyDi
3cde019208 fix: profile item loading state 2022-03-21 11:40:27 +08:00
GyDi
2f6efbed63 chore: tauri allowList 2022-03-20 13:16:50 +08:00
GyDi
5cff4e299b chore: update clash version 2022-03-20 12:37:55 +08:00
GyDi
bce33639da v0.0.24 2022-03-20 01:50:39 +08:00
GyDi
366c465cad chore: update log 2022-03-20 01:50:15 +08:00
GyDi
acc6e05bdc feat: system tray supports system proxy setting 2022-03-20 01:36:43 +08:00
GyDi
4ce15577cd feat: prevent context menu on Windows close #22 2022-03-19 19:28:53 +08:00
GyDi
98fa4d5e65 feat: create local profile with selected file 2022-03-19 19:21:55 +08:00
GyDi
7fe94076c7 feat: reduce the impact of the enhanced mode 2022-03-19 16:02:47 +08:00
GyDi
b8b0c8fa63 fix: adjust windows style 2022-03-19 15:35:59 +08:00
GyDi
e585e87bec feat: parse update log 2022-03-19 15:31:58 +08:00
GyDi
6a4924bb16 chore: update log supports 2022-03-19 14:04:58 +08:00
GyDi
ab0d516d91 chore: updater proxy 2022-03-19 11:14:12 +08:00
GyDi
b756ae39d0 chore: ci support linux 2022-03-19 10:50:44 +08:00
GyDi
c15c38ea8f chore: readme 2022-03-18 19:02:53 +08:00
GyDi
743963318f feat: fill i18n 2022-03-18 14:59:23 +08:00
GyDi
ed3fc50858 feat: dayjs i18n 2022-03-18 14:45:24 +08:00
GyDi
5b886fe6be feat: connections page simply support 2022-03-18 14:43:22 +08:00
GyDi
7074bbc405 feat: add wintun.dll by default 2022-03-18 11:49:00 +08:00
GyDi
ef314c1707 fix: change mixed port error 2022-03-18 11:39:02 +08:00
GyDi
a3e7626dd9 chore: add dev feature 2022-03-18 10:59:35 +08:00
GyDi
5cb5d74eed chore: rename temp dir 2022-03-18 10:20:24 +08:00
GyDi
6eee10d46d chore: resolve wintun.dll 2022-03-17 19:29:30 +08:00
GyDi
2d95f2b0d6 fix: auto launch path 2022-03-16 18:44:25 +08:00
GyDi
ec41bb9c70 fix: tun mode config 2022-03-15 14:23:57 +08:00
GyDi
2d1780b1cf fix: adjsut open cmd error 2022-03-15 12:51:39 +08:00
GyDi
d9ce99887c chore: fix ci env 2022-03-15 00:00:20 +08:00
GyDi
9b9cc90414 v0.0.23 2022-03-14 01:34:26 +08:00
GyDi
c1eb539a5c feat: event emit when clash config update 2022-03-13 01:37:41 +08:00
GyDi
e1793f57ef chore: fix ci 2022-03-13 00:59:42 +08:00
GyDi
dbd09a8743 chore: update tauri action 2022-03-13 00:58:49 +08:00
GyDi
0d189ca617 chore: green version bundle 2022-03-13 00:52:31 +08:00
GyDi
dc9bcc40ee chore: rm then 2022-03-12 23:58:20 +08:00
GyDi
4991f7ff39 feat: i18n supports 2022-03-12 23:07:45 +08:00
GyDi
a393b8b122 fix: parse external-controller 2022-03-12 21:35:20 +08:00
GyDi
c73b354386 fix: config file case close #18 2022-03-12 21:03:17 +08:00
GyDi
392ecee3ff chore: merge 2022-03-12 18:45:07 +08:00
ttyS3
bae721c49e chore: show open app and log dir failed message 2022-03-12 18:04:56 +08:00
GyDi
4e806e21a6 chore: adjust error log 2022-03-12 15:57:16 +08:00
GyDi
ec0fdf83b2 feat: change open command on linux
refactor(logging): refine open dir failed log message, add Linux support
2022-03-12 15:40:23 +08:00
ttyS3
cb94d8414f feat: add Linux open dir support
refactor(logging): refine open dir failed log message
2022-03-12 03:18:25 +08:00
GyDi
8890051c17 fix: patch item option 2022-03-11 19:56:56 +08:00
GyDi
cf00c9476f fix: user agent not works 2022-03-11 19:50:51 +08:00
80 changed files with 3909 additions and 1932 deletions

View File

@@ -10,7 +10,7 @@ jobs:
release: release:
strategy: strategy:
matrix: matrix:
os: [windows-latest, macos-11] os: [windows-latest, ubuntu-latest, macos-latest]
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
if: | if: |
startsWith(github.repository, 'zzzgydi') && startsWith(github.repository, 'zzzgydi') &&
@@ -34,6 +34,12 @@ jobs:
with: with:
node-version: 14 node-version: 14
- name: Install Dependencies (ubuntu only)
if: matrix.os == 'ubuntu-latest'
run: |
sudo apt-get update
sudo apt-get install -y libgtk-3-dev webkit2gtk-4.0 libappindicator3-dev librsvg2-dev patchelf
- name: Get yarn cache dir path - name: Get yarn cache dir path
id: yarn-cache-dir-path id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)" run: echo "::set-output name=dir::$(yarn cache dir)"
@@ -53,9 +59,9 @@ jobs:
yarn run check yarn run check
- name: Tauri build - name: Tauri build
uses: tauri-apps/tauri-action@b9ce5d7dc68082d21d30a60103b0ab8c5ddae3a1 uses: tauri-apps/tauri-action@0e558392ccadcb49bcc89e7df15a400e8f0c954d
# enable cache even though failed # enable cache even though failed
continue-on-error: true # continue-on-error: true
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }} TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
@@ -67,9 +73,16 @@ jobs:
releaseDraft: false releaseDraft: false
prerelease: true prerelease: true
- name: Green zip bundle
if: matrix.os == 'windows-latest'
run: |
yarn run portable
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
release-update: release-update:
needs: release needs: release
runs-on: macos-11 runs-on: macos-latest
if: | if: |
startsWith(github.repository, 'zzzgydi') && startsWith(github.repository, 'zzzgydi') &&
startsWith(github.ref, 'refs/tags/v') startsWith(github.ref, 'refs/tags/v')
@@ -91,9 +104,9 @@ jobs:
${{ runner.os }}-yarn- ${{ runner.os }}-yarn-
- name: Yarn install - name: Yarn install
run: yarn run: yarn install
- name: Release update.json - name: Release updater file
run: yarn run release run: yarn run updater
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

32
.github/workflows/updater.yml vendored Normal file
View File

@@ -0,0 +1,32 @@
name: Updater CI
on: workflow_dispatch
jobs:
release-update:
runs-on: macos-latest
if: startsWith(github.repository, 'zzzgydi')
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 install
- name: Release updater file
run: yarn run updater
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -11,7 +11,18 @@ A <a href="https://github.com/Dreamacro/clash">Clash</a> GUI based on <a href="h
## Features ## Features
Now it's no different from the others, maybe fewer. (WIP) - Full `clash` config supported, Partial `clash premium` config supported.
- Profiles management and enhancement (by yaml and Javascript). [Doc](https://github.com/zzzgydi/clash-verge/issues/12)
- Simple UI and supports custom theme color.
- System proxy setting and guard.
## Install
Download from [release](https://github.com/zzzgydi/clash-verge/releases). Supports Windows x64, Linux x86_64 and macOS 11+
Or you can build it yourself. Supports Windows, Linux and macOS 10.15+
Notes: If you could not start the app on Windows, please check that you have [Webview2](https://developer.microsoft.com/en-us/microsoft-edge/webview2/#download-section) installed.
## Development ## Development
@@ -33,6 +44,12 @@ Then run
yarn dev yarn dev
``` ```
Or you can build it
```shell
yarn build
```
## Todos ## Todos
> This keng is a little big... > This keng is a little big...
@@ -48,6 +65,17 @@ yarn dev
<img src="./docs/demo6.png" alt="demo6" width="32%" /> <img src="./docs/demo6.png" alt="demo6" width="32%" />
</div> </div>
### Custom Theme
<div align="center">
<img src="./docs/color1.png" alt="demo1" width="16%" />
<img src="./docs/color2.png" alt="demo2" width="16%" />
<img src="./docs/color3.png" alt="demo3" width="16%" />
<img src="./docs/color4.png" alt="demo4" width="16%" />
<img src="./docs/color5.png" alt="demo5" width="16%" />
<img src="./docs/color6.png" alt="demo6" width="16%" />
</div>
## Disclaimer ## Disclaimer
This is a learning project for Rust practice. This is a learning project for Rust practice.

101
UPDATELOG.md Normal file
View File

@@ -0,0 +1,101 @@
## v0.0.29
### Features
- sort proxy node
- custom proxy test url
- logs page filter
- connections page filter
- default user agent for subscription
- system tray add tun mode toggle
- enable to change the config dir (Windows only)
## v0.0.28
### Features
- enable to use clash config fields (UI)
### Bug Fixes
- remove the character
- fix some icon color
---
## v0.0.27
### Features
- supports custom theme color
- tun mode setting control the final config
### Bug Fixes
- fix transition flickers (macOS)
- reduce proxy page render
---
## v0.0.26
### Features
- silent start
- profile editor
- profile enhance mode supports more fields
- optimize profile enhance mode strategy
### Bug Fixes
- fix csp restriction on macOS
- window controllers on Linux
---
## v0.0.25
### Features
- update clash core version
### Bug Fixes
- app updater error
- display window controllers on Linux
### Notes
If you can't update the app properly, please consider downloading the latest version from github release.
---
## v0.0.24
### Features
- Connections page
- add wintun.dll (Windows)
- supports create local profile with selected file (Windows)
- system tray enable set system proxy
### Bug Fixes
- open dir error
- auto launch path (Windows)
- fix some clash config error
- reduce the impact of the enhanced mode
---
## v0.0.23
### Features
- i18n supports
- Remote profile User Agent supports
### Bug Fixes
- clash config file case ignore
- clash `external-controller` only port

BIN
docs/color1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

BIN
docs/color2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

BIN
docs/color3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

BIN
docs/color4.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

BIN
docs/color5.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

BIN
docs/color6.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

View File

@@ -1,6 +1,6 @@
{ {
"name": "clash-verge", "name": "clash-verge",
"version": "0.0.22", "version": "0.0.29",
"license": "GPL-3.0", "license": "GPL-3.0",
"scripts": { "scripts": {
"dev": "tauri dev", "dev": "tauri dev",
@@ -10,31 +10,37 @@
"web:build": "tsc && vite build", "web:build": "tsc && vite build",
"web:serve": "vite preview", "web:serve": "vite preview",
"check": "node scripts/check.mjs", "check": "node scripts/check.mjs",
"updater": "node scripts/updater.mjs",
"publish": "node scripts/publish.mjs", "publish": "node scripts/publish.mjs",
"release": "node scripts/release.mjs", "portable": "node scripts/portable.mjs",
"prepare": "husky install" "prepare": "husky install"
}, },
"dependencies": { "dependencies": {
"@emotion/react": "^11.8.1", "@emotion/react": "^11.8.2",
"@emotion/styled": "^11.8.1", "@emotion/styled": "^11.8.1",
"@mui/icons-material": "^5.4.4", "@mui/icons-material": "^5.6.1",
"@mui/material": "^5.4.4", "@mui/material": "^5.6.1",
"@tauri-apps/api": "^1.0.0-rc.2", "@tauri-apps/api": "^1.0.0-rc.3",
"ahooks": "^3.1.13", "ahooks": "^3.2.0",
"axios": "^0.26.0", "axios": "^0.26.0",
"dayjs": "^1.10.8", "dayjs": "^1.11.0",
"i18next": "^21.6.14",
"monaco-editor": "^0.33.0",
"react": "^17.0.2", "react": "^17.0.2",
"react-dom": "^17.0.2", "react-dom": "^17.0.2",
"react-i18next": "^11.15.6",
"react-router-dom": "^6.2.2", "react-router-dom": "^6.2.2",
"react-virtuoso": "^2.7.0", "react-virtuoso": "~2.7.2",
"recoil": "^0.6.1", "recoil": "^0.6.1",
"swr": "^1.2.1" "snarkdown": "^2.0.0",
"swr": "^1.2.2"
}, },
"devDependencies": { "devDependencies": {
"@actions/github": "^5.0.0", "@actions/github": "^5.0.0",
"@tauri-apps/cli": "^1.0.0-rc.7", "@tauri-apps/cli": "^1.0.0-rc.8",
"@types/fs-extra": "^9.0.13", "@types/fs-extra": "^9.0.13",
"@types/js-cookie": "^3.0.1", "@types/js-cookie": "^3.0.1",
"@types/lodash": "^4.14.180",
"@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.2.0", "@vitejs/plugin-react": "^1.2.0",
@@ -45,7 +51,9 @@
"pretty-quick": "^3.1.3", "pretty-quick": "^3.1.3",
"sass": "^1.49.7", "sass": "^1.49.7",
"typescript": "^4.5.5", "typescript": "^4.5.5",
"vite": "^2.8.6" "vite": "^2.8.6",
"vite-plugin-monaco-editor": "^1.0.10",
"vite-plugin-svgr": "^1.1.0"
}, },
"prettier": { "prettier": {
"tabWidth": 2, "tabWidth": 2,

View File

@@ -8,16 +8,16 @@ import { execSync } from "child_process";
const cwd = process.cwd(); const cwd = process.cwd();
const FORCE = process.argv.includes("--force"); const FORCE = process.argv.includes("--force");
const CLASH_URL_PREFIX =
"https://github.com/Dreamacro/clash/releases/download/premium/";
const CLASH_LATEST_DATE = "2022.01.27";
/** /**
* get the correct clash release infomation * get the correct clash release infomation
*/ */
function resolveClash() { function resolveClash() {
const { platform, arch } = process; const { platform, arch } = process;
const CLASH_URL_PREFIX =
"https://github.com/Dreamacro/clash/releases/download/premium/";
const CLASH_LATEST_DATE = "2022.04.11";
// todo // todo
const map = { const map = {
"win32-x64": "clash-windows-amd64", "win32-x64": "clash-windows-amd64",
@@ -84,13 +84,55 @@ async function resolveSidecar() {
console.log(`[INFO]: gunzip finished`); console.log(`[INFO]: gunzip finished`);
execSync(`chmod 755 ${sidecarPath}`); execSync(`chmod 755 ${sidecarPath}`);
console.log(`[INFO]: chmod binary finished`); console.log(`[INFO]: chmod binary finished`);
}); })
.on("error", (error) => console.error(error));
} }
// delete temp dir // delete temp dir
await fs.remove(tempDir); await fs.remove(tempDir);
} }
/**
* only Windows
* get the wintun.dll (not required)
*/
async function resolveWintun() {
const { platform } = process;
if (platform !== "win32") return;
const url = "https://www.wintun.net/builds/wintun-0.14.1.zip";
const tempDir = path.join(cwd, "pre-dev-temp-1");
const tempZip = path.join(tempDir, "wintun.zip");
const wintunPath = path.join(tempDir, "wintun/bin/amd64/wintun.dll");
const targetPath = path.join(cwd, "src-tauri/resources", "wintun.dll");
if (!FORCE && (await fs.pathExists(targetPath))) return;
await fs.mkdirp(tempDir);
if (!(await fs.pathExists(tempZip))) {
await downloadFile(url, tempZip);
}
// unzip
const zip = new AdmZip(tempZip);
zip.extractAllTo(tempDir, true);
if (!(await fs.pathExists(wintunPath))) {
throw new Error(`path not found "${wintunPath}"`);
}
// move wintun.dll to resources
await fs.rename(wintunPath, targetPath);
// delete temp dir
await fs.remove(tempDir);
console.log(`[INFO]: resolve wintun.dll finished`);
}
/** /**
* get the Country.mmdb (not required) * get the Country.mmdb (not required)
*/ */
@@ -123,4 +165,5 @@ async function downloadFile(url, path) {
/// main /// main
resolveSidecar().catch(console.error); resolveSidecar().catch(console.error);
resolveWintun().catch(console.error);
resolveMmdb().catch(console.error); resolveMmdb().catch(console.error);

56
scripts/portable.mjs Normal file
View File

@@ -0,0 +1,56 @@
import fs from "fs-extra";
import path from "path";
import AdmZip from "adm-zip";
import { createRequire } from "module";
import { getOctokit, context } from "@actions/github";
/// Script for ci
/// 打包绿色版/便携版 (only Windows)
async function resolvePortable() {
if (process.platform !== "win32") return;
const releaseDir = "./src-tauri/target/release";
if (!(await fs.pathExists(releaseDir))) {
throw new Error("could not found the release dir");
}
const zip = new AdmZip();
zip.addLocalFile(path.join(releaseDir, "Clash Verge.exe"));
zip.addLocalFile(path.join(releaseDir, "clash.exe"));
zip.addLocalFolder(path.join(releaseDir, "resources"), "resources");
const require = createRequire(import.meta.url);
const packageJson = require("../package.json");
const { version } = packageJson;
const zipFile = `Clash.Verge_${version}_x64_portable.zip`;
zip.writeZip(zipFile);
console.log("[INFO]: create portable zip successfully");
// push release assets
if (process.env.GITHUB_TOKEN === undefined) {
throw new Error("GITHUB_TOKEN is required");
}
const options = { owner: context.repo.owner, repo: context.repo.repo };
const github = getOctokit(process.env.GITHUB_TOKEN);
const { data: release } = await github.rest.repos.getReleaseByTag({
...options,
tag: `v${version}`,
});
console.log(release.name);
await github.rest.repos.uploadReleaseAsset({
...options,
release_id: release.id,
name: zipFile,
data: zip.toBuffer(),
});
}
resolvePortable().catch(console.error);

View File

@@ -1,9 +1,11 @@
import fs from "fs-extra"; import fs from "fs-extra";
import { createRequire } from "module"; import { createRequire } from "module";
import { execSync } from "child_process"; import { execSync } from "child_process";
import { resolveUpdateLog } from "./updatelog.mjs";
const require = createRequire(import.meta.url); const require = createRequire(import.meta.url);
// publish
async function resolvePublish() { async function resolvePublish() {
const flag = process.argv[2] ?? "patch"; const flag = process.argv[2] ?? "patch";
const packageJson = require("../package.json"); const packageJson = require("../package.json");
@@ -26,6 +28,10 @@ async function resolvePublish() {
packageJson.version = nextVersion; packageJson.version = nextVersion;
tauriJson.package.version = nextVersion; tauriJson.package.version = nextVersion;
// 发布更新前先写更新日志
const nextTag = `v${nextVersion}`;
await resolveUpdateLog(nextTag);
await fs.writeFile( await fs.writeFile(
"./package.json", "./package.json",
JSON.stringify(packageJson, undefined, 2) JSON.stringify(packageJson, undefined, 2)

View File

@@ -1,117 +0,0 @@
import fetch from "node-fetch";
import { getOctokit, context } from "@actions/github";
const UPDATE_TAG_NAME = "updater";
const UPDATE_JSON_FILE = "update.json";
/// 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 options = { owner: context.repo.owner, repo: context.repo.repo };
const github = getOctokit(process.env.GITHUB_TOKEN);
const { data: tags } = await github.rest.repos.listTags({
...options,
per_page: 10,
page: 1,
});
// get the latest publish tag
const tag = tags.find((t) => t.name.startsWith("v"));
console.log(tag);
console.log();
const { data: latestRelease } = await github.rest.repos.getReleaseByTag({
...options,
tag: tag.name,
});
const updateData = {
name: tag.name,
notes: latestRelease.body, // use the release body directly
pub_date: new Date().toISOString(),
platforms: {
win64: { signature: "", url: "" },
darwin: { signature: "", url: "" },
},
};
const promises = latestRelease.assets.map(async (asset) => {
const { name, browser_download_url } = asset;
// win64 url
if (/\.msi\.zip$/.test(name)) {
updateData.platforms.win64.url = browser_download_url;
}
// darwin url
if (/\.app\.tar\.gz$/.test(name)) {
updateData.platforms.darwin.url = browser_download_url;
}
// win64 signature
if (/\.msi\.zip\.sig$/.test(name)) {
updateData.platforms.win64.signature = await getSignature(
browser_download_url
);
}
// darwin signature
if (/\.app\.tar\.gz\.sig$/.test(name)) {
updateData.platforms.darwin.signature = await getSignature(
browser_download_url
);
}
});
await Promise.allSettled(promises);
console.log(updateData);
// maybe should test the signature as well
const { darwin, win64 } = updateData.platforms;
if (!darwin.url) {
console.log(`[Error]: failed to parse release for darwin`);
delete updateData.platforms.darwin;
}
if (!win64.url) {
console.log(`[Error]: failed to parse release for win64`);
delete updateData.platforms.win64;
}
// update the update.json
const { data: updateRelease } = await github.rest.repos.getReleaseByTag({
...options,
tag: UPDATE_TAG_NAME,
});
for (let asset of updateRelease.assets) {
if (asset.name === UPDATE_JSON_FILE) {
await github.rest.repos.deleteReleaseAsset({
...options,
asset_id: asset.id,
});
break;
}
}
await github.rest.repos.uploadReleaseAsset({
...options,
release_id: updateRelease.id,
name: UPDATE_JSON_FILE,
data: JSON.stringify(updateData, null, 2),
});
}
// get the signature file content
async function getSignature(url) {
const response = await fetch(url, {
method: "GET",
headers: { "Content-Type": "application/octet-stream" },
});
return response.text();
}
resolveRelease().catch(console.error);

44
scripts/updatelog.mjs Normal file
View File

@@ -0,0 +1,44 @@
import fs from "fs-extra";
import path from "path";
const UPDATE_LOG = "UPDATELOG.md";
// parse the UPDATELOG.md
export async function resolveUpdateLog(tag) {
const cwd = process.cwd();
const reTitle = /^## v[\d\.]+/;
const reEnd = /^---/;
const file = path.join(cwd, UPDATE_LOG);
if (!(await fs.pathExists(file))) {
throw new Error("could not found UPDATELOG.md");
}
const data = await fs.readFile(file).then((d) => d.toString("utf8"));
const map = {};
let p = "";
data.split("\n").forEach((line) => {
if (reTitle.test(line)) {
p = line.slice(3).trim();
if (!map[p]) {
map[p] = [];
} else {
throw new Error(`Tag ${p} dup`);
}
} else if (reEnd.test(line)) {
p = "";
} else if (p) {
map[p].push(line);
}
});
if (!map[tag]) {
throw new Error(`could not found "${tag}" in UPDATELOG.md`);
}
return map[tag].join("\n").trim();
}

177
scripts/updater.mjs Normal file
View File

@@ -0,0 +1,177 @@
import fetch from "node-fetch";
import { getOctokit, context } from "@actions/github";
import { resolveUpdateLog } from "./updatelog.mjs";
const UPDATE_TAG_NAME = "updater";
const UPDATE_JSON_FILE = "update.json";
const UPDATE_JSON_PROXY = "update-proxy.json";
/// generate update.json
/// upload to update tag's release asset
async function resolveUpdater() {
if (process.env.GITHUB_TOKEN === undefined) {
throw new Error("GITHUB_TOKEN is required");
}
const options = { owner: context.repo.owner, repo: context.repo.repo };
const github = getOctokit(process.env.GITHUB_TOKEN);
const { data: tags } = await github.rest.repos.listTags({
...options,
per_page: 10,
page: 1,
});
// get the latest publish tag
const tag = tags.find((t) => t.name.startsWith("v"));
console.log(tag);
console.log();
const { data: latestRelease } = await github.rest.repos.getReleaseByTag({
...options,
tag: tag.name,
});
const updateData = {
name: tag.name,
notes: await resolveUpdateLog(tag.name), // use updatelog.md
pub_date: new Date().toISOString(),
platforms: {
win64: { signature: "", url: "" }, // compatible with older formats
linux: { signature: "", url: "" }, // compatible with older formats
darwin: { signature: "", url: "" }, // compatible with older formats
"darwin-aarch64": { signature: "", url: "" },
"darwin-intel": { signature: "", url: "" },
"linux-x86_64": { signature: "", url: "" },
"windows-x86_64": { signature: "", url: "" },
"windows-i686": { signature: "", url: "" }, // no supported
},
};
const promises = latestRelease.assets.map(async (asset) => {
const { name, browser_download_url } = asset;
// win64 url
if (name.endsWith(".msi.zip")) {
updateData.platforms.win64.url = browser_download_url;
updateData.platforms["windows-x86_64"].url = browser_download_url;
}
// win64 signature
if (name.endsWith(".msi.zip.sig")) {
const sig = await getSignature(browser_download_url);
updateData.platforms.win64.signature = sig;
updateData.platforms["windows-x86_64"].signature = sig;
}
// darwin url (intel)
if (name.endsWith(".app.tar.gz") && !name.includes("aarch")) {
updateData.platforms.darwin.url = browser_download_url;
updateData.platforms["darwin-intel"].url = browser_download_url;
}
// darwin signature (intel)
if (name.endsWith(".app.tar.gz.sig") && !name.includes("aarch")) {
const sig = await getSignature(browser_download_url);
updateData.platforms.darwin.signature = sig;
updateData.platforms["darwin-intel"].signature = sig;
}
// darwin url (aarch)
if (name.endsWith("aarch.app.tar.gz")) {
updateData.platforms["darwin-aarch64"].url = browser_download_url;
}
// darwin signature (aarch)
if (name.endsWith("aarch.app.tar.gz.sig")) {
const sig = await getSignature(browser_download_url);
updateData.platforms["darwin-aarch64"].signature = sig;
}
// linux url
if (name.endsWith(".AppImage.tar.gz")) {
updateData.platforms.linux.url = browser_download_url;
updateData.platforms["linux-x86_64"].url = browser_download_url;
}
// linux signature
if (name.endsWith(".AppImage.tar.gz.sig")) {
const sig = await getSignature(browser_download_url);
updateData.platforms.linux.signature = sig;
updateData.platforms["linux-x86_64"].signature = sig;
}
});
await Promise.allSettled(promises);
console.log(updateData);
// maybe should test the signature as well
// delete the null field
Object.entries(updateData.platforms).forEach(([key, value]) => {
if (!value.url) {
console.log(`[Error]: failed to parse release for "${key}"`);
delete updateData.platforms[key];
}
});
// 生成一个代理github的更新文件
// 使用 https://hub.fastgit.xyz/ 做github资源的加速
const updateDataNew = JSON.parse(JSON.stringify(updateData));
Object.entries(updateDataNew.platforms).forEach(([key, value]) => {
if (value.url) {
updateDataNew.platforms[key].url = value.url.replace(
"https://github.com/",
"https://hub.fastgit.xyz/"
);
} else {
console.log(`[Error]: updateDataNew.platforms.${key} is null`);
}
});
// update the update.json
const { data: updateRelease } = await github.rest.repos.getReleaseByTag({
...options,
tag: UPDATE_TAG_NAME,
});
// delete the old assets
for (let asset of updateRelease.assets) {
if (asset.name === UPDATE_JSON_FILE) {
await github.rest.repos.deleteReleaseAsset({
...options,
asset_id: asset.id,
});
}
if (asset.name === UPDATE_JSON_PROXY) {
await github.rest.repos
.deleteReleaseAsset({ ...options, asset_id: asset.id })
.catch(console.error); // do not break the pipeline
}
}
// upload new assets
await github.rest.repos.uploadReleaseAsset({
...options,
release_id: updateRelease.id,
name: UPDATE_JSON_FILE,
data: JSON.stringify(updateData, null, 2),
});
await github.rest.repos.uploadReleaseAsset({
...options,
release_id: updateRelease.id,
name: UPDATE_JSON_PROXY,
data: JSON.stringify(updateDataNew, null, 2),
});
}
// get the signature file content
async function getSignature(url) {
const response = await fetch(url, {
method: "GET",
headers: { "Content-Type": "application/octet-stream" },
});
return response.text();
}
resolveUpdater().catch(console.error);

View File

@@ -2,5 +2,5 @@
# will have compiled files and executables # will have compiled files and executables
/target/ /target/
WixTools WixTools
resources/Country.mmdb resources
sidecar sidecar

946
src-tauri/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -10,18 +10,19 @@ edition = "2021"
build = "build.rs" build = "build.rs"
[build-dependencies] [build-dependencies]
tauri-build = { version = "1.0.0-rc.4", features = [] } tauri-build = { version = "1.0.0-rc.5", features = [] }
[dependencies] [dependencies]
anyhow = "1.0" anyhow = "1.0"
dirs = "4.0.0" dirs = "4.0.0"
open = "2.1.1"
dunce = "1.0.2" dunce = "1.0.2"
nanoid = "0.4.0" nanoid = "0.4.0"
chrono = "0.4.19" 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-rc.4", features = ["shell-all", "system-tray", "updater", "window-all"] } tauri = { version = "1.0.0-rc.6", features = ["process-all", "shell-all", "system-tray", "updater", "window-all"] }
window-shadows = { git = "https://github.com/tauri-apps/window-shadows" } window-shadows = { git = "https://github.com/tauri-apps/window-shadows" }
window-vibrancy = { git = "https://github.com/tauri-apps/window-vibrancy" } window-vibrancy = { git = "https://github.com/tauri-apps/window-vibrancy" }
@@ -40,3 +41,11 @@ winreg = { version = "0.10", features = ["transactions"] }
[features] [features]
default = [ "custom-protocol" ] default = [ "custom-protocol" ]
custom-protocol = [ "tauri/custom-protocol" ] custom-protocol = [ "tauri/custom-protocol" ]
verge-dev = []
debug-yml = []
[profile.release]
panic = "abort"
codegen-units = 1
lto = true
opt-level = "s"

View File

@@ -6,7 +6,7 @@ use crate::{
use crate::{ret_err, wrap_err}; use crate::{ret_err, wrap_err};
use anyhow::Result; use anyhow::Result;
use serde_yaml::Mapping; use serde_yaml::Mapping;
use std::{path::PathBuf, process::Command}; use std::process::Command;
use tauri::{api, Manager, State}; use tauri::{api, Manager, State};
/// get all profiles from `profiles.yaml` /// get all profiles from `profiles.yaml`
@@ -43,9 +43,10 @@ pub async fn import_profile(
#[tauri::command] #[tauri::command]
pub async fn create_profile( pub async fn create_profile(
item: PrfItem, // partial item: PrfItem, // partial
file_data: Option<String>,
profiles_state: State<'_, ProfilesState>, profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> { ) -> Result<(), String> {
let item = wrap_err!(PrfItem::from(item).await)?; let item = wrap_err!(PrfItem::from(item, file_data).await)?;
let mut profiles = profiles_state.0.lock().unwrap(); let mut profiles = profiles_state.0.lock().unwrap();
wrap_err!(profiles.append_item(item)) wrap_err!(profiles.append_item(item))
@@ -59,19 +60,27 @@ pub async fn update_profile(
clash_state: State<'_, ClashState>, clash_state: State<'_, ClashState>,
profiles_state: State<'_, ProfilesState>, profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> { ) -> Result<(), String> {
let url = { let (url, opt) = {
// must release the lock here // must release the lock here
let profiles = profiles_state.0.lock().unwrap(); let profiles = profiles_state.0.lock().unwrap();
let item = wrap_err!(profiles.get_item(&index))?; let item = wrap_err!(profiles.get_item(&index))?;
// check the profile type
if let Some(typ) = item.itype.as_ref() {
if *typ != "remote" {
ret_err!(format!("could not update the `{typ}` profile"));
}
}
if item.url.is_none() { if item.url.is_none() {
ret_err!("failed to get the item url"); ret_err!("failed to get the item url");
} }
item.url.clone().unwrap() (item.url.clone().unwrap(), item.option.clone())
}; };
let item = wrap_err!(PrfItem::from_url(&url, None, None, option).await)?; let fetch_opt = PrfOption::merge(opt, option);
let item = wrap_err!(PrfItem::from_url(&url, None, None, fetch_opt).await)?;
let mut profiles = profiles_state.0.lock().unwrap(); let mut profiles = profiles_state.0.lock().unwrap();
wrap_err!(profiles.update_item(index.clone(), item))?; wrap_err!(profiles.update_item(index.clone(), item))?;
@@ -79,7 +88,7 @@ pub async fn update_profile(
// reactivate the profile // reactivate the profile
if Some(index) == profiles.get_current() { if Some(index) == profiles.get_current() {
let clash = clash_state.0.lock().unwrap(); let clash = clash_state.0.lock().unwrap();
wrap_err!(clash.activate(&profiles, false))?; wrap_err!(clash.activate_enhanced(&profiles, false, false))?;
} }
Ok(()) Ok(())
@@ -96,7 +105,7 @@ pub fn select_profile(
wrap_err!(profiles.put_current(index))?; wrap_err!(profiles.put_current(index))?;
let clash = clash_state.0.lock().unwrap(); let clash = clash_state.0.lock().unwrap();
wrap_err!(clash.activate(&profiles, false)) wrap_err!(clash.activate_enhanced(&profiles, false, false))
} }
/// change the profile chain /// change the profile chain
@@ -113,7 +122,24 @@ pub fn change_profile_chain(
profiles.put_chain(chain); profiles.put_chain(chain);
clash.set_window(app_handle.get_window("main")); clash.set_window(app_handle.get_window("main"));
wrap_err!(clash.activate_enhanced(&profiles, false)) wrap_err!(clash.activate_enhanced(&profiles, false, false))
}
/// change the profile valid fields
#[tauri::command]
pub fn change_profile_valid(
valid: Option<Vec<String>>,
app_handle: tauri::AppHandle,
clash_state: State<'_, ClashState>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let mut clash = clash_state.0.lock().unwrap();
let mut profiles = profiles_state.0.lock().unwrap();
profiles.put_valid(valid);
clash.set_window(app_handle.get_window("main"));
wrap_err!(clash.activate_enhanced(&profiles, false, false))
} }
/// manually exec enhanced profile /// manually exec enhanced profile
@@ -128,7 +154,7 @@ pub fn enhance_profiles(
clash.set_window(app_handle.get_window("main")); clash.set_window(app_handle.get_window("main"));
wrap_err!(clash.activate_enhanced(&profiles, false)) wrap_err!(clash.activate_enhanced(&profiles, false, false))
} }
/// delete profile item /// delete profile item
@@ -142,7 +168,7 @@ pub fn delete_profile(
if wrap_err!(profiles.delete_item(index))? { if wrap_err!(profiles.delete_item(index))? {
let clash = clash_state.0.lock().unwrap(); let clash = clash_state.0.lock().unwrap();
wrap_err!(clash.activate(&profiles, false))?; wrap_err!(clash.activate_enhanced(&profiles, false, false))?;
} }
Ok(()) Ok(())
@@ -186,21 +212,50 @@ pub fn view_profile(index: String, profiles_state: State<'_, ProfilesState>) ->
.arg(path) .arg(path)
.spawn() .spawn()
{ {
log::error!("{err}"); log::error!("failed to open file by VScode for {err}");
return Err("failed to open file by VScode".into()); return Err("failed to open file by VScode".into());
} }
} }
#[cfg(not(target_os = "windows"))] #[cfg(not(target_os = "windows"))]
if let Err(err) = Command::new(code).arg(path).spawn() { if let Err(err) = Command::new(code).arg(path).spawn() {
log::error!("{err}"); log::error!("failed to open file by VScode for {err}");
return Err("failed to open file by VScode".into()); return Err("failed to open file by VScode".into());
} }
return Ok(()); return Ok(());
} }
open_path_cmd(path, "failed to open file by `open`") wrap_err!(open::that(path))
}
/// read the profile item file data
#[tauri::command]
pub fn read_profile_file(
index: String,
profiles_state: State<'_, ProfilesState>,
) -> Result<String, String> {
let profiles = profiles_state.0.lock().unwrap();
let item = wrap_err!(profiles.get_item(&index))?;
let data = wrap_err!(item.read_file())?;
Ok(data)
}
/// save the profile item file data
#[tauri::command]
pub fn save_profile_file(
index: String,
file_data: Option<String>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
if file_data.is_none() {
return Ok(());
}
let profiles = profiles_state.0.lock().unwrap();
let item = wrap_err!(profiles.get_item(&index))?;
wrap_err!(item.save_file(file_data.unwrap()))
} }
/// restart the sidecar /// restart the sidecar
@@ -271,23 +326,37 @@ pub fn get_verge_config(verge_state: State<'_, VergeState>) -> Result<VergeConfi
#[tauri::command] #[tauri::command]
pub fn patch_verge_config( pub fn patch_verge_config(
payload: VergeConfig, payload: VergeConfig,
app_handle: tauri::AppHandle,
clash_state: State<'_, ClashState>, clash_state: State<'_, ClashState>,
verge_state: State<'_, VergeState>, verge_state: State<'_, VergeState>,
profiles_state: State<'_, ProfilesState>, profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> { ) -> Result<(), String> {
let tun_mode = payload.enable_tun_mode.clone(); let tun_mode = payload.enable_tun_mode.clone();
let system_proxy = payload.enable_system_proxy.clone();
let mut verge = verge_state.0.lock().unwrap(); let mut verge = verge_state.0.lock().unwrap();
wrap_err!(verge.patch_config(payload))?; wrap_err!(verge.patch_config(payload))?;
// change tun mode // change tun mode
if tun_mode.is_some() { if tun_mode.is_some() {
let mut clash = clash_state.0.lock().unwrap(); #[cfg(target_os = "windows")]
if *tun_mode.as_ref().unwrap() {
let wintun_dll = dirs::app_home_dir().join("wintun.dll");
if !wintun_dll.exists() {
log::error!("failed to enable TUN for missing `wintun.dll`");
return Err("failed to enable TUN for missing `wintun.dll`".into());
}
}
let clash = clash_state.0.lock().unwrap();
let profiles = profiles_state.0.lock().unwrap(); let profiles = profiles_state.0.lock().unwrap();
wrap_err!(clash.tun_mode(tun_mode.unwrap()))?; wrap_err!(clash.activate_enhanced(&profiles, false, false))?;
clash.update_config(); }
wrap_err!(clash.activate(&profiles, false))?;
// change system tray
if system_proxy.is_some() || tun_mode.is_some() {
verge.update_systray(&app_handle).unwrap();
} }
Ok(()) Ok(())
@@ -303,37 +372,12 @@ pub fn kill_sidecars() {
#[tauri::command] #[tauri::command]
pub fn open_app_dir() -> Result<(), String> { pub fn open_app_dir() -> Result<(), String> {
let app_dir = dirs::app_home_dir(); let app_dir = dirs::app_home_dir();
open_path_cmd(app_dir, "failed to open app dir") wrap_err!(open::that(app_dir))
} }
/// open logs dir /// open logs dir
#[tauri::command] #[tauri::command]
pub fn open_logs_dir() -> Result<(), String> { pub fn open_logs_dir() -> Result<(), String> {
let log_dir = dirs::app_logs_dir(); let log_dir = dirs::app_logs_dir();
open_path_cmd(log_dir, "failed to open logs dir") wrap_err!(open::that(log_dir))
}
/// get open/explorer command
fn open_path_cmd(dir: PathBuf, err_str: &str) -> Result<(), String> {
#[cfg(target_os = "windows")]
{
use std::os::windows::process::CommandExt;
if let Err(err) = Command::new("explorer")
.creation_flags(0x08000000)
.arg(dir)
.spawn()
{
log::error!("{err}");
return Err(err_str.into());
}
}
#[cfg(not(target_os = "windows"))]
if let Err(err) = Command::new("open").arg(dir).spawn() {
log::error!("{err}");
return Err(err_str.into());
}
return Ok(());
} }

View File

@@ -1,4 +1,5 @@
use super::{PrfEnhancedResult, Profiles, Verge}; use super::{PrfEnhancedResult, Profiles, Verge, VergeConfig};
use crate::log_if_err;
use crate::utils::{config, dirs, help}; use crate::utils::{config, dirs, help};
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use reqwest::header::HeaderMap; use reqwest::header::HeaderMap;
@@ -95,7 +96,18 @@ impl Clash {
let server = match clash_config.get(&key_server) { let server = match clash_config.get(&key_server) {
Some(value) => match value { Some(value) => match value {
Value::String(val_str) => Some(val_str.clone()), Value::String(val_str) => {
// `external-controller` could be
// "127.0.0.1:9090" or ":9090"
// Todo: maybe it could support single port
let server = val_str.clone();
let server = match server.starts_with(":") {
true => format!("127.0.0.1{server}"),
false => server,
};
Some(server)
}
_ => None, _ => None,
}, },
_ => None, _ => None,
@@ -165,7 +177,8 @@ impl Clash {
self.update_config(); self.update_config();
self.drop_sidecar()?; self.drop_sidecar()?;
self.run_sidecar()?; self.run_sidecar()?;
self.activate(profiles, false) self.activate(profiles)?;
self.activate_enhanced(profiles, false, true)
} }
/// update the clash info /// update the clash info
@@ -181,91 +194,123 @@ impl Clash {
verge: &mut Verge, verge: &mut Verge,
profiles: &mut Profiles, profiles: &mut Profiles,
) -> Result<()> { ) -> Result<()> {
for (key, value) in patch.iter() { let mix_port_key = Value::from("mixed-port");
let mut port = None;
for (key, value) in patch.into_iter() {
let value = value.clone(); let value = value.clone();
let key_str = key.as_str().clone().unwrap_or("");
// restart the clash // check whether the mix_port is changed
if key_str == "mixed-port" { if key == mix_port_key {
self.restart_sidecar(profiles)?; if value.is_number() {
port = value.as_i64().as_ref().map(|n| n.to_string());
let port = if value.is_number() {
match value.as_i64().clone() {
Some(num) => Some(format!("{num}")),
None => None,
}
} else { } else {
match value.as_str().clone() { port = value.as_str().as_ref().map(|s| s.to_string());
Some(num) => Some(num.into()), }
None => None,
}
};
verge.init_sysproxy(port);
} }
self.config.insert(key.clone(), value); self.config.insert(key.clone(), value);
} }
self.save_config()
}
/// enable tun mode self.save_config()?;
/// only revise the config and restart the
pub fn tun_mode(&mut self, enable: bool) -> Result<()> {
let tun_key = Value::String("tun".into());
let tun_val = self.config.get(&tun_key);
let mut new_val = Mapping::new(); if let Some(port) = port {
self.restart_sidecar(profiles)?;
if tun_val.is_some() && tun_val.as_ref().unwrap().is_mapping() { verge.init_sysproxy(Some(port));
new_val = tun_val.as_ref().unwrap().as_mapping().unwrap().clone();
} }
Ok(())
}
/// revise the `tun` and `dns` config
fn _tun_mode(mut config: Mapping, enable: bool) -> Mapping {
macro_rules! revise { macro_rules! revise {
($map: expr, $key: expr, $val: expr) => { ($map: expr, $key: expr, $val: expr) => {
let ret_key = Value::String($key.into()); let ret_key = Value::String($key.into());
if $map.contains_key(&ret_key) { $map.insert(ret_key, Value::from($val));
$map[&ret_key] = $val;
} else {
$map.insert(ret_key, $val);
}
}; };
} }
// if key not exists then append value
macro_rules! append { macro_rules! append {
($map: expr, $key: expr, $val: expr) => { ($map: expr, $key: expr, $val: expr) => {
let ret_key = Value::String($key.into()); let ret_key = Value::String($key.into());
if !$map.contains_key(&ret_key) { if !$map.contains_key(&ret_key) {
$map.insert(ret_key, $val); $map.insert(ret_key, Value::from($val));
} }
}; };
} }
revise!(new_val, "enable", Value::from(enable)); // tun config
append!(new_val, "stack", Value::from("gvisor")); let tun_val = config.get(&Value::from("tun"));
append!(new_val, "auto-route", Value::from(true)); let mut new_tun = Mapping::new();
append!(new_val, "auto-detect-interface", Value::from(true));
revise!(self.config, "tun", Value::from(new_val)); if tun_val.is_some() && tun_val.as_ref().unwrap().is_mapping() {
new_tun = tun_val.as_ref().unwrap().as_mapping().unwrap().clone();
}
self.save_config() revise!(new_tun, "enable", enable);
if enable {
append!(new_tun, "stack", "gvisor");
append!(new_tun, "dns-hijack", vec!["198.18.0.2:53"]);
append!(new_tun, "auto-route", true);
append!(new_tun, "auto-detect-interface", true);
}
revise!(config, "tun", new_tun);
// dns config
let dns_val = config.get(&Value::from("dns"));
let mut new_dns = Mapping::new();
if dns_val.is_some() && dns_val.as_ref().unwrap().is_mapping() {
new_dns = dns_val.as_ref().unwrap().as_mapping().unwrap().clone();
}
// 借鉴cfw的默认配置
revise!(new_dns, "enable", enable);
if enable {
append!(new_dns, "enhanced-mode", "fake-ip");
append!(
new_dns,
"nameserver",
vec!["114.114.114.114", "223.5.5.5", "8.8.8.8"]
);
append!(new_dns, "fallback", vec![] as Vec<&str>);
#[cfg(target_os = "windows")]
append!(
new_dns,
"fake-ip-filter",
vec![
"dns.msftncsi.com",
"www.msftncsi.com",
"www.msftconnecttest.com"
]
);
}
revise!(config, "dns", new_dns);
config
} }
/// activate the profile /// activate the profile
/// generate a new profile to the temp_dir /// generate a new profile to the temp_dir
/// then put the path to the clash core /// then put the path to the clash core
fn _activate(info: ClashInfo, config: Mapping) -> Result<()> { fn _activate(info: ClashInfo, config: Mapping, window: Option<Window>) -> Result<()> {
let verge_config = VergeConfig::new();
let tun_enable = verge_config.enable_tun_mode.unwrap_or(false);
let config = Clash::_tun_mode(config, tun_enable);
let temp_path = dirs::profiles_temp_path(); let temp_path = dirs::profiles_temp_path();
config::save_yaml(temp_path.clone(), &config, Some("# Clash Verge Temp File"))?; config::save_yaml(temp_path.clone(), &config, Some("# Clash Verge Temp File"))?;
tauri::async_runtime::spawn(async move { tauri::async_runtime::spawn(async move {
// `external-controller` could be
// "127.0.0.1:9090" or ":9090"
// Todo: maybe it could support single port
let server = info.server.unwrap(); let server = info.server.unwrap();
let server = match server.starts_with(":") { let server = format!("http://{server}/configs");
true => format!("http://127.0.0.1{server}/configs"),
false => format!("http://{server}/configs"),
};
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());
@@ -289,6 +334,12 @@ impl Clash {
if resp.status() != 204 { if resp.status() != 204 {
log::error!("failed to activate clash for status \"{}\"", resp.status()); log::error!("failed to activate clash for status \"{}\"", resp.status());
} }
// emit the window to update something
if let Some(window) = window {
window.emit("verge://refresh-clash-config", "yes").unwrap();
}
// do not retry // do not retry
break; break;
} }
@@ -305,55 +356,57 @@ impl Clash {
} }
/// enhanced profiles mode /// enhanced profiles mode
/// only change the enhanced profiles /// - (sync) refresh config if enhance chain is null
pub fn activate_enhanced(&self, profiles: &Profiles, delay: bool) -> Result<()> { /// - (async) enhanced config
pub fn activate_enhanced(&self, profiles: &Profiles, delay: bool, skip: bool) -> Result<()> {
if self.window.is_none() { if self.window.is_none() {
bail!("failed to get the main window"); bail!("failed to get the main window");
} }
let win = self.window.clone().unwrap();
let event_name = help::get_uid("e"); let event_name = help::get_uid("e");
let event_name = format!("enhanced-cb-{event_name}"); let event_name = format!("enhanced-cb-{event_name}");
let info = self.info.clone();
let mut config = self.config.clone();
// generate the payload // generate the payload
let payload = profiles.gen_enhanced(event_name.clone())?; let payload = profiles.gen_enhanced(event_name.clone())?;
win.once(&event_name, move |event| { let info = self.info.clone();
// do not run enhanced
if payload.chain.len() == 0 {
if skip {
return Ok(());
}
let mut config = self.config.clone();
let filter_data = Clash::strict_filter(payload.current);
for (key, value) in filter_data.into_iter() {
config.insert(key, value);
}
return Clash::_activate(info, config, self.window.clone());
}
let window = self.window.clone().unwrap();
let window_move = self.window.clone();
window.once(&event_name, move |event| {
if let Some(result) = event.payload() { if let Some(result) = event.payload() {
let result: PrfEnhancedResult = serde_json::from_str(result).unwrap(); let result: PrfEnhancedResult = serde_json::from_str(result).unwrap();
if let Some(data) = result.data { if let Some(data) = result.data {
// all of these can not be revised by script let mut config = Clash::read_config();
// http/https/socks port should be under control let filter_data = Clash::loose_filter(data); // loose filter
let not_allow: Vec<Value> = vec![
"port",
"socks-port",
"mixed-port",
"allow-lan",
"mode",
"external-controller",
"secret",
"log-level",
]
.iter()
.map(|&i| Value::from(i))
.collect();
for (key, value) in data.into_iter() { for (key, value) in filter_data.into_iter() {
if not_allow.iter().find(|&i| i == &key).is_none() { config.insert(key, value);
config.insert(key, value);
}
} }
Self::_activate(info, config).unwrap(); log_if_err!(Clash::_activate(info, config, window_move));
log::info!("profile enhanced status {}", result.status);
} }
log::info!("profile enhanced status {}", result.status); result.error.map(|err| log::error!("{err}"));
result.error.map(|error| log::error!("{error}"));
} }
}); });
@@ -362,7 +415,7 @@ impl Clash {
if delay { if delay {
sleep(Duration::from_secs(2)).await; sleep(Duration::from_secs(2)).await;
} }
win.emit("script-handler", payload).unwrap(); window.emit("script-handler", payload).unwrap();
}); });
Ok(()) Ok(())
@@ -370,17 +423,83 @@ impl Clash {
/// activate the profile /// activate the profile
/// auto activate enhanced profile /// auto activate enhanced profile
pub fn activate(&self, profiles: &Profiles, delay: bool) -> Result<()> { pub fn activate(&self, profiles: &Profiles) -> Result<()> {
let gen_map = profiles.gen_activate()?; let data = profiles.gen_activate()?;
let data = Clash::strict_filter(data);
let info = self.info.clone(); let info = self.info.clone();
let mut config = self.config.clone(); let mut config = self.config.clone();
for (key, value) in gen_map.into_iter() { for (key, value) in data.into_iter() {
config.insert(key, value); config.insert(key, value);
} }
Self::_activate(info, config)?; Clash::_activate(info, config, self.window.clone())
self.activate_enhanced(profiles, delay) }
/// only 5 default fields available (clash config fields)
/// convert to lowercase
fn strict_filter(config: Mapping) -> Mapping {
// Only the following fields are allowed:
// proxies/proxy-providers/proxy-groups/rule-providers/rules
let valid_keys = vec![
"proxies",
"proxy-providers",
"proxy-groups",
"rules",
"rule-providers",
];
let mut new_config = Mapping::new();
for (key, value) in config.into_iter() {
key.as_str().map(|key_str| {
// change to lowercase
let mut key_str = String::from(key_str);
key_str.make_ascii_lowercase();
// filter
if valid_keys.contains(&&*key_str) {
new_config.insert(Value::String(key_str), value);
}
});
}
new_config
}
/// more clash config fields available
/// convert to lowercase
fn loose_filter(config: Mapping) -> Mapping {
// all of these can not be revised by script or merge
// http/https/socks port should be under control
let not_allow = vec![
"port",
"socks-port",
"mixed-port",
"allow-lan",
"mode",
"external-controller",
"secret",
"log-level",
];
let mut new_config = Mapping::new();
for (key, value) in config.into_iter() {
key.as_str().map(|key_str| {
// change to lowercase
let mut key_str = String::from(key_str);
key_str.make_ascii_lowercase();
// filter
if !not_allow.contains(&&*key_str) {
new_config.insert(Value::String(key_str), value);
}
});
}
new_config
} }
} }

View File

@@ -1,7 +1,7 @@
use crate::utils::{config, dirs, help, tmpl}; use crate::utils::{config, dirs, help, tmpl};
use anyhow::{bail, Context, Result}; use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_yaml::{Mapping, Value}; use serde_yaml::Mapping;
use std::{fs, io::Write}; use std::{fs, io::Write};
#[derive(Debug, Clone, Deserialize, Serialize)] #[derive(Debug, Clone, Deserialize, Serialize)]
@@ -73,6 +73,31 @@ pub struct PrfOption {
pub with_proxy: Option<bool>, pub with_proxy: Option<bool>,
} }
impl PrfOption {
pub fn merge(one: Option<Self>, other: Option<Self>) -> Option<Self> {
if one.is_some() && other.is_some() {
let mut one = one.unwrap();
let other = other.unwrap();
if let Some(val) = other.user_agent {
one.user_agent = Some(val);
}
if let Some(val) = other.with_proxy {
one.with_proxy = Some(val);
}
return Some(one);
}
if one.is_none() {
return other;
}
return one;
}
}
impl Default for PrfItem { impl Default for PrfItem {
fn default() -> Self { fn default() -> Self {
PrfItem { PrfItem {
@@ -94,7 +119,7 @@ impl Default for PrfItem {
impl PrfItem { impl PrfItem {
/// From partial item /// From partial item
/// must contain `itype` /// must contain `itype`
pub async fn from(item: PrfItem) -> Result<PrfItem> { pub async fn from(item: PrfItem, file_data: Option<String>) -> Result<PrfItem> {
if item.itype.is_none() { if item.itype.is_none() {
bail!("type should not be null"); bail!("type should not be null");
} }
@@ -112,7 +137,7 @@ impl PrfItem {
"local" => { "local" => {
let name = item.name.unwrap_or("Local File".into()); let name = item.name.unwrap_or("Local File".into());
let desc = item.desc.unwrap_or("".into()); let desc = item.desc.unwrap_or("".into());
PrfItem::from_local(name, desc) PrfItem::from_local(name, desc, file_data)
} }
"merge" => { "merge" => {
let name = item.name.unwrap_or("Merge".into()); let name = item.name.unwrap_or("Merge".into());
@@ -130,7 +155,7 @@ impl PrfItem {
/// ## Local type /// ## Local type
/// create a new item from name/desc /// create a new item from name/desc
pub fn from_local(name: String, desc: String) -> Result<PrfItem> { pub fn from_local(name: String, desc: String, file_data: Option<String>) -> Result<PrfItem> {
let uid = help::get_uid("l"); let uid = help::get_uid("l");
let file = format!("{uid}.yaml"); let file = format!("{uid}.yaml");
@@ -145,7 +170,7 @@ impl PrfItem {
extra: None, extra: None,
option: None, option: None,
updated: Some(help::get_now()), updated: Some(help::get_now()),
file_data: Some(tmpl::ITEM_LOCAL.into()), file_data: Some(file_data.unwrap_or(tmpl::ITEM_LOCAL.into())),
}) })
} }
@@ -171,9 +196,8 @@ impl PrfItem {
if !with_proxy { if !with_proxy {
builder = builder.no_proxy(); builder = builder.no_proxy();
} }
if let Some(user_agent) = user_agent {
builder = builder.user_agent(user_agent); builder = builder.user_agent(user_agent.unwrap_or("clash-verge/v0.1.0".into()));
}
let resp = builder.build()?.get(url).send().await?; let resp = builder.build()?.get(url).send().await?;
let header = resp.headers(); let header = resp.headers();
@@ -254,6 +278,28 @@ impl PrfItem {
file_data: Some(tmpl::ITEM_SCRIPT.into()), file_data: Some(tmpl::ITEM_SCRIPT.into()),
}) })
} }
/// get the file data
pub fn read_file(&self) -> Result<String> {
if self.file.is_none() {
bail!("could not find the file");
}
let file = self.file.clone().unwrap();
let path = dirs::app_profiles_dir().join(file);
fs::read_to_string(path).context("failed to read the file")
}
/// save the file data
pub fn save_file(&self, data: String) -> Result<()> {
if self.file.is_none() {
bail!("could not find the file");
}
let file = self.file.clone().unwrap();
let path = dirs::app_profiles_dir().join(file);
fs::write(path, data.as_bytes()).context("failed to save the file")
}
} }
/// ///
@@ -269,6 +315,9 @@ pub struct Profiles {
/// same as PrfConfig.chain /// same as PrfConfig.chain
chain: Option<Vec<String>>, chain: Option<Vec<String>>,
/// record valid fields for clash
valid: Option<Vec<String>>,
/// profile list /// profile list
items: Option<Vec<PrfItem>>, items: Option<Vec<PrfItem>>,
} }
@@ -352,6 +401,11 @@ impl Profiles {
self.chain = chain; self.chain = chain;
} }
/// just change the `field`
pub fn put_valid(&mut self, valid: Option<Vec<String>>) {
self.valid = valid;
}
/// find the item by the uid /// find the item by the uid
pub fn get_item(&self, uid: &String) -> Result<&PrfItem> { pub fn get_item(&self, uid: &String) -> Result<&PrfItem> {
if self.items.is_some() { if self.items.is_some() {
@@ -414,9 +468,7 @@ impl Profiles {
patch!(each, item, selected); patch!(each, item, selected);
patch!(each, item, extra); patch!(each, item, extra);
patch!(each, item, updated); patch!(each, item, updated);
patch!(each, item, option);
// can be removed
each.option = item.option;
self.items = Some(items); self.items = Some(items);
return self.save_file(); return self.save_file();
@@ -530,28 +582,7 @@ impl Profiles {
bail!("failed to read the file \"{}\"", file_path.display()); bail!("failed to read the file \"{}\"", file_path.display());
} }
let mut new_config = Mapping::new(); return Ok(config::read_yaml::<Mapping>(file_path.clone()));
let def_config = config::read_yaml::<Mapping>(file_path.clone());
// Only the following fields are allowed:
// proxies/proxy-providers/proxy-groups/rule-providers/rules
let valid_keys = vec![
"proxies",
"proxy-providers",
"proxy-groups",
"rule-providers",
"rules",
];
valid_keys.iter().for_each(|key| {
let key = Value::String(key.to_string());
if def_config.contains_key(&key) {
let value = def_config[&key].clone();
new_config.insert(key, value);
}
});
return Ok(new_config);
} }
} }
@@ -575,9 +606,12 @@ impl Profiles {
None => vec![], None => vec![],
}; };
let valid = self.valid.clone().unwrap_or(vec![]);
Ok(PrfEnhanced { Ok(PrfEnhanced {
current, current,
chain, chain,
valid,
callback, callback,
}) })
} }
@@ -585,11 +619,13 @@ impl Profiles {
#[derive(Default, Debug, Clone, Serialize, Deserialize)] #[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct PrfEnhanced { pub struct PrfEnhanced {
current: Mapping, pub current: Mapping,
chain: Vec<PrfData>, pub chain: Vec<PrfData>,
callback: String, pub valid: Vec<String>,
pub callback: String,
} }
#[derive(Default, Debug, Clone, Serialize, Deserialize)] #[derive(Default, Debug, Clone, Serialize, Deserialize)]

View File

@@ -1,6 +1,6 @@
use crate::log_if_err;
use crate::{ use crate::{
core::Clash, core::Clash,
log_if_err,
utils::{config, dirs, sysopt::SysProxyConfig}, utils::{config, dirs, sysopt::SysProxyConfig},
}; };
use anyhow::{bail, Result}; use anyhow::{bail, Result};
@@ -8,10 +8,14 @@ use auto_launch::{AutoLaunch, AutoLaunchBuilder};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::sync::Arc; use std::sync::Arc;
use tauri::{async_runtime::Mutex, utils::platform::current_exe}; use tauri::{async_runtime::Mutex, utils::platform::current_exe};
use tauri::{AppHandle, Manager};
/// ### `verge.yaml` schema /// ### `verge.yaml` schema
#[derive(Default, Debug, Clone, Deserialize, Serialize)] #[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct VergeConfig { pub struct VergeConfig {
// i18n
pub language: Option<String>,
/// `light` or `dark` /// `light` or `dark`
pub theme_mode: Option<String>, pub theme_mode: Option<String>,
@@ -28,6 +32,9 @@ pub struct VergeConfig {
/// can the app auto startup /// can the app auto startup
pub enable_auto_launch: Option<bool>, pub enable_auto_launch: Option<bool>,
/// not show the window on launch
pub enable_silent_start: Option<bool>,
/// set system proxy /// set system proxy
pub enable_system_proxy: Option<bool>, pub enable_system_proxy: Option<bool>,
@@ -39,6 +46,25 @@ pub struct VergeConfig {
/// proxy guard duration /// proxy guard duration
pub proxy_guard_duration: Option<u64>, pub proxy_guard_duration: Option<u64>,
/// theme setting
pub theme_setting: Option<VergeTheme>,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct VergeTheme {
pub primary_color: Option<String>,
pub secondary_color: Option<String>,
pub primary_text: Option<String>,
pub secondary_text: Option<String>,
pub info_color: Option<String>,
pub error_color: Option<String>,
pub warning_color: Option<String>,
pub success_color: Option<String>,
pub font_family: Option<String>,
pub css_injection: Option<String>,
} }
impl VergeConfig { impl VergeConfig {
@@ -124,43 +150,37 @@ impl Verge {
if let Some(sysproxy) = self.old_sysproxy.take() { if let Some(sysproxy) = self.old_sysproxy.take() {
match sysproxy.set_sys() { match sysproxy.set_sys() {
Ok(_) => self.cur_sysproxy = None, Ok(_) => self.cur_sysproxy = None,
Err(_) => log::error!("failed to reset proxy for"), Err(_) => log::error!("failed to reset proxy"),
} }
} }
} }
/// init the auto launch /// init the auto launch
pub fn init_launch(&mut self) { pub fn init_launch(&mut self) -> Result<()> {
let app_exe = current_exe().unwrap(); let app_exe = current_exe().unwrap();
let app_exe = dunce::canonicalize(app_exe).unwrap(); let app_exe = dunce::canonicalize(app_exe).unwrap();
let app_name = app_exe.file_stem().unwrap().to_str().unwrap(); let app_name = app_exe.file_stem().unwrap().to_str().unwrap();
let app_path = app_exe.as_os_str().to_str().unwrap(); let app_path = app_exe.as_os_str().to_str().unwrap();
// fix issue #26
#[cfg(target_os = "windows")]
let app_path = format!("\"{app_path}\"");
#[cfg(target_os = "windows")]
let app_path = app_path.as_str();
let auto = AutoLaunchBuilder::new() let auto = AutoLaunchBuilder::new()
.set_app_name(app_name) .set_app_name(app_name)
.set_app_path(app_path) .set_app_path(app_path)
.build(); .build();
if let Some(enable) = self.config.enable_auto_launch.as_ref() {
// fix issue #26
if *enable {
auto.enable()?;
}
}
self.auto_launch = Some(auto); self.auto_launch = Some(auto);
}
/// sync the startup when run the app
pub fn sync_launch(&self) -> Result<()> {
let enable = self.config.enable_auto_launch.clone().unwrap_or(false);
if !enable {
return Ok(());
}
if self.auto_launch.is_none() {
bail!("should init the auto launch first");
}
let auto_launch = self.auto_launch.clone().unwrap();
let is_enabled = auto_launch.is_enabled().unwrap_or(false);
if !is_enabled {
auto_launch.enable()?;
}
Ok(()) Ok(())
} }
@@ -188,6 +208,9 @@ impl Verge {
/// so call the save_file at the end is savely /// so call the save_file at the end is savely
pub fn patch_config(&mut self, patch: VergeConfig) -> Result<()> { pub fn patch_config(&mut self, patch: VergeConfig) -> Result<()> {
// only change it // only change it
if patch.language.is_some() {
self.config.language = patch.language;
}
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;
} }
@@ -197,6 +220,12 @@ impl Verge {
if patch.traffic_graph.is_some() { if patch.traffic_graph.is_some() {
self.config.traffic_graph = patch.traffic_graph; self.config.traffic_graph = patch.traffic_graph;
} }
if patch.enable_silent_start.is_some() {
self.config.enable_silent_start = patch.enable_silent_start;
}
if patch.theme_setting.is_some() {
self.config.theme_setting = patch.theme_setting;
}
// should update system startup // should update system startup
if patch.enable_auto_launch.is_some() { if patch.enable_auto_launch.is_some() {
@@ -214,7 +243,6 @@ impl Verge {
if sysproxy.set_sys().is_err() { if sysproxy.set_sys().is_err() {
self.cur_sysproxy = Some(sysproxy); self.cur_sysproxy = Some(sysproxy);
log::error!("failed to set system proxy");
bail!("failed to set system proxy"); bail!("failed to set system proxy");
} }
self.cur_sysproxy = Some(sysproxy); self.cur_sysproxy = Some(sysproxy);
@@ -233,7 +261,6 @@ impl Verge {
if sysproxy.set_sys().is_err() { if sysproxy.set_sys().is_err() {
self.cur_sysproxy = Some(sysproxy); self.cur_sysproxy = Some(sysproxy);
log::error!("failed to set system proxy");
bail!("failed to set system proxy"); bail!("failed to set system proxy");
} }
} }
@@ -265,6 +292,35 @@ impl Verge {
self.config.save_file() self.config.save_file()
} }
/// update the system tray state
pub fn update_systray(&self, app_handle: &AppHandle) -> Result<()> {
// system proxy
let system_proxy = self.config.enable_system_proxy.as_ref();
system_proxy.map(|system_proxy| {
app_handle
.tray_handle()
.get_item("system_proxy")
.set_selected(*system_proxy)
.unwrap();
});
// tun mode
let tun_mode = self.config.enable_tun_mode.as_ref();
tun_mode.map(|tun_mode| {
app_handle
.tray_handle()
.get_item("tun_mode")
.set_selected(*tun_mode)
.unwrap();
});
// update verge config
let window = app_handle.get_window("main").unwrap();
window.emit("verge://refresh-verge-config", "yes").unwrap();
Ok(())
}
} }
impl Verge { impl Verge {

View File

@@ -8,7 +8,10 @@ mod core;
mod states; mod states;
mod utils; mod utils;
use crate::utils::{resolve, server}; use crate::{
core::VergeConfig,
utils::{dirs, resolve, server},
};
use tauri::{ use tauri::{
api, CustomMenuItem, Manager, SystemTray, SystemTrayEvent, SystemTrayMenu, SystemTrayMenuItem, api, CustomMenuItem, Manager, SystemTray, SystemTrayEvent, SystemTrayMenu, SystemTrayMenuItem,
}; };
@@ -19,8 +22,15 @@ fn main() -> std::io::Result<()> {
return Ok(()); return Ok(());
} }
#[cfg(target_os = "windows")]
unsafe {
dirs::init_portable_flag();
}
let tray_menu = SystemTrayMenu::new() let tray_menu = SystemTrayMenu::new()
.add_item(CustomMenuItem::new("open_window", "Show")) .add_item(CustomMenuItem::new("open_window", "Show"))
.add_item(CustomMenuItem::new("system_proxy", "System Proxy"))
.add_item(CustomMenuItem::new("tun_mode", "Tun Mode"))
.add_item(CustomMenuItem::new("restart_clash", "Restart Clash")) .add_item(CustomMenuItem::new("restart_clash", "Restart Clash"))
.add_native_item(SystemTrayMenuItem::Separator) .add_native_item(SystemTrayMenuItem::Separator)
.add_item(CustomMenuItem::new("quit", "Quit").accelerator("CmdOrControl+Q")); .add_item(CustomMenuItem::new("quit", "Quit").accelerator("CmdOrControl+Q"));
@@ -40,18 +50,43 @@ fn main() -> std::io::Result<()> {
window.show().unwrap(); window.show().unwrap();
window.set_focus().unwrap(); window.set_focus().unwrap();
} }
"system_proxy" => {
let verge_state = app_handle.state::<states::VergeState>();
let mut verge = verge_state.0.lock().unwrap();
let old_value = verge.config.enable_system_proxy.clone().unwrap_or(false);
let new_value = !old_value;
match verge.patch_config(VergeConfig {
enable_system_proxy: Some(new_value),
..VergeConfig::default()
}) {
Ok(_) => verge.update_systray(app_handle).unwrap(),
Err(err) => log::error!("{err}"),
}
}
"tun_mode" => {
let verge_state = app_handle.state::<states::VergeState>();
let mut verge = verge_state.0.lock().unwrap();
let old_value = verge.config.enable_tun_mode.clone().unwrap_or(false);
let new_value = !old_value;
match verge.patch_config(VergeConfig {
enable_tun_mode: Some(new_value),
..VergeConfig::default()
}) {
Ok(_) => verge.update_systray(app_handle).unwrap(),
Err(err) => log::error!("{err}"),
}
}
"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 profiles_state = app_handle.state::<states::ProfilesState>();
let mut clash = clash_state.0.lock().unwrap(); let mut clash = clash_state.0.lock().unwrap();
let mut profiles = profiles_state.0.lock().unwrap(); let mut profiles = profiles_state.0.lock().unwrap();
match clash.restart_sidecar(&mut profiles) {
Ok(_) => { crate::log_if_err!(clash.restart_sidecar(&mut profiles));
let window = app_handle.get_window("main").unwrap();
window.emit("restart_clash", "yes").unwrap();
}
Err(err) => log::error!("{}", err),
}
} }
"quit" => { "quit" => {
resolve::resolve_reset(app_handle); resolve::resolve_reset(app_handle);
@@ -60,13 +95,12 @@ fn main() -> std::io::Result<()> {
} }
_ => {} _ => {}
}, },
#[cfg(target_os = "windows")]
SystemTrayEvent::LeftClick { .. } => { SystemTrayEvent::LeftClick { .. } => {
if cfg![target_os = "windows"] { let window = app_handle.get_window("main").unwrap();
let window = app_handle.get_window("main").unwrap(); window.unminimize().unwrap();
window.unminimize().unwrap(); window.show().unwrap();
window.show().unwrap(); window.set_focus().unwrap();
window.set_focus().unwrap();
}
} }
_ => {} _ => {}
}) })
@@ -95,7 +129,10 @@ fn main() -> std::io::Result<()> {
cmds::get_profiles, cmds::get_profiles,
cmds::sync_profiles, cmds::sync_profiles,
cmds::enhance_profiles, cmds::enhance_profiles,
cmds::change_profile_chain cmds::change_profile_chain,
cmds::change_profile_valid,
cmds::read_profile_file,
cmds::save_profile_file
]); ]);
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
@@ -119,11 +156,14 @@ fn main() -> std::io::Result<()> {
.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::RunEvent::CloseRequested { label, api, .. } => { tauri::RunEvent::WindowEvent { label, event, .. } => match event {
let app_handle = app_handle.clone(); tauri::WindowEvent::CloseRequested { api, .. } => {
api.prevent_close(); let app_handle = app_handle.clone();
app_handle.get_window(&label).unwrap().hide().unwrap(); api.prevent_close();
} app_handle.get_window(&label).unwrap().hide().unwrap();
}
_ => {}
},
tauri::RunEvent::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,16 +1,55 @@
use std::env::temp_dir; use std::env::temp_dir;
use std::path::{Path, PathBuf}; use std::path::PathBuf;
use tauri::utils::platform::current_exe;
use tauri::{ use tauri::{
api::path::{home_dir, resource_dir}, api::path::{home_dir, resource_dir},
Env, PackageInfo, Env, PackageInfo,
}; };
#[cfg(not(feature = "verge-dev"))]
static APP_DIR: &str = "clash-verge";
#[cfg(feature = "verge-dev")]
static APP_DIR: &str = "clash-verge-dev";
static CLASH_CONFIG: &str = "config.yaml";
static VERGE_CONFIG: &str = "verge.yaml";
static PROFILE_YAML: &str = "profiles.yaml";
static PROFILE_TEMP: &str = "clash-verge-runtime.yaml";
/// portable flag
#[allow(unused)]
static mut PORTABLE_FLAG: bool = false;
/// initialize portable flag
pub unsafe fn init_portable_flag() {
#[cfg(target_os = "windows")]
{
let exe = current_exe().unwrap();
let dir = exe.parent().unwrap();
let dir = PathBuf::from(dir).join(".config/PORTABLE");
if dir.exists() {
PORTABLE_FLAG = true;
}
}
}
/// get the verge app home dir /// get the verge app home dir
pub fn app_home_dir() -> PathBuf { pub fn app_home_dir() -> PathBuf {
home_dir() #[cfg(target_os = "windows")]
.unwrap() unsafe {
.join(Path::new(".config")) if !PORTABLE_FLAG {
.join(Path::new("clash-verge")) home_dir().unwrap().join(".config").join(APP_DIR)
} else {
let app_exe = current_exe().unwrap();
let app_exe = dunce::canonicalize(app_exe).unwrap();
let app_dir = app_exe.parent().unwrap();
PathBuf::from(app_dir).join(".config").join(APP_DIR)
}
}
#[cfg(not(target_os = "windows"))]
home_dir().unwrap().join(".config").join(APP_DIR)
} }
/// get the resources dir /// get the resources dir
@@ -30,11 +69,6 @@ pub fn app_logs_dir() -> PathBuf {
app_home_dir().join("logs") app_home_dir().join("logs")
} }
static CLASH_CONFIG: &str = "config.yaml";
static VERGE_CONFIG: &str = "verge.yaml";
static PROFILE_YAML: &str = "profiles.yaml";
static PROFILE_TEMP: &str = "clash-verge-runtime.yaml";
pub fn clash_path() -> PathBuf { pub fn clash_path() -> PathBuf {
app_home_dir().join(CLASH_CONFIG) app_home_dir().join(CLASH_CONFIG)
} }
@@ -48,5 +82,9 @@ pub fn profiles_path() -> PathBuf {
} }
pub fn profiles_temp_path() -> PathBuf { pub fn profiles_temp_path() -> PathBuf {
temp_dir().join(PROFILE_TEMP) #[cfg(not(feature = "debug-yml"))]
return temp_dir().join(PROFILE_TEMP);
#[cfg(feature = "debug-yml")]
return app_home_dir().join(PROFILE_TEMP);
} }

View File

@@ -68,7 +68,7 @@ macro_rules! wrap_err {
/// return the string literal error /// return the string literal error
#[macro_export] #[macro_export]
macro_rules! ret_err { macro_rules! ret_err {
($str: literal) => { ($str: expr) => {
return Err($str.into()) return Err($str.into())
}; };
} }

View File

@@ -87,4 +87,14 @@ pub fn init_app(package_info: &PackageInfo) {
if !mmdb_path.exists() && mmdb_tmpl.exists() { if !mmdb_path.exists() && mmdb_tmpl.exists() {
fs::copy(mmdb_tmpl, mmdb_path).unwrap(); fs::copy(mmdb_tmpl, mmdb_path).unwrap();
} }
// copy the wintun.dll
#[cfg(target_os = "windows")]
{
let wintun_path = app_dir.join("wintun.dll");
let wintun_tmpl = res_dir.join("wintun.dll");
if !wintun_path.exists() && wintun_tmpl.exists() {
fs::copy(wintun_tmpl, wintun_path).unwrap();
}
}
} }

View File

@@ -4,8 +4,6 @@ use tauri::{App, AppHandle, Manager};
/// handle something when start app /// handle something when start app
pub fn resolve_setup(app: &App) { pub fn resolve_setup(app: &App) {
resolve_window(app);
// setup a simple http server for singleton // setup a simple http server for singleton
server::embed_server(&app.handle()); server::embed_server(&app.handle());
@@ -26,20 +24,21 @@ pub fn resolve_setup(app: &App) {
*profiles = Profiles::read_file(); *profiles = Profiles::read_file();
clash.set_window(app.get_window("main")); clash.set_window(app.get_window("main"));
log_if_err!(clash.activate(&profiles, true)); log_if_err!(clash.activate(&profiles));
log_if_err!(clash.activate_enhanced(&profiles, true, true));
verge.init_sysproxy(clash.info.port.clone()); verge.init_sysproxy(clash.info.port.clone());
// enable tun mode
if verge.config.enable_tun_mode.clone().unwrap_or(false)
&& verge.cur_sysproxy.is_some()
&& verge.cur_sysproxy.as_ref().unwrap().enable
{
log::info!("enable tun mode");
clash.tun_mode(true).unwrap();
}
verge.init_launch(); log_if_err!(verge.init_launch());
log_if_err!(verge.sync_launch());
verge.config.enable_system_proxy.map(|enable| {
log_if_err!(app
.tray_handle()
.get_item("system_proxy")
.set_selected(enable));
});
resolve_window(app, verge.config.enable_silent_start.clone());
} }
/// reset system proxy /// reset system proxy
@@ -51,9 +50,16 @@ pub fn resolve_reset(app_handle: &AppHandle) {
} }
/// customize the window theme /// customize the window theme
fn resolve_window(app: &App) { fn resolve_window(app: &App, hide: Option<bool>) {
let window = app.get_window("main").unwrap(); let window = app.get_window("main").unwrap();
// silent start
hide.map(|hide| {
if hide {
window.hide().unwrap();
}
});
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
{ {
use window_shadows::set_shadow; use window_shadows::set_shadow;

View File

@@ -4,7 +4,10 @@ use port_scanner::local_port_available;
use tauri::{AppHandle, Manager}; use tauri::{AppHandle, Manager};
use warp::Filter; use warp::Filter;
#[cfg(not(feature = "verge-dev"))]
const SERVER_PORT: u16 = 33333; const SERVER_PORT: u16 = 33333;
#[cfg(feature = "verge-dev")]
const SERVER_PORT: u16 = 11233;
/// check whether there is already exists /// check whether there is already exists
pub fn check_singleton() -> Result<(), ()> { pub fn check_singleton() -> Result<(), ()> {

View File

@@ -21,6 +21,7 @@ items: ~
/// template for `verge.yaml` /// template for `verge.yaml`
pub const VERGE_CONFIG: &[u8] = b"# Defaulf Config For Clash Verge pub const VERGE_CONFIG: &[u8] = b"# Defaulf Config For Clash Verge
language: en
theme_mode: light theme_mode: light
theme_blur: false theme_blur: false
traffic_graph: true traffic_graph: true

View File

@@ -1,7 +1,7 @@
{ {
"package": { "package": {
"productName": "Clash Verge", "productName": "Clash Verge",
"version": "0.0.22" "version": "0.0.29"
}, },
"build": { "build": {
"distDir": "../dist", "distDir": "../dist",
@@ -52,7 +52,8 @@
"updater": { "updater": {
"active": true, "active": true,
"endpoints": [ "endpoints": [
"https://github.com/zzzgydi/clash-verge/releases/download/updater/update.json" "https://github.com/zzzgydi/clash-verge/releases/download/updater/update.json",
"https://hub.fastgit.xyz/zzzgydi/clash-verge/releases/download/updater/update-proxy.json"
], ],
"dialog": false, "dialog": false,
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDExNUFBNTBBN0FDNEFBRTUKUldUbHFzUjZDcVZhRVRJM25NS3NkSFlFVElxUkNZMzZ6bHUwRVJjb2F3alJXVzRaeDdSaTA2YWYK" "pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDExNUFBNTBBN0FDNEFBRTUKUldUbHFzUjZDcVZhRVRJM25NS3NkSFlFVElxUkNZMzZ6bHUwRVJjb2F3alJXVzRaeDdSaTA2YWYK"
@@ -63,6 +64,9 @@
}, },
"window": { "window": {
"all": true "all": true
},
"process": {
"all": true
} }
}, },
"windows": [ "windows": [
@@ -79,7 +83,7 @@
} }
], ],
"security": { "security": {
"csp": "default-src blob: data: filesystem: ws: wss: http: https: tauri: 'unsafe-eval' 'unsafe-inline' 'self' img-src: 'self'" "csp": "script-src 'unsafe-eval' 'self'; default-src blob: data: filesystem: ws: wss: http: https: tauri: 'unsafe-eval' 'unsafe-inline' 'self'; img-src data: 'self';"
} }
} }
} }

View File

@@ -18,7 +18,7 @@
.the-logo { .the-logo {
position: relative; position: relative;
flex: 0 1 180px; flex: 0 1 168px;
width: 100%; width: 100%;
max-width: 168px; max-width: 168px;
max-height: 168px; max-height: 168px;
@@ -27,8 +27,11 @@
text-align: center; text-align: center;
box-sizing: border-box; box-sizing: border-box;
img { img,
svg {
width: 100%; width: 100%;
height: 100%;
pointer-events: none;
} }
.the-newbtn { .the-newbtn {
@@ -72,7 +75,7 @@
.the-content { .the-content {
position: absolute; position: absolute;
top: 30px; top: 0;
left: 0; left: 0;
right: 2px; right: 2px;
bottom: 10px; bottom: 10px;
@@ -80,8 +83,12 @@
} }
} }
.macos.layout { .linux,
.layout__right .the-content { .windows,
top: 0; .unknown {
&.layout {
.layout__right .the-content {
top: 30px;
}
} }
} }

View File

@@ -1,4 +1,21 @@
import dayjs from "dayjs";
import { useLockFn } from "ahooks";
import { styled, ListItem, IconButton, ListItemText } from "@mui/material";
import { CloseRounded } from "@mui/icons-material";
import { ApiType } from "../../services/types"; import { ApiType } from "../../services/types";
import { deleteConnection } from "../../services/api";
import parseTraffic from "../../utils/parse-traffic";
const Tag = styled("span")(({ theme }) => ({
display: "inline-block",
fontSize: "12px",
padding: "0 4px",
lineHeight: 1.375,
border: "1px solid #ccc",
borderRadius: 4,
marginRight: "0.1em",
transform: "scale(0.92)",
}));
interface Props { interface Props {
value: ApiType.ConnectionsItem; value: ApiType.ConnectionsItem;
@@ -7,7 +24,44 @@ interface Props {
const ConnectionItem = (props: Props) => { const ConnectionItem = (props: Props) => {
const { value } = props; const { value } = props;
return <div>{value.metadata.host || value.metadata.destinationIP}</div>; const { id, metadata, chains, start, curUpload, curDownload } = value;
const onDelete = useLockFn(async () => deleteConnection(id));
const showTraffic = curUpload! > 1024 || curDownload! > 1024;
return (
<ListItem
dense
secondaryAction={
<IconButton edge="end" color="inherit" onClick={onDelete}>
<CloseRounded />
</IconButton>
}
>
<ListItemText
primary={metadata.host || metadata.destinationIP}
secondary={
<>
<Tag sx={{ textTransform: "uppercase", color: "success" }}>
{metadata.network}
</Tag>
<Tag>{metadata.type}</Tag>
{chains.length > 0 && <Tag>{chains[value.chains.length - 1]}</Tag>}
<Tag>{dayjs(start).fromNow()}</Tag>
{showTraffic && (
<Tag>
{parseTraffic(curUpload!)} / {parseTraffic(curDownload!)}
</Tag>
)}
</>
}
/>
</ListItem>
);
}; };
export default ConnectionItem; export default ConnectionItem;

View File

@@ -12,6 +12,7 @@ import useLogSetup from "./use-log-setup";
import useTrafficGraph from "./use-traffic-graph"; import useTrafficGraph from "./use-traffic-graph";
import parseTraffic from "../../utils/parse-traffic"; import parseTraffic from "../../utils/parse-traffic";
// setup the traffic
const LayoutTraffic = () => { const LayoutTraffic = () => {
const portValue = useRecoilValue(atomClashPort); const portValue = useRecoilValue(atomClashPort);
const [traffic, setTraffic] = useState({ up: 0, down: 0 }); const [traffic, setTraffic] = useState({ up: 0, down: 0 });
@@ -26,12 +27,14 @@ const LayoutTraffic = () => {
useLogSetup(); useLogSetup();
useEffect(() => { useEffect(() => {
let unlisten: () => void = null!;
// should reconnect the traffic ws // should reconnect the traffic ws
listen("restart_clash", () => setRefresh({})).then((fn) => (unlisten = fn)); const unlisten = listen("verge://refresh-clash-config", () =>
setRefresh({})
);
return () => unlisten?.(); return () => {
unlisten.then((fn) => fn());
};
}, []); }, []);
useEffect(() => { useEffect(() => {

View File

@@ -32,7 +32,9 @@ const UpdateButton = (props: Props) => {
New New
</Button> </Button>
<UpdateDialog open={dialogOpen} onClose={() => setDialogOpen(false)} /> {dialogOpen && (
<UpdateDialog open={dialogOpen} onClose={() => setDialogOpen(false)} />
)}
</> </>
); );
}; };

View File

@@ -1,16 +1,20 @@
import useSWR from "swr"; import useSWR from "swr";
import { useState } from "react"; import snarkdown from "snarkdown";
import { useMemo } from "react";
import { useRecoilState } from "recoil";
import { import {
Box,
Button, Button,
Dialog, Dialog,
DialogActions, DialogActions,
DialogContent, DialogContent,
DialogContentText,
DialogTitle, DialogTitle,
styled,
} from "@mui/material"; } from "@mui/material";
import { relaunch } from "@tauri-apps/api/process"; import { relaunch } from "@tauri-apps/api/process";
import { checkUpdate, installUpdate } from "@tauri-apps/api/updater"; import { checkUpdate, installUpdate } from "@tauri-apps/api/updater";
import { killSidecars, restartSidecar } from "../../services/cmds"; import { killSidecars, restartSidecar } from "../../services/cmds";
import { atomUpdateState } from "../../services/states";
import Notice from "../base/base-notice"; import Notice from "../base/base-notice";
interface Props { interface Props {
@@ -18,7 +22,9 @@ interface Props {
onClose: () => void; onClose: () => void;
} }
let uploadingState = false; const UpdateLog = styled(Box)(() => ({
"h1,h2,h3,ul,ol,p": { margin: "0.5em 0", color: "inherit" },
}));
const UpdateDialog = (props: Props) => { const UpdateDialog = (props: Props) => {
const { open, onClose } = props; const { open, onClose } = props;
@@ -27,38 +33,48 @@ const UpdateDialog = (props: Props) => {
revalidateIfStale: false, revalidateIfStale: false,
focusThrottleInterval: 36e5, // 1 hour focusThrottleInterval: 36e5, // 1 hour
}); });
const [uploading, setUploading] = useState(uploadingState);
const [updateState, setUpdateState] = useRecoilState(atomUpdateState);
const onUpdate = async () => { const onUpdate = async () => {
setUploading(true); if (updateState) return;
uploadingState = true; setUpdateState(true);
try { try {
await installUpdate();
await killSidecars(); await killSidecars();
await installUpdate();
await relaunch(); await relaunch();
} catch (err: any) { } catch (err: any) {
await restartSidecar(); await restartSidecar();
Notice.error(err?.message || err.toString()); Notice.error(err?.message || err.toString());
} finally { } finally {
setUploading(false); setUpdateState(false);
uploadingState = false;
} }
}; };
// markdown parser
const parseContent = useMemo(() => {
if (!updateInfo?.manifest?.body) {
return "New Version is available";
}
return snarkdown(updateInfo?.manifest?.body);
}, [updateInfo]);
return ( return (
<Dialog open={open} onClose={onClose}> <Dialog open={open} onClose={onClose}>
<DialogTitle>New Version v{updateInfo?.manifest?.version}</DialogTitle> <DialogTitle>New Version v{updateInfo?.manifest?.version}</DialogTitle>
<DialogContent sx={{ minWidth: 360, maxWidth: 400, maxHeight: "50vh" }}> <DialogContent sx={{ minWidth: 360, maxWidth: 400, maxHeight: "50vh" }}>
<DialogContentText>{updateInfo?.manifest?.body}</DialogContentText> <UpdateLog dangerouslySetInnerHTML={{ __html: parseContent }} />
</DialogContent> </DialogContent>
<DialogActions> <DialogActions>
<Button onClick={onClose}>Cancel</Button> <Button onClick={onClose}>Cancel</Button>
<Button <Button
variant="contained"
autoFocus autoFocus
variant="contained"
disabled={updateState}
onClick={onUpdate} onClick={onUpdate}
disabled={uploading}
> >
Update Update
</Button> </Button>

View File

@@ -0,0 +1,79 @@
import useSWR from "swr";
import { useMemo } from "react";
import { createTheme } from "@mui/material";
import { getVergeConfig } from "../../services/cmds";
import { defaultTheme as dt } from "../../pages/_theme";
/**
* custome theme
*/
export default function useCustomTheme() {
const { data } = useSWR("getVergeConfig", getVergeConfig);
const { theme_mode, theme_setting } = data ?? {};
const theme = useMemo(() => {
const mode = theme_mode ?? "light";
// const background = mode === "light" ? "#f5f5f5" : "#000";
const selectColor = mode === "light" ? "#f5f5f5" : "#d5d5d5";
const rootEle = document.documentElement;
rootEle.style.background = "transparent";
rootEle.style.setProperty("--selection-color", selectColor);
const setting = theme_setting || {};
const theme = createTheme({
breakpoints: {
values: { xs: 0, sm: 650, md: 900, lg: 1200, xl: 1536 },
},
palette: {
mode,
primary: { main: setting.primary_color || dt.primary_color },
secondary: { main: setting.secondary_color || dt.secondary_color },
info: { main: setting.info_color || dt.info_color },
error: { main: setting.error_color || dt.error_color },
warning: { main: setting.warning_color || dt.warning_color },
success: { main: setting.success_color || dt.success_color },
text: {
primary: setting.primary_text || dt.primary_text,
secondary: setting.secondary_text || dt.secondary_text,
},
},
typography: {
// todo
fontFamily: setting.font_family
? `${setting.font_family}, ${dt.font_family}`
: dt.font_family,
},
});
// inject css
let style = document.querySelector("style#verge-theme");
if (!style) {
style = document.createElement("style");
style.id = "verge-theme";
document.head.appendChild(style!);
}
if (style) {
style.innerHTML = setting.css_injection || "";
}
// update svg icon
const { palette } = theme;
setTimeout(() => {
const dom = document.querySelector("#Gradient2");
if (dom) {
dom.innerHTML = `
<stop offset="0%" stop-color="${palette.primary.main}" />
<stop offset="80%" stop-color="${palette.primary.dark}" />
<stop offset="100%" stop-color="${palette.primary.dark}" />
`;
}
}, 0);
return theme;
}, [theme_mode, theme_setting]);
return { theme };
}

View File

@@ -1,5 +1,5 @@
import dayjs from "dayjs"; import dayjs from "dayjs";
import { useEffect } from "react"; import { useEffect, useState } from "react";
import { useSetRecoilState } from "recoil"; import { useSetRecoilState } from "recoil";
import { listen } from "@tauri-apps/api/event"; import { listen } from "@tauri-apps/api/event";
import { ApiType } from "../../services/types"; import { ApiType } from "../../services/types";
@@ -10,11 +10,11 @@ const MAX_LOG_NUM = 1000;
// setup the log websocket // setup the log websocket
export default function useLogSetup() { export default function useLogSetup() {
const [refresh, setRefresh] = useState({});
const setLogData = useSetRecoilState(atomLogData); const setLogData = useSetRecoilState(atomLogData);
useEffect(() => { useEffect(() => {
let ws: WebSocket = null!; let ws: WebSocket = null!;
let unlisten: () => void = null!;
const handler = (event: MessageEvent<any>) => { const handler = (event: MessageEvent<any>) => {
const data = JSON.parse(event.data) as ApiType.LogItem; const data = JSON.parse(event.data) as ApiType.LogItem;
@@ -25,25 +25,19 @@ export default function useLogSetup() {
}); });
}; };
(async () => { getInfomation().then((info) => {
const { server = "", secret = "" } = await getInfomation(); const { server = "", secret = "" } = info;
ws = new WebSocket(`ws://${server}/logs?token=${secret}`); ws = new WebSocket(`ws://${server}/logs?token=${secret}`);
ws.addEventListener("message", handler); ws.addEventListener("message", handler);
});
// reconnect the websocket const unlisten = listen("verge://refresh-clash-config", () =>
unlisten = await listen("restart_clash", async () => { setRefresh({})
const { server = "", secret = "" } = await getInfomation(); );
ws?.close();
ws = new WebSocket(`ws://${server}/logs?token=${secret}`);
ws.addEventListener("message", handler);
});
})();
return () => { return () => {
ws?.close(); ws?.close();
unlisten?.(); unlisten?.then((fn) => fn());
}; };
}, []); }, [refresh]);
} }

View File

@@ -1,19 +1,17 @@
import { useRef } from "react"; import { useEffect, useRef } from "react";
import { useTheme } from "@mui/material";
const minPoint = 10; const minPoint = 10;
const maxPoint = 36; const maxPoint = 36;
const refLineAlpha = 0.5; const refLineAlpha = 1;
const refLineWidth = 2; const refLineWidth = 2;
const refLineColor = "#ccc";
const upLineAlpha = 0.6; const upLineAlpha = 0.6;
const upLineWidth = 4; const upLineWidth = 4;
const upLineColor = "#9c27b0";
const downLineAlpha = 1; const downLineAlpha = 1;
const downLineWidth = 4; const downLineWidth = 4;
const downLineColor = "#5b5c9d";
/** /**
* draw the traffic graph * draw the traffic graph
@@ -24,11 +22,23 @@ export default function useTrafficGraph() {
const styleRef = useRef(true); const styleRef = useRef(true);
const canvasRef = useRef<HTMLCanvasElement>(null!); const canvasRef = useRef<HTMLCanvasElement>(null!);
const { palette } = useTheme();
const paletteRef = useRef(palette);
useEffect(() => {
paletteRef.current = palette;
}, [palette]);
const drawGraph = () => { const drawGraph = () => {
const canvas = canvasRef.current!; const canvas = canvasRef.current!;
if (!canvas) return; if (!canvas) return;
const { primary, secondary, divider } = paletteRef.current;
const refLineColor = divider || "rgba(0, 0, 0, 0.12)";
const upLineColor = secondary.main || "#9c27b0";
const downLineColor = primary.main || "#5b5c9d";
const context = canvas.getContext("2d")!; const context = canvas.getContext("2d")!;
const width = canvas.width; const width = canvas.width;
const height = canvas.height; const height = canvas.height;

View File

@@ -6,6 +6,8 @@ const Item = styled(Box)(({ theme }) => ({
margin: "0 12px", margin: "0 12px",
lineHeight: 1.35, lineHeight: 1.35,
borderBottom: `1px solid ${theme.palette.divider}`, borderBottom: `1px solid ${theme.palette.divider}`,
fontSize: "0.875rem",
userSelect: "text",
"& .time": {}, "& .time": {},
"& .type": { "& .type": {
display: "inline-block", display: "inline-block",

View File

@@ -0,0 +1,221 @@
import useSWR from "swr";
import { useState } from "react";
import { useLockFn } from "ahooks";
import {
Box,
Divider,
Grid,
IconButton,
ListItemIcon,
ListItemText,
Menu,
MenuItem,
Stack,
} from "@mui/material";
import {
AddchartRounded,
CheckRounded,
MenuRounded,
RestartAltRounded,
} from "@mui/icons-material";
import {
getProfiles,
deleteProfile,
enhanceProfiles,
changeProfileChain,
changeProfileValid,
} from "../../services/cmds";
import { CmdType } from "../../services/types";
import getSystem from "../../utils/get-system";
import ProfileMore from "./profile-more";
import Notice from "../base/base-notice";
interface Props {
items: CmdType.ProfileItem[];
chain: string[];
}
const OS = getSystem();
const EnhancedMode = (props: Props) => {
const { items, chain } = props;
const { data, mutate } = useSWR("getProfiles", getProfiles);
const valid = data?.valid || [];
const [anchorEl, setAnchorEl] = useState<any>(null);
// handler
const onEnhance = useLockFn(async () => {
try {
await enhanceProfiles();
Notice.success("Refresh clash config", 2000);
} catch (err: any) {
Notice.error(err.message || err.toString());
}
});
const onEnhanceEnable = useLockFn(async (uid: string) => {
if (chain.includes(uid)) return;
const newChain = [...chain, uid];
await changeProfileChain(newChain);
mutate((conf = {}) => ({ ...conf, chain: newChain }), true);
});
const onEnhanceDisable = useLockFn(async (uid: string) => {
if (!chain.includes(uid)) return;
const newChain = chain.filter((i) => i !== uid);
await changeProfileChain(newChain);
mutate((conf = {}) => ({ ...conf, chain: newChain }), true);
});
const onEnhanceDelete = useLockFn(async (uid: string) => {
try {
await onEnhanceDisable(uid);
await deleteProfile(uid);
mutate();
} catch (err: any) {
Notice.error(err?.message || err.toString());
}
});
const onMoveTop = useLockFn(async (uid: string) => {
if (!chain.includes(uid)) return;
const newChain = [uid].concat(chain.filter((i) => i !== uid));
await changeProfileChain(newChain);
mutate((conf = {}) => ({ ...conf, chain: newChain }), true);
});
const onMoveEnd = useLockFn(async (uid: string) => {
if (!chain.includes(uid)) return;
const newChain = chain.filter((i) => i !== uid).concat([uid]);
await changeProfileChain(newChain);
mutate((conf = {}) => ({ ...conf, chain: newChain }), true);
});
// update valid list
const onToggleValid = useLockFn(async (key: string) => {
try {
const newValid = valid.includes(key)
? valid.filter((i) => i !== key)
: valid.concat(key);
await changeProfileValid(newValid);
mutate();
} catch (err: any) {
Notice.error(err.message || err.toString());
}
});
return (
<Box sx={{ mt: 4 }}>
<Stack
spacing={1}
direction="row"
alignItems="center"
justifyContent="flex-end"
sx={{ mb: 0.5 }}
>
<IconButton
size="small"
color="inherit"
title="refresh enhanced profiles"
onClick={onEnhance}
>
<RestartAltRounded />
</IconButton>
<IconButton
size="small"
color="inherit"
id="profile-use-button"
title="enable clash fields"
aria-controls={!!anchorEl ? "profile-use-menu" : undefined}
aria-haspopup="true"
aria-expanded={!!anchorEl ? "true" : undefined}
onClick={(e) => setAnchorEl(e.currentTarget)}
>
<MenuRounded />
</IconButton>
<Menu
id="profile-use-menu"
open={!!anchorEl}
anchorEl={anchorEl}
onClose={() => setAnchorEl(null)}
transitionDuration={225}
TransitionProps={
OS === "macos" ? { style: { transitionDuration: "225ms" } } : {}
}
MenuListProps={{
dense: true,
"aria-labelledby": "profile-use-button",
}}
onContextMenu={(e) => {
setAnchorEl(null);
e.preventDefault();
}}
>
<MenuItem>
<ListItemIcon color="inherit">
<AddchartRounded />
</ListItemIcon>
Use Clash Fields
</MenuItem>
<Divider />
{[
"tun",
"dns",
"hosts",
"script",
"profile",
"payload",
"interface-name",
"routing-mark",
].map((key) => {
const has = valid.includes(key);
return (
<MenuItem
key={key}
sx={{ width: 180 }}
onClick={() => onToggleValid(key)}
>
{has && (
<ListItemIcon color="inherit">
<CheckRounded />
</ListItemIcon>
)}
<ListItemText inset={!has}>{key}</ListItemText>
</MenuItem>
);
})}
</Menu>
</Stack>
<Grid container spacing={2}>
{items.map((item) => (
<Grid item xs={12} sm={6} key={item.file}>
<ProfileMore
selected={!!chain.includes(item.uid)}
itemData={item}
enableNum={chain.length}
onEnable={() => onEnhanceEnable(item.uid)}
onDisable={() => onEnhanceDisable(item.uid)}
onDelete={() => onEnhanceDelete(item.uid)}
onMoveTop={() => onMoveTop(item.uid)}
onMoveEnd={() => onMoveEnd(item.uid)}
/>
</Grid>
))}
</Grid>
</Box>
);
};
export default EnhancedMode;

View File

@@ -0,0 +1,98 @@
import useSWR from "swr";
import { useEffect, useRef } from "react";
import { useLockFn } from "ahooks";
import { useTranslation } from "react-i18next";
import {
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
} from "@mui/material";
import {
getVergeConfig,
readProfileFile,
saveProfileFile,
} from "../../services/cmds";
import Notice from "../base/base-notice";
import "monaco-editor/esm/vs/basic-languages/javascript/javascript.contribution.js";
import "monaco-editor/esm/vs/basic-languages/yaml/yaml.contribution.js";
import "monaco-editor/esm/vs/editor/contrib/folding/browser/folding.js";
import { editor } from "monaco-editor/esm/vs/editor/editor.api";
interface Props {
uid: string;
open: boolean;
mode: "yaml" | "javascript";
onClose: () => void;
onChange?: () => void;
}
const FileEditor = (props: Props) => {
const { uid, open, mode, onClose, onChange } = props;
const { t } = useTranslation();
const editorRef = useRef<any>();
const instanceRef = useRef<editor.IStandaloneCodeEditor | null>(null);
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
const { theme_mode } = vergeConfig ?? {};
useEffect(() => {
if (!open) return;
readProfileFile(uid).then((data) => {
const dom = editorRef.current;
if (!dom) return;
if (instanceRef.current) instanceRef.current.dispose();
instanceRef.current = editor.create(editorRef.current, {
value: data,
language: mode,
theme: theme_mode === "light" ? "vs" : "vs-dark",
minimap: { enabled: false },
});
});
return () => {
if (instanceRef.current) {
instanceRef.current.dispose();
instanceRef.current = null;
}
};
}, [open]);
const onSave = useLockFn(async () => {
const value = instanceRef.current?.getValue();
if (value == null) return;
try {
await saveProfileFile(uid, value);
onChange?.();
onClose();
} catch (err: any) {
Notice.error(err.message || err.toString());
}
});
return (
<Dialog open={open} onClose={onClose}>
<DialogTitle>{t("Edit File")}</DialogTitle>
<DialogContent sx={{ width: 520, pb: 1 }}>
<div style={{ width: "100%", height: "420px" }} ref={editorRef} />
</DialogContent>
<DialogActions>
<Button onClick={onClose}>{t("Cancel")}</Button>
<Button onClick={onSave} variant="contained">
{t("Save")}
</Button>
</DialogActions>
</Dialog>
);
};
export default FileEditor;

View File

@@ -0,0 +1,61 @@
import { useRef, useState } from "react";
import { useLockFn } from "ahooks";
import { Box, Button, Typography } from "@mui/material";
interface Props {
onChange: (value: string) => void;
}
const FileInput = (props: Props) => {
const { onChange } = props;
// file input
const inputRef = useRef<any>();
const [loading, setLoading] = useState(false);
const [fileName, setFileName] = useState("");
const onFileInput = useLockFn(async (e: any) => {
const file = e.target.files?.[0] as File;
if (!file) return;
setFileName(file.name);
setLoading(true);
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (event) => {
resolve(null);
onChange(event.target?.result as string);
};
reader.onerror = reject;
reader.readAsText(file);
}).finally(() => setLoading(false));
});
return (
<Box sx={{ mt: 2, mb: 1, display: "flex", alignItems: "center" }}>
<Button
variant="outlined"
sx={{ flex: "none" }}
onClick={() => inputRef.current?.click()}
>
Choose File
</Button>
<input
type="file"
accept=".yaml,.yml"
ref={inputRef}
style={{ display: "none" }}
onChange={onFileInput}
/>
<Typography noWrap sx={{ ml: 1 }}>
{loading ? "Loading..." : fileName}
</Typography>
</Box>
);
};
export default FileInput;

View File

@@ -41,7 +41,7 @@ const ProfileEdit = (props: Props) => {
try { try {
const { uid } = itemData; const { uid } = itemData;
const { name, desc, url } = form; const { name, desc, url } = form;
const option_ = showOpt ? option : undefined; const option_ = itemData.type === "remote" ? option : undefined;
if (itemData.type === "remote" && !url) { if (itemData.type === "remote" && !url) {
throw new Error("Remote URL should not be null"); throw new Error("Remote URL should not be null");

View File

@@ -1,7 +1,9 @@
import dayjs from "dayjs"; import dayjs from "dayjs";
import { useState } from "react";
import { useLockFn } from "ahooks"; import { useLockFn } from "ahooks";
import { useSWRConfig } from "swr"; import { useSWRConfig } from "swr";
import { useEffect, useState } from "react"; import { useRecoilState } from "recoil";
import { useTranslation } from "react-i18next";
import { import {
alpha, alpha,
Box, Box,
@@ -15,14 +17,14 @@ import {
} from "@mui/material"; } from "@mui/material";
import { RefreshRounded } from "@mui/icons-material"; import { RefreshRounded } from "@mui/icons-material";
import { CmdType } from "../../services/types"; import { CmdType } from "../../services/types";
import { atomLoadingCache } from "../../services/states";
import { updateProfile, deleteProfile, viewProfile } from "../../services/cmds"; import { updateProfile, deleteProfile, viewProfile } from "../../services/cmds";
import relativeTime from "dayjs/plugin/relativeTime";
import parseTraffic from "../../utils/parse-traffic"; import parseTraffic from "../../utils/parse-traffic";
import getSystem from "../../utils/get-system";
import ProfileEdit from "./profile-edit"; import ProfileEdit from "./profile-edit";
import FileEditor from "./file-editor";
import Notice from "../base/base-notice"; import Notice from "../base/base-notice";
dayjs.extend(relativeTime);
const Wrapper = styled(Box)(({ theme }) => ({ const Wrapper = styled(Box)(({ theme }) => ({
width: "100%", width: "100%",
display: "block", display: "block",
@@ -39,8 +41,7 @@ const round = keyframes`
to { transform: rotate(360deg); } to { transform: rotate(360deg); }
`; `;
// save the state of each item loading const OS = getSystem();
const loadingCache: Record<string, boolean> = {};
interface Props { interface Props {
selected: boolean; selected: boolean;
@@ -51,12 +52,13 @@ interface Props {
const ProfileItem = (props: Props) => { const ProfileItem = (props: Props) => {
const { selected, itemData, onSelect } = props; const { selected, itemData, onSelect } = props;
const { t } = useTranslation();
const { mutate } = useSWRConfig(); const { mutate } = useSWRConfig();
const [loading, setLoading] = useState(loadingCache[itemData.uid] ?? false);
const [anchorEl, setAnchorEl] = useState<any>(null); const [anchorEl, setAnchorEl] = useState<any>(null);
const [position, setPosition] = useState({ left: 0, top: 0 }); const [position, setPosition] = useState({ left: 0, top: 0 });
const [loadingCache, setLoadingCache] = useRecoilState(atomLoadingCache);
const { name = "Profile", extra, updated = 0 } = itemData; const { uid, name = "Profile", extra, updated = 0 } = itemData;
const { upload = 0, download = 0, total = 0 } = extra ?? {}; const { upload = 0, download = 0, total = 0 } = extra ?? {};
const from = parseUrl(itemData.url); const from = parseUrl(itemData.url);
const expire = parseExpire(extra?.expire); const expire = parseExpire(extra?.expire);
@@ -69,23 +71,19 @@ const ProfileItem = (props: Props) => {
const hasUrl = !!itemData.url; const hasUrl = !!itemData.url;
const hasExtra = !!extra; // only subscription url has extra info const hasExtra = !!extra; // only subscription url has extra info
useEffect(() => { const loading = loadingCache[itemData.uid] ?? false;
loadingCache[itemData.uid] = loading;
}, [itemData, loading]);
const [editOpen, setEditOpen] = useState(false); const [editOpen, setEditOpen] = useState(false);
const onEdit = () => { const [fileOpen, setFileOpen] = useState(false);
const onEditInfo = () => {
setAnchorEl(null); setAnchorEl(null);
setEditOpen(true); setEditOpen(true);
}; };
const onView = async () => { const onEditFile = () => {
setAnchorEl(null); setAnchorEl(null);
try { setFileOpen(true);
await viewProfile(itemData.uid);
} catch (err: any) {
Notice.error(err?.message || err.toString());
}
}; };
const onForceSelect = () => { const onForceSelect = () => {
@@ -93,19 +91,28 @@ const ProfileItem = (props: Props) => {
onSelect(true); onSelect(true);
}; };
const onUpdateWrapper = (withProxy: boolean) => async () => { const onOpenFile = useLockFn(async () => {
setAnchorEl(null); setAnchorEl(null);
if (loading) return;
setLoading(true);
try { try {
await updateProfile(itemData.uid, { with_proxy: withProxy }); await viewProfile(itemData.uid);
setLoading(false);
mutate("getProfiles");
} catch (err: any) { } catch (err: any) {
setLoading(false);
Notice.error(err?.message || err.toString()); Notice.error(err?.message || err.toString());
} }
}; });
const onUpdate = useLockFn(async (withProxy: boolean) => {
setAnchorEl(null);
setLoadingCache((cache) => ({ ...cache, [itemData.uid]: true }));
try {
await updateProfile(itemData.uid, { with_proxy: withProxy });
mutate("getProfiles");
} catch (err: any) {
Notice.error(err?.message || err.toString());
} finally {
setLoadingCache((cache) => ({ ...cache, [itemData.uid]: false }));
}
});
const onDelete = useLockFn(async () => { const onDelete = useLockFn(async () => {
setAnchorEl(null); setAnchorEl(null);
@@ -126,16 +133,18 @@ const ProfileItem = (props: Props) => {
const urlModeMenu = [ const urlModeMenu = [
{ label: "Select", handler: onForceSelect }, { label: "Select", handler: onForceSelect },
{ label: "Edit", handler: onEdit }, { label: "Edit Info", handler: onEditInfo },
{ label: "File", handler: onView }, { label: "Edit File", handler: onEditFile },
{ label: "Update", handler: onUpdateWrapper(false) }, { label: "Open File", handler: onOpenFile },
{ label: "Update(Proxy)", handler: onUpdateWrapper(true) }, { label: "Update", handler: () => onUpdate(false) },
{ label: "Update(Proxy)", handler: () => onUpdate(true) },
{ label: "Delete", handler: onDelete }, { label: "Delete", handler: onDelete },
]; ];
const fileModeMenu = [ const fileModeMenu = [
{ label: "Select", handler: onForceSelect }, { label: "Select", handler: onForceSelect },
{ label: "Edit", handler: onEdit }, { label: "Edit Info", handler: onEditInfo },
{ label: "File", handler: onView }, { label: "Edit File", handler: onEditFile },
{ label: "Open File", handler: onOpenFile },
{ label: "Delete", handler: onDelete }, { label: "Delete", handler: onDelete },
]; ];
@@ -200,7 +209,7 @@ const ProfileItem = (props: Props) => {
disabled={loading} disabled={loading}
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
onUpdateWrapper(false)(); onUpdate(false);
}} }}
> >
<RefreshRounded /> <RefreshRounded />
@@ -260,6 +269,10 @@ const ProfileItem = (props: Props) => {
onClose={() => setAnchorEl(null)} onClose={() => setAnchorEl(null)}
anchorPosition={position} anchorPosition={position}
anchorReference="anchorPosition" anchorReference="anchorPosition"
transitionDuration={225}
TransitionProps={
OS === "macos" ? { style: { transitionDuration: "225ms" } } : {}
}
onContextMenu={(e) => { onContextMenu={(e) => {
setAnchorEl(null); setAnchorEl(null);
e.preventDefault(); e.preventDefault();
@@ -271,7 +284,7 @@ const ProfileItem = (props: Props) => {
onClick={item.handler} onClick={item.handler}
sx={{ minWidth: 133 }} sx={{ minWidth: 133 }}
> >
{item.label} {t(item.label)}
</MenuItem> </MenuItem>
))} ))}
</Menu> </Menu>
@@ -283,6 +296,15 @@ const ProfileItem = (props: Props) => {
onClose={() => setEditOpen(false)} onClose={() => setEditOpen(false)}
/> />
)} )}
{fileOpen && (
<FileEditor
uid={uid}
open={fileOpen}
mode="yaml"
onClose={() => setFileOpen(false)}
/>
)}
</> </>
); );
}; };

View File

@@ -1,5 +1,7 @@
import dayjs from "dayjs"; import dayjs from "dayjs";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { useLockFn } from "ahooks";
import { import {
alpha, alpha,
Box, Box,
@@ -11,12 +13,11 @@ import {
} from "@mui/material"; } from "@mui/material";
import { CmdType } from "../../services/types"; import { CmdType } from "../../services/types";
import { viewProfile } from "../../services/cmds"; import { viewProfile } from "../../services/cmds";
import relativeTime from "dayjs/plugin/relativeTime"; import getSystem from "../../utils/get-system";
import ProfileEdit from "./profile-edit";
import Notice from "../base/base-notice";
import enhance from "../../services/enhance"; import enhance from "../../services/enhance";
import ProfileEdit from "./profile-edit";
dayjs.extend(relativeTime); import FileEditor from "./file-editor";
import Notice from "../base/base-notice";
const Wrapper = styled(Box)(({ theme }) => ({ const Wrapper = styled(Box)(({ theme }) => ({
width: "100%", width: "100%",
@@ -29,15 +30,17 @@ const Wrapper = styled(Box)(({ theme }) => ({
boxSizing: "border-box", boxSizing: "border-box",
})); }));
const OS = getSystem();
interface Props { interface Props {
selected: boolean; selected: boolean;
itemData: CmdType.ProfileItem; itemData: CmdType.ProfileItem;
enableNum: number;
onEnable: () => void; onEnable: () => void;
onDisable: () => void; onDisable: () => void;
onMoveTop: () => void; onMoveTop: () => void;
onMoveEnd: () => void; onMoveEnd: () => void;
onDelete: () => void; onDelete: () => void;
onEnhance: () => void;
} }
// profile enhanced item // profile enhanced item
@@ -45,18 +48,21 @@ const ProfileMore = (props: Props) => {
const { const {
selected, selected,
itemData, itemData,
enableNum,
onEnable, onEnable,
onDisable, onDisable,
onMoveTop, onMoveTop,
onMoveEnd, onMoveEnd,
onDelete, onDelete,
onEnhance,
} = props; } = props;
const { uid, type } = itemData; const { uid, type } = itemData;
const { t } = useTranslation();
const [anchorEl, setAnchorEl] = useState<any>(null); const [anchorEl, setAnchorEl] = useState<any>(null);
const [position, setPosition] = useState({ left: 0, top: 0 }); const [position, setPosition] = useState({ left: 0, top: 0 });
const [editOpen, setEditOpen] = useState(false); const [editOpen, setEditOpen] = useState(false);
const [fileOpen, setFileOpen] = useState(false);
const [status, setStatus] = useState(enhance.status(uid)); const [status, setStatus] = useState(enhance.status(uid));
// unlisten when unmount // unlisten when unmount
@@ -65,40 +71,48 @@ const ProfileMore = (props: Props) => {
// error during enhanced mode // error during enhanced mode
const hasError = selected && status?.status === "error"; const hasError = selected && status?.status === "error";
const onEdit = () => { const onEditInfo = () => {
setAnchorEl(null); setAnchorEl(null);
setEditOpen(true); setEditOpen(true);
}; };
const onView = async () => { const onEditFile = () => {
setAnchorEl(null);
setFileOpen(true);
};
const onOpenFile = useLockFn(async () => {
setAnchorEl(null); setAnchorEl(null);
try { try {
await viewProfile(itemData.uid); await viewProfile(itemData.uid);
} catch (err: any) { } catch (err: any) {
Notice.error(err?.message || err.toString()); Notice.error(err?.message || err.toString());
} }
}; });
const closeWrapper = (fn: () => void) => () => { const fnWrapper = (fn: () => void) => () => {
setAnchorEl(null); setAnchorEl(null);
return fn(); return fn();
}; };
const showMove = enableNum > 1 && !hasError;
const enableMenu = [ const enableMenu = [
{ label: "Disable", handler: closeWrapper(onDisable) }, { label: "Disable", handler: fnWrapper(onDisable) },
{ label: "Refresh", handler: closeWrapper(onEnhance) }, { label: "Edit Info", handler: onEditInfo },
{ label: "Edit", handler: onEdit }, { label: "Edit File", handler: onEditFile },
{ label: "File", handler: onView }, { label: "Open File", handler: onOpenFile },
{ label: "To Top", show: !hasError, handler: closeWrapper(onMoveTop) }, { label: "To Top", show: showMove, handler: fnWrapper(onMoveTop) },
{ label: "To End", show: !hasError, handler: closeWrapper(onMoveEnd) }, { label: "To End", show: showMove, handler: fnWrapper(onMoveEnd) },
{ label: "Delete", handler: closeWrapper(onDelete) }, { label: "Delete", handler: fnWrapper(onDelete) },
]; ];
const disableMenu = [ const disableMenu = [
{ label: "Enable", handler: closeWrapper(onEnable) }, { label: "Enable", handler: fnWrapper(onEnable) },
{ label: "Edit", handler: onEdit }, { label: "Edit Info", handler: onEditInfo },
{ label: "File", handler: onView }, { label: "Edit File", handler: onEditFile },
{ label: "Delete", handler: closeWrapper(onDelete) }, { label: "Open File", handler: onOpenFile },
{ label: "Delete", handler: fnWrapper(onDelete) },
]; ];
const boxStyle = { const boxStyle = {
@@ -208,6 +222,10 @@ const ProfileMore = (props: Props) => {
onClose={() => setAnchorEl(null)} onClose={() => setAnchorEl(null)}
anchorPosition={position} anchorPosition={position}
anchorReference="anchorPosition" anchorReference="anchorPosition"
transitionDuration={225}
TransitionProps={
OS === "macos" ? { style: { transitionDuration: "225ms" } } : {}
}
onContextMenu={(e) => { onContextMenu={(e) => {
setAnchorEl(null); setAnchorEl(null);
e.preventDefault(); e.preventDefault();
@@ -221,7 +239,7 @@ const ProfileMore = (props: Props) => {
onClick={item.handler} onClick={item.handler}
sx={{ minWidth: 133 }} sx={{ minWidth: 133 }}
> >
{item.label} {t(item.label)}
</MenuItem> </MenuItem>
))} ))}
</Menu> </Menu>
@@ -233,6 +251,15 @@ const ProfileMore = (props: Props) => {
onClose={() => setEditOpen(false)} onClose={() => setEditOpen(false)}
/> />
)} )}
{fileOpen && (
<FileEditor
uid={uid}
open={fileOpen}
mode={type === "merge" ? "yaml" : "javascript"}
onClose={() => setFileOpen(false)}
/>
)}
</> </>
); );
}; };

View File

@@ -1,4 +1,4 @@
import { useState } from "react"; import { useRef, useState } from "react";
import { useSWRConfig } from "swr"; import { useSWRConfig } from "swr";
import { useLockFn, useSetState } from "ahooks"; import { useLockFn, useSetState } from "ahooks";
import { import {
@@ -17,6 +17,7 @@ import {
import { Settings } from "@mui/icons-material"; import { Settings } from "@mui/icons-material";
import { createProfile } from "../../services/cmds"; import { createProfile } from "../../services/cmds";
import Notice from "../base/base-notice"; import Notice from "../base/base-notice";
import FileInput from "./file-input";
interface Props { interface Props {
open: boolean; open: boolean;
@@ -37,9 +38,10 @@ const ProfileNew = (props: Props) => {
}); });
const [showOpt, setShowOpt] = useState(false); const [showOpt, setShowOpt] = useState(false);
const [option, setOption] = useSetState({ // can add more option
user_agent: "", const [option, setOption] = useSetState({ user_agent: "" });
}); // able to add more option // file input
const fileDataRef = useRef<string | null>(null);
const onCreate = useLockFn(async () => { const onCreate = useLockFn(async () => {
if (!form.type) { if (!form.type) {
@@ -54,11 +56,16 @@ const ProfileNew = (props: Props) => {
throw new Error("The URL should not be null"); throw new Error("The URL should not be null");
} }
const option_ = showOpt ? option : undefined; const option_ = form.type === "remote" ? option : undefined;
await createProfile({ ...form, name, option: option_ }); const item = { ...form, name, option: option_ };
const fileData = form.type === "local" ? fileDataRef.current : null;
await createProfile(item, fileData);
setForm({ type: "remote", name: "", desc: "", url: "" }); setForm({ type: "remote", name: "", desc: "", url: "" });
setOption({ user_agent: "" }); setOption({ user_agent: "" });
setShowOpt(false); setShowOpt(false);
fileDataRef.current = null;
mutate("getProfiles"); mutate("getProfiles");
onClose(); onClose();
@@ -97,6 +104,7 @@ const ProfileNew = (props: Props) => {
<TextField <TextField
{...textFieldProps} {...textFieldProps}
label="Name" label="Name"
autoComplete="off"
value={form.name} value={form.name}
onChange={(e) => setForm({ name: e.target.value })} onChange={(e) => setForm({ name: e.target.value })}
/> />
@@ -104,6 +112,7 @@ const ProfileNew = (props: Props) => {
<TextField <TextField
{...textFieldProps} {...textFieldProps}
label="Descriptions" label="Descriptions"
autoComplete="off"
value={form.desc} value={form.desc}
onChange={(e) => setForm({ desc: e.target.value })} onChange={(e) => setForm({ desc: e.target.value })}
/> />
@@ -112,15 +121,21 @@ const ProfileNew = (props: Props) => {
<TextField <TextField
{...textFieldProps} {...textFieldProps}
label="Subscription Url" label="Subscription Url"
autoComplete="off"
value={form.url} value={form.url}
onChange={(e) => setForm({ url: e.target.value })} onChange={(e) => setForm({ url: e.target.value })}
/> />
)} )}
{form.type === "local" && (
<FileInput onChange={(val) => (fileDataRef.current = val)} />
)}
{showOpt && ( {showOpt && (
<TextField <TextField
{...textFieldProps} {...textFieldProps}
label="User Agent" label="User Agent"
autoComplete="off"
value={option.user_agent} value={option.user_agent}
onChange={(e) => setOption({ user_agent: e.target.value })} onChange={(e) => setOption({ user_agent: e.target.value })}
/> />

View File

@@ -1,20 +1,14 @@
import useSWR, { useSWRConfig } from "swr";
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
import { useSWRConfig } from "swr";
import { useLockFn } from "ahooks"; import { useLockFn } from "ahooks";
import { Virtuoso } from "react-virtuoso"; import { Virtuoso } from "react-virtuoso";
import { Box, IconButton, TextField } from "@mui/material";
import {
MyLocationRounded,
NetworkCheckRounded,
FilterAltRounded,
FilterAltOffRounded,
VisibilityRounded,
VisibilityOffRounded,
} from "@mui/icons-material";
import { ApiType } from "../../services/types"; import { ApiType } from "../../services/types";
import { updateProxy } from "../../services/api"; import { updateProxy } from "../../services/api";
import delayManager from "../../services/delay"; import { getProfiles, patchProfile } from "../../services/cmds";
import useSortProxy, { ProxySortType } from "./use-sort-proxy";
import useFilterProxy from "./use-filter-proxy"; import useFilterProxy from "./use-filter-proxy";
import delayManager from "../../services/delay";
import ProxyHead from "./proxy-head";
import ProxyItem from "./proxy-item"; import ProxyItem from "./proxy-item";
interface Props { interface Props {
@@ -23,26 +17,46 @@ interface Props {
proxies: ApiType.ProxyItem[]; proxies: ApiType.ProxyItem[];
} }
// this component will be used for DIRECT/GLOBAL
const ProxyGlobal = (props: Props) => { const ProxyGlobal = (props: Props) => {
const { groupName, curProxy, proxies } = props; const { groupName, curProxy, proxies } = props;
const { mutate } = useSWRConfig(); const { mutate } = useSWRConfig();
const [now, setNow] = useState(curProxy || "DIRECT"); const [now, setNow] = useState(curProxy || "DIRECT");
const [showType, setShowType] = useState(true); const [showType, setShowType] = useState(true);
const [showFilter, setShowFilter] = useState(false); const [sortType, setSortType] = useState<ProxySortType>(0);
const [filterText, setFilterText] = useState(""); const [filterText, setFilterText] = useState("");
const virtuosoRef = useRef<any>(); const virtuosoRef = useRef<any>();
const filterProxies = useFilterProxy(proxies, groupName, filterText); const filterProxies = useFilterProxy(proxies, groupName, filterText);
const sortedProxies = useSortProxy(filterProxies, groupName, sortType);
const { data: profiles } = useSWR("getProfiles", getProfiles);
const onChangeProxy = useLockFn(async (name: string) => { const onChangeProxy = useLockFn(async (name: string) => {
await updateProxy("GLOBAL", name); await updateProxy(groupName, name);
mutate("getProxies");
setNow(name); setNow(name);
if (groupName === "DIRECT") return;
// update global selected
const profile = profiles?.items?.find((p) => p.uid === profiles.current);
if (!profile) return;
if (!profile.selected) profile.selected = [];
const index = profile.selected.findIndex((item) => item.name === groupName);
if (index < 0) {
profile.selected.unshift({ name: groupName, now: name });
} else {
profile.selected[index] = { name: groupName, now: name };
}
await patchProfile(profiles!.current!, { selected: profile.selected });
}); });
const onLocation = (smooth = true) => { const onLocation = (smooth = true) => {
const index = filterProxies.findIndex((p) => p.name === now); const index = sortedProxies.findIndex((p) => p.name === now);
if (index >= 0) { if (index >= 0) {
virtuosoRef.current?.scrollToIndex?.({ virtuosoRef.current?.scrollToIndex?.({
@@ -54,89 +68,60 @@ const ProxyGlobal = (props: Props) => {
}; };
const onCheckAll = useLockFn(async () => { const onCheckAll = useLockFn(async () => {
const names = filterProxies.map((p) => p.name); const names = sortedProxies.map((p) => p.name);
await delayManager.checkListDelay( await delayManager.checkListDelay({ names, groupName, skipNum: 8 }, () =>
{ names, groupName, skipNum: 8, maxTimeout: 600 }, mutate("getProxies")
() => mutate("getProxies")
); );
mutate("getProxies");
}); });
useEffect(() => onLocation(false), [groupName]); useEffect(() => onLocation(false), [groupName]);
useEffect(() => {
if (!showFilter) setFilterText("");
}, [showFilter]);
useEffect(() => { useEffect(() => {
if (groupName === "DIRECT") setNow("DIRECT"); if (groupName === "DIRECT") setNow("DIRECT");
if (groupName === "GLOBAL") setNow(curProxy || "DIRECT"); else if (groupName === "GLOBAL") {
}, [groupName, curProxy]); if (profiles) {
const current = profiles.current;
const profile = profiles.items?.find((p) => p.uid === current);
profile?.selected?.forEach((item) => {
if (item.name === "GLOBAL") {
if (item.now && item.now !== curProxy) {
updateProxy("GLOBAL", item.now).then(() => setNow(item!.now!));
mutate("getProxies");
}
}
});
}
setNow(curProxy || "DIRECT");
}
}, [groupName, curProxy, profiles]);
return ( return (
<> <>
<Box <ProxyHead
sx={{ sx={{ px: 3, my: 0.5, button: { mr: 0.5 } }}
px: 3, showType={showType}
my: 0.5, sortType={sortType}
display: "flex", groupName={groupName}
alignItems: "center", filterText={filterText}
button: { mr: 0.5 }, onLocation={onLocation}
}} onCheckDelay={onCheckAll}
> onShowType={setShowType}
<IconButton onSortType={setSortType}
size="small" onFilterText={setFilterText}
title="location" />
onClick={() => onLocation(true)}
>
<MyLocationRounded />
</IconButton>
<IconButton size="small" title="check" onClick={onCheckAll}>
<NetworkCheckRounded />
</IconButton>
<IconButton
size="small"
title="check"
onClick={() => setShowType(!showType)}
>
{showType ? <VisibilityRounded /> : <VisibilityOffRounded />}
</IconButton>
<IconButton
size="small"
title="check"
onClick={() => setShowFilter(!showFilter)}
>
{showFilter ? <FilterAltRounded /> : <FilterAltOffRounded />}
</IconButton>
{showFilter && (
<TextField
autoFocus
hiddenLabel
value={filterText}
size="small"
variant="outlined"
placeholder="Filter conditions"
onChange={(e) => setFilterText(e.target.value)}
sx={{ ml: 0.5, flex: "1 1 auto", input: { py: 0.65, px: 1 } }}
/>
)}
</Box>
<Virtuoso <Virtuoso
ref={virtuosoRef} ref={virtuosoRef}
style={{ height: "calc(100% - 40px)" }} style={{ height: "calc(100% - 40px)" }}
totalCount={filterProxies.length} totalCount={sortedProxies.length}
itemContent={(index) => ( itemContent={(index) => (
<ProxyItem <ProxyItem
groupName={groupName} groupName={groupName}
proxy={filterProxies[index]} proxy={sortedProxies[index]}
selected={filterProxies[index].name === now} selected={sortedProxies[index].name === now}
showType={showType} showType={showType}
onClick={onChangeProxy} onClick={onChangeProxy}
sx={{ py: 0, px: 2 }} sx={{ py: 0, px: 2 }}

View File

@@ -6,28 +6,22 @@ import {
Box, Box,
Collapse, Collapse,
Divider, Divider,
IconButton,
List, List,
ListItem, ListItem,
ListItemText, ListItemText,
TextField,
} from "@mui/material"; } from "@mui/material";
import { import {
SendRounded, SendRounded,
ExpandLessRounded, ExpandLessRounded,
ExpandMoreRounded, ExpandMoreRounded,
MyLocationRounded,
NetworkCheckRounded,
FilterAltRounded,
FilterAltOffRounded,
VisibilityRounded,
VisibilityOffRounded,
} from "@mui/icons-material"; } from "@mui/icons-material";
import { ApiType } from "../../services/types"; import { ApiType } from "../../services/types";
import { updateProxy } from "../../services/api"; import { updateProxy } from "../../services/api";
import { getProfiles, patchProfile } from "../../services/cmds"; import { getProfiles, patchProfile } from "../../services/cmds";
import delayManager from "../../services/delay"; import useSortProxy, { ProxySortType } from "./use-sort-proxy";
import useFilterProxy from "./use-filter-proxy"; import useFilterProxy from "./use-filter-proxy";
import delayManager from "../../services/delay";
import ProxyHead from "./proxy-head";
import ProxyItem from "./proxy-item"; import ProxyItem from "./proxy-item";
interface Props { interface Props {
@@ -38,13 +32,14 @@ const ProxyGroup = ({ group }: Props) => {
const { mutate } = useSWRConfig(); const { mutate } = useSWRConfig();
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [now, setNow] = useState(group.now); const [now, setNow] = useState(group.now);
const [showType, setShowType] = useState(false); const [showType, setShowType] = useState(false);
const [showFilter, setShowFilter] = useState(false); const [sortType, setSortType] = useState<ProxySortType>(0);
const [filterText, setFilterText] = useState(""); const [filterText, setFilterText] = useState("");
const proxies = group.all ?? [];
const virtuosoRef = useRef<any>(); const virtuosoRef = useRef<any>();
const filterProxies = useFilterProxy(proxies, group.name, filterText); const filterProxies = useFilterProxy(group.all, group.name, filterText);
const sortedProxies = useSortProxy(filterProxies, group.name, sortType);
const { data: profiles } = useSWR("getProfiles", getProfiles); const { data: profiles } = useSWR("getProfiles", getProfiles);
@@ -82,7 +77,7 @@ const ProxyGroup = ({ group }: Props) => {
}); });
const onLocation = (smooth = true) => { const onLocation = (smooth = true) => {
const index = filterProxies.findIndex((p) => p.name === now); const index = sortedProxies.findIndex((p) => p.name === now);
if (index >= 0) { if (index >= 0) {
virtuosoRef.current?.scrollToIndex?.({ virtuosoRef.current?.scrollToIndex?.({
@@ -94,21 +89,14 @@ const ProxyGroup = ({ group }: Props) => {
}; };
const onCheckAll = useLockFn(async () => { const onCheckAll = useLockFn(async () => {
const names = filterProxies.map((p) => p.name); const names = sortedProxies.map((p) => p.name);
const groupName = group.name; const groupName = group.name;
await delayManager.checkListDelay( await delayManager.checkListDelay({ names, groupName, skipNum: 8 }, () =>
{ names, groupName, skipNum: 8, maxTimeout: 600 }, mutate("getProxies")
() => mutate("getProxies")
); );
mutate("getProxies");
}); });
useEffect(() => {
if (!showFilter) setFilterText("");
}, [showFilter]);
// auto scroll to current index // auto scroll to current index
useEffect(() => { useEffect(() => {
if (open) { if (open) {
@@ -136,59 +124,20 @@ const ProxyGroup = ({ group }: Props) => {
</ListItem> </ListItem>
<Collapse in={open} timeout="auto" unmountOnExit> <Collapse in={open} timeout="auto" unmountOnExit>
<Box <ProxyHead
sx={{ sx={{ pl: 4, pr: 3, my: 0.5, button: { mr: 0.5 } }}
pl: 4, showType={showType}
pr: 3, sortType={sortType}
my: 0.5, groupName={group.name}
display: "flex", filterText={filterText}
alignItems: "center", onLocation={onLocation}
button: { mr: 0.5 }, onCheckDelay={onCheckAll}
}} onShowType={setShowType}
> onSortType={setSortType}
<IconButton onFilterText={setFilterText}
size="small" />
title="location"
onClick={() => onLocation(true)}
>
<MyLocationRounded />
</IconButton>
<IconButton size="small" title="check" onClick={onCheckAll}> {!sortedProxies.length && (
<NetworkCheckRounded />
</IconButton>
<IconButton
size="small"
title="check"
onClick={() => setShowType(!showType)}
>
{showType ? <VisibilityRounded /> : <VisibilityOffRounded />}
</IconButton>
<IconButton
size="small"
title="check"
onClick={() => setShowFilter(!showFilter)}
>
{showFilter ? <FilterAltRounded /> : <FilterAltOffRounded />}
</IconButton>
{showFilter && (
<TextField
autoFocus
hiddenLabel
value={filterText}
size="small"
variant="outlined"
placeholder="Filter conditions"
onChange={(e) => setFilterText(e.target.value)}
sx={{ ml: 0.5, flex: "1 1 auto", input: { py: 0.65, px: 1 } }}
/>
)}
</Box>
{!filterProxies.length && (
<Box <Box
sx={{ sx={{
py: 3, py: 3,
@@ -201,16 +150,16 @@ const ProxyGroup = ({ group }: Props) => {
</Box> </Box>
)} )}
{filterProxies.length >= 10 ? ( {sortedProxies.length >= 10 ? (
<Virtuoso <Virtuoso
ref={virtuosoRef} ref={virtuosoRef}
style={{ height: "320px", marginBottom: "4px" }} style={{ height: "320px", marginBottom: "4px" }}
totalCount={filterProxies.length} totalCount={sortedProxies.length}
itemContent={(index) => ( itemContent={(index) => (
<ProxyItem <ProxyItem
groupName={group.name} groupName={group.name}
proxy={filterProxies[index]} proxy={sortedProxies[index]}
selected={filterProxies[index].name === now} selected={sortedProxies[index].name === now}
showType={showType} showType={showType}
sx={{ py: 0, pl: 4 }} sx={{ py: 0, pl: 4 }}
onClick={onChangeProxy} onClick={onChangeProxy}
@@ -223,7 +172,7 @@ const ProxyGroup = ({ group }: Props) => {
disablePadding disablePadding
sx={{ maxHeight: "320px", overflow: "auto", mb: "4px" }} sx={{ maxHeight: "320px", overflow: "auto", mb: "4px" }}
> >
{filterProxies.map((proxy) => ( {sortedProxies.map((proxy) => (
<ProxyItem <ProxyItem
key={proxy.name} key={proxy.name}
groupName={group.name} groupName={group.name}

View File

@@ -0,0 +1,147 @@
import { useState } from "react";
import { Box, IconButton, TextField, SxProps } from "@mui/material";
import {
AccessTimeRounded,
MyLocationRounded,
NetworkCheckRounded,
FilterAltRounded,
FilterAltOffRounded,
VisibilityRounded,
VisibilityOffRounded,
WifiTetheringRounded,
WifiTetheringOffRounded,
SortByAlphaRounded,
SortRounded,
} from "@mui/icons-material";
import delayManager from "../../services/delay";
import type { ProxySortType } from "./use-sort-proxy";
interface Props {
sx?: SxProps;
groupName: string;
showType: boolean;
sortType: ProxySortType;
filterText: string;
onLocation: () => void;
onCheckDelay: () => void;
onShowType: (val: boolean) => void;
onSortType: (val: ProxySortType) => void;
onFilterText: (val: string) => void;
}
const ProxyHead = (props: Props) => {
const { sx = {}, groupName, showType, sortType, filterText } = props;
const [textState, setTextState] = useState<"url" | "filter" | null>(null);
const [testUrl, setTestUrl] = useState(delayManager.getUrl(groupName) || "");
return (
<Box sx={{ display: "flex", alignItems: "center", ...sx }}>
<IconButton
size="small"
title="location"
color="inherit"
onClick={props.onLocation}
>
<MyLocationRounded />
</IconButton>
<IconButton
size="small"
color="inherit"
title="delay check"
onClick={() => {
// Remind the user that it is custom test url
if (testUrl?.trim() && textState !== "filter") {
setTextState("url");
}
props.onCheckDelay();
}}
>
<NetworkCheckRounded />
</IconButton>
<IconButton
size="small"
color="inherit"
title={["sort by default", "sort by delay", "sort by name"][sortType]}
onClick={() => props.onSortType(((sortType + 1) % 3) as ProxySortType)}
>
{sortType === 0 && <SortRounded />}
{sortType === 1 && <AccessTimeRounded />}
{sortType === 2 && <SortByAlphaRounded />}
</IconButton>
<IconButton
size="small"
color="inherit"
title="edit test url"
onClick={() => setTextState((ts) => (ts === "url" ? null : "url"))}
>
{textState === "url" ? (
<WifiTetheringRounded />
) : (
<WifiTetheringOffRounded />
)}
</IconButton>
<IconButton
size="small"
color="inherit"
title="proxy detail"
onClick={() => props.onShowType(!showType)}
>
{showType ? <VisibilityRounded /> : <VisibilityOffRounded />}
</IconButton>
<IconButton
size="small"
color="inherit"
title="filter"
onClick={() =>
setTextState((ts) => (ts === "filter" ? null : "filter"))
}
>
{textState === "filter" ? (
<FilterAltRounded />
) : (
<FilterAltOffRounded />
)}
</IconButton>
{textState === "filter" && (
<TextField
autoFocus
hiddenLabel
value={filterText}
size="small"
variant="outlined"
placeholder="Filter conditions"
onChange={(e) => props.onFilterText(e.target.value)}
sx={{ ml: 0.5, flex: "1 1 auto", input: { py: 0.65, px: 1 } }}
/>
)}
{textState === "url" && (
<TextField
autoFocus
hiddenLabel
autoSave="off"
autoComplete="off"
value={testUrl}
size="small"
variant="outlined"
placeholder="Test url"
onChange={(e) => {
setTestUrl(e.target.value);
delayManager.setUrl(groupName, e.target.value);
}}
sx={{ ml: 0.5, flex: "1 1 auto", input: { py: 0.65, px: 1 } }}
/>
)}
</Box>
);
};
export default ProxyHead;

View File

@@ -1,4 +1,5 @@
import { useEffect, useRef, useState } from "react"; import { useEffect, useState } from "react";
import { useLockFn } from "ahooks";
import { CheckCircleOutlineRounded } from "@mui/icons-material"; import { CheckCircleOutlineRounded } from "@mui/icons-material";
import { import {
alpha, alpha,
@@ -24,8 +25,9 @@ interface Props {
} }
const Widget = styled(Box)(() => ({ const Widget = styled(Box)(() => ({
padding: "4px 6px", padding: "3px 6px",
fontSize: 14, fontSize: 14,
borderRadius: "4px",
})); }));
const TypeBox = styled(Box)(({ theme }) => ({ const TypeBox = styled(Box)(({ theme }) => ({
@@ -50,20 +52,12 @@ const ProxyItem = (props: Props) => {
} }
}, [proxy]); }, [proxy]);
const delayRef = useRef(false); const onDelay = useLockFn(async () => {
const onDelay = (e: any) => { return delayManager
e.preventDefault();
e.stopPropagation();
if (delayRef.current) return;
delayRef.current = true;
delayManager
.checkDelay(proxy.name, groupName) .checkDelay(proxy.name, groupName)
.then((result) => setDelay(result)) .then((result) => setDelay(result))
.catch(() => setDelay(1e6)) .catch(() => setDelay(1e6));
.finally(() => (delayRef.current = false)); });
};
return ( return (
<ListItem sx={sx}> <ListItem sx={sx}>
@@ -111,13 +105,27 @@ const ProxyItem = (props: Props) => {
<ListItemIcon <ListItemIcon
sx={{ justifyContent: "flex-end", color: "primary.main" }} sx={{ justifyContent: "flex-end", color: "primary.main" }}
> >
<Widget className="the-check" onClick={onDelay}> <Widget
className="the-check"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
onDelay();
}}
sx={(theme) => ({
":hover": { bgcolor: alpha(theme.palette.primary.main, 0.15) },
})}
>
Check Check
</Widget> </Widget>
<Widget <Widget
className="the-delay" className="the-delay"
onClick={onDelay} onClick={(e) => {
e.preventDefault();
e.stopPropagation();
onDelay();
}}
color={ color={
delay > 500 delay > 500
? "error.main" ? "error.main"
@@ -125,6 +133,9 @@ const ProxyItem = (props: Props) => {
? "success.main" ? "success.main"
: "text.secondary" : "text.secondary"
} }
sx={(theme) => ({
":hover": { bgcolor: alpha(theme.palette.primary.main, 0.15) },
})}
> >
{delay > 1e5 ? "Error" : delay > 3000 ? "Timeout" : `${delay}ms`} {delay > 1e5 ? "Error" : delay > 3000 ? "Timeout" : `${delay}ms`}
</Widget> </Widget>

View File

@@ -15,6 +15,7 @@ export default function useFilterProxy(
filterText: string filterText: string
) { ) {
return useMemo(() => { return useMemo(() => {
if (!proxies) return [];
if (!filterText) return proxies; if (!filterText) return proxies;
const res1 = regex1.exec(filterText); const res1 = regex1.exec(filterText);

View File

@@ -0,0 +1,38 @@
import { useMemo } from "react";
import { ApiType } from "../../services/types";
import delayManager from "../../services/delay";
// default | delay | alpha
export type ProxySortType = 0 | 1 | 2;
/**
* sort the proxy
*/
export default function useSortProxy(
proxies: ApiType.ProxyItem[],
groupName: string,
sortType: ProxySortType
) {
return useMemo(() => {
if (!proxies) return [];
if (sortType === 0) return proxies;
const list = proxies.slice();
if (sortType === 1) {
list.sort((a, b) => {
const ad = delayManager.getDelay(a.name, groupName);
const bd = delayManager.getDelay(b.name, groupName);
if (ad === -1) return 1;
if (bd === -1) return -1;
return ad - bd;
});
} else {
list.sort((a, b) => a.name.localeCompare(b.name));
}
return list;
}, [proxies, groupName, sortType]);
}

View File

@@ -1,5 +1,6 @@
import useSWR, { useSWRConfig } from "swr"; import useSWR, { useSWRConfig } from "swr";
import { useSetRecoilState } from "recoil"; import { useSetRecoilState } from "recoil";
import { useTranslation } from "react-i18next";
import { import {
ListItemText, ListItemText,
TextField, TextField,
@@ -21,15 +22,16 @@ interface Props {
} }
const SettingClash = ({ onError }: Props) => { const SettingClash = ({ onError }: Props) => {
const { t } = useTranslation();
const { mutate } = useSWRConfig(); const { mutate } = useSWRConfig();
const { data: clashConfig } = useSWR("getClashConfig", getClashConfig); const { data: clashConfig } = useSWR("getClashConfig", getClashConfig);
const { data: versionData } = useSWR("getVersion", getVersion); const { data: versionData } = useSWR("getVersion", getVersion);
const { const {
ipv6 = false, ipv6,
"allow-lan": allowLan = false, "allow-lan": allowLan,
"log-level": logLevel = "silent", "log-level": logLevel,
"mixed-port": mixedPort = 0, "mixed-port": mixedPort,
} = clashConfig ?? {}; } = clashConfig ?? {};
const setGlobalClashPort = useSetRecoilState(atomClashPort); const setGlobalClashPort = useSetRecoilState(atomClashPort);
@@ -64,11 +66,11 @@ const SettingClash = ({ onError }: Props) => {
: versionData?.version || "-"; : versionData?.version || "-";
return ( return (
<SettingList title="Clash Setting"> <SettingList title={t("Clash Setting")}>
<SettingItem> <SettingItem>
<ListItemText primary="Allow Lan" /> <ListItemText primary={t("Allow Lan")} />
<GuardState <GuardState
value={allowLan} value={allowLan ?? false}
valueProps="checked" valueProps="checked"
onCatch={onError} onCatch={onError}
onFormat={onSwitchFormat} onFormat={onSwitchFormat}
@@ -80,9 +82,9 @@ const SettingClash = ({ onError }: Props) => {
</SettingItem> </SettingItem>
<SettingItem> <SettingItem>
<ListItemText primary="IPv6" /> <ListItemText primary={t("IPv6")} />
<GuardState <GuardState
value={ipv6} value={ipv6 ?? false}
valueProps="checked" valueProps="checked"
onCatch={onError} onCatch={onError}
onFormat={onSwitchFormat} onFormat={onSwitchFormat}
@@ -94,9 +96,9 @@ const SettingClash = ({ onError }: Props) => {
</SettingItem> </SettingItem>
<SettingItem> <SettingItem>
<ListItemText primary="Log Level" /> <ListItemText primary={t("Log Level")} />
<GuardState <GuardState
value={logLevel} value={logLevel ?? "info"}
onCatch={onError} onCatch={onError}
onFormat={(e: any) => e.target.value} onFormat={(e: any) => e.target.value}
onChange={(e) => onChangeData({ "log-level": e })} onChange={(e) => onChangeData({ "log-level": e })}
@@ -113,9 +115,9 @@ const SettingClash = ({ onError }: Props) => {
</SettingItem> </SettingItem>
<SettingItem> <SettingItem>
<ListItemText primary="Mixed Port" /> <ListItemText primary={t("Mixed Port")} />
<GuardState <GuardState
value={mixedPort!} value={mixedPort ?? 0}
onCatch={onError} onCatch={onError}
onFormat={(e: any) => +e.target.value?.replace(/\D+/, "")} onFormat={(e: any) => +e.target.value?.replace(/\D+/, "")}
onChange={(e) => onChangeData({ "mixed-port": e })} onChange={(e) => onChangeData({ "mixed-port": e })}
@@ -127,7 +129,7 @@ const SettingClash = ({ onError }: Props) => {
</SettingItem> </SettingItem>
<SettingItem> <SettingItem>
<ListItemText primary="Clash core" /> <ListItemText primary={t("Clash core")} />
<Typography sx={{ py: 1 }}>{clashVer}</Typography> <Typography sx={{ py: 1 }}>{clashVer}</Typography>
</SettingItem> </SettingItem>
</SettingList> </SettingList>

View File

@@ -1,4 +1,5 @@
import useSWR, { useSWRConfig } from "swr"; import useSWR, { useSWRConfig } from "swr";
import { useTranslation } from "react-i18next";
import { Box, ListItemText, Switch, TextField } from "@mui/material"; import { Box, ListItemText, Switch, TextField } from "@mui/material";
import { getVergeConfig, patchVergeConfig } from "../../services/cmds"; import { getVergeConfig, patchVergeConfig } from "../../services/cmds";
import { SettingList, SettingItem } from "./setting"; import { SettingList, SettingItem } from "./setting";
@@ -11,15 +12,17 @@ interface Props {
} }
const SettingSystem = ({ onError }: Props) => { const SettingSystem = ({ onError }: Props) => {
const { t } = useTranslation();
const { mutate } = useSWRConfig(); const { mutate } = useSWRConfig();
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig); const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
const { const {
enable_tun_mode = false, enable_tun_mode,
enable_auto_launch = false, enable_auto_launch,
enable_system_proxy = false, enable_silent_start,
system_proxy_bypass = "", enable_system_proxy,
enable_proxy_guard = false, system_proxy_bypass,
enable_proxy_guard,
} = vergeConfig ?? {}; } = vergeConfig ?? {};
const onSwitchFormat = (_e: any, value: boolean) => value; const onSwitchFormat = (_e: any, value: boolean) => value;
@@ -28,11 +31,11 @@ const SettingSystem = ({ onError }: Props) => {
}; };
return ( return (
<SettingList title="System Setting"> <SettingList title={t("System Setting")}>
<SettingItem> <SettingItem>
<ListItemText primary="Tun Mode" /> <ListItemText primary={t("Tun Mode")} />
<GuardState <GuardState
value={enable_tun_mode} value={enable_tun_mode ?? false}
valueProps="checked" valueProps="checked"
onCatch={onError} onCatch={onError}
onFormat={onSwitchFormat} onFormat={onSwitchFormat}
@@ -44,9 +47,9 @@ const SettingSystem = ({ onError }: Props) => {
</SettingItem> </SettingItem>
<SettingItem> <SettingItem>
<ListItemText primary="Auto Launch" /> <ListItemText primary={t("Auto Launch")} />
<GuardState <GuardState
value={enable_auto_launch} value={enable_auto_launch ?? false}
valueProps="checked" valueProps="checked"
onCatch={onError} onCatch={onError}
onFormat={onSwitchFormat} onFormat={onSwitchFormat}
@@ -57,17 +60,31 @@ const SettingSystem = ({ onError }: Props) => {
</GuardState> </GuardState>
</SettingItem> </SettingItem>
<SettingItem>
<ListItemText primary={t("Silent Start")} />
<GuardState
value={enable_silent_start ?? false}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_silent_start: e })}
onGuard={(e) => patchVergeConfig({ enable_silent_start: e })}
>
<Switch edge="end" />
</GuardState>
</SettingItem>
<SettingItem> <SettingItem>
<ListItemText <ListItemText
primary={ primary={
<Box sx={{ display: "flex", alignItems: "center" }}> <Box sx={{ display: "flex", alignItems: "center" }}>
System Proxy {t("System Proxy")}
<SysproxyTooltip /> <SysproxyTooltip />
</Box> </Box>
} }
/> />
<GuardState <GuardState
value={enable_system_proxy} value={enable_system_proxy ?? false}
valueProps="checked" valueProps="checked"
onCatch={onError} onCatch={onError}
onFormat={onSwitchFormat} onFormat={onSwitchFormat}
@@ -83,9 +100,9 @@ const SettingSystem = ({ onError }: Props) => {
{enable_system_proxy && ( {enable_system_proxy && (
<SettingItem> <SettingItem>
<ListItemText primary="Proxy Guard" /> <ListItemText primary={t("Proxy Guard")} />
<GuardState <GuardState
value={enable_proxy_guard} value={enable_proxy_guard ?? false}
valueProps="checked" valueProps="checked"
onCatch={onError} onCatch={onError}
onFormat={onSwitchFormat} onFormat={onSwitchFormat}
@@ -99,7 +116,7 @@ const SettingSystem = ({ onError }: Props) => {
{enable_system_proxy && ( {enable_system_proxy && (
<SettingItem> <SettingItem>
<ListItemText primary="Proxy Bypass" /> <ListItemText primary={t("Proxy Bypass")} />
<GuardState <GuardState
value={system_proxy_bypass ?? ""} value={system_proxy_bypass ?? ""}
onCatch={onError} onCatch={onError}

View File

@@ -0,0 +1,146 @@
import useSWR from "swr";
import { useEffect, useState } from "react";
import { useLockFn } from "ahooks";
import { useTranslation } from "react-i18next";
import {
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
List,
ListItem,
ListItemText,
styled,
TextField,
} from "@mui/material";
import { getVergeConfig, patchVergeConfig } from "../../services/cmds";
import { defaultTheme } from "../../pages/_theme";
interface Props {
open: boolean;
onClose: () => void;
onError?: (err: Error) => void;
}
const Item = styled(ListItem)(() => ({
padding: "5px 2px",
}));
const Round = styled("div")(() => ({
width: "24px",
height: "24px",
borderRadius: "18px",
display: "inline-block",
marginRight: "8px",
}));
const SettingTheme = (props: Props) => {
const { open, onClose, onError } = props;
const { t } = useTranslation();
const { data: vergeConfig, mutate } = useSWR(
"getVergeConfig",
getVergeConfig
);
const { theme_setting } = vergeConfig ?? {};
const [theme, setTheme] = useState(theme_setting || {});
useEffect(() => {
setTheme({ ...theme_setting } || {});
}, [theme_setting]);
const textProps = {
size: "small",
autoComplete: "off",
sx: { width: 135 },
} as const;
const handleChange = (field: keyof typeof theme) => (e: any) => {
setTheme((t) => ({ ...t, [field]: e.target.value }));
};
const onSave = useLockFn(async () => {
try {
await patchVergeConfig({ theme_setting: theme });
mutate();
onClose();
} catch (err: any) {
onError?.(err);
}
});
const renderItem = (label: string, key: keyof typeof defaultTheme) => {
return (
<Item>
<ListItemText primary={label} />
<Round sx={{ background: theme[key] || defaultTheme[key] }} />
<TextField
{...textProps}
value={theme[key] ?? ""}
placeholder={defaultTheme[key]}
onChange={handleChange(key)}
onKeyDown={(e) => e.key === "Enter" && onSave()}
/>
</Item>
);
};
return (
<Dialog open={open} onClose={onClose}>
<DialogTitle>{t("Theme Setting")}</DialogTitle>
<DialogContent
sx={{ width: 400, maxHeight: 300, overflow: "auto", pb: 0 }}
>
<List sx={{ pt: 0 }}>
{renderItem("Primary Color", "primary_color")}
{renderItem("Secondary Color", "secondary_color")}
{renderItem("Primary Text", "primary_text")}
{renderItem("Secondary Text", "secondary_text")}
{renderItem("Info Color", "info_color")}
{renderItem("Error Color", "error_color")}
{renderItem("Warning Color", "warning_color")}
{renderItem("Success Color", "success_color")}
<Item>
<ListItemText primary="Font Family" />
<TextField
{...textProps}
value={theme.font_family ?? ""}
onChange={handleChange("font_family")}
onKeyDown={(e) => e.key === "Enter" && onSave()}
/>
</Item>
<Item>
<ListItemText primary="CSS Injection" />
<TextField
{...textProps}
value={theme.css_injection ?? ""}
onChange={handleChange("css_injection")}
onKeyDown={(e) => e.key === "Enter" && onSave()}
/>
</Item>
</List>
</DialogContent>
<DialogActions>
<Button onClick={onClose}>{t("Cancel")}</Button>
<Button onClick={onSave} variant="contained">
{t("Save")}
</Button>
</DialogActions>
</Dialog>
);
};
export default SettingTheme;

View File

@@ -1,5 +1,14 @@
import useSWR, { useSWRConfig } from "swr"; import useSWR, { useSWRConfig } from "swr";
import { IconButton, ListItemText, Switch, Typography } from "@mui/material"; import { useState } from "react";
import { useTranslation } from "react-i18next";
import {
IconButton,
ListItemText,
MenuItem,
Select,
Switch,
Typography,
} from "@mui/material";
import { import {
getVergeConfig, getVergeConfig,
openAppDir, openAppDir,
@@ -12,17 +21,20 @@ import { CmdType } from "../../services/types";
import { version } from "../../../package.json"; import { version } from "../../../package.json";
import PaletteSwitch from "./palette-switch"; import PaletteSwitch from "./palette-switch";
import GuardState from "./guard-state"; import GuardState from "./guard-state";
import SettingTheme from "./setting-theme";
interface Props { interface Props {
onError?: (err: Error) => void; onError?: (err: Error) => void;
} }
const SettingVerge = ({ onError }: Props) => { const SettingVerge = ({ onError }: Props) => {
const { t } = useTranslation();
const { mutate } = useSWRConfig(); const { mutate } = useSWRConfig();
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig); const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
const { theme_mode = "light", theme_blur = false, traffic_graph } = const { theme_mode, theme_blur, traffic_graph, language } = vergeConfig ?? {};
vergeConfig ?? {};
const [themeOpen, setThemeOpen] = useState(false);
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>) => {
@@ -30,9 +42,9 @@ const SettingVerge = ({ onError }: Props) => {
}; };
return ( return (
<SettingList title="Verge Setting"> <SettingList title={t("Verge Setting")}>
<SettingItem> <SettingItem>
<ListItemText primary="Theme Mode" /> <ListItemText primary={t("Theme Mode")} />
<GuardState <GuardState
value={theme_mode === "dark"} value={theme_mode === "dark"}
valueProps="checked" valueProps="checked"
@@ -48,9 +60,9 @@ const SettingVerge = ({ onError }: Props) => {
</SettingItem> </SettingItem>
<SettingItem> <SettingItem>
<ListItemText primary="Theme Blur" /> <ListItemText primary={t("Theme Blur")} />
<GuardState <GuardState
value={theme_blur} value={theme_blur ?? false}
valueProps="checked" valueProps="checked"
onCatch={onError} onCatch={onError}
onFormat={onSwitchFormat} onFormat={onSwitchFormat}
@@ -62,7 +74,7 @@ const SettingVerge = ({ onError }: Props) => {
</SettingItem> </SettingItem>
<SettingItem> <SettingItem>
<ListItemText primary="Traffic Graph" /> <ListItemText primary={t("Traffic Graph")} />
<GuardState <GuardState
value={traffic_graph ?? true} value={traffic_graph ?? true}
valueProps="checked" valueProps="checked"
@@ -76,23 +88,52 @@ const SettingVerge = ({ onError }: Props) => {
</SettingItem> </SettingItem>
<SettingItem> <SettingItem>
<ListItemText primary="Open App Dir" /> <ListItemText primary={t("Language")} />
<GuardState
value={language ?? "en"}
onCatch={onError}
onFormat={(e: any) => e.target.value}
onChange={(e) => onChangeData({ language: e })}
onGuard={(e) => patchVergeConfig({ language: e })}
>
<Select size="small" sx={{ width: 100 }}>
<MenuItem value="zh"></MenuItem>
<MenuItem value="en">English</MenuItem>
</Select>
</GuardState>
</SettingItem>
<SettingItem>
<ListItemText primary={t("Theme Setting")} />
<IconButton
color="inherit"
size="small"
onClick={() => setThemeOpen(true)}
>
<ArrowForward />
</IconButton>
</SettingItem>
<SettingItem>
<ListItemText primary={t("Open App Dir")} />
<IconButton color="inherit" size="small" onClick={openAppDir}> <IconButton color="inherit" size="small" onClick={openAppDir}>
<ArrowForward /> <ArrowForward />
</IconButton> </IconButton>
</SettingItem> </SettingItem>
<SettingItem> <SettingItem>
<ListItemText primary="Open Logs Dir" /> <ListItemText primary={t("Open Logs Dir")} />
<IconButton color="inherit" size="small" onClick={openLogsDir}> <IconButton color="inherit" size="small" onClick={openLogsDir}>
<ArrowForward /> <ArrowForward />
</IconButton> </IconButton>
</SettingItem> </SettingItem>
<SettingItem> <SettingItem>
<ListItemText primary="Version" /> <ListItemText primary={t("Version")} />
<Typography sx={{ py: "6px" }}>v{version}</Typography> <Typography sx={{ py: "6px" }}>v{version}</Typography>
</SettingItem> </SettingItem>
<SettingTheme open={themeOpen} onClose={() => setThemeOpen(false)} />
</SettingList> </SettingList>
); );
}; };

60
src/locales/en.json Normal file
View File

@@ -0,0 +1,60 @@
{
"Label-Proxies": "Proxies",
"Label-Profiles": "Profiles",
"Label-Connections": "Connections",
"Label-Logs": "Logs",
"Label-Settings": "Settings",
"Connections": "Connections",
"Logs": "Logs",
"Clear": "Clear",
"Proxies": "Proxies",
"Proxy Groups": "Proxy Groups",
"rule": "rule",
"global": "global",
"direct": "direct",
"Profiles": "Profiles",
"Profile URL": "Profile URL",
"Import": "Import",
"New": "New",
"Close All": "Close All",
"Select": "Select",
"Edit Info": "Edit Info",
"Edit File": "Edit File",
"Open File": "Open File",
"Update": "Update",
"Update(Proxy)": "Update(Proxy)",
"Delete": "Delete",
"Enable": "Enable",
"Disable": "Disable",
"Refresh": "Refresh",
"To Top": "To Top",
"To End": "To End",
"Settings": "Settings",
"Clash Setting": "Clash Setting",
"System Setting": "System Setting",
"Verge Setting": "Verge Setting",
"Allow Lan": "Allow Lan",
"IPv6": "IPv6",
"Log Level": "Log Level",
"Mixed Port": "Mixed Port",
"Clash core": "Clash core",
"Tun Mode": "Tun Mode",
"Auto Launch": "Auto Launch",
"Silent Start": "Silent Start",
"System Proxy": "System Proxy",
"Proxy Guard": "Proxy Guard",
"Proxy Bypass": "Proxy Bypass",
"Theme Mode": "Theme Mode",
"Theme Blur": "Theme Blur",
"Theme Setting": "Theme Setting",
"Traffic Graph": "Traffic Graph",
"Language": "Language",
"Open App Dir": "Open App Dir",
"Open Logs Dir": "Open Logs Dir",
"Version": "Version",
"Save": "Save",
"Cancel": "Cancel"
}

60
src/locales/zh.json Normal file
View File

@@ -0,0 +1,60 @@
{
"Label-Proxies": "代 理",
"Label-Profiles": "配 置",
"Label-Connections": "连 接",
"Label-Logs": "日 志",
"Label-Settings": "设 置",
"Connections": "连接",
"Logs": "日志",
"Clear": "清除",
"Proxies": "代理",
"Proxy Groups": "代理组",
"rule": "规则",
"global": "全局",
"direct": "直连",
"Profiles": "配置",
"Profile URL": "配置文件链接",
"Import": "导入",
"New": "新建",
"Close All": "关闭全部",
"Select": "使用",
"Edit Info": "编辑信息",
"Edit File": "编辑文件",
"Open File": "打开文件",
"Update": "更新",
"Update(Proxy)": "更新(代理)",
"Delete": "删除",
"Enable": "启用",
"Disable": "禁用",
"Refresh": "刷新",
"To Top": "移到最前",
"To End": "移到末尾",
"Settings": "设置",
"Clash Setting": "Clash 设置",
"System Setting": "系统设置",
"Verge Setting": "Verge 设置",
"Allow Lan": "局域网连接",
"IPv6": "IPv6",
"Log Level": "日志等级",
"Mixed Port": "端口设置",
"Clash core": "Clash 内核",
"Tun Mode": "Tun 模式",
"Auto Launch": "开机自启",
"Silent Start": "静默启动",
"System Proxy": "系统代理",
"Proxy Guard": "系统代理守卫",
"Proxy Bypass": "Proxy Bypass",
"Theme Mode": "暗夜模式",
"Theme Blur": "背景模糊",
"Theme Setting": "主题设置",
"Traffic Graph": "流量图显",
"Language": "语言设置",
"Open App Dir": "应用目录",
"Open Logs Dir": "日志目录",
"Version": "版本",
"Save": "保存",
"Cancel": "取消"
}

View File

@@ -1,4 +1,5 @@
/// <reference types="vite/client" /> /// <reference types="vite/client" />
/// <reference types="vite-plugin-svgr/client" />
import "./assets/styles/index.scss"; import "./assets/styles/index.scss";
import React from "react"; import React from "react";
@@ -7,6 +8,7 @@ import { RecoilRoot } from "recoil";
import { BrowserRouter } from "react-router-dom"; import { BrowserRouter } from "react-router-dom";
import Layout from "./pages/_layout"; import Layout from "./pages/_layout";
import enhance from "./services/enhance"; import enhance from "./services/enhance";
import "./services/i18n";
enhance.setup(); enhance.setup();

View File

@@ -1,67 +1,60 @@
import dayjs from "dayjs";
import i18next from "i18next";
import relativeTime from "dayjs/plugin/relativeTime";
import useSWR, { SWRConfig, useSWRConfig } from "swr"; import useSWR, { SWRConfig, useSWRConfig } from "swr";
import { useEffect, useMemo } from "react"; import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { Route, Routes } from "react-router-dom"; import { Route, Routes } from "react-router-dom";
import { alpha, createTheme, List, Paper, ThemeProvider } from "@mui/material"; import { alpha, List, Paper, ThemeProvider } from "@mui/material";
import { listen } from "@tauri-apps/api/event"; import { listen } from "@tauri-apps/api/event";
import { appWindow } from "@tauri-apps/api/window"; import { appWindow } from "@tauri-apps/api/window";
import { routers } from "./_routers"; import { routers } from "./_routers";
import { getAxios } from "../services/api"; import { getAxios } from "../services/api";
import { getVergeConfig } from "../services/cmds"; import { getVergeConfig } from "../services/cmds";
import LogoSvg from "../assets/image/logo.svg"; import { ReactComponent as LogoSvg } from "../assets/image/logo.svg";
import LayoutItem from "../components/layout/layout-item"; import LayoutItem from "../components/layout/layout-item";
import LayoutControl from "../components/layout/layout-control"; import LayoutControl from "../components/layout/layout-control";
import LayoutTraffic from "../components/layout/layout-traffic"; import LayoutTraffic from "../components/layout/layout-traffic";
import UpdateButton from "../components/layout/update-button"; import UpdateButton from "../components/layout/update-button";
import useCustomTheme from "../components/layout/use-custom-theme";
import getSystem from "../utils/get-system";
import "dayjs/locale/zh-cn";
const isMacos = navigator.userAgent.includes("Mac OS X"); dayjs.extend(relativeTime);
const OS = getSystem();
const Layout = () => { const Layout = () => {
const { t } = useTranslation();
const { mutate } = useSWRConfig(); const { mutate } = useSWRConfig();
const { data } = useSWR("getVergeConfig", getVergeConfig);
const blur = !!data?.theme_blur; const { theme } = useCustomTheme();
const mode = data?.theme_mode ?? "light";
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
const { theme_blur, language } = vergeConfig || {};
useEffect(() => { useEffect(() => {
window.addEventListener("keydown", (e) => { window.addEventListener("keydown", (e) => {
if (e.key === "Escape") appWindow.hide(); if (e.key === "Escape") appWindow.hide();
}); });
listen("restart_clash", async () => { listen("verge://refresh-clash-config", async () => {
// the clash info may be updated // the clash info may be updated
await getAxios(true); await getAxios(true);
// make sure that the clash is ok mutate("getProxies");
setTimeout(() => mutate("getProxies"), 1000);
setTimeout(() => mutate("getProxies"), 2000);
mutate("getClashConfig"); mutate("getClashConfig");
}); });
// update the verge config
listen("verge://refresh-verge-config", () => mutate("getVergeConfig"));
}, []); }, []);
const theme = useMemo(() => { useEffect(() => {
// const background = mode === "light" ? "#f5f5f5" : "#000"; if (language) {
const selectColor = mode === "light" ? "#f5f5f5" : "#d5d5d5"; dayjs.locale(language === "zh" ? "zh-cn" : language);
i18next.changeLanguage(language);
const rootEle = document.documentElement;
rootEle.style.background = "transparent";
rootEle.style.setProperty("--selection-color", selectColor);
return createTheme({
breakpoints: {
values: { xs: 0, sm: 650, md: 900, lg: 1200, xl: 1536 },
},
palette: {
mode,
primary: { main: "#5b5c9d" },
text: { primary: "#637381", secondary: "#909399" },
},
});
}, [mode]);
const onDragging = (e: any) => {
if (e?.target?.dataset?.windrag) {
appWindow.startDragging();
} }
}; }, [language]);
return ( return (
<SWRConfig value={{}}> <SWRConfig value={{}}>
@@ -69,17 +62,23 @@ const Layout = () => {
<Paper <Paper
square square
elevation={0} elevation={0}
className={`${isMacos ? "macos " : ""}layout`} className={`${OS} layout`}
onPointerDown={onDragging} onPointerDown={(e: any) => {
if (e.target?.dataset?.windrag) appWindow.startDragging();
}}
onContextMenu={(e) => {
// only prevent it on Windows
if (OS === "windows") e.preventDefault();
}}
sx={[ sx={[
(theme) => ({ ({ palette }) => ({
bgcolor: alpha(theme.palette.background.paper, blur ? 0.85 : 1), bgcolor: alpha(palette.background.paper, theme_blur ? 0.85 : 1),
}), }),
]} ]}
> >
<div className="layout__left" data-windrag> <div className="layout__left" data-windrag>
<div className="the-logo" data-windrag> <div className="the-logo" data-windrag>
<img src={LogoSvg} alt="" data-windrag /> <LogoSvg />
<UpdateButton className="the-newbtn" /> <UpdateButton className="the-newbtn" />
</div> </div>
@@ -87,7 +86,7 @@ const Layout = () => {
<List className="the-menu" data-windrag> <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} {t(router.label)}
</LayoutItem> </LayoutItem>
))} ))}
</List> </List>
@@ -98,7 +97,7 @@ const Layout = () => {
</div> </div>
<div className="layout__right" data-windrag> <div className="layout__right" data-windrag>
{!isMacos && ( {OS !== "macos" && (
<div className="the-bar"> <div className="the-bar">
<LayoutControl /> <LayoutControl />
</div> </div>

View File

@@ -6,27 +6,27 @@ import ConnectionsPage from "./connections";
export const routers = [ export const routers = [
{ {
label: "Proxies", label: "Label-Proxies",
link: "/", link: "/",
ele: ProxiesPage, ele: ProxiesPage,
}, },
{ {
label: "Profiles", label: "Label-Profiles",
link: "/profile", link: "/profile",
ele: ProfilesPage, ele: ProfilesPage,
}, },
{ {
label: "Connections", label: "Label-Connections",
link: "/connections", link: "/connections",
ele: ConnectionsPage, ele: ConnectionsPage,
}, },
{ {
label: "Logs", label: "Label-Logs",
link: "/logs", link: "/logs",
ele: LogsPage, ele: LogsPage,
}, },
{ {
label: "Settings", label: "Label-Settings",
link: "/settings", link: "/settings",
ele: SettingsPage, ele: SettingsPage,
}, },

12
src/pages/_theme.tsx Normal file
View File

@@ -0,0 +1,12 @@
// default theme setting
export const defaultTheme = {
primary_color: "#5b5c9d",
secondary_color: "#9c27b0",
primary_text: "#637381",
secondary_text: "#909399",
info_color: "#0288d1",
error_color: "#d32f2f",
warning_color: "#ed6c02",
success_color: "#2e7d32",
font_family: `"Roboto", "Helvetica", "Arial", sans-serif`,
};

View File

@@ -1,14 +1,26 @@
import { useEffect, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import { Paper } from "@mui/material"; import { useLockFn } from "ahooks";
import { Box, Button, Paper, TextField } from "@mui/material";
import { Virtuoso } from "react-virtuoso"; import { Virtuoso } from "react-virtuoso";
import { useTranslation } from "react-i18next";
import { ApiType } from "../services/types"; import { ApiType } from "../services/types";
import { getInfomation } from "../services/api"; import { closeAllConnections, getInfomation } from "../services/api";
import BasePage from "../components/base/base-page"; import BasePage from "../components/base/base-page";
import ConnectionItem from "../components/connection/connection-item"; import ConnectionItem from "../components/connection/connection-item";
const initConn = { uploadTotal: 0, downloadTotal: 0, connections: [] };
const ConnectionsPage = () => { const ConnectionsPage = () => {
const initConn = { uploadTotal: 0, downloadTotal: 0, connections: [] }; const { t } = useTranslation();
const [conn, setConn] = useState<ApiType.Connections>(initConn);
const [filterText, setFilterText] = useState("");
const [connData, setConnData] = useState<ApiType.Connections>(initConn);
const filterConn = useMemo(() => {
return connData.connections.filter((conn) =>
(conn.metadata.host || conn.metadata.destinationIP)?.includes(filterText)
);
}, [connData, filterText]);
useEffect(() => { useEffect(() => {
let ws: WebSocket | null = null; let ws: WebSocket | null = null;
@@ -19,20 +31,104 @@ const ConnectionsPage = () => {
ws.addEventListener("message", (event) => { ws.addEventListener("message", (event) => {
const data = JSON.parse(event.data) as ApiType.Connections; const data = JSON.parse(event.data) as ApiType.Connections;
setConn(data);
// 与前一次connections的展示顺序尽量保持一致
setConnData((old) => {
const oldConn = old.connections;
const maxLen = data.connections.length;
const connections: typeof oldConn = [];
const rest = data.connections.filter((each) => {
const index = oldConn.findIndex((o) => o.id === each.id);
if (index >= 0 && index < maxLen) {
const old = oldConn[index];
each.curUpload = each.upload - old.upload;
each.curDownload = each.download - old.download;
connections[index] = each;
return false;
}
return true;
});
for (let i = 0; i < maxLen; ++i) {
if (!connections[i] && rest.length > 0) {
connections[i] = rest.shift()!;
connections[i].curUpload = 0;
connections[i].curDownload = 0;
}
}
return { ...data, connections };
});
}); });
}); });
return () => ws?.close(); return () => ws?.close();
}, []); }, []);
const onCloseAll = useLockFn(closeAllConnections);
return ( return (
<BasePage title="Connections" contentStyle={{ height: "100%" }}> <BasePage
title={t("Connections")}
contentStyle={{ height: "100%" }}
header={
<Button
size="small"
sx={{ mt: 1 }}
variant="contained"
onClick={onCloseAll}
>
{t("Close All")}
</Button>
}
>
<Paper sx={{ boxShadow: 2, height: "100%" }}> <Paper sx={{ boxShadow: 2, height: "100%" }}>
<Virtuoso <Box
data={conn.connections} sx={{
itemContent={(index, item) => <ConnectionItem value={item} />} pt: 1,
/> mb: 0.5,
mx: "12px",
height: "36px",
display: "flex",
alignItems: "center",
}}
>
{/* <Select
size="small"
autoComplete="off"
value={logState}
onChange={(e) => setLogState(e.target.value)}
sx={{ width: 120, mr: 1, '[role="button"]': { py: 0.65 } }}
>
<MenuItem value="all">ALL</MenuItem>
<MenuItem value="info">INFO</MenuItem>
<MenuItem value="warn">WARN</MenuItem>
</Select> */}
<TextField
hiddenLabel
fullWidth
size="small"
autoComplete="off"
variant="outlined"
placeholder="Filter conditions"
value={filterText}
onChange={(e) => setFilterText(e.target.value)}
sx={{ input: { py: 0.65, px: 1.25 } }}
/>
</Box>
<Box height="calc(100% - 50px)">
<Virtuoso
initialTopMostItemIndex={999}
data={filterConn}
itemContent={(index, item) => <ConnectionItem value={item} />}
/>
</Box>
</Paper> </Paper>
</BasePage> </BasePage>
); );

View File

@@ -1,16 +1,31 @@
import { useMemo, useState } from "react";
import { useRecoilState } from "recoil"; import { useRecoilState } from "recoil";
import { Button, Paper } from "@mui/material"; import { Box, Button, MenuItem, Paper, Select, TextField } from "@mui/material";
import { Virtuoso } from "react-virtuoso"; import { Virtuoso } from "react-virtuoso";
import { useTranslation } from "react-i18next";
import { atomLogData } from "../services/states"; import { atomLogData } from "../services/states";
import BasePage from "../components/base/base-page"; import BasePage from "../components/base/base-page";
import LogItem from "../components/log/log-item"; import LogItem from "../components/log/log-item";
const LogPage = () => { const LogPage = () => {
const { t } = useTranslation();
const [logData, setLogData] = useRecoilState(atomLogData); const [logData, setLogData] = useRecoilState(atomLogData);
const [logState, setLogState] = useState("all");
const [filterText, setFilterText] = useState("");
const filterLogs = useMemo(() => {
return logData.filter((data) => {
return (
data.payload.includes(filterText) &&
(logState === "all" ? true : data.type.includes(logState))
);
});
}, [logData, logState, filterText]);
return ( return (
<BasePage <BasePage
title="Logs" title={t("Logs")}
contentStyle={{ height: "100%" }} contentStyle={{ height: "100%" }}
header={ header={
<Button <Button
@@ -19,17 +34,54 @@ const LogPage = () => {
variant="contained" variant="contained"
onClick={() => setLogData([])} onClick={() => setLogData([])}
> >
Clear {t("Clear")}
</Button> </Button>
} }
> >
<Paper sx={{ boxShadow: 2, height: "100%" }}> <Paper sx={{ boxSizing: "border-box", boxShadow: 2, height: "100%" }}>
<Virtuoso <Box
initialTopMostItemIndex={999} sx={{
data={logData} pt: 1,
itemContent={(index, item) => <LogItem value={item} />} mb: 0.5,
followOutput={"smooth"} mx: "12px",
/> height: "36px",
display: "flex",
alignItems: "center",
}}
>
<Select
size="small"
autoComplete="off"
value={logState}
onChange={(e) => setLogState(e.target.value)}
sx={{ width: 120, mr: 1, '[role="button"]': { py: 0.65 } }}
>
<MenuItem value="all">ALL</MenuItem>
<MenuItem value="info">INFO</MenuItem>
<MenuItem value="warn">WARN</MenuItem>
</Select>
<TextField
hiddenLabel
fullWidth
size="small"
autoComplete="off"
variant="outlined"
placeholder="Filter conditions"
value={filterText}
onChange={(e) => setFilterText(e.target.value)}
sx={{ input: { py: 0.65, px: 1.25 } }}
/>
</Box>
<Box height="calc(100% - 50px)">
<Virtuoso
initialTopMostItemIndex={999}
data={filterLogs}
itemContent={(index, item) => <LogItem value={item} />}
followOutput={"smooth"}
/>
</Box>
</Paper> </Paper>
</BasePage> </BasePage>
); );

View File

@@ -2,23 +2,22 @@ import useSWR, { useSWRConfig } from "swr";
import { useLockFn } from "ahooks"; import { useLockFn } from "ahooks";
import { useEffect, useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import { Box, Button, Grid, TextField } from "@mui/material"; import { Box, Button, Grid, TextField } from "@mui/material";
import { useTranslation } from "react-i18next";
import { import {
getProfiles, getProfiles,
patchProfile, patchProfile,
deleteProfile,
selectProfile, selectProfile,
importProfile, importProfile,
enhanceProfiles,
changeProfileChain,
} from "../services/cmds"; } from "../services/cmds";
import { getProxies, updateProxy } from "../services/api"; import { getProxies, updateProxy } from "../services/api";
import Notice from "../components/base/base-notice"; import Notice from "../components/base/base-notice";
import BasePage from "../components/base/base-page"; import BasePage from "../components/base/base-page";
import ProfileNew from "../components/profile/profile-new"; import ProfileNew from "../components/profile/profile-new";
import ProfileItem from "../components/profile/profile-item"; import ProfileItem from "../components/profile/profile-item";
import ProfileMore from "../components/profile/profile-more"; import EnhancedMode from "../components/profile/enhanced";
const ProfilePage = () => { const ProfilePage = () => {
const { t } = useTranslation();
const { mutate } = useSWRConfig(); const { mutate } = useSWRConfig();
const [url, setUrl] = useState(""); const [url, setUrl] = useState("");
@@ -27,6 +26,7 @@ const ProfilePage = () => {
const { data: profiles = {} } = useSWR("getProfiles", getProfiles); const { data: profiles = {} } = useSWR("getProfiles", getProfiles);
// distinguish type
const { regularItems, enhanceItems } = useMemo(() => { const { regularItems, enhanceItems } = useMemo(() => {
const items = profiles.items || []; const items = profiles.items || [];
const chain = profiles.chain || []; const chain = profiles.chain || [];
@@ -46,6 +46,7 @@ const ProfilePage = () => {
return { regularItems, enhanceItems }; return { regularItems, enhanceItems };
}, [profiles]); }, [profiles]);
// sync selected proxy
useEffect(() => { useEffect(() => {
if (profiles.current == null) return; if (profiles.current == null) return;
@@ -63,9 +64,10 @@ const ProfilePage = () => {
selected.map((each) => [each.name!, each.now!]) selected.map((each) => [each.name!, each.now!])
); );
// todo: enhance error handle
let hasChange = false; let hasChange = false;
proxiesData.groups.forEach((group) => {
const { global, groups } = proxiesData;
[global, ...groups].forEach((group) => {
const { name, now } = group; const { name, now } = group;
if (!now || selectedMap[name] === now) return; if (!now || selectedMap[name] === now) return;
@@ -76,15 +78,14 @@ const ProfilePage = () => {
updateProxy(name, selectedMap[name]); updateProxy(name, selectedMap[name]);
} }
}); });
// update profile selected list // update profile selected list
profile.selected = Object.entries(selectedMap).map(([name, now]) => ({ profile.selected = Object.entries(selectedMap).map(([name, now]) => ({
name, name,
now, now,
})); }));
patchProfile(current!, { selected: profile.selected }).catch( patchProfile(current!, { selected: profile.selected });
console.error
);
// update proxies cache // update proxies cache
if (hasChange) mutate("getProxies", getProxies()); if (hasChange) mutate("getProxies", getProxies());
}, 100); }, 100);
@@ -126,61 +127,13 @@ const ProfilePage = () => {
} }
}); });
/** enhanced profile mode */
const chain = profiles.chain || [];
const onEnhance = useLockFn(enhanceProfiles);
const onEnhanceEnable = useLockFn(async (uid: string) => {
if (chain.includes(uid)) return;
const newChain = [...chain, uid];
await changeProfileChain(newChain);
mutate("getProfiles", { ...profiles, chain: newChain }, true);
});
const onEnhanceDisable = useLockFn(async (uid: string) => {
if (!chain.includes(uid)) return;
const newChain = chain.filter((i) => i !== uid);
await changeProfileChain(newChain);
mutate("getProfiles", { ...profiles, chain: newChain }, true);
});
const onEnhanceDelete = useLockFn(async (uid: string) => {
try {
await onEnhanceDisable(uid);
await deleteProfile(uid);
mutate("getProfiles");
} catch (err: any) {
Notice.error(err?.message || err.toString());
}
});
const onMoveTop = useLockFn(async (uid: string) => {
if (!chain.includes(uid)) return;
const newChain = [uid].concat(chain.filter((i) => i !== uid));
await changeProfileChain(newChain);
mutate("getProfiles", { ...profiles, chain: newChain }, true);
});
const onMoveEnd = useLockFn(async (uid: string) => {
if (!chain.includes(uid)) return;
const newChain = chain.filter((i) => i !== uid).concat([uid]);
await changeProfileChain(newChain);
mutate("getProfiles", { ...profiles, chain: newChain }, true);
});
return ( return (
<BasePage title="Profiles"> <BasePage title={t("Profiles")}>
<Box sx={{ display: "flex", mb: 2.5 }}> <Box sx={{ display: "flex", mb: 2.5 }}>
<TextField <TextField
id="clas_verge_profile_url" id="clas_verge_profile_url"
name="profile_url" name="profile_url"
label="Profile URL" label={t("Profile URL")}
size="small" size="small"
fullWidth fullWidth
value={url} value={url}
@@ -193,10 +146,10 @@ const ProfilePage = () => {
onClick={onImport} onClick={onImport}
sx={{ mr: 1 }} sx={{ mr: 1 }}
> >
Import {t("Import")}
</Button> </Button>
<Button variant="contained" onClick={() => setDialogOpen(true)}> <Button variant="contained" onClick={() => setDialogOpen(true)}>
New {t("New")}
</Button> </Button>
</Box> </Box>
@@ -212,22 +165,9 @@ const ProfilePage = () => {
))} ))}
</Grid> </Grid>
<Grid container spacing={2} sx={{ mt: 3 }}> {enhanceItems.length > 0 && (
{enhanceItems.map((item) => ( <EnhancedMode items={enhanceItems} chain={profiles.chain || []} />
<Grid item xs={12} sm={6} key={item.file}> )}
<ProfileMore
selected={!!profiles.chain?.includes(item.uid)}
itemData={item}
onEnable={() => onEnhanceEnable(item.uid)}
onDisable={() => onEnhanceDisable(item.uid)}
onDelete={() => onEnhanceDelete(item.uid)}
onMoveTop={() => onMoveTop(item.uid)}
onMoveEnd={() => onMoveEnd(item.uid)}
onEnhance={onEnhance}
/>
</Grid>
))}
</Grid>
<ProfileNew open={dialogOpen} onClose={() => setDialogOpen(false)} /> <ProfileNew open={dialogOpen} onClose={() => setDialogOpen(false)} />
</BasePage> </BasePage>

View File

@@ -1,6 +1,7 @@
import useSWR, { useSWRConfig } from "swr"; import useSWR, { useSWRConfig } from "swr";
import { useEffect } from "react"; import { useEffect } from "react";
import { useLockFn } from "ahooks"; import { useLockFn } from "ahooks";
import { useTranslation } from "react-i18next";
import { Button, ButtonGroup, List, Paper } from "@mui/material"; import { Button, ButtonGroup, List, Paper } from "@mui/material";
import { getClashConfig, updateConfigs } from "../services/api"; import { getClashConfig, updateConfigs } from "../services/api";
import { patchClashConfig } from "../services/cmds"; import { patchClashConfig } from "../services/cmds";
@@ -10,12 +11,13 @@ import ProxyGroup from "../components/proxy/proxy-group";
import ProxyGlobal from "../components/proxy/proxy-global"; import ProxyGlobal from "../components/proxy/proxy-global";
const ProxyPage = () => { const ProxyPage = () => {
const { t } = useTranslation();
const { mutate } = useSWRConfig(); const { mutate } = useSWRConfig();
const { data: proxiesData } = useSWR("getProxies", getProxies); const { data: proxiesData } = useSWR("getProxies", getProxies);
const { data: clashConfig } = useSWR("getClashConfig", getClashConfig); const { data: clashConfig } = useSWR("getClashConfig", getClashConfig);
const modeList = ["rule", "global", "direct"]; const modeList = ["rule", "global", "direct"];
const curMode = clashConfig?.mode.toLowerCase() ?? "direct"; const curMode = clashConfig?.mode.toLowerCase();
const { groups = [], proxies = [] } = proxiesData ?? {}; const { groups = [], proxies = [] } = proxiesData ?? {};
// make sure that fetch the proxies successfully // make sure that fetch the proxies successfully
@@ -45,7 +47,7 @@ const ProxyPage = () => {
return ( return (
<BasePage <BasePage
contentStyle={pageStyle} contentStyle={pageStyle}
title={showGroup ? "Proxy Groups" : "Proxies"} title={showGroup ? t("Proxy Groups") : t("Proxies")}
header={ header={
<ButtonGroup size="small"> <ButtonGroup size="small">
{modeList.map((mode) => ( {modeList.map((mode) => (
@@ -55,7 +57,7 @@ const ProxyPage = () => {
onClick={() => onChangeMode(mode)} onClick={() => onChangeMode(mode)}
sx={{ textTransform: "capitalize" }} sx={{ textTransform: "capitalize" }}
> >
{mode} {t(mode)}
</Button> </Button>
))} ))}
</ButtonGroup> </ButtonGroup>

View File

@@ -1,4 +1,5 @@
import { Paper } from "@mui/material"; import { Paper } from "@mui/material";
import { useTranslation } from "react-i18next";
import Notice from "../components/base/base-notice"; import Notice from "../components/base/base-notice";
import BasePage from "../components/base/base-page"; import BasePage from "../components/base/base-page";
import SettingVerge from "../components/setting/setting-verge"; import SettingVerge from "../components/setting/setting-verge";
@@ -6,12 +7,14 @@ import SettingClash from "../components/setting/setting-clash";
import SettingSystem from "../components/setting/setting-system"; import SettingSystem from "../components/setting/setting-system";
const SettingPage = () => { const SettingPage = () => {
const onError = (error: any) => { const { t } = useTranslation();
error && Notice.error(error.toString());
const onError = (err: any) => {
Notice.error(err?.message || err.toString());
}; };
return ( return (
<BasePage title="Settings"> <BasePage title={t("Settings")}>
<Paper sx={{ borderRadius: 1, boxShadow: 2, mb: 3 }}> <Paper sx={{ borderRadius: 1, boxShadow: 2, mb: 3 }}>
<SettingClash onError={onError} /> <SettingClash onError={onError} />
</Paper> </Paper>

View File

@@ -141,3 +141,23 @@ export async function getProviders() {
const response = await instance.get<any, any>("/providers/proxies"); const response = await instance.get<any, any>("/providers/proxies");
return response.providers as any; return response.providers as any;
} }
// todo: proxy providers health check
export async function getProviderHealthCheck(name: string) {
const instance = await getAxios();
return instance.get(
`/providers/proxies/${encodeURIComponent(name)}/healthcheck`
);
}
// Close specific connection
export async function deleteConnection(id: string) {
const instance = await getAxios();
await instance.delete<any, any>(`/connections/${encodeURIComponent(id)}`);
}
// Close all connections
export async function closeAllConnections() {
const instance = await getAxios();
await instance.delete<any, any>(`/connections`);
}

View File

@@ -1,5 +1,6 @@
import { invoke } from "@tauri-apps/api/tauri"; import { invoke } from "@tauri-apps/api/tauri";
import { ApiType, CmdType } from "./types"; import { ApiType, CmdType } from "./types";
import Notice from "../components/base/base-notice";
export async function getProfiles() { export async function getProfiles() {
return invoke<CmdType.ProfilesConfig>("get_profiles"); return invoke<CmdType.ProfilesConfig>("get_profiles");
@@ -13,14 +14,25 @@ export async function enhanceProfiles() {
return invoke<void>("enhance_profiles"); return invoke<void>("enhance_profiles");
} }
export async function createProfile(item: Partial<CmdType.ProfileItem>) { export async function createProfile(
return invoke<void>("create_profile", { item }); item: Partial<CmdType.ProfileItem>,
fileData?: string | null
) {
return invoke<void>("create_profile", { item, fileData });
} }
export async function viewProfile(index: string) { export async function viewProfile(index: string) {
return invoke<void>("view_profile", { index }); return invoke<void>("view_profile", { index });
} }
export async function readProfileFile(index: string) {
return invoke<string>("read_profile_file", { index });
}
export async function saveProfileFile(index: string, fileData: string) {
return invoke<void>("save_profile_file", { index, fileData });
}
export async function importProfile(url: string) { export async function importProfile(url: string) {
return invoke<void>("import_profile", { return invoke<void>("import_profile", {
url, url,
@@ -54,6 +66,10 @@ export async function changeProfileChain(chain?: string[]) {
return invoke<void>("change_profile_chain", { chain }); return invoke<void>("change_profile_chain", { chain });
} }
export async function changeProfileValid(valid?: string[]) {
return invoke<void>("change_profile_valid", { valid });
}
export async function getClashInfo() { export async function getClashInfo() {
return invoke<CmdType.ClashInfo | null>("get_clash_info"); return invoke<CmdType.ClashInfo | null>("get_clash_info");
} }
@@ -83,9 +99,13 @@ export async function killSidecars() {
} }
export async function openAppDir() { export async function openAppDir() {
return invoke<void>("open_app_dir"); return invoke<void>("open_app_dir").catch((err) =>
Notice.error(err?.message || err.toString(), 1500)
);
} }
export async function openLogsDir() { export async function openLogsDir() {
return invoke<void>("open_logs_dir"); return invoke<void>("open_logs_dir").catch((err) =>
Notice.error(err?.message || err.toString(), 1500)
);
} }

View File

@@ -4,6 +4,15 @@ const hashKey = (name: string, group: string) => `${group ?? ""}::${name}`;
class DelayManager { class DelayManager {
private cache = new Map<string, [number, number]>(); private cache = new Map<string, [number, number]>();
private urlMap = new Map<string, string>();
setUrl(group: string, url: string) {
this.urlMap.set(group, url);
}
getUrl(group: string) {
return this.urlMap.get(group);
}
setDelay(name: string, group: string, delay: number) { setDelay(name: string, group: string, delay: number) {
this.cache.set(hashKey(name, group), [Date.now(), delay]); this.cache.set(hashKey(name, group), [Date.now(), delay]);
@@ -23,7 +32,8 @@ class DelayManager {
let delay = -1; let delay = -1;
try { try {
const result = await getProxyDelay(name); const url = this.getUrl(group);
const result = await getProxyDelay(name, url);
delay = result.delay; delay = result.delay;
} catch { } catch {
delay = 1e6; // error delay = 1e6; // error
@@ -38,32 +48,36 @@ class DelayManager {
names: readonly string[]; names: readonly string[];
groupName: string; groupName: string;
skipNum: number; skipNum: number;
maxTimeout: number;
}, },
callback: Function callback: Function
) { ) {
let names = [...options.names]; const { groupName, skipNum } = options;
const { groupName, skipNum, maxTimeout } = options;
while (names.length) { const names = [...options.names];
const list = names.slice(0, skipNum); const total = names.length;
names = names.slice(skipNum);
let called = false; let count = 0;
setTimeout(() => { let current = 0;
if (!called) {
called = true;
callback();
}
}, maxTimeout);
await Promise.all(list.map((n) => this.checkDelay(n, groupName))); return new Promise((resolve) => {
const help = async (): Promise<void> => {
if (current >= skipNum) return;
if (!called) { const task = names.shift();
called = true; if (!task) return;
callback();
} current += 1;
} await this.checkDelay(task, groupName);
current -= 1;
if (count++ % skipNum === 0 || count === total) callback();
if (count === total) resolve(null);
return help();
};
for (let i = 0; i < skipNum; ++i) help();
});
} }
} }

View File

@@ -1,48 +1,80 @@
import { emit, listen } from "@tauri-apps/api/event"; import { emit, listen } from "@tauri-apps/api/event";
import { CmdType } from "./types"; import { CmdType } from "./types";
import ignoreCase from "../utils/ignore-case";
const DEFAULT_FIELDS = [
"rules",
"proxies",
"proxy-groups",
"proxy-providers",
"rule-providers",
] as const;
const USE_FLAG_FIELDS = [
"tun",
"dns",
"hosts",
"script",
"profile",
"payload",
"interface-name",
"routing-mark",
] as const;
/** /**
* process the merge mode * process the merge mode
*/ */
function toMerge( function toMerge(merge: CmdType.ProfileMerge, data: CmdType.ProfileData) {
merge: CmdType.ProfileMerge, if (!merge) return { data, use: [] };
data: CmdType.ProfileData
): CmdType.ProfileData {
if (!merge) return data;
const newData = { ...data }; const {
use,
"prepend-rules": preRules,
"append-rules": postRules,
"prepend-proxies": preProxies,
"append-proxies": postProxies,
"prepend-proxy-groups": preProxyGroups,
"append-proxy-groups": postProxyGroups,
...mergeConfig
} = merge;
[...DEFAULT_FIELDS, ...USE_FLAG_FIELDS].forEach((key) => {
// the value should not be null
if (mergeConfig[key] != null) {
data[key] = mergeConfig[key];
}
});
// init
if (!data.rules) data.rules = [];
if (!data.proxies) data.proxies = [];
if (!data["proxy-groups"]) data["proxy-groups"] = [];
// rules // rules
if (Array.isArray(merge["prepend-rules"])) { if (Array.isArray(preRules)) {
if (!newData.rules) newData.rules = []; data.rules.unshift(...preRules);
newData.rules.unshift(...merge["prepend-rules"]);
} }
if (Array.isArray(merge["append-rules"])) { if (Array.isArray(postRules)) {
if (!newData.rules) newData.rules = []; data.rules.push(...postRules);
newData.rules.push(...merge["append-rules"]);
} }
// proxies // proxies
if (Array.isArray(merge["prepend-proxies"])) { if (Array.isArray(preProxies)) {
if (!newData.proxies) newData.proxies = []; data.proxies.unshift(...preProxies);
newData.proxies.unshift(...merge["prepend-proxies"]);
} }
if (Array.isArray(merge["append-proxies"])) { if (Array.isArray(postProxies)) {
if (!newData.proxies) newData.proxies = []; data.proxies.push(...postProxies);
newData.proxies.push(...merge["append-proxies"]);
} }
// proxy-groups // proxy-groups
if (Array.isArray(merge["prepend-proxy-groups"])) { if (Array.isArray(preProxyGroups)) {
if (!newData["proxy-groups"]) newData["proxy-groups"] = []; data["proxy-groups"].unshift(...preProxyGroups);
newData["proxy-groups"].unshift(...merge["prepend-proxy-groups"]);
} }
if (Array.isArray(merge["append-proxy-groups"])) { if (Array.isArray(postProxyGroups)) {
if (!newData["proxy-groups"]) newData["proxy-groups"] = []; data["proxy-groups"].push(...postProxyGroups);
newData["proxy-groups"].push(...merge["append-proxy-groups"]);
} }
return newData; return { data, use: Array.isArray(use) ? use : [] };
} }
/** /**
@@ -99,44 +131,76 @@ class Enhance {
listen("script-handler", async (event) => { listen("script-handler", async (event) => {
const payload = event.payload as CmdType.EnhancedPayload; const payload = event.payload as CmdType.EnhancedPayload;
let pdata = payload.current || {};
for (const each of payload.chain) { const result = await this.runner(payload).catch((err: any) => ({
const { uid, type = "" } = each.item; data: null,
status: "error",
error: err.message,
}));
try {
// process script
if (type === "script") {
// support async main function
pdata = await toScript(each.script!, { ...pdata });
}
// process merge
else if (type === "merge") {
pdata = toMerge(each.merge!, { ...pdata });
}
// invalid type
else {
throw new Error(`invalid enhanced profile type "${type}"`);
}
this.exec(uid, { status: "ok" });
} catch (err: any) {
this.exec(uid, {
status: "error",
message: err.message || err.toString(),
});
console.error(err);
}
}
const result = { data: pdata, status: "ok" };
emit(payload.callback, JSON.stringify(result)).catch(console.error); emit(payload.callback, JSON.stringify(result)).catch(console.error);
}); });
} }
// enhanced mode runner
private async runner(payload: CmdType.EnhancedPayload) {
const chain = payload.chain || [];
const valid = payload.valid || [];
if (!Array.isArray(chain)) throw new Error("unhandle error");
let pdata = payload.current || {};
let useList = valid;
for (const each of chain) {
const { uid, type = "" } = each.item;
try {
// process script
if (type === "script") {
// support async main function
pdata = await toScript(each.script!, ignoreCase(pdata));
}
// process merge
else if (type === "merge") {
const temp = toMerge(each.merge!, ignoreCase(pdata));
pdata = temp.data;
useList = useList.concat(temp.use || []);
}
// invalid type
else {
throw new Error(`invalid enhanced profile type "${type}"`);
}
this.exec(uid, { status: "ok" });
} catch (err: any) {
console.error(err);
this.exec(uid, {
status: "error",
message: err.message || err.toString(),
});
}
}
pdata = ignoreCase(pdata);
// filter the data
const filterData: typeof pdata = {};
Object.keys(pdata).forEach((key: any) => {
if (
DEFAULT_FIELDS.includes(key) ||
(USE_FLAG_FIELDS.includes(key) && useList.includes(key))
) {
filterData[key] = pdata[key];
}
});
return { data: filterData, status: "ok" };
}
// exec the listener // exec the listener
private exec(uid: string, status: EStatus) { private exec(uid: string, status: EStatus) {
this.resultMap.set(uid, status); this.resultMap.set(uid, status);

17
src/services/i18n.ts Normal file
View File

@@ -0,0 +1,17 @@
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import en from "../locales/en.json";
import zh from "../locales/zh.json";
const resources = {
en: { translation: en },
zh: { translation: zh },
};
i18n.use(initReactI18next).init({
resources,
lng: "en",
interpolation: {
escapeValue: false,
},
});

View File

@@ -10,3 +10,15 @@ export const atomLogData = atom<ApiType.LogItem[]>({
key: "atomLogData", key: "atomLogData",
default: [], default: [],
}); });
// save the state of each profile item loading
export const atomLoadingCache = atom<Record<string, boolean>>({
key: "atomLoadingCache",
default: {},
});
// save update state
export const atomUpdateState = atom<boolean>({
key: "atomUpdateState",
default: false,
});

View File

@@ -65,6 +65,8 @@ export namespace ApiType {
chains: string[]; chains: string[];
rule: string; rule: string;
rulePayload: string; rulePayload: string;
curUpload?: number; // calculate
curDownload?: number; // calculate
} }
export interface Connections { export interface Connections {
@@ -116,21 +118,62 @@ export namespace CmdType {
export interface ProfilesConfig { export interface ProfilesConfig {
current?: string; current?: string;
chain?: string[]; chain?: string[];
valid?: string[];
items?: ProfileItem[]; items?: ProfileItem[];
} }
export interface VergeConfig { export interface VergeConfig {
language?: string;
theme_mode?: "light" | "dark"; theme_mode?: "light" | "dark";
theme_blur?: boolean; theme_blur?: boolean;
traffic_graph?: boolean; traffic_graph?: boolean;
enable_tun_mode?: boolean; enable_tun_mode?: boolean;
enable_auto_launch?: boolean; enable_auto_launch?: boolean;
enable_silent_start?: boolean;
enable_system_proxy?: boolean; enable_system_proxy?: boolean;
enable_proxy_guard?: boolean; enable_proxy_guard?: boolean;
system_proxy_bypass?: string; system_proxy_bypass?: string;
theme_setting?: {
primary_color?: string;
secondary_color?: string;
primary_text?: string;
secondary_text?: string;
info_color?: string;
error_color?: string;
warning_color?: string;
success_color?: string;
font_family?: string;
css_injection?: string;
};
} }
export type ProfileMerge = Record<string, any>; type ClashConfigValue = any;
export interface ProfileMerge {
// clash config fields (default supports)
rules?: ClashConfigValue;
proxies?: ClashConfigValue;
"proxy-groups"?: ClashConfigValue;
"proxy-providers"?: ClashConfigValue;
"rule-providers"?: ClashConfigValue;
// clash config fields (use flag)
tun?: ClashConfigValue;
dns?: ClashConfigValue;
hosts?: ClashConfigValue;
script?: ClashConfigValue;
profile?: ClashConfigValue;
payload?: ClashConfigValue;
"interface-name"?: ClashConfigValue;
"routing-mark"?: ClashConfigValue;
// functional fields
use?: string[];
"prepend-rules"?: any[];
"append-rules"?: any[];
"prepend-proxies"?: any[];
"append-proxies"?: any[];
"prepend-proxy-groups"?: any[];
"append-proxy-groups"?: any[];
}
// partial of the clash config // partial of the clash config
export type ProfileData = Partial<{ export type ProfileData = Partial<{
@@ -139,6 +182,8 @@ export namespace CmdType {
"proxy-groups": any[]; "proxy-groups": any[];
"proxy-providers": any[]; "proxy-providers": any[];
"rule-providers": any[]; "rule-providers": any[];
[k: string]: any;
}>; }>;
export interface ChainItem { export interface ChainItem {
@@ -149,6 +194,7 @@ export namespace CmdType {
export interface EnhancedPayload { export interface EnhancedPayload {
chain: ChainItem[]; chain: ChainItem[];
valid: string[];
current: ProfileData; current: ProfileData;
callback: string; callback: string;
} }

13
src/utils/get-system.ts Normal file
View File

@@ -0,0 +1,13 @@
// get the system os
// according to UA
export default function getSystem() {
const ua = navigator.userAgent;
if (ua.includes("Mac OS X")) return "macos";
if (/win64|win32/i.test(ua)) return "windows";
if (/linux/i.test(ua)) return "linux";
return "unknown";
}

14
src/utils/ignore-case.ts Normal file
View File

@@ -0,0 +1,14 @@
// Deep copy and change all keys to lowercase
type TData = Record<string, any>;
export default function ignoreCase(data: TData): TData {
if (!data) return data;
const newData = {} as TData;
Object.entries(data).forEach(([key, value]) => {
newData[key.toLowerCase()] = JSON.parse(JSON.stringify(value));
});
return newData;
}

View File

@@ -1,10 +1,12 @@
import { defineConfig } from "vite"; import { defineConfig } from "vite";
import svgr from "vite-plugin-svgr";
import react from "@vitejs/plugin-react"; import react from "@vitejs/plugin-react";
import monaco from "vite-plugin-monaco-editor";
// https://vitejs.dev/config/ // https://vitejs.dev/config/
export default defineConfig({ export default defineConfig({
root: "src", root: "src",
plugins: [react()], plugins: [svgr(), react(), monaco()],
build: { build: {
outDir: "../dist", outDir: "../dist",
emptyOutDir: true, emptyOutDir: true,

854
yarn.lock

File diff suppressed because it is too large Load Diff