173 Commits

Author SHA1 Message Date
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
GyDi
b2a24c7abd v0.0.22 2022-03-10 02:27:00 +08:00
GyDi
732a1f4694 chore: rm dead code 2022-03-10 02:25:35 +08:00
GyDi
4c5aa7084e fix: external-controller 2022-03-10 02:19:06 +08:00
GyDi
fe1fea671c feat: support more options for remote profile 2022-03-10 02:03:55 +08:00
GyDi
04c754c0ac chore: reduce icon size on macOS 2022-03-10 01:04:53 +08:00
GyDi
754c22c84e chore: adjust icon 2022-03-10 00:04:59 +08:00
GyDi
629331870b chore: add linux link 2022-03-09 20:14:15 +08:00
GyDi
78774315cb feat: linux system proxy 2022-03-09 19:48:32 +08:00
GyDi
36b9c07928 chore: update deps 2022-03-09 02:36:40 +08:00
GyDi
40a818630d fix: change proxy bypass on mac 2022-03-09 02:36:03 +08:00
GyDi
568511a4cf fix: kill sidecars after install still in test 2022-03-09 02:09:51 +08:00
GyDi
109fb39e09 fix: log some error 2022-03-09 02:00:56 +08:00
GyDi
68450d2042 chore: rename productName 2022-03-09 01:53:34 +08:00
GyDi
8a052bbed6 chore: update tauri version 2022-03-09 01:50:37 +08:00
GyDi
3afbb56640 fix: apply_blur parameter 2022-03-08 10:44:41 +08:00
GyDi
c0ad84a491 fix: limit enhanced profile range 2022-03-08 01:45:46 +08:00
GyDi
c72f17605c chore: update deps 2022-03-08 01:18:20 +08:00
GyDi
42fbee0cdb chore: add default bypass 2022-03-08 00:39:09 +08:00
GyDi
e9b7ec735f fix: profile updated field 2022-03-07 01:41:42 +08:00
GyDi
743788135f fix: profile field check 2022-03-07 01:30:32 +08:00
GyDi
8ea3e6fa26 fix: create dir panic 2022-03-07 01:06:21 +08:00
GyDi
f23c83e681 v0.0.21 2022-03-06 18:36:02 +08:00
GyDi
b615bda17e chore: default release body 2022-03-06 18:34:38 +08:00
GyDi
f7c7cd1d3c chore: update deps 2022-03-06 18:04:44 +08:00
GyDi
c7e7be4379 fix: only error when selected 2022-03-06 17:06:45 +08:00
GyDi
d63d49f246 feat: enhance profile status 2022-03-06 17:02:29 +08:00
GyDi
dad94edb20 feat: menu item refresh enhanced mode 2022-03-06 15:46:16 +08:00
GyDi
7108d5f3ab fix: enhanced profile consistency 2022-03-06 15:40:16 +08:00
GyDi
ef47a74920 feat: profile enhanced mode 2022-03-06 14:59:25 +08:00
GyDi
a43dab8057 feat: profile enhanced ui 2022-03-05 22:54:39 +08:00
GyDi
f44039b628 feat: profile item adjust 2022-03-05 19:04:20 +08:00
GyDi
08fa5205b0 fix: simply compatible with proxy providers 2022-03-05 16:18:44 +08:00
GyDi
b91daebd92 fix: component warning 2022-03-05 15:48:39 +08:00
GyDi
9cd6c5c624 chore: update copyright 2022-03-05 01:51:29 +08:00
GyDi
650e017b72 fix: when updater failed 2022-03-04 02:10:27 +08:00
GyDi
18f9d6dec5 fix: log file 2022-03-04 02:08:26 +08:00
GyDi
4df6571ad9 chore: update deps 2022-03-03 20:37:06 +08:00
GyDi
0f5923a10a chore: enhance wip 2022-03-03 01:58:05 +08:00
GyDi
bcdae1169e fix: result 2022-03-03 01:56:47 +08:00
GyDi
f260d5df49 feat: enhanced profile (wip) 2022-03-03 01:52:02 +08:00
GyDi
808b861dd1 v0.0.20 2022-03-02 01:59:53 +08:00
GyDi
17f1c487a8 feat: edit profile item 2022-03-02 01:58:16 +08:00
GyDi
8dc2c1a38f fix: cover profile extra 2022-03-02 01:45:00 +08:00
GyDi
220a494692 chore: adjust log field 2022-03-02 01:13:31 +08:00
GyDi
db6bc10196 chore: rm file 2022-03-02 00:58:07 +08:00
GyDi
1880363aeb feat: use nanoid 2022-03-02 00:56:05 +08:00
GyDi
19c7b59883 feat: compatible profile config 2022-03-01 11:05:33 +08:00
GyDi
749df89229 refactor: profile config 2022-03-01 08:58:47 +08:00
GyDi
444f2172fa v0.0.19 2022-02-28 01:59:53 +08:00
GyDi
77a77c0ea7 wip: refactor profile 2022-02-28 01:59:13 +08:00
GyDi
dbf380a0d1 refactor: use anyhow to handle error 2022-02-28 01:34:25 +08:00
GyDi
ade34f5217 fix: display menu only on macos 2022-02-27 01:47:56 +08:00
GyDi
e89607799a fix: proxy global showType 2022-02-27 01:33:22 +08:00
GyDi
d05d8d6a9e feat: native menu supports 2022-02-27 01:29:57 +08:00
GyDi
b6aa50d3dc chore: update deps 2022-02-27 01:16:43 +08:00
GyDi
9df361935f feat: filter proxy and display type 2022-02-27 00:58:14 +08:00
GyDi
98b8a122b6 feat: use lock fn 2022-02-26 17:39:36 +08:00
GyDi
c7232522ee feat: refactor proxy page 2022-02-26 17:39:08 +08:00
GyDi
5280f1d745 feat: proxy group auto scroll to current 2022-02-26 01:21:39 +08:00
GyDi
b52a081e7b v0.0.18 2022-02-25 02:13:41 +08:00
GyDi
f981a44861 chore: ci 2022-02-25 02:12:55 +08:00
GyDi
d7c5ce0750 feat: clash tun mode supports 2022-02-25 02:09:39 +08:00
GyDi
9ccc66ca1e feat: use enhanced guard-state 2022-02-25 01:22:33 +08:00
GyDi
8606af3616 feat: guard state supports debounce guard 2022-02-25 01:21:13 +08:00
GyDi
f6e821ba6b feat: adjust clash version display 2022-02-24 23:04:18 +08:00
GyDi
e8dbcf819b feat: hide command window 2022-02-24 22:46:12 +08:00
GyDi
bbe2ef4e8e fix: use full clash config 2022-02-23 23:23:07 +08:00
GyDi
dd15455031 feat: enhance log data 2022-02-23 02:00:45 +08:00
GyDi
12ac7bb338 chore: update readme 2022-02-22 21:54:33 +08:00
GyDi
46ef348f0d v0.0.17 2022-02-22 02:08:31 +08:00
GyDi
1a55cca8af fix: reconnect websocket when restart clash 2022-02-22 02:05:22 +08:00
GyDi
81ee989f1f chore: enhance publish ci 2022-02-22 01:56:06 +08:00
GyDi
c9c06f8a3d fix: wrong exe path 2022-02-21 22:33:37 +08:00
GyDi
72127979c3 chore: use tauri cli 2022-02-21 22:31:00 +08:00
GyDi
1ad3ddef94 v0.0.16 2022-02-21 01:33:11 +08:00
GyDi
97ec5eabf7 feat: change window style 2022-02-20 23:46:13 +08:00
GyDi
e12e3a3f2d feat: fill verge template 2022-02-20 20:12:55 +08:00
GyDi
4ff625f23b feat: enable customize guard duration 2022-02-20 20:11:39 +08:00
GyDi
e38dcd85ac feat: system proxy guard 2022-02-20 18:53:21 +08:00
GyDi
0245baf1b6 feat: enable show or hide traffic graph 2022-02-19 18:14:40 +08:00
GyDi
10b55c043c fix: patch verge config 2022-02-19 17:32:23 +08:00
GyDi
457655b416 feat: traffic line graph 2022-02-19 17:02:24 +08:00
GyDi
7e4506c860 chore: update deps 2022-02-19 00:34:09 +08:00
GyDi
794d376348 feat: adjust profile item ui 2022-02-19 00:23:47 +08:00
GyDi
c60578f5b5 feat: adjust fetch profile url 2022-02-19 00:09:36 +08:00
GyDi
3a9a392a77 feat: inline config file template 2022-02-18 23:57:13 +08:00
GyDi
a13d4698be chore: update check script 2022-02-18 23:49:39 +08:00
GyDi
c046a1993e fix: fetch profile panic 2022-02-17 13:44:26 +08:00
GyDi
f709117cc4 feat: kill sidecars when update app 2022-02-17 02:10:25 +08:00
GyDi
30dd298fca feat: delete file 2022-02-17 01:58:12 +08:00
GyDi
0ff8bb8090 feat: lock some async functions 2022-02-17 01:42:25 +08:00
GyDi
74bbd3c3a2 chore: tauri updater env 2022-02-16 11:02:00 +08:00
GyDi
2e82eaf59a chore: add pubkey 2022-02-16 10:59:31 +08:00
GyDi
7f1df1f1bd v0.0.15 2022-02-16 03:22:25 +08:00
GyDi
3c79238a44 feat: support open dir 2022-02-16 03:21:34 +08:00
GyDi
0aa2565df3 fix: spawn command 2022-02-16 02:43:52 +08:00
GyDi
22b11db16e feat: change allow list 2022-02-16 02:42:56 +08:00
GyDi
d0e678b5e9 feat: support check delay 2022-02-16 02:22:01 +08:00
GyDi
e7bba968b3 fix: import error 2022-02-15 01:36:19 +08:00
GyDi
4934a24293 feat: scroll to proxy item 2022-02-15 01:34:10 +08:00
GyDi
ccb68bcda9 chore: update deps 2022-02-15 00:33:58 +08:00
GyDi
66bf4ba3ad fix: not open file when new profile 2022-02-15 00:21:34 +08:00
GyDi
78a0cfd052 feat: edit system proxy bypass 2022-02-14 01:26:24 +08:00
GyDi
8548373742 feat: disable user select 2022-02-13 19:52:35 +08:00
GyDi
2dfd725ee0 fix: reset value correctly 2022-02-13 19:40:31 +08:00
GyDi
5b779b4f14 feat: new profile able to edit name and desc 2022-02-13 19:33:24 +08:00
GyDi
fc48aa7155 chore: adjust files 2022-02-13 19:27:24 +08:00
GyDi
6193a842f4 feat: update tauri version 2022-02-13 18:45:03 +08:00
GyDi
eb86b471fe fix: something 2022-02-12 21:12:39 +08:00
GyDi
2b52584547 fix: menu without fragment 2022-02-10 01:42:52 +08:00
GyDi
6e3cc57f48 feat: display clash core version 2022-02-10 01:35:55 +08:00
GyDi
f2c04621a5 feat: adjust profile item menu 2022-02-10 01:14:57 +08:00
GyDi
3ed6938d4a v0.0.14 2022-02-09 02:11:01 +08:00
GyDi
99fec25ed5 feat: profile item ui 2022-02-09 02:08:27 +08:00
GyDi
73758ad1fd fix: proxy list error 2022-02-09 02:02:29 +08:00
GyDi
c53fe0ed1f feat: support new profile 2022-02-07 17:26:05 +08:00
GyDi
6082c2bcac feat: support open command for viewing 2022-02-07 16:45:20 +08:00
GyDi
069abed784 chore: add item template yaml 2022-02-02 20:56:06 +08:00
GyDi
7d8fa4d78a fix: something 2022-01-31 23:34:58 +08:00
GyDi
76081f8d89 fix: macos auto launch fail 2022-01-31 23:32:41 +08:00
GyDi
5ef4285558 chore: update deps and app name 2022-01-31 23:27:11 +08:00
GyDi
aa7df4282e chore: cargo update 2022-01-28 22:02:17 +08:00
GyDi
0ef1d5d0de chore: update clash version 2022-01-28 22:00:15 +08:00
89 changed files with 6902 additions and 5619 deletions

View File

@@ -1,4 +1,4 @@
name: CI name: Release CI
on: [push] on: [push]
@@ -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,21 +59,30 @@ jobs:
yarn run check yarn run check
- name: Tauri build - name: Tauri build
uses: tauri-apps/tauri-action@v0 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_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
with: with:
tagName: v__VERSION__ tagName: v__VERSION__
releaseName: "Clash Verge v__VERSION__" releaseName: "Clash Verge v__VERSION__"
releaseBody: "Clash Verge now supports Windows and macos(intel)." releaseBody: "More new features are now supported."
releaseDraft: false releaseDraft: false
prerelease: true prerelease: true
- name: Green zip bundle
if: matrix.os == 'windows-latest'
run: |
yarn run green
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')
@@ -89,10 +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 update.json
run: yarn run release run: yarn run release
continue-on-error: true
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -11,19 +11,27 @@ 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, even fewer. (WIP) - Full `clash` config supported, Partial `clash premium` config supported.
- Profiles management and enhancement (by yaml and Javascript).
- 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
You should install Rust and Nodejs. Then install tauri cli and packages. You should install Rust and Nodejs, see [here](https://tauri.studio/docs/getting-started/prerequisites) for more details. Then install Nodejs packages.
```shell ```shell
cargo install tauri-cli --git https://github.com/tauri-apps/tauri
yarn install yarn install
``` ```
Then download the clash binary... Or you can download it from [clash premium release](https://github.com/Dreamacro/clash/releases/tag/premium) and rename it according to [tauri config](https://tauri.studio/en/docs/api/config#tauri.bundle.externalBin). Then download the clash binary... Or you can download it from [clash premium release](https://github.com/Dreamacro/clash/releases/tag/premium) and rename it according to [tauri config](https://tauri.studio/docs/api/config/#tauri.bundle.externalBin).
```shell ```shell
yarn run check yarn run check
@@ -35,6 +43,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...
@@ -56,7 +70,7 @@ This is a learning project for Rust practice.
## Contributions ## Contributions
PR welcome! Issue and PR welcome!
## Acknowledgement ## Acknowledgement

46
UPDATELOG.md Normal file
View File

@@ -0,0 +1,46 @@
## 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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

After

Width:  |  Height:  |  Size: 28 KiB

View File

@@ -1,51 +1,55 @@
{ {
"name": "clash-verge", "name": "clash-verge",
"version": "0.0.13", "version": "0.0.25",
"license": "GPL-3.0", "license": "GPL-3.0",
"scripts": { "scripts": {
"dev": "cargo tauri dev", "dev": "tauri dev",
"build": "cargo tauri build", "build": "tauri build",
"tauri": "tauri", "tauri": "tauri",
"web:dev": "vite", "web:dev": "vite",
"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",
"green": "node scripts/green.mjs",
"publish": "node scripts/publish.mjs", "publish": "node scripts/publish.mjs",
"release": "node scripts/release.mjs", "release": "node scripts/release.mjs",
"prepare": "husky install" "prepare": "husky install"
}, },
"dependencies": { "dependencies": {
"@emotion/react": "^11.7.0", "@emotion/react": "^11.8.1",
"@emotion/styled": "^11.6.0", "@emotion/styled": "^11.8.1",
"@mui/icons-material": "^5.2.1", "@mui/icons-material": "^5.4.4",
"@mui/material": "^5.2.3", "@mui/material": "^5.4.4",
"@tauri-apps/api": "^1.0.0-beta.8", "@tauri-apps/api": "^1.0.0-rc.2",
"ahooks": "^3.1.7", "ahooks": "^3.1.13",
"axios": "^0.24.0", "axios": "^0.26.0",
"dayjs": "^1.10.7", "dayjs": "^1.10.8",
"react": "^17.0.0", "i18next": "^21.6.14",
"react-dom": "^17.0.0", "react": "^17.0.2",
"react-router-dom": "^6.0.2", "react-dom": "^17.0.2",
"react-virtuoso": "^2.3.1", "react-i18next": "^11.15.6",
"recoil": "^0.5.2", "react-router-dom": "^6.2.2",
"swr": "^1.1.2-beta.0" "react-virtuoso": "^2.7.0",
"recoil": "^0.6.1",
"snarkdown": "^2.0.0",
"swr": "^1.2.1"
}, },
"devDependencies": { "devDependencies": {
"@actions/github": "^5.0.0", "@actions/github": "^5.0.0",
"@tauri-apps/cli": "^1.0.0-beta.10", "@tauri-apps/cli": "^1.0.0-rc.7",
"@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/react": "^17.0.0", "@types/react": "^17.0.0",
"@types/react-dom": "^17.0.0", "@types/react-dom": "^17.0.0",
"@vitejs/plugin-react": "^1.1.1", "@vitejs/plugin-react": "^1.2.0",
"adm-zip": "^0.5.9", "adm-zip": "^0.5.9",
"fs-extra": "^10.0.0", "fs-extra": "^10.0.0",
"husky": "^7.0.0", "husky": "^7.0.0",
"node-fetch": "^3.1.0", "node-fetch": "^3.2.0",
"pretty-quick": "^3.1.3", "pretty-quick": "^3.1.3",
"sass": "^1.44.0", "sass": "^1.49.7",
"typescript": "^4.5.2", "typescript": "^4.5.5",
"vite": "^2.7.1" "vite": "^2.8.6"
}, },
"prettier": { "prettier": {
"tabWidth": 2, "tabWidth": 2,

View File

@@ -6,10 +6,7 @@ import fetch from "node-fetch";
import { execSync } from "child_process"; import { execSync } from "child_process";
const cwd = process.cwd(); const cwd = process.cwd();
const FORCE = process.argv.includes("--force");
const CLASH_URL_PREFIX =
"https://github.com/Dreamacro/clash/releases/download/premium/";
const CLASH_LATEST_DATE = "2022.01.03";
/** /**
* get the correct clash release infomation * get the correct clash release infomation
@@ -17,11 +14,16 @@ const CLASH_LATEST_DATE = "2022.01.03";
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.03.21";
// todo // todo
const map = { const map = {
"win32-x64": "clash-windows-386", "win32-x64": "clash-windows-amd64",
"darwin-x64": "clash-darwin-amd64", "darwin-x64": "clash-darwin-amd64",
"darwin-arm64": "clash-darwin-arm64", "darwin-arm64": "clash-darwin-arm64",
"linux-x64": "clash-linux-amd64",
}; };
const name = map[`${platform}-${arch}`]; const name = map[`${platform}-${arch}`];
@@ -50,8 +52,8 @@ async function resolveSidecar() {
const sidecarFile = `clash-${host}${ext}`; const sidecarFile = `clash-${host}${ext}`;
const sidecarPath = path.join(sidecarDir, sidecarFile); const sidecarPath = path.join(sidecarDir, sidecarFile);
if (!(await fs.pathExists(sidecarDir))) await fs.mkdir(sidecarDir); await fs.mkdirp(sidecarDir);
if (await fs.pathExists(sidecarPath)) return; if (!FORCE && (await fs.pathExists(sidecarPath))) return;
// download sidecar // download sidecar
const binInfo = resolveClash(); const binInfo = resolveClash();
@@ -59,7 +61,7 @@ async function resolveSidecar() {
const tempZip = path.join(tempDir, binInfo.zipfile); const tempZip = path.join(tempDir, binInfo.zipfile);
const tempExe = path.join(tempDir, binInfo.exefile); const tempExe = path.join(tempDir, binInfo.exefile);
if (!(await fs.pathExists(tempDir))) await fs.mkdir(tempDir); await fs.mkdirp(tempDir);
if (!(await fs.pathExists(tempZip))) await downloadFile(binInfo.url, tempZip); if (!(await fs.pathExists(tempZip))) await downloadFile(binInfo.url, tempZip);
if (binInfo.zip === "zip") { if (binInfo.zip === "zip") {
@@ -82,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)
*/ */
@@ -96,8 +140,10 @@ async function resolveMmdb() {
const url = const url =
"https://github.com/Dreamacro/maxmind-geoip/releases/latest/download/Country.mmdb"; "https://github.com/Dreamacro/maxmind-geoip/releases/latest/download/Country.mmdb";
const resPath = path.join(cwd, "src-tauri", "resources", "Country.mmdb"); const resDir = path.join(cwd, "src-tauri", "resources");
if (await fs.pathExists(resPath)) return; const resPath = path.join(resDir, "Country.mmdb");
if (!FORCE && (await fs.pathExists(resPath))) return;
await fs.mkdirp(resDir);
await downloadFile(url, resPath); await downloadFile(url, resPath);
} }
@@ -118,5 +164,6 @@ async function downloadFile(url, path) {
} }
/// main /// main
resolveSidecar(); resolveSidecar().catch(console.error);
resolveMmdb(); resolveWintun().catch(console.error);
resolveMmdb().catch(console.error);

56
scripts/green.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 resolveGreen() {
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_green.zip`;
zip.writeZip(zipFile);
console.log("[INFO]: create green 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(),
});
}
resolveGreen().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,7 +1,10 @@
import { createRequire } from "module"; import fetch from "node-fetch";
import { getOctokit, context } from "@actions/github"; import { getOctokit, context } from "@actions/github";
import { resolveUpdateLog } from "./updatelog.mjs";
const require = createRequire(import.meta.url); const UPDATE_TAG_NAME = "updater";
const UPDATE_JSON_FILE = "update.json";
const UPDATE_JSON_PROXY = "update-proxy.json";
/// generate update.json /// generate update.json
/// upload to update tag's release asset /// upload to update tag's release asset
@@ -10,59 +13,152 @@ async function resolveRelease() {
throw new Error("GITHUB_TOKEN is required"); throw new Error("GITHUB_TOKEN is required");
} }
const packageJson = require("../package.json"); 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 { version } = packageJson;
const urlPrefix = "https://github.com/zzzgydi/clash-verge/releases/download";
const updateData = { const updateData = {
name: `v${version}`, name: tag.name,
notes: `Version ${version} is available now!!!`, notes: await resolveUpdateLog(tag.name), // use updatelog.md
pub_date: new Date().toISOString(), pub_date: new Date().toISOString(),
platforms: { platforms: {
win64: { win64: { signature: "", url: "" },
signature: "", linux: { signature: "", url: "" },
url: `${urlPrefix}/v${version}/clash-verge_${version}_x64.msi.zip`, darwin: { signature: "", url: "" },
},
darwin: {
signature: "",
url: `${urlPrefix}/v${version}/clash-verge.app.tar.gz`,
},
}, },
}; };
console.log(`Generating Version "${version}" update.json`); const promises = latestRelease.assets.map(async (asset) => {
const { name, browser_download_url } = asset;
const github = getOctokit(process.env.GITHUB_TOKEN); // win64 url
if (/\.msi\.zip$/.test(name)) {
updateData.platforms.win64.url = browser_download_url;
}
// win64 signature
if (/\.msi\.zip\.sig$/.test(name)) {
updateData.platforms.win64.signature = await getSignature(
browser_download_url
);
}
const { data: release } = await github.rest.repos.getReleaseByTag({ // darwin url
owner: context.repo.owner, if (/\.app\.tar\.gz$/.test(name)) {
repo: context.repo.repo, updateData.platforms.darwin.url = browser_download_url;
tag: "updater", }
}); // darwin signature
const { data: assets } = await github.rest.repos.listReleaseAssets({ if (/\.app\.tar\.gz\.sig$/.test(name)) {
owner: context.repo.owner, updateData.platforms.darwin.signature = await getSignature(
repo: context.repo.repo, browser_download_url
release_id: release.id, );
}
// linux url
if (/\.AppImage\.tar\.gz$/.test(name)) {
updateData.platforms.linux.url = browser_download_url;
}
// linux signature
if (/\.AppImage\.tar\.gz\.sig$/.test(name)) {
updateData.platforms.linux.signature = await getSignature(
browser_download_url
);
}
}); });
for (let asset of assets) { await Promise.allSettled(promises);
if (asset.name === "update.json") { console.log(updateData);
// maybe should test the signature as well
const { darwin, win64, linux } = 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;
}
if (!linux.url) {
console.log(`[Error]: failed to parse release for linux`);
delete updateData.platforms.linux;
}
// 生成一个代理github的更新文件
// 使用 https://hub.fastgit.xyz/ 做github资源的加速
const updateDataNew = JSON.parse(JSON.stringify(updateData));
Object.keys(updateDataNew.platforms).forEach((key) => {
if (updateDataNew.platforms[key]) {
updateDataNew.platforms[key].url = updateDataNew.platforms[
key
].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({ await github.rest.repos.deleteReleaseAsset({
owner: context.repo.owner, ...options,
repo: context.repo.repo,
asset_id: asset.id, asset_id: asset.id,
}); });
break; }
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 assets
await github.rest.repos.uploadReleaseAsset({ await github.rest.repos.uploadReleaseAsset({
owner: context.repo.owner, ...options,
repo: context.repo.repo, release_id: updateRelease.id,
release_id: release.id, name: UPDATE_JSON_FILE,
name: "update.json",
data: JSON.stringify(updateData, null, 2), 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),
});
} }
resolveRelease(); // 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();
}

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

1651
src-tauri/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,28 +1,29 @@
[package] [package]
name = "app" name = "clash-verge"
version = "0.1.0" version = "0.1.0"
description = "clash verge" description = "clash verge"
authors = ["zzzgydi"] authors = ["zzzgydi"]
license = "GPL-3.0" license = "GPL-3.0"
repository = "https://github.com/zzzgydi/clash-verge.git" repository = "https://github.com/zzzgydi/clash-verge.git"
default-run = "app" default-run = "clash-verge"
edition = "2021" edition = "2021"
build = "build.rs" build = "build.rs"
[build-dependencies] [build-dependencies]
tauri-build = { version = "1.0.0-beta.4" } tauri-build = { version = "1.0.0-rc.4", features = [] }
[dependencies] [dependencies]
anyhow = "1.0"
dirs = "4.0.0" dirs = "4.0.0"
dunce = "1.0.2"
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-beta.8", features = ["api-all", "system-tray"] } tauri = { version = "1.0.0-rc.4", features = ["process-all", "shell-all", "system-tray", "updater", "window-all"] }
# tauri = { git = "https://github.com/tauri-apps/tauri", rev = "5e0d59ec", features = ["api-all", "system-tray"] } window-shadows = { git = "https://github.com/tauri-apps/window-shadows" }
tauri = { git = "https://github.com/tauri-apps/tauri", branch = "next", features = ["api-all", "system-tray", "updater"] } window-vibrancy = { git = "https://github.com/tauri-apps/window-vibrancy" }
tauri-plugin-shadows = { git = "https://github.com/tauri-apps/tauri-plugin-shadows", features = ["tauri-impl"] }
tauri-plugin-vibrancy = { git = "https://github.com/tauri-apps/tauri-plugin-vibrancy", features = ["tauri-impl"] }
reqwest = { version = "0.11", features = ["json"] } reqwest = { version = "0.11", features = ["json"] }
tokio = { version = "1", features = ["full"] } tokio = { version = "1", features = ["full"] }
@@ -39,3 +40,4 @@ 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 = []

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

View File

@@ -1,8 +0,0 @@
# Default Config For Clash Core
mixed-port: 7890
log-level: info
allow-lan: false
external-controller: 127.0.0.1:9090
mode: rule
secret: ""

View File

@@ -1,3 +0,0 @@
# Profiles Config for Clash Verge
current: 0

View File

@@ -1,6 +0,0 @@
# Defaulf Config For Clash Verge
theme_mode: light
enable_self_startup: false
enable_system_proxy: false
system_proxy_bypass: localhost;127.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;192.168.*;<local>

View File

@@ -1,29 +1,26 @@
use crate::{ use crate::{
core::{ClashInfo, ProfileItem, Profiles, VergeConfig}, core::{ClashInfo, PrfItem, PrfOption, Profiles, VergeConfig},
states::{ClashState, ProfilesState, VergeState}, states::{ClashState, ProfilesState, VergeState},
utils::{dirs::app_home_dir, fetch::fetch_profile, sysopt::SysProxyConfig}, utils::{dirs, sysopt::SysProxyConfig},
}; };
use crate::{ret_err, wrap_err};
use anyhow::Result;
use serde_yaml::Mapping; use serde_yaml::Mapping;
use std::process::Command; use std::{path::PathBuf, process::Command};
use tauri::State; use tauri::{api, Manager, State};
/// get all profiles from `profiles.yaml` /// get all profiles from `profiles.yaml`
/// do not acquire the lock of ProfileLock
#[tauri::command] #[tauri::command]
pub fn get_profiles(profiles_state: State<'_, ProfilesState>) -> Result<Profiles, String> { pub fn get_profiles<'a>(profiles_state: State<'_, ProfilesState>) -> Result<Profiles, String> {
match profiles_state.0.lock() { let profiles = profiles_state.0.lock().unwrap();
Ok(profiles) => Ok(profiles.clone()), Ok(profiles.clone())
Err(_) => Err("failed to get profiles lock".into()),
}
} }
/// synchronize data irregularly /// synchronize data irregularly
#[tauri::command] #[tauri::command]
pub fn sync_profiles(profiles_state: State<'_, ProfilesState>) -> Result<(), String> { pub fn sync_profiles(profiles_state: State<'_, ProfilesState>) -> Result<(), String> {
match profiles_state.0.lock() { let mut profiles = profiles_state.0.lock().unwrap();
Ok(mut profiles) => profiles.sync_file(), wrap_err!(profiles.sync_file())
Err(_) => Err("failed to get profiles lock".into()),
}
} }
/// import the profile from url /// import the profile from url
@@ -31,140 +28,188 @@ pub fn sync_profiles(profiles_state: State<'_, ProfilesState>) -> Result<(), Str
#[tauri::command] #[tauri::command]
pub async fn import_profile( pub async fn import_profile(
url: String, url: String,
with_proxy: bool, option: Option<PrfOption>,
profiles_state: State<'_, ProfilesState>, profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> { ) -> Result<(), String> {
match fetch_profile(&url, with_proxy).await { let item = wrap_err!(PrfItem::from_url(&url, None, None, option).await)?;
Some(result) => {
let mut profiles = profiles_state.0.lock().unwrap(); let mut profiles = profiles_state.0.lock().unwrap();
profiles.import_from_url(url, result) wrap_err!(profiles.append_item(item))
} }
None => Err(format!("failed to fetch profile from `{}`", url)),
} /// new a profile
/// append a temp profile item file to the `profiles` dir
/// view the temp profile file by using vscode or other editor
#[tauri::command]
pub async fn create_profile(
item: PrfItem, // partial
file_data: Option<String>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let item = wrap_err!(PrfItem::from(item, file_data).await)?;
let mut profiles = profiles_state.0.lock().unwrap();
wrap_err!(profiles.append_item(item))
} }
/// Update the profile /// Update the profile
#[tauri::command] #[tauri::command]
pub async fn update_profile( pub async fn update_profile(
index: usize, index: String,
with_proxy: bool, option: Option<PrfOption>,
clash_state: State<'_, ClashState>, clash_state: State<'_, ClashState>,
profiles_state: State<'_, ProfilesState>, profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> { ) -> Result<(), String> {
// maybe we can get the url from the web app directly let (url, opt) = {
let url = match profiles_state.0.lock() { // must release the lock here
Ok(mut profile) => { let profiles = profiles_state.0.lock().unwrap();
let items = profile.items.take().unwrap_or(vec![]); let item = wrap_err!(profiles.get_item(&index))?;
if index >= items.len() {
return Err("the index out of bound".into()); // check the profile type
if let Some(typ) = item.itype.as_ref() {
if *typ != "remote" {
ret_err!(format!("could not update the `{typ}` profile"));
} }
let url = match &items[index].url {
Some(u) => u.clone(),
None => return Err("failed to update profile for `invalid url`".into()),
};
profile.items = Some(items);
url
} }
Err(_) => return Err("failed to get profiles lock".into()),
if item.url.is_none() {
ret_err!("failed to get the item url");
}
(item.url.clone().unwrap(), item.option.clone())
}; };
match fetch_profile(&url, with_proxy).await { let fetch_opt = PrfOption::merge(opt, option);
Some(result) => match profiles_state.0.lock() { let item = wrap_err!(PrfItem::from_url(&url, None, None, fetch_opt).await)?;
Ok(mut profiles) => {
profiles.update_item(index, result)?;
// reactivate the profile let mut profiles = profiles_state.0.lock().unwrap();
let current = profiles.current.clone().unwrap_or(0); wrap_err!(profiles.update_item(index.clone(), item))?;
if current == index {
let clash = clash_state.0.lock().unwrap(); // reactivate the profile
profiles.activate(&clash) if Some(index) == profiles.get_current() {
} else { let clash = clash_state.0.lock().unwrap();
Ok(()) wrap_err!(clash.activate(&profiles, false))?;
}
}
Err(_) => Err("failed to get profiles lock".into()),
},
None => Err(format!("failed to fetch profile from `{}`", url)),
} }
Ok(())
} }
/// change the current profile /// change the current profile
#[tauri::command] #[tauri::command]
pub fn select_profile( pub fn select_profile(
index: usize, index: String,
clash_state: State<'_, ClashState>, clash_state: State<'_, ClashState>,
profiles_state: State<'_, ProfilesState>, profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> { ) -> Result<(), String> {
let mut profiles = profiles_state.0.lock().unwrap(); let mut profiles = profiles_state.0.lock().unwrap();
wrap_err!(profiles.put_current(index))?;
match profiles.put_current(index) { let clash = clash_state.0.lock().unwrap();
Ok(()) => { wrap_err!(clash.activate(&profiles, false))
let clash = clash_state.0.lock().unwrap(); }
profiles.activate(&clash)
} /// change the profile chain
Err(err) => Err(err), #[tauri::command]
} pub fn change_profile_chain(
chain: 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_chain(chain);
clash.set_window(app_handle.get_window("main"));
wrap_err!(clash.activate_enhanced(&profiles, false))
}
/// manually exec enhanced profile
#[tauri::command]
pub fn enhance_profiles(
app_handle: tauri::AppHandle,
clash_state: State<'_, ClashState>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let mut clash = clash_state.0.lock().unwrap();
let profiles = profiles_state.0.lock().unwrap();
clash.set_window(app_handle.get_window("main"));
wrap_err!(clash.activate_enhanced(&profiles, false))
} }
/// delete profile item /// delete profile item
#[tauri::command] #[tauri::command]
pub fn delete_profile( pub fn delete_profile(
index: usize, index: String,
clash_state: State<'_, ClashState>, clash_state: State<'_, ClashState>,
profiles_state: State<'_, ProfilesState>, profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> { ) -> Result<(), String> {
let mut profiles = profiles_state.0.lock().unwrap(); let mut profiles = profiles_state.0.lock().unwrap();
match profiles.delete_item(index) {
Ok(change) => match change { if wrap_err!(profiles.delete_item(index))? {
true => { let clash = clash_state.0.lock().unwrap();
let clash = clash_state.0.lock().unwrap(); wrap_err!(clash.activate(&profiles, false))?;
profiles.activate(&clash)
}
false => Ok(()),
},
Err(err) => Err(err),
} }
Ok(())
} }
/// patch the profile config /// patch the profile config
#[tauri::command] #[tauri::command]
pub fn patch_profile( pub fn patch_profile(
index: usize, index: String,
profile: ProfileItem, profile: PrfItem,
profiles_state: State<'_, ProfilesState>, profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> { ) -> Result<(), String> {
match profiles_state.0.lock() { let mut profiles = profiles_state.0.lock().unwrap();
Ok(mut profiles) => profiles.patch_item(index, profile), wrap_err!(profiles.patch_item(index, profile))
Err(_) => Err("can not get profiles lock".into()),
}
} }
/// run vscode command to edit the profile /// run vscode command to edit the profile
#[tauri::command] #[tauri::command]
pub fn view_profile(index: usize, profiles_state: State<'_, ProfilesState>) -> Result<(), String> { pub fn view_profile(index: String, profiles_state: State<'_, ProfilesState>) -> Result<(), String> {
let mut profiles = profiles_state.0.lock().unwrap(); let profiles = profiles_state.0.lock().unwrap();
let items = profiles.items.take().unwrap_or(vec![]); let item = wrap_err!(profiles.get_item(&index))?;
if index >= items.len() { let file = item.file.clone();
profiles.items = Some(items); if file.is_none() {
return Err("the index out of bound".into()); ret_err!("the file is null");
} }
let file = items[index].file.clone().unwrap_or("".into()); let path = dirs::app_profiles_dir().join(file.unwrap());
profiles.items = Some(items);
let path = app_home_dir().join("profiles").join(file);
if !path.exists() { if !path.exists() {
return Err("failed to open the file".into()); ret_err!("the file not found");
} }
match which::which("code") { // use vscode first
Ok(code) => match Command::new(code).arg(path).status() { if let Ok(code) = which::which("code") {
Ok(_) => Ok(()), #[cfg(target_os = "windows")]
Err(_) => Err("failed to open file by VScode".into()), {
}, use std::os::windows::process::CommandExt;
Err(_) => Err("please install VScode for edit".into()),
if let Err(err) = Command::new(code)
.creation_flags(0x08000000)
.arg(path)
.spawn()
{
log::error!("{err}");
return Err("failed to open file by VScode".into());
}
}
#[cfg(not(target_os = "windows"))]
if let Err(err) = Command::new(code).arg(path).spawn() {
log::error!("{err}");
return Err("failed to open file by VScode".into());
}
return Ok(());
} }
open_path_cmd(path, "failed to open file by `open`")
} }
/// restart the sidecar /// restart the sidecar
@@ -176,23 +221,15 @@ pub fn restart_sidecar(
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) { wrap_err!(clash.restart_sidecar(&mut profiles))
Ok(_) => Ok(()),
Err(err) => {
log::error!("{}", err);
Err(err)
}
}
} }
/// get the clash core info from the state /// get the clash core info from the state
/// the caller can also get the infomation by clash's api /// the caller can also get the infomation by clash's api
#[tauri::command] #[tauri::command]
pub fn get_clash_info(clash_state: State<'_, ClashState>) -> Result<ClashInfo, String> { pub fn get_clash_info(clash_state: State<'_, ClashState>) -> Result<ClashInfo, String> {
match clash_state.0.lock() { let clash = clash_state.0.lock().unwrap();
Ok(clash) => Ok(clash.info.clone()), Ok(clash.info.clone())
Err(_) => Err("failed to get clash lock".into()),
}
} }
/// update the clash core config /// update the clash core config
@@ -208,44 +245,144 @@ pub fn patch_clash_config(
let mut clash = clash_state.0.lock().unwrap(); let mut clash = clash_state.0.lock().unwrap();
let mut verge = verge_state.0.lock().unwrap(); let mut verge = verge_state.0.lock().unwrap();
let mut profiles = profiles_state.0.lock().unwrap(); let mut profiles = profiles_state.0.lock().unwrap();
clash.patch_config(payload, &mut verge, &mut profiles) wrap_err!(clash.patch_config(payload, &mut verge, &mut profiles))
} }
/// get the system proxy /// get the system proxy
#[tauri::command] #[tauri::command]
pub fn get_sys_proxy() -> Result<SysProxyConfig, String> { pub fn get_sys_proxy() -> Result<SysProxyConfig, String> {
match SysProxyConfig::get_sys() { wrap_err!(SysProxyConfig::get_sys())
Ok(value) => Ok(value),
Err(err) => Err(err.to_string()),
}
} }
/// get the current proxy config /// get the current proxy config
/// which may not the same as system proxy /// which may not the same as system proxy
#[tauri::command] #[tauri::command]
pub fn get_cur_proxy(verge_state: State<'_, VergeState>) -> Result<Option<SysProxyConfig>, String> { pub fn get_cur_proxy(verge_state: State<'_, VergeState>) -> Result<Option<SysProxyConfig>, String> {
match verge_state.0.lock() { let verge = verge_state.0.lock().unwrap();
Ok(verge) => Ok(verge.cur_sysproxy.clone()), Ok(verge.cur_sysproxy.clone())
Err(_) => Err("failed to get verge lock".into()),
}
} }
/// get the verge config /// get the verge config
#[tauri::command] #[tauri::command]
pub fn get_verge_config(verge_state: State<'_, VergeState>) -> Result<VergeConfig, String> { pub fn get_verge_config(verge_state: State<'_, VergeState>) -> Result<VergeConfig, String> {
match verge_state.0.lock() { let verge = verge_state.0.lock().unwrap();
Ok(arc) => Ok(arc.config.clone()), let mut config = verge.config.clone();
Err(_) => Err("failed to get verge lock".into()),
if config.system_proxy_bypass.is_none() && verge.cur_sysproxy.is_some() {
config.system_proxy_bypass = Some(verge.cur_sysproxy.clone().unwrap().bypass)
} }
Ok(config)
} }
/// patch the verge config /// patch the verge config
/// this command only save the config and not responsible for other things /// this command only save the config and not responsible for other things
#[tauri::command] #[tauri::command]
pub async fn patch_verge_config( pub fn patch_verge_config(
payload: VergeConfig, payload: VergeConfig,
app_handle: tauri::AppHandle,
clash_state: State<'_, ClashState>,
verge_state: State<'_, VergeState>, verge_state: State<'_, VergeState>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> { ) -> Result<(), String> {
let tun_mode = payload.enable_tun_mode.clone();
let system_proxy = payload.enable_system_proxy.clone();
// change tun mode
if tun_mode.is_some() {
let mut clash = clash_state.0.lock().unwrap();
let profiles = profiles_state.0.lock().unwrap();
wrap_err!(clash.tun_mode(tun_mode.unwrap()))?;
clash.update_config();
wrap_err!(clash.activate(&profiles, false))?;
}
let mut verge = verge_state.0.lock().unwrap(); let mut verge = verge_state.0.lock().unwrap();
verge.patch_config(payload) wrap_err!(verge.patch_config(payload))?;
// change system tray
if system_proxy.is_some() {
app_handle
.tray_handle()
.get_item("system_proxy")
.set_selected(system_proxy.unwrap())
.unwrap();
}
Ok(())
}
/// kill all sidecars when update app
#[tauri::command]
pub fn kill_sidecars() {
api::process::kill_children();
}
/// open app config dir
#[tauri::command]
pub fn open_app_dir() -> Result<(), String> {
let app_dir = dirs::app_home_dir();
open_path_cmd(app_dir, "failed to open app dir")
}
/// open logs dir
#[tauri::command]
pub fn open_logs_dir() -> Result<(), String> {
let log_dir = dirs::app_logs_dir();
open_path_cmd(log_dir, "failed to open logs dir")
}
/// use the os default open command to open file or dir
fn open_path_cmd(path: PathBuf, err_str: &str) -> Result<(), String> {
let result;
#[cfg(target_os = "windows")]
{
use std::os::windows::process::CommandExt;
result = Command::new("explorer")
.creation_flags(0x08000000)
.arg(&path)
.spawn();
}
#[cfg(target_os = "macos")]
{
result = Command::new("open").arg(&path).spawn();
}
#[cfg(target_os = "linux")]
{
result = Command::new("xdg-open").arg(&path).spawn();
}
match result {
Ok(child) => match child.wait_with_output() {
Ok(out) => {
// 退出码不为0 不一定没有调用成功
// 因此仅做warn log且不返回错误
if let Some(code) = out.status.code() {
if code != 0 {
log::warn!("failed to open {:?} (code {})", &path, code);
log::warn!(
"open cmd stdout: {}, stderr: {}",
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr),
);
}
}
}
Err(err) => {
log::error!("failed to open {:?} for {err}", &path);
return Err(err_str.into());
}
},
Err(err) => {
log::error!("failed to open {:?} for {err}", &path);
return Err(err_str.into());
}
}
return Ok(());
} }

View File

@@ -1,8 +1,13 @@
use super::{Profiles, Verge}; use super::{PrfEnhancedResult, Profiles, Verge};
use crate::utils::{config, dirs}; use crate::utils::{config, dirs, help};
use anyhow::{bail, Result};
use reqwest::header::HeaderMap;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_yaml::{Mapping, Value}; use serde_yaml::{Mapping, Value};
use std::{collections::HashMap, time::Duration};
use tauri::api::process::{Command, CommandChild, CommandEvent}; use tauri::api::process::{Command, CommandChild, CommandEvent};
use tauri::Window;
use tokio::time::sleep;
#[derive(Default, Debug, Clone, Deserialize, Serialize)] #[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct ClashInfo { pub struct ClashInfo {
@@ -19,7 +24,6 @@ pub struct ClashInfo {
pub secret: Option<String>, pub secret: Option<String>,
} }
#[derive(Debug)]
pub struct Clash { pub struct Clash {
/// maintain the clash config /// maintain the clash config
pub config: Mapping, pub config: Mapping,
@@ -29,23 +33,38 @@ pub struct Clash {
/// clash sidecar /// clash sidecar
pub sidecar: Option<CommandChild>, pub sidecar: Option<CommandChild>,
/// save the main window
pub window: Option<Window>,
} }
static CLASH_CONFIG: &str = "config.yaml";
// todo: be able to change config field
impl Clash { impl Clash {
pub fn new() -> Clash { pub fn new() -> Clash {
let config = Clash::get_config(); let config = Clash::read_config();
let info = Clash::get_info(&config); let info = Clash::get_info(&config);
Clash { Clash {
config, config,
info, info,
sidecar: None, sidecar: None,
window: None,
} }
} }
/// get clash config
fn read_config() -> Mapping {
config::read_yaml::<Mapping>(dirs::clash_path())
}
/// save the clash config
fn save_config(&self) -> Result<()> {
config::save_yaml(
dirs::clash_path(),
&self.config,
Some("# Default Config For Clash Core\n\n"),
)
}
/// parse the clash's config.yaml /// parse the clash's config.yaml
/// get some information /// get some information
fn get_info(clash_config: &Mapping) -> ClashInfo { fn get_info(clash_config: &Mapping) -> ClashInfo {
@@ -76,7 +95,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,
@@ -99,8 +129,13 @@ impl Clash {
} }
} }
/// save the main window
pub fn set_window(&mut self, win: Option<Window>) {
self.window = win;
}
/// run clash sidecar /// run clash sidecar
pub fn run_sidecar(&mut self) -> Result<(), String> { pub fn run_sidecar(&mut self) -> Result<()> {
let app_dir = dirs::app_home_dir(); let app_dir = dirs::app_home_dir();
let app_dir = app_dir.as_os_str().to_str().unwrap(); let app_dir = app_dir.as_os_str().to_str().unwrap();
@@ -113,96 +148,296 @@ impl Clash {
tauri::async_runtime::spawn(async move { tauri::async_runtime::spawn(async move {
while let Some(event) = rx.recv().await { while let Some(event) = rx.recv().await {
match event { match event {
CommandEvent::Stdout(line) => log::info!("[stdout]: {}", line), CommandEvent::Stdout(line) => log::info!("[clash]: {}", line),
CommandEvent::Stderr(err) => log::error!("[stderr]: {}", err), CommandEvent::Stderr(err) => log::error!("[clash]: {}", err),
_ => {} _ => {}
} }
} }
}); });
Ok(()) Ok(())
} }
Err(err) => Err(err.to_string()), Err(err) => bail!(err.to_string()),
}, },
Err(err) => Err(err.to_string()), Err(err) => bail!(err.to_string()),
} }
} }
/// drop clash sidecar /// drop clash sidecar
pub fn drop_sidecar(&mut self) -> Result<(), String> { pub fn drop_sidecar(&mut self) -> Result<()> {
if let Some(sidecar) = self.sidecar.take() { if let Some(sidecar) = self.sidecar.take() {
if let Err(err) = sidecar.kill() { sidecar.kill()?;
return Err(format!("failed to drop clash for \"{}\"", err));
}
} }
Ok(()) Ok(())
} }
/// restart clash sidecar /// restart clash sidecar
/// should reactivate profile after restart /// should reactivate profile after restart
pub fn restart_sidecar(&mut self, profiles: &mut Profiles) -> Result<(), String> { pub fn restart_sidecar(&mut self, profiles: &mut Profiles) -> Result<()> {
self.update_config(); self.update_config();
self.drop_sidecar()?; self.drop_sidecar()?;
self.run_sidecar()?; self.run_sidecar()?;
profiles.activate(&self) self.activate(profiles, false)
} }
/// update the clash info /// update the clash info
pub fn update_config(&mut self) { pub fn update_config(&mut self) {
self.config = Clash::get_config(); self.config = Clash::read_config();
self.info = Clash::get_info(&self.config); self.info = Clash::get_info(&self.config);
} }
/// get clash config
fn get_config() -> Mapping {
config::read_yaml::<Mapping>(dirs::app_home_dir().join(CLASH_CONFIG))
}
/// save the clash config
fn save_config(&self) -> Result<(), String> {
config::save_yaml(
dirs::app_home_dir().join(CLASH_CONFIG),
&self.config,
Some("# Default Config For Clash Core\n\n"),
)
}
/// patch update the clash config /// patch update the clash config
pub fn patch_config( pub fn patch_config(
&mut self, &mut self,
patch: Mapping, patch: Mapping,
verge: &mut Verge, verge: &mut Verge,
profiles: &mut Profiles, profiles: &mut Profiles,
) -> Result<(), String> { ) -> 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);
} }
if self.config.contains_key(key) { self.config.insert(key.clone(), value);
self.config[key] = value; }
} else {
self.config.insert(key.clone(), value); self.save_config()?;
if let Some(port) = port {
self.restart_sidecar(profiles)?;
verge.init_sysproxy(Some(port));
}
Ok(())
}
/// enable tun mode
/// only revise the config and restart the
pub fn tun_mode(&mut self, enable: bool) -> Result<()> {
// Windows 需要wintun.dll文件
#[cfg(target_os = "windows")]
if enable {
let wintun_dll = dirs::app_home_dir().join("wintun.dll");
if !wintun_dll.exists() {
bail!("failed to enable TUN for missing `wintun.dll`");
} }
} }
macro_rules! revise {
($map: expr, $key: expr, $val: expr) => {
let ret_key = Value::String($key.into());
$map.insert(ret_key, Value::from($val));
};
}
// if key not exists then append value
macro_rules! append {
($map: expr, $key: expr, $val: expr) => {
let ret_key = Value::String($key.into());
if !$map.contains_key(&ret_key) {
$map.insert(ret_key, Value::from($val));
}
};
}
// tun config
let tun_val = self.config.get(&Value::from("tun"));
let mut new_tun = Mapping::new();
if tun_val.is_some() && tun_val.as_ref().unwrap().is_mapping() {
new_tun = tun_val.as_ref().unwrap().as_mapping().unwrap().clone();
}
revise!(new_tun, "enable", enable);
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!(self.config, "tun", new_tun);
// dns config
let dns_val = self.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);
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!(self.config, "dns", new_dns);
self.save_config() self.save_config()
} }
/// activate the profile
/// generate a new profile to the temp_dir
/// then put the path to the clash core
fn _activate(info: ClashInfo, config: Mapping, window: Option<Window>) -> Result<()> {
let temp_path = dirs::profiles_temp_path();
config::save_yaml(temp_path.clone(), &config, Some("# Clash Verge Temp File"))?;
tauri::async_runtime::spawn(async move {
let server = info.server.unwrap();
let server = format!("http://{server}/configs");
let mut headers = HeaderMap::new();
headers.insert("Content-Type", "application/json".parse().unwrap());
if let Some(secret) = info.secret.as_ref() {
let secret = format!("Bearer {}", secret.clone()).parse().unwrap();
headers.insert("Authorization", secret);
}
let mut data = HashMap::new();
data.insert("path", temp_path.as_os_str().to_str().unwrap());
// retry 5 times
for _ in 0..5 {
match reqwest::ClientBuilder::new().no_proxy().build() {
Ok(client) => {
let builder = client.put(&server).headers(headers.clone()).json(&data);
match builder.send().await {
Ok(resp) => {
if resp.status() != 204 {
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
break;
}
Err(err) => log::error!("failed to activate for `{err}`"),
}
}
Err(err) => log::error!("failed to activate for `{err}`"),
}
sleep(Duration::from_millis(500)).await;
}
});
Ok(())
}
/// enhanced profiles mode
/// only change the enhanced profiles
pub fn activate_enhanced(&self, profiles: &Profiles, delay: bool) -> Result<()> {
if self.window.is_none() {
bail!("failed to get the main window");
}
let win = self.window.clone().unwrap();
let event_name = help::get_uid("e");
let event_name = format!("enhanced-cb-{event_name}");
let info = self.info.clone();
let mut config = self.config.clone();
// generate the payload
let payload = profiles.gen_enhanced(event_name.clone())?;
let window = self.window.clone();
win.once(&event_name, move |event| {
if let Some(result) = event.payload() {
let result: PrfEnhancedResult = serde_json::from_str(result).unwrap();
if let Some(data) = result.data {
// all of these can not be revised by script
// 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",
];
for (key, value) in data.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) {
config.insert(Value::String(key_str), value);
}
});
}
log::info!("profile enhanced status {}", result.status);
Self::_activate(info, config, window).unwrap();
}
if let Some(error) = result.error {
log::error!("{error}");
}
}
});
tauri::async_runtime::spawn(async move {
// wait the window setup during resolve app
if delay {
sleep(Duration::from_secs(2)).await;
}
win.emit("script-handler", payload).unwrap();
});
Ok(())
}
/// activate the profile
/// auto activate enhanced profile
pub fn activate(&self, profiles: &Profiles, delay: bool) -> Result<()> {
let gen_map = profiles.gen_activate()?;
let info = self.info.clone();
let mut config = self.config.clone();
for (key, value) in gen_map.into_iter() {
config.insert(key, value);
}
Self::_activate(info, config, self.window.clone())?;
self.activate_enhanced(profiles, delay)
}
} }
impl Default for Clash { impl Default for Clash {
@@ -214,7 +449,7 @@ impl Default for Clash {
impl Drop for Clash { impl Drop for Clash {
fn drop(&mut self) { fn drop(&mut self) {
if let Err(err) = self.drop_sidecar() { if let Err(err) = self.drop_sidecar() {
log::error!("{}", err); log::error!("{err}");
} }
} }
} }

View File

@@ -1,50 +1,60 @@
use super::{Clash, ClashInfo}; use crate::utils::{config, dirs, help, tmpl};
use crate::utils::{config, dirs}; use anyhow::{bail, Context, Result};
use reqwest::header::HeaderMap;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_yaml::{Mapping, Value}; use serde_yaml::{Mapping, Value};
use std::collections::HashMap; use std::{fs, io::Write};
use std::env::temp_dir;
use std::fs::File;
use std::io::Write;
use std::time::{SystemTime, UNIX_EPOCH};
/// Define the `profiles.yaml` schema #[derive(Debug, Clone, Deserialize, Serialize)]
#[derive(Default, Debug, Clone, Deserialize, Serialize)] pub struct PrfItem {
pub struct Profiles { pub uid: Option<String>,
/// current profile's name
pub current: Option<usize>,
/// profile list /// profile item type
pub items: Option<Vec<ProfileItem>>, /// enum value: remote | local | script | merge
} #[serde(rename = "type")]
pub itype: Option<String>,
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct ProfileItem {
/// profile name /// profile name
pub name: Option<String>, pub name: Option<String>,
/// profile description
#[serde(skip_serializing_if = "Option::is_none")]
pub desc: Option<String>,
/// profile file /// profile file
pub file: Option<String>, pub file: Option<String>,
/// current mode
pub mode: Option<String>,
/// source url /// source url
#[serde(skip_serializing_if = "Option::is_none")]
pub url: Option<String>, pub url: Option<String>,
/// selected infomation /// selected infomation
pub selected: Option<Vec<ProfileSelected>>, #[serde(skip_serializing_if = "Option::is_none")]
/// user info pub selected: Option<Vec<PrfSelected>>,
pub extra: Option<ProfileExtra>,
/// subscription user info
#[serde(skip_serializing_if = "Option::is_none")]
pub extra: Option<PrfExtra>,
/// updated time /// updated time
pub updated: Option<usize>, pub updated: Option<usize>,
/// some options of the item
#[serde(skip_serializing_if = "Option::is_none")]
pub option: Option<PrfOption>,
/// the file data
#[serde(skip)]
pub file_data: Option<String>,
} }
#[derive(Default, Debug, Clone, Deserialize, Serialize)] #[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct ProfileSelected { pub struct PrfSelected {
pub name: Option<String>, pub name: Option<String>,
pub now: Option<String>, pub now: Option<String>,
} }
#[derive(Default, Debug, Clone, Copy, Deserialize, Serialize)] #[derive(Default, Debug, Clone, Copy, Deserialize, Serialize)]
pub struct ProfileExtra { pub struct PrfExtra {
pub upload: usize, pub upload: usize,
pub download: usize, pub download: usize,
pub total: usize, pub total: usize,
@@ -52,299 +62,609 @@ pub struct ProfileExtra {
} }
#[derive(Default, Debug, Clone, Deserialize, Serialize)] #[derive(Default, Debug, Clone, Deserialize, Serialize)]
/// the result from url pub struct PrfOption {
pub struct ProfileResponse { /// for `remote` profile's http request
pub name: String, /// see issue #13
pub file: String, #[serde(skip_serializing_if = "Option::is_none")]
pub data: String, pub user_agent: Option<String>,
pub extra: ProfileExtra,
/// for `remote` profile
#[serde(skip_serializing_if = "Option::is_none")]
pub with_proxy: Option<bool>,
} }
static PROFILE_YAML: &str = "profiles.yaml"; impl PrfOption {
static PROFILE_TEMP: &str = "clash-verge-runtime.yaml"; 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 {
fn default() -> Self {
PrfItem {
uid: None,
itype: None,
name: None,
desc: None,
file: None,
url: None,
selected: None,
extra: None,
updated: None,
option: None,
file_data: None,
}
}
}
impl PrfItem {
/// From partial item
/// must contain `itype`
pub async fn from(item: PrfItem, file_data: Option<String>) -> Result<PrfItem> {
if item.itype.is_none() {
bail!("type should not be null");
}
match item.itype.unwrap().as_str() {
"remote" => {
if item.url.is_none() {
bail!("url should not be null");
}
let url = item.url.as_ref().unwrap().as_str();
let name = item.name;
let desc = item.desc;
PrfItem::from_url(url, name, desc, item.option).await
}
"local" => {
let name = item.name.unwrap_or("Local File".into());
let desc = item.desc.unwrap_or("".into());
PrfItem::from_local(name, desc, file_data)
}
"merge" => {
let name = item.name.unwrap_or("Merge".into());
let desc = item.desc.unwrap_or("".into());
PrfItem::from_merge(name, desc)
}
"script" => {
let name = item.name.unwrap_or("Script".into());
let desc = item.desc.unwrap_or("".into());
PrfItem::from_script(name, desc)
}
typ @ _ => bail!("invalid type \"{typ}\""),
}
}
/// ## Local type
/// create a new item from name/desc
pub fn from_local(name: String, desc: String, file_data: Option<String>) -> Result<PrfItem> {
let uid = help::get_uid("l");
let file = format!("{uid}.yaml");
Ok(PrfItem {
uid: Some(uid),
itype: Some("local".into()),
name: Some(name),
desc: Some(desc),
file: Some(file),
url: None,
selected: None,
extra: None,
option: None,
updated: Some(help::get_now()),
file_data: Some(file_data.unwrap_or(tmpl::ITEM_LOCAL.into())),
})
}
/// ## Remote type
/// create a new item from url
pub async fn from_url(
url: &str,
name: Option<String>,
desc: Option<String>,
option: Option<PrfOption>,
) -> Result<PrfItem> {
let with_proxy = match option.as_ref() {
Some(opt) => opt.with_proxy.unwrap_or(false),
None => false,
};
let user_agent = match option.as_ref() {
Some(opt) => opt.user_agent.clone(),
None => None,
};
let mut builder = reqwest::ClientBuilder::new();
if !with_proxy {
builder = builder.no_proxy();
}
if let Some(user_agent) = user_agent {
builder = builder.user_agent(user_agent);
}
let resp = builder.build()?.get(url).send().await?;
let header = resp.headers();
// parse the Subscription Userinfo
let extra = match header.get("Subscription-Userinfo") {
Some(value) => {
let sub_info = value.to_str().unwrap_or("");
Some(PrfExtra {
upload: help::parse_str(sub_info, "upload=").unwrap_or(0),
download: help::parse_str(sub_info, "download=").unwrap_or(0),
total: help::parse_str(sub_info, "total=").unwrap_or(0),
expire: help::parse_str(sub_info, "expire=").unwrap_or(0),
})
}
None => None,
};
let uid = help::get_uid("r");
let file = format!("{uid}.yaml");
let name = name.unwrap_or(uid.clone());
let data = resp.text_with_charset("utf-8").await?;
Ok(PrfItem {
uid: Some(uid),
itype: Some("remote".into()),
name: Some(name),
desc,
file: Some(file),
url: Some(url.into()),
selected: None,
extra,
option,
updated: Some(help::get_now()),
file_data: Some(data),
})
}
/// ## Merge type (enhance)
/// create the enhanced item by using `merge` rule
pub fn from_merge(name: String, desc: String) -> Result<PrfItem> {
let uid = help::get_uid("m");
let file = format!("{uid}.yaml");
Ok(PrfItem {
uid: Some(uid),
itype: Some("merge".into()),
name: Some(name),
desc: Some(desc),
file: Some(file),
url: None,
selected: None,
extra: None,
option: None,
updated: Some(help::get_now()),
file_data: Some(tmpl::ITEM_MERGE.into()),
})
}
/// ## Script type (enhance)
/// create the enhanced item by using javascript(browserjs)
pub fn from_script(name: String, desc: String) -> Result<PrfItem> {
let uid = help::get_uid("s");
let file = format!("{uid}.js"); // js ext
Ok(PrfItem {
uid: Some(uid),
itype: Some("script".into()),
name: Some(name),
desc: Some(desc),
file: Some(file),
url: None,
selected: None,
extra: None,
option: None,
updated: Some(help::get_now()),
file_data: Some(tmpl::ITEM_SCRIPT.into()),
})
}
}
///
/// ## Profiles Config
///
/// Define the `profiles.yaml` schema
///
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct Profiles {
/// same as PrfConfig.current
current: Option<String>,
/// same as PrfConfig.chain
chain: Option<Vec<String>>,
/// profile list
items: Option<Vec<PrfItem>>,
}
macro_rules! patch {
($lv: expr, $rv: expr, $key: tt) => {
if ($rv.$key).is_some() {
$lv.$key = $rv.$key;
}
};
}
impl Profiles { impl Profiles {
/// read the config from the file /// read the config from the file
pub fn read_file() -> Self { pub fn read_file() -> Self {
config::read_yaml::<Profiles>(dirs::app_home_dir().join(PROFILE_YAML)) let mut profiles = config::read_yaml::<Self>(dirs::profiles_path());
if profiles.items.is_none() {
profiles.items = Some(vec![]);
}
profiles.items.as_mut().map(|items| {
for mut item in items.iter_mut() {
if item.uid.is_none() {
item.uid = Some(help::get_uid("d"));
}
}
});
profiles
} }
/// save the config to the file /// save the config to the file
pub fn save_file(&self) -> Result<(), String> { pub fn save_file(&self) -> Result<()> {
config::save_yaml( config::save_yaml(
dirs::app_home_dir().join(PROFILE_YAML), dirs::profiles_path(),
self, self,
Some("# Profiles Config for Clash Verge\n\n"), Some("# Profiles Config for Clash Verge\n\n"),
) )
} }
/// sync the config between file and memory /// sync the config between file and memory
pub fn sync_file(&mut self) -> Result<(), String> { pub fn sync_file(&mut self) -> Result<()> {
let data = config::read_yaml::<Self>(dirs::app_home_dir().join(PROFILE_YAML)); let data = Self::read_file();
if data.current.is_none() { if data.current.is_none() && data.items.is_none() {
Err("failed to read profiles.yaml".into()) bail!("failed to read profiles.yaml");
} else {
self.current = data.current;
self.items = data.items;
Ok(())
} }
self.current = data.current;
self.chain = data.chain;
self.items = data.items;
Ok(())
} }
/// import the new profile from the url /// get the current uid
/// and update the config file pub fn get_current(&self) -> Option<String> {
pub fn import_from_url(&mut self, url: String, result: ProfileResponse) -> Result<(), String> { self.current.clone()
// save the profile file }
let path = dirs::app_home_dir().join("profiles").join(&result.file);
let file_data = result.data.as_bytes();
File::create(path).unwrap().write(file_data).unwrap();
// update `profiles.yaml` /// only change the main to the target id
let data = Profiles::read_file(); pub fn put_current(&mut self, uid: String) -> Result<()> {
let mut items = data.items.unwrap_or(vec![]); if self.items.is_none() {
self.items = Some(vec![]);
}
let now = SystemTime::now() let items = self.items.as_ref().unwrap();
.duration_since(UNIX_EPOCH) let some_uid = Some(uid.clone());
.unwrap()
.as_secs();
items.push(ProfileItem { for each in items.iter() {
name: Some(result.name), if each.uid == some_uid {
file: Some(result.file), self.current = some_uid;
mode: Some(format!("rule")), return self.save_file();
url: Some(url), }
selected: Some(vec![]), }
extra: Some(result.extra),
updated: Some(now as usize), bail!("invalid uid \"{uid}\"");
}
/// just change the `chain`
pub fn put_chain(&mut self, chain: Option<Vec<String>>) {
self.chain = chain;
}
/// find the item by the uid
pub fn get_item(&self, uid: &String) -> Result<&PrfItem> {
if self.items.is_some() {
let items = self.items.as_ref().unwrap();
let some_uid = Some(uid.clone());
for each in items.iter() {
if each.uid == some_uid {
return Ok(each);
}
}
}
bail!("failed to get the item by \"{}\"", uid);
}
/// append new item
/// if the file_data is some
/// then should save the data to file
pub fn append_item(&mut self, mut item: PrfItem) -> Result<()> {
if item.uid.is_none() {
bail!("the uid should not be null");
}
// save the file data
// move the field value after save
if let Some(file_data) = item.file_data.take() {
if item.file.is_none() {
bail!("the file should not be null");
}
let file = item.file.clone().unwrap();
let path = dirs::app_profiles_dir().join(&file);
fs::File::create(path)
.context(format!("failed to create file \"{}\"", file))?
.write(file_data.as_bytes())
.context(format!("failed to write to file \"{}\"", file))?;
}
if self.items.is_none() {
self.items = Some(vec![]);
}
self.items.as_mut().map(|items| items.push(item));
self.save_file()
}
/// update the item's value
pub fn patch_item(&mut self, uid: String, item: PrfItem) -> Result<()> {
let mut items = self.items.take().unwrap_or(vec![]);
for mut each in items.iter_mut() {
if each.uid == Some(uid.clone()) {
patch!(each, item, itype);
patch!(each, item, name);
patch!(each, item, desc);
patch!(each, item, file);
patch!(each, item, url);
patch!(each, item, selected);
patch!(each, item, extra);
patch!(each, item, updated);
patch!(each, item, option);
self.items = Some(items);
return self.save_file();
}
}
self.items = Some(items);
bail!("failed to found the uid \"{uid}\"")
}
/// be used to update the remote item
/// only patch `updated` `extra` `file_data`
pub fn update_item(&mut self, uid: String, mut item: PrfItem) -> Result<()> {
if self.items.is_none() {
self.items = Some(vec![]);
}
// find the item
let _ = self.get_item(&uid)?;
self.items.as_mut().map(|items| {
let some_uid = Some(uid.clone());
for mut each in items.iter_mut() {
if each.uid == some_uid {
each.extra = item.extra;
each.updated = item.updated;
// save the file data
// move the field value after save
if let Some(file_data) = item.file_data.take() {
let file = each.file.take();
let file = file.unwrap_or(item.file.take().unwrap_or(format!("{}.yaml", &uid)));
// the file must exists
each.file = Some(file.clone());
let path = dirs::app_profiles_dir().join(&file);
fs::File::create(path)
.unwrap()
.write(file_data.as_bytes())
.unwrap();
}
break;
}
}
}); });
self.items = Some(items);
if data.current.is_none() {
self.current = Some(0);
}
self.save_file() self.save_file()
} }
/// set the current and save to file /// delete item
pub fn put_current(&mut self, index: usize) -> Result<(), String> { /// if delete the current then return true
let items = self.items.take().unwrap_or(vec![]); pub fn delete_item(&mut self, uid: String) -> Result<bool> {
let current = self.current.as_ref().unwrap_or(&uid);
let current = current.clone();
if index >= items.len() {
return Err("the index out of bound".into());
}
self.items = Some(items);
self.current = Some(index);
self.save_file()
}
/// update the target profile
/// and save to config file
/// only support the url item
pub fn update_item(&mut self, index: usize, result: ProfileResponse) -> Result<(), String> {
let mut items = self.items.take().unwrap_or(vec![]); let mut items = self.items.take().unwrap_or(vec![]);
let mut index = None;
let now = SystemTime::now() // get the index
.duration_since(UNIX_EPOCH) for i in 0..items.len() {
.unwrap() if items[i].uid == Some(uid.clone()) {
.as_secs() as usize; index = Some(i);
break;
// update file }
let file_path = &items[index].file.as_ref().unwrap();
let file_path = dirs::app_home_dir().join("profiles").join(file_path);
let file_data = result.data.as_bytes();
File::create(file_path).unwrap().write(file_data).unwrap();
items[index].name = Some(result.name);
items[index].extra = Some(result.extra);
items[index].updated = Some(now);
self.items = Some(items);
self.save_file()
}
/// patch item
pub fn patch_item(&mut self, index: usize, profile: ProfileItem) -> Result<(), String> {
let mut items = self.items.take().unwrap_or(vec![]);
if index >= items.len() {
return Err("index out of bound".into());
} }
if profile.name.is_some() { if let Some(index) = index {
items[index].name = profile.name; items.remove(index).file.map(|file| {
let path = dirs::app_profiles_dir().join(file);
if path.exists() {
let _ = fs::remove_file(path);
}
});
} }
if profile.file.is_some() {
items[index].file = profile.file; // delete the original uid
} if current == uid {
if profile.mode.is_some() { self.current = match items.len() > 0 {
items[index].mode = profile.mode; true => items[0].uid.clone(),
} false => None,
if profile.url.is_some() { };
items[index].url = profile.url;
}
if profile.selected.is_some() {
items[index].selected = profile.selected;
}
if profile.extra.is_some() {
items[index].extra = profile.extra;
} }
self.items = Some(items); self.items = Some(items);
self.save_file() self.save_file()?;
Ok(current == uid)
} }
/// delete the item /// only generate config mapping
pub fn delete_item(&mut self, index: usize) -> Result<bool, String> { pub fn gen_activate(&self) -> Result<Mapping> {
let mut current = self.current.clone().unwrap_or(0); let config = Mapping::new();
let mut items = self.items.clone().unwrap_or(vec![]);
if index >= items.len() { if self.current.is_none() || self.items.is_none() {
return Err("index out of bound".into()); return Ok(config);
} }
items.remove(index); let current = self.current.clone().unwrap();
let mut should_change = false; for item in self.items.as_ref().unwrap().iter() {
if item.uid == Some(current.clone()) {
let file_path = match item.file.clone() {
Some(file) => dirs::app_profiles_dir().join(file),
None => bail!("failed to get the file field"),
};
if current == index { if !file_path.exists() {
current = 0; bail!("failed to read the file \"{}\"", file_path.display());
should_change = true;
} else if current > index {
current = current - 1;
}
self.current = Some(current);
self.items = Some(items);
match self.save_file() {
Ok(_) => Ok(should_change),
Err(err) => Err(err),
}
}
/// activate current profile
pub fn activate(&self, clash: &Clash) -> Result<(), String> {
let current = self.current.unwrap_or(0);
match self.items.clone() {
Some(items) => {
if current >= items.len() {
return Err("the index out of bound".into());
} }
let profile = items[current].clone(); let mut new_config = Mapping::new();
let clash_config = clash.config.clone(); let def_config = config::read_yaml::<Mapping>(file_path.clone());
let clash_info = clash.info.clone();
tauri::async_runtime::spawn(async move { // Only the following fields are allowed:
let mut count = 5; // retry times // proxies/proxy-providers/proxy-groups/rule-providers/rules
let mut err = String::from(""); let valid_keys = vec![
while count > 0 { "proxies",
match activate_profile(&profile, &clash_config, &clash_info).await { "proxy-providers",
Ok(_) => return, "proxy-groups",
Err(e) => err = e, "rule-providers",
"rules",
];
for (key, value) in def_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();
if valid_keys.contains(&&*key_str) {
new_config.insert(Value::String(key_str), value);
} }
count -= 1; });
} }
log::error!("failed to activate for `{}`", err);
});
Ok(()) return Ok(new_config);
} }
None => Err("empty profiles".into()),
} }
bail!("failed to found the uid \"{current}\"");
} }
}
/// put the profile to clash /// gen the enhanced profiles
pub async fn activate_profile( pub fn gen_enhanced(&self, callback: String) -> Result<PrfEnhanced> {
profile_item: &ProfileItem, let current = self.gen_activate()?;
clash_config: &Mapping,
clash_info: &ClashInfo,
) -> Result<(), String> {
// temp profile's path
let temp_path = temp_dir().join(PROFILE_TEMP);
// generate temp profile let chain = match self.chain.as_ref() {
{ Some(chain) => chain
let file_name = match profile_item.file.clone() { .iter()
Some(file_name) => file_name, .map(|uid| self.get_item(uid))
None => return Err("profile item should have `file` field".into()), .filter(|item| item.is_ok())
.map(|item| item.unwrap())
.map(|item| PrfData::from_item(item))
.filter(|o| o.is_some())
.map(|o| o.unwrap())
.collect::<Vec<PrfData>>(),
None => vec![],
}; };
let file_path = dirs::app_home_dir().join("profiles").join(file_name); Ok(PrfEnhanced {
if !file_path.exists() { current,
return Err(format!( chain,
"profile `{}` not exists", callback,
file_path.as_os_str().to_str().unwrap() })
)); }
} }
// begin to generate the new profile config #[derive(Default, Debug, Clone, Serialize, Deserialize)]
let def_config = config::read_yaml::<Mapping>(file_path.clone()); pub struct PrfEnhanced {
let mut new_config = Mapping::new(); current: Mapping,
// Only the following fields are allowed: chain: Vec<PrfData>,
// proxies/proxy-providers/proxy-groups/rule-providers/rules
let valid_keys = vec![ callback: String,
"proxies", }
"proxy-providers",
"proxy-groups", #[derive(Default, Debug, Clone, Serialize, Deserialize)]
"rule-providers", pub struct PrfEnhancedResult {
"rules", pub data: Option<Mapping>,
];
valid_keys.iter().for_each(|key| { pub status: String,
let key = Value::String(key.to_string());
if def_config.contains_key(&key) { pub error: Option<String>,
let value = def_config[&key].clone(); }
new_config.insert(key, value);
} #[derive(Default, Debug, Clone, Serialize, Deserialize)]
}); pub struct PrfData {
item: PrfItem,
// add some of the clash `config.yaml` config to it
let valid_keys = vec![ #[serde(skip_serializing_if = "Option::is_none")]
"mixed-port", merge: Option<Mapping>,
"log-level",
"allow-lan", #[serde(skip_serializing_if = "Option::is_none")]
"external-controller", script: Option<String>,
"secret", }
"mode",
"ipv6", impl PrfData {
]; pub fn from_item(item: &PrfItem) -> Option<PrfData> {
valid_keys.iter().for_each(|key| { match item.itype.as_ref() {
let key = Value::String(key.to_string()); Some(itype) => {
if clash_config.contains_key(&key) { let file = item.file.clone()?;
let value = clash_config[&key].clone(); let path = dirs::app_profiles_dir().join(file);
new_config.insert(key, value);
} if !path.exists() {
}); return None;
}
config::save_yaml(
temp_path.clone(), match itype.as_str() {
&new_config, "script" => Some(PrfData {
Some("# Clash Verge Temp File"), item: item.clone(),
)? script: Some(fs::read_to_string(path).unwrap_or("".into())),
}; merge: None,
}),
let server = format!("http://{}/configs", clash_info.server.clone().unwrap()); "merge" => Some(PrfData {
item: item.clone(),
let mut headers = HeaderMap::new(); merge: Some(config::read_yaml::<Mapping>(path)),
headers.insert("Content-Type", "application/json".parse().unwrap()); script: None,
}),
if let Some(secret) = clash_info.secret.clone() { _ => None,
headers.insert( }
"Authorization", }
format!("Bearer {}", secret).parse().unwrap(), None => None,
); }
}
let mut data = HashMap::new();
data.insert("path", temp_path.as_os_str().to_str().unwrap());
let client = match reqwest::ClientBuilder::new().no_proxy().build() {
Ok(c) => c,
Err(_) => return Err("failed to create http::put".into()),
};
match client.put(server).headers(headers).json(&data).send().await {
Ok(_) => Ok(()),
Err(err) => Err(format!("request failed `{}`", err.to_string())),
} }
} }

View File

@@ -1,11 +1,20 @@
use crate::utils::{config, dirs, sysopt::SysProxyConfig}; use crate::log_if_err;
use crate::{
core::Clash,
utils::{config, dirs, sysopt::SysProxyConfig},
};
use anyhow::{bail, Result};
use auto_launch::{AutoLaunch, AutoLaunchBuilder}; use auto_launch::{AutoLaunch, AutoLaunchBuilder};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tauri::api::path::resource_dir; use std::sync::Arc;
use tauri::{async_runtime::Mutex, utils::platform::current_exe};
/// ### `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>,
@@ -13,27 +22,37 @@ pub struct VergeConfig {
/// maybe be able to set the alpha /// maybe be able to set the alpha
pub theme_blur: Option<bool>, pub theme_blur: Option<bool>,
/// enable traffic graph default is true
pub traffic_graph: Option<bool>,
/// clash tun mode
pub enable_tun_mode: Option<bool>,
/// can the app auto startup /// can the app auto startup
pub enable_auto_launch: Option<bool>, pub enable_auto_launch: Option<bool>,
/// set system proxy /// set system proxy
pub enable_system_proxy: Option<bool>, pub enable_system_proxy: Option<bool>,
/// enable proxy guard
pub enable_proxy_guard: Option<bool>,
/// set system proxy bypass /// set system proxy bypass
pub system_proxy_bypass: Option<String>, pub system_proxy_bypass: Option<String>,
}
static VERGE_CONFIG: &str = "verge.yaml"; /// proxy guard duration
pub proxy_guard_duration: Option<u64>,
}
impl VergeConfig { impl VergeConfig {
pub fn new() -> Self { pub fn new() -> Self {
config::read_yaml::<VergeConfig>(dirs::app_home_dir().join(VERGE_CONFIG)) config::read_yaml::<VergeConfig>(dirs::verge_path())
} }
/// Save Verge App Config /// Save Verge App Config
pub fn save_file(&self) -> Result<(), String> { pub fn save_file(&self) -> Result<()> {
config::save_yaml( config::save_yaml(
dirs::app_home_dir().join(VERGE_CONFIG), dirs::verge_path(),
self, self,
Some("# The Config for Clash Verge App\n\n"), Some("# The Config for Clash Verge App\n\n"),
) )
@@ -43,13 +62,21 @@ impl VergeConfig {
/// Verge App abilities /// Verge App abilities
#[derive(Debug)] #[derive(Debug)]
pub struct Verge { pub struct Verge {
/// manage the verge config
pub config: VergeConfig, pub config: VergeConfig,
pub old_sysproxy: Option<SysProxyConfig>, /// current system proxy setting
pub cur_sysproxy: Option<SysProxyConfig>, pub cur_sysproxy: Option<SysProxyConfig>,
pub auto_launch: Option<AutoLaunch>, /// record the original system proxy
/// recover it when exit
old_sysproxy: Option<SysProxyConfig>,
/// helps to auto launch the app
auto_launch: Option<AutoLaunch>,
/// record whether the guard async is running or not
guard_state: Arc<Mutex<bool>>,
} }
impl Default for Verge { impl Default for Verge {
@@ -65,6 +92,7 @@ impl Verge {
old_sysproxy: None, old_sysproxy: None,
cur_sysproxy: None, cur_sysproxy: None,
auto_launch: None, auto_launch: None,
guard_state: Arc::new(Mutex::new(false)),
} }
} }
@@ -89,6 +117,9 @@ impl Verge {
self.cur_sysproxy = Some(sysproxy); self.cur_sysproxy = Some(sysproxy);
} }
// launchs the system proxy guard
Verge::guard_proxy(self.guard_state.clone());
} }
/// reset the sysproxy /// reset the sysproxy
@@ -102,45 +133,37 @@ impl Verge {
} }
/// init the auto launch /// init the auto launch
pub fn init_launch(&mut self, package_info: &tauri::PackageInfo) { pub fn init_launch(&mut self) -> Result<()> {
let app_name = "clash-verge"; let app_exe = current_exe().unwrap();
let app_path = get_app_path(app_name); let app_exe = dunce::canonicalize(app_exe).unwrap();
let app_path = resource_dir(package_info).unwrap().join(app_path); let app_name = app_exe.file_stem().unwrap().to_str().unwrap();
let app_path = app_path.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();
self.auto_launch = Some(auto); if let Some(enable) = self.config.enable_auto_launch.as_ref() {
} // fix issue #26
if *enable {
/// sync the startup when run the app auto.enable()?;
pub fn sync_launch(&self) -> Result<(), String> {
let enable = self.config.enable_auto_launch.clone().unwrap_or(false);
if !enable {
return Ok(());
}
if self.auto_launch.is_none() {
return Err("should init the auto launch first".into());
}
let auto_launch = self.auto_launch.clone().unwrap();
let is_enabled = auto_launch.is_enabled().unwrap_or(false);
if !is_enabled {
if let Err(_) = auto_launch.enable() {
return Err("failed to enable auto-launch".into());
} }
} }
self.auto_launch = Some(auto);
Ok(()) Ok(())
} }
/// update the startup /// update the startup
fn update_launch(&mut self, enable: bool) -> Result<(), String> { fn update_launch(&mut self, enable: bool) -> Result<()> {
let conf_enable = self.config.enable_auto_launch.clone().unwrap_or(false); let conf_enable = self.config.enable_auto_launch.clone().unwrap_or(false);
if enable == conf_enable { if enable == conf_enable {
@@ -149,47 +172,31 @@ impl Verge {
let auto_launch = self.auto_launch.clone().unwrap(); let auto_launch = self.auto_launch.clone().unwrap();
let result = if enable { match enable {
auto_launch.enable() true => auto_launch.enable()?,
} else { false => auto_launch.disable()?,
auto_launch.disable()
}; };
match result { Ok(())
Ok(_) => Ok(()),
Err(_) => Err("failed to set system startup info".into()),
}
} }
// fn guard_thread(&mut self) -> Result<(), String> {
// let sysproxy = self.cur_sysproxy.clone();
// use std::{thread, time};
// tauri::async_runtime::spawn(async move {
// if let Some(sysproxy) = sysproxy {
// sysproxy.set_sys();
// }
// let ten_millis = time::Duration::from_millis(10);
// let now = time::Instant::now();
// thread::sleep(ten_millis);
// });
// Ok(())
// }
/// patch verge config /// patch verge config
/// There should be only one update at a time here /// There should be only one update at a time here
/// so call the save_file at the end is savely /// so call the save_file at the end is savely
pub fn patch_config(&mut self, patch: VergeConfig) -> Result<(), String> { 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;
} }
if patch.theme_blur.is_some() { if patch.theme_blur.is_some() {
self.config.theme_blur = patch.theme_blur; self.config.theme_blur = patch.theme_blur;
} }
if patch.traffic_graph.is_some() {
self.config.traffic_graph = patch.traffic_graph;
}
// should update system startup // should update system startup
if patch.enable_auto_launch.is_some() { if patch.enable_auto_launch.is_some() {
@@ -201,34 +208,119 @@ impl Verge {
// should update system proxy // should update system proxy
if patch.enable_system_proxy.is_some() { if patch.enable_system_proxy.is_some() {
let enable = patch.enable_system_proxy.unwrap(); let enable = patch.enable_system_proxy.unwrap();
if let Some(mut sysproxy) = self.cur_sysproxy.take() { if let Some(mut sysproxy) = self.cur_sysproxy.take() {
sysproxy.enable = enable; sysproxy.enable = enable;
if sysproxy.set_sys().is_err() { if sysproxy.set_sys().is_err() {
self.cur_sysproxy = Some(sysproxy);
log::error!("failed to set system proxy"); log::error!("failed to set system proxy");
return Err("failed to set system proxy".into()); bail!("failed to set system proxy");
} }
self.cur_sysproxy = Some(sysproxy); self.cur_sysproxy = Some(sysproxy);
} }
self.config.enable_system_proxy = Some(enable); self.config.enable_system_proxy = Some(enable);
} }
// todo
// should update system proxy too // should update system proxy too
if patch.system_proxy_bypass.is_some() { if patch.system_proxy_bypass.is_some() {
self.config.system_proxy_bypass = patch.system_proxy_bypass; let bypass = patch.system_proxy_bypass.unwrap();
if let Some(mut sysproxy) = self.cur_sysproxy.take() {
if sysproxy.enable {
sysproxy.bypass = bypass.clone();
if sysproxy.set_sys().is_err() {
self.cur_sysproxy = Some(sysproxy);
log::error!("failed to set system proxy");
bail!("failed to set system proxy");
}
}
self.cur_sysproxy = Some(sysproxy);
}
self.config.system_proxy_bypass = Some(bypass);
}
// proxy guard
// only change it
if patch.enable_proxy_guard.is_some() {
self.config.enable_proxy_guard = patch.enable_proxy_guard;
}
if patch.proxy_guard_duration.is_some() {
self.config.proxy_guard_duration = patch.proxy_guard_duration;
}
// relaunch the guard
if patch.enable_system_proxy.is_some() || patch.enable_proxy_guard.is_some() {
Verge::guard_proxy(self.guard_state.clone());
}
// handle the tun mode
if patch.enable_tun_mode.is_some() {
self.config.enable_tun_mode = patch.enable_tun_mode;
} }
self.config.save_file() self.config.save_file()
} }
} }
// Get the target app_path impl Verge {
fn get_app_path(app_name: &str) -> String { /// launch a system proxy guard
#[cfg(target_os = "linux")] /// read config from file directly
let ext = ""; pub fn guard_proxy(guard_state: Arc<Mutex<bool>>) {
#[cfg(target_os = "macos")] use tokio::time::{sleep, Duration};
let ext = ".app";
#[cfg(target_os = "windows")] tauri::async_runtime::spawn(async move {
let ext = ".exe"; // if it is running, exit
String::from(app_name) + ext let mut state = guard_state.lock().await;
if *state {
return;
}
*state = true;
std::mem::drop(state);
// default duration is 10s
let mut wait_secs = 10u64;
loop {
sleep(Duration::from_secs(wait_secs)).await;
log::debug!("guard heartbeat detection");
let verge = Verge::new();
let enable_proxy = verge.config.enable_system_proxy.unwrap_or(false);
let enable_guard = verge.config.enable_proxy_guard.unwrap_or(false);
let guard_duration = verge.config.proxy_guard_duration.unwrap_or(10);
// update duration
wait_secs = guard_duration;
// stop loop
if !enable_guard || !enable_proxy {
break;
}
log::info!("try to guard proxy");
let clash = Clash::new();
match &clash.info.port {
Some(port) => {
let bypass = verge.config.system_proxy_bypass.clone();
let sysproxy = SysProxyConfig::new(true, port.clone(), bypass);
log_if_err!(sysproxy.set_sys());
}
None => log::error!("fail to parse clash port"),
}
}
let mut state = guard_state.lock().await;
*state = false;
});
}
} }

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::{resolve, server},
};
use tauri::{ use tauri::{
api, CustomMenuItem, Manager, SystemTray, SystemTrayEvent, SystemTrayMenu, SystemTrayMenuItem, api, CustomMenuItem, Manager, SystemTray, SystemTrayEvent, SystemTrayMenu, SystemTrayMenuItem,
}; };
@@ -19,18 +22,20 @@ fn main() -> std::io::Result<()> {
return Ok(()); return Ok(());
} }
let 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("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"));
tauri::Builder::default() #[allow(unused_mut)]
let mut builder = tauri::Builder::default()
.manage(states::VergeState::default()) .manage(states::VergeState::default())
.manage(states::ClashState::default()) .manage(states::ClashState::default())
.manage(states::ProfilesState::default()) .manage(states::ProfilesState::default())
.setup(|app| Ok(resolve::resolve_setup(app))) .setup(|app| Ok(resolve::resolve_setup(app)))
.system_tray(SystemTray::new().with_menu(menu)) .system_tray(SystemTray::new().with_menu(tray_menu))
.on_system_tray_event(move |app_handle, event| match event { .on_system_tray_event(move |app_handle, event| match event {
SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() { SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() {
"open_window" => { "open_window" => {
@@ -39,26 +44,47 @@ 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(_) => {
app_handle
.tray_handle()
.get_item(id.as_str())
.set_selected(new_value)
.unwrap();
// update verge config
let window = app_handle.get_window("main").unwrap();
window.emit("verge://refresh-verge-config", "yes").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" => {
api::process::kill_children();
resolve::resolve_reset(app_handle); resolve::resolve_reset(app_handle);
app_handle.exit(0); api::process::kill_children();
std::process::exit(0);
} }
_ => {} _ => {}
}, },
#[cfg(target_os = "windows")]
SystemTrayEvent::LeftClick { .. } => { SystemTrayEvent::LeftClick { .. } => {
let window = app_handle.get_window("main").unwrap(); let window = app_handle.get_window("main").unwrap();
window.unminimize().unwrap(); window.unminimize().unwrap();
@@ -72,6 +98,9 @@ fn main() -> std::io::Result<()> {
cmds::restart_sidecar, cmds::restart_sidecar,
cmds::get_sys_proxy, cmds::get_sys_proxy,
cmds::get_cur_proxy, cmds::get_cur_proxy,
cmds::kill_sidecars,
cmds::open_app_dir,
cmds::open_logs_dir,
// clash // clash
cmds::get_clash_info, cmds::get_clash_info,
cmds::patch_clash_config, cmds::patch_clash_config,
@@ -81,22 +110,44 @@ fn main() -> std::io::Result<()> {
// profile // profile
cmds::view_profile, cmds::view_profile,
cmds::patch_profile, cmds::patch_profile,
cmds::create_profile,
cmds::import_profile, cmds::import_profile,
cmds::update_profile, cmds::update_profile,
cmds::delete_profile, cmds::delete_profile,
cmds::select_profile, cmds::select_profile,
cmds::get_profiles, cmds::get_profiles,
cmds::sync_profiles, cmds::sync_profiles,
]) cmds::enhance_profiles,
cmds::change_profile_chain
]);
#[cfg(target_os = "macos")]
{
use tauri::{Menu, MenuItem, Submenu};
let submenu_file = Submenu::new(
"File",
Menu::new()
.add_native_item(MenuItem::Undo)
.add_native_item(MenuItem::Redo)
.add_native_item(MenuItem::Copy)
.add_native_item(MenuItem::Paste)
.add_native_item(MenuItem::Cut)
.add_native_item(MenuItem::SelectAll),
);
builder = builder.menu(Menu::new().add_submenu(submenu_file));
}
builder
.build(tauri::generate_context!()) .build(tauri::generate_context!())
.expect("error while running tauri application") .expect("error while running tauri application")
.run(|app_handle, e| match e { .run(|app_handle, e| match e {
tauri::Event::CloseRequested { label, api, .. } => { tauri::RunEvent::CloseRequested { label, api, .. } => {
let app_handle = app_handle.clone(); let app_handle = app_handle.clone();
api.prevent_close(); api.prevent_close();
app_handle.get_window(&label).unwrap().hide().unwrap(); app_handle.get_window(&label).unwrap().hide().unwrap();
} }
tauri::Event::ExitRequested { .. } => { tauri::RunEvent::ExitRequested { .. } => {
resolve::resolve_reset(app_handle); resolve::resolve_reset(app_handle);
api::process::kill_children(); api::process::kill_children();
} }

View File

@@ -1,3 +1,4 @@
use anyhow::{Context, Result};
use serde::{de::DeserializeOwned, Serialize}; use serde::{de::DeserializeOwned, Serialize};
use std::{fs, path::PathBuf}; use std::{fs, path::PathBuf};
@@ -7,26 +8,16 @@ pub fn read_yaml<T: DeserializeOwned + Default>(path: PathBuf) -> T {
serde_yaml::from_str::<T>(&yaml_str).unwrap_or(T::default()) serde_yaml::from_str::<T>(&yaml_str).unwrap_or(T::default())
} }
/// - save the data to the file /// save the data to the file
/// - can set `prefix` string to add some comments /// can set `prefix` string to add some comments
pub fn save_yaml<T: Serialize>( pub fn save_yaml<T: Serialize>(path: PathBuf, data: &T, prefix: Option<&str>) -> Result<()> {
path: PathBuf, let data_str = serde_yaml::to_string(data)?;
data: &T,
prefix: Option<&str>,
) -> Result<(), String> {
match serde_yaml::to_string(data) {
Ok(data_str) => {
let yaml_str = match prefix {
Some(prefix) => format!("{}{}", prefix, data_str),
None => data_str,
};
let path_str = path.as_os_str().to_string_lossy().to_string(); let yaml_str = match prefix {
match fs::write(path, yaml_str.as_bytes()) { Some(prefix) => format!("{prefix}{data_str}"),
Ok(_) => Ok(()), None => data_str,
Err(_) => Err(format!("can not save file `{}`", path_str)), };
}
} let path_str = path.as_os_str().to_string_lossy().to_string();
Err(_) => Err("can not convert the data to yaml".into()), fs::write(path, yaml_str.as_bytes()).context(format!("failed to save file \"{path_str}\""))
}
} }

View File

@@ -1,18 +1,57 @@
use std::env::temp_dir;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use tauri::{ use tauri::{
api::path::{home_dir, resource_dir}, api::path::{home_dir, resource_dir},
PackageInfo, Env, PackageInfo,
}; };
#[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";
/// 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() home_dir()
.unwrap() .unwrap()
.join(Path::new(".config")) .join(Path::new(".config"))
.join(Path::new("clash-verge")) .join(Path::new(APP_DIR))
} }
/// get the resources dir /// get the resources dir
pub fn app_resources_dir(package_info: &PackageInfo) -> PathBuf { pub fn app_resources_dir(package_info: &PackageInfo) -> PathBuf {
resource_dir(package_info).unwrap().join("resources") resource_dir(package_info, &Env::default())
.unwrap()
.join("resources")
}
/// profiles dir
pub fn app_profiles_dir() -> PathBuf {
app_home_dir().join("profiles")
}
/// logs dir
pub fn app_logs_dir() -> PathBuf {
app_home_dir().join("logs")
}
pub fn clash_path() -> PathBuf {
app_home_dir().join(CLASH_CONFIG)
}
pub fn verge_path() -> PathBuf {
app_home_dir().join(VERGE_CONFIG)
}
pub fn profiles_path() -> PathBuf {
app_home_dir().join(PROFILE_YAML)
}
pub fn profiles_temp_path() -> PathBuf {
temp_dir().join(PROFILE_TEMP)
} }

View File

@@ -1,105 +0,0 @@
use crate::core::{ProfileExtra, ProfileResponse};
use std::{
str::FromStr,
time::{SystemTime, UNIX_EPOCH},
};
/// parse the string
fn parse_string<T: FromStr>(target: &str, key: &str) -> Option<T> {
match target.find(key) {
Some(idx) => {
let idx = idx + key.len();
let value = &target[idx..];
match match value.split(';').nth(0) {
Some(value) => value.trim().parse(),
None => value.trim().parse(),
} {
Ok(r) => Some(r),
Err(_) => None,
}
}
None => None,
}
}
/// fetch and parse the profile
pub async fn fetch_profile(url: &str, with_proxy: bool) -> Option<ProfileResponse> {
let builder = reqwest::ClientBuilder::new();
let client = match with_proxy {
true => builder.build(),
false => builder.no_proxy().build(),
};
let resp = match client {
Ok(client) => match client.get(url).send().await {
Ok(res) => res,
Err(_) => return None,
},
Err(_) => return None,
};
let header = resp.headers();
// parse the Subscription Userinfo
let extra = {
let sub_info = match header.get("Subscription-Userinfo") {
Some(value) => value.to_str().unwrap_or(""),
None => "",
};
ProfileExtra {
upload: parse_string(sub_info, "upload=").unwrap_or(0),
download: parse_string(sub_info, "download=").unwrap_or(0),
total: parse_string(sub_info, "total=").unwrap_or(0),
expire: parse_string(sub_info, "expire=").unwrap_or(0),
}
};
// parse the `name` and `file`
let (name, file) = {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
let file = format!("{}.yaml", now);
let name = header.get("Content-Disposition").unwrap().to_str().unwrap();
let name = parse_string::<String>(name, "filename=");
match name {
Some(f) => (f, file),
None => (file.clone(), file),
}
};
// get the data
let data = match resp.text_with_charset("utf-8").await {
Ok(d) => d,
Err(_) => return None,
};
Some(ProfileResponse {
file,
name,
data,
extra,
})
}
#[test]
fn test_parse_value() {
let test_1 = "upload=111; download=2222; total=3333; expire=444";
let test_2 = "attachment; filename=Clash.yaml";
assert_eq!(parse_string::<usize>(test_1, "upload=").unwrap(), 111);
assert_eq!(parse_string::<usize>(test_1, "download=").unwrap(), 2222);
assert_eq!(parse_string::<usize>(test_1, "total=").unwrap(), 3333);
assert_eq!(parse_string::<usize>(test_1, "expire=").unwrap(), 444);
assert_eq!(
parse_string::<String>(test_2, "filename=").unwrap(),
format!("Clash.yaml")
);
assert_eq!(parse_string::<usize>(test_1, "aaa="), None);
assert_eq!(parse_string::<usize>(test_1, "upload1="), None);
assert_eq!(parse_string::<usize>(test_1, "expire1="), None);
assert_eq!(parse_string::<usize>(test_2, "attachment="), None);
}

View File

@@ -0,0 +1,94 @@
use nanoid::nanoid;
use std::str::FromStr;
use std::time::{SystemTime, UNIX_EPOCH};
pub fn get_now() -> usize {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs() as _
}
const ALPHABET: [char; 62] = [
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B',
'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
'V', 'W', 'X', 'Y', 'Z',
];
/// generate the uid
pub fn get_uid(prefix: &str) -> String {
let id = nanoid!(11, &ALPHABET);
format!("{prefix}{id}")
}
/// parse the string
/// xxx=123123; => 123123
pub fn parse_str<T: FromStr>(target: &str, key: &str) -> Option<T> {
match target.find(key) {
Some(idx) => {
let idx = idx + key.len();
let value = &target[idx..];
match match value.split(';').nth(0) {
Some(value) => value.trim().parse(),
None => value.trim().parse(),
} {
Ok(r) => Some(r),
Err(_) => None,
}
}
None => None,
}
}
#[macro_export]
macro_rules! log_if_err {
($result: expr) => {
if let Err(err) = $result {
log::error!("{err}");
}
};
}
/// wrap the anyhow error
/// transform the error to String
#[macro_export]
macro_rules! wrap_err {
($stat: expr) => {
match $stat {
Ok(a) => Ok(a),
Err(err) => {
log::error!("{}", err.to_string());
Err(format!("{}", err.to_string()))
}
}
};
}
/// return the string literal error
#[macro_export]
macro_rules! ret_err {
($str: expr) => {
return Err($str.into())
};
}
#[test]
fn test_parse_value() {
let test_1 = "upload=111; download=2222; total=3333; expire=444";
let test_2 = "attachment; filename=Clash.yaml";
assert_eq!(parse_str::<usize>(test_1, "upload=").unwrap(), 111);
assert_eq!(parse_str::<usize>(test_1, "download=").unwrap(), 2222);
assert_eq!(parse_str::<usize>(test_1, "total=").unwrap(), 3333);
assert_eq!(parse_str::<usize>(test_1, "expire=").unwrap(), 444);
assert_eq!(
parse_str::<String>(test_2, "filename=").unwrap(),
format!("Clash.yaml")
);
assert_eq!(parse_str::<usize>(test_1, "aaa="), None);
assert_eq!(parse_str::<usize>(test_1, "upload1="), None);
assert_eq!(parse_str::<usize>(test_1, "expire1="), None);
assert_eq!(parse_str::<usize>(test_2, "attachment="), None);
}

View File

@@ -1,13 +1,11 @@
extern crate serde_yaml; use crate::utils::{dirs, tmpl};
use crate::utils::dirs;
use chrono::Local; use chrono::Local;
use log::LevelFilter; use log::LevelFilter;
use log4rs::append::console::ConsoleAppender; use log4rs::append::console::ConsoleAppender;
use log4rs::append::file::FileAppender; use log4rs::append::file::FileAppender;
use log4rs::config::{Appender, Config, Root}; use log4rs::config::{Appender, Config, Root};
use log4rs::encode::pattern::PatternEncoder; use log4rs::encode::pattern::PatternEncoder;
use std::fs::{self, File}; use std::fs;
use std::io::Write; use std::io::Write;
use std::path::PathBuf; use std::path::PathBuf;
use tauri::PackageInfo; use tauri::PackageInfo;
@@ -33,7 +31,7 @@ fn init_log(log_dir: &PathBuf) {
.build( .build(
Root::builder() Root::builder()
.appenders(["stdout", "file"]) .appenders(["stdout", "file"])
.build(LevelFilter::Debug), .build(LevelFilter::Info),
) )
.unwrap(); .unwrap();
@@ -41,65 +39,62 @@ fn init_log(log_dir: &PathBuf) {
} }
/// Initialize all the files from resources /// Initialize all the files from resources
fn init_config_file(app_dir: &PathBuf, res_dir: &PathBuf) { fn init_config(app_dir: &PathBuf) -> std::io::Result<()> {
// target path // target path
let clash_path = app_dir.join("config.yaml"); let clash_path = app_dir.join("config.yaml");
let verge_path = app_dir.join("verge.yaml"); let verge_path = app_dir.join("verge.yaml");
let profile_path = app_dir.join("profiles.yaml"); let profile_path = app_dir.join("profiles.yaml");
let mmdb_path = app_dir.join("Country.mmdb");
// template path
let clash_tmpl = res_dir.join("config_tmp.yaml");
let verge_tmpl = res_dir.join("verge_tmp.yaml");
let profiles_tmpl = res_dir.join("profiles_tmp.yaml");
let mmdb_tmpl = res_dir.join("Country.mmdb");
if !clash_path.exists() { if !clash_path.exists() {
if clash_tmpl.exists() { fs::File::create(clash_path)?.write(tmpl::CLASH_CONFIG)?;
fs::copy(clash_tmpl, clash_path).unwrap();
} else {
// make sure that the config.yaml not null
let content = b"\
mixed-port: 7890\n\
log-level: info\n\
allow-lan: false\n\
external-controller: 127.0.0.1:9090\n\
secret: \"\"\n";
File::create(clash_path).unwrap().write(content).unwrap();
}
} }
if !verge_path.exists() {
// only copy it fs::File::create(verge_path)?.write(tmpl::VERGE_CONFIG)?;
if !verge_path.exists() && verge_tmpl.exists() {
fs::copy(verge_tmpl, verge_path).unwrap();
} }
if !profile_path.exists() && profiles_tmpl.exists() { if !profile_path.exists() {
fs::copy(profiles_tmpl, profile_path).unwrap(); fs::File::create(profile_path)?.write(tmpl::PROFILES_CONFIG)?;
}
if !mmdb_path.exists() && mmdb_tmpl.exists() {
fs::copy(mmdb_tmpl, mmdb_path).unwrap();
} }
Ok(())
} }
/// initialize app /// initialize app
pub fn init_app(package_info: &PackageInfo) { pub fn init_app(package_info: &PackageInfo) {
// create app dir // create app dir
let app_dir = dirs::app_home_dir(); let app_dir = dirs::app_home_dir();
let log_dir = app_dir.join("logs"); let log_dir = dirs::app_logs_dir();
let profiles_dir = app_dir.join("profiles"); let profiles_dir = dirs::app_profiles_dir();
let res_dir = dirs::app_resources_dir(package_info); let res_dir = dirs::app_resources_dir(package_info);
if !app_dir.exists() { if !app_dir.exists() {
fs::create_dir(&app_dir).unwrap(); fs::create_dir_all(&app_dir).unwrap();
} }
if !log_dir.exists() { if !log_dir.exists() {
fs::create_dir(&log_dir).unwrap(); fs::create_dir_all(&log_dir).unwrap();
} }
if !profiles_dir.exists() { if !profiles_dir.exists() {
fs::create_dir(&profiles_dir).unwrap(); fs::create_dir_all(&profiles_dir).unwrap();
} }
init_log(&log_dir); init_log(&log_dir);
init_config_file(&app_dir, &res_dir); if let Err(err) = init_config(&app_dir) {
log::error!("{err}");
}
// copy the resource file
let mmdb_path = app_dir.join("Country.mmdb");
let mmdb_tmpl = res_dir.join("Country.mmdb");
if !mmdb_path.exists() && mmdb_tmpl.exists() {
fs::copy(mmdb_tmpl, mmdb_path).unwrap();
}
// 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

@@ -1,7 +1,8 @@
pub mod config; pub mod config;
pub mod dirs; pub mod dirs;
pub mod fetch; pub mod help;
pub mod init; pub mod init;
pub mod resolve; pub mod resolve;
pub mod server; pub mod server;
pub mod sysopt; pub mod sysopt;
pub mod tmpl;

View File

@@ -1,23 +1,10 @@
use super::{init, server}; use super::{init, server};
use crate::{core::Profiles, states}; use crate::{core::Profiles, log_if_err, states};
use tauri::{App, AppHandle, Manager}; use tauri::{App, AppHandle, Manager};
use tauri_plugin_shadows::Shadows;
/// handle something when start app /// handle something when start app
pub fn resolve_setup(app: &App) { pub fn resolve_setup(app: &App) {
// set shadow when window decorations resolve_window(app);
let window = app.get_window("main").unwrap();
window.set_shadow(true);
// enable system blur
use tauri_plugin_vibrancy::Vibrancy;
#[cfg(target_os = "windows")]
window.apply_blur();
#[cfg(target_os = "macos")]
{
use tauri_plugin_vibrancy::MacOSVibrancy;
window.apply_vibrancy(MacOSVibrancy::AppearanceBased);
}
// setup a simple http server for singleton // setup a simple http server for singleton
server::embed_server(&app.handle()); server::embed_server(&app.handle());
@@ -34,20 +21,31 @@ pub fn resolve_setup(app: &App) {
let mut verge = verge_state.0.lock().unwrap(); let mut verge = verge_state.0.lock().unwrap();
let mut profiles = profiles_state.0.lock().unwrap(); let mut profiles = profiles_state.0.lock().unwrap();
if let Err(err) = clash.run_sidecar() { log_if_err!(clash.run_sidecar());
log::error!("{}", err);
}
*profiles = Profiles::read_file(); *profiles = Profiles::read_file();
if let Err(err) = profiles.activate(&clash) {
log::error!("{}", err); clash.set_window(app.get_window("main"));
} log_if_err!(clash.activate(&profiles, true));
verge.init_sysproxy(clash.info.port.clone()); verge.init_sysproxy(clash.info.port.clone());
verge.init_launch(app.package_info()); // enable tun mode
if let Err(err) = verge.sync_launch() { if verge.config.enable_tun_mode.clone().unwrap_or(false)
log::error!("{}", err); && verge.cur_sysproxy.is_some()
&& verge.cur_sysproxy.as_ref().unwrap().enable
{
log::info!("enable tun mode");
clash.tun_mode(true).unwrap();
} }
log_if_err!(verge.init_launch());
verge.config.enable_system_proxy.map(|enable| {
log_if_err!(app
.tray_handle()
.get_item("system_proxy")
.set_selected(enable));
});
} }
/// reset system proxy /// reset system proxy
@@ -57,3 +55,34 @@ pub fn resolve_reset(app_handle: &AppHandle) {
verge.reset_sysproxy(); verge.reset_sysproxy();
} }
/// customize the window theme
fn resolve_window(app: &App) {
let window = app.get_window("main").unwrap();
#[cfg(target_os = "windows")]
{
use window_shadows::set_shadow;
use window_vibrancy::apply_blur;
window.set_decorations(false).unwrap();
set_shadow(&window, true).unwrap();
apply_blur(&window, None).unwrap();
}
#[cfg(target_os = "macos")]
{
use tauri::LogicalSize;
use tauri::Size::Logical;
window.set_decorations(true).unwrap();
window
.set_size(Logical(LogicalSize {
width: 800.0,
height: 610.0,
}))
.unwrap();
// use tauri_plugin_vibrancy::MacOSVibrancy;
// #[allow(deprecated)]
// window.apply_vibrancy(MacOSVibrancy::AppearanceBased);
}
}

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

@@ -1,8 +1,10 @@
use anyhow::Result;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::io;
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
static DEFAULT_BYPASS: &str = "localhost;127.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;192.168.*;<local>"; static DEFAULT_BYPASS: &str = "localhost;127.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;192.168.*;<local>";
#[cfg(target_os = "linux")]
static DEFAULT_BYPASS: &str = "localhost,127.0.0.1/8,::1";
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
static DEFAULT_BYPASS: &str = static DEFAULT_BYPASS: &str =
"192.168.0.0/16\n10.0.0.0/8\n172.16.0.0/12\n127.0.0.1\nlocalhost\n*.local\ntimestamp.apple.com\n"; "192.168.0.0/16\n10.0.0.0/8\n172.16.0.0/12\n127.0.0.1\nlocalhost\n*.local\ntimestamp.apple.com\n";
@@ -34,10 +36,12 @@ impl SysProxyConfig {
bypass: bypass.unwrap_or(DEFAULT_BYPASS.into()), bypass: bypass.unwrap_or(DEFAULT_BYPASS.into()),
} }
} }
}
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
impl SysProxyConfig {
/// Get the windows system proxy config /// Get the windows system proxy config
pub fn get_sys() -> io::Result<Self> { pub fn get_sys() -> Result<Self> {
use winreg::enums::*; use winreg::enums::*;
use winreg::RegKey; use winreg::RegKey;
@@ -54,9 +58,30 @@ impl SysProxyConfig {
}) })
} }
#[cfg(target_os = "macos")] /// Set the windows system proxy config
pub fn set_sys(&self) -> Result<()> {
use winreg::enums::*;
use winreg::RegKey;
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
let cur_var = hkcu.open_subkey_with_flags(
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",
KEY_SET_VALUE,
)?;
let enable: u32 = if self.enable { 1u32 } else { 0u32 };
cur_var.set_value("ProxyEnable", &enable)?;
cur_var.set_value("ProxyServer", &self.server)?;
cur_var.set_value("ProxyOverride", &self.bypass)?;
Ok(())
}
}
#[cfg(target_os = "macos")]
impl SysProxyConfig {
/// Get the macos system proxy config /// Get the macos system proxy config
pub fn get_sys() -> io::Result<Self> { pub fn get_sys() -> Result<Self> {
use std::process::Command; use std::process::Command;
let http = macproxy::get_proxy(&["-getwebproxy", MACOS_SERVICE])?; let http = macproxy::get_proxy(&["-getwebproxy", MACOS_SERVICE])?;
@@ -82,63 +107,59 @@ impl SysProxyConfig {
let bypass_output = Command::new("networksetup") let bypass_output = Command::new("networksetup")
.args(["-getproxybypassdomains", MACOS_SERVICE]) .args(["-getproxybypassdomains", MACOS_SERVICE])
.output()?; .output()?;
let bypass = std::str::from_utf8(&bypass_output.stdout).unwrap_or(DEFAULT_BYPASS);
// change the format to xxx,xxx
let bypass = std::str::from_utf8(&bypass_output.stdout)
.unwrap_or(DEFAULT_BYPASS)
.to_string()
.split('\n')
.collect::<Vec<_>>()
.join(",");
Ok(SysProxyConfig { Ok(SysProxyConfig {
enable, enable,
server, server,
bypass: bypass.into(), bypass,
}) })
} }
#[cfg(target_os = "windows")]
/// Set the windows system proxy config
pub fn set_sys(&self) -> io::Result<()> {
use winreg::enums::*;
use winreg::RegKey;
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
let cur_var = hkcu.open_subkey_with_flags(
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",
KEY_SET_VALUE,
)?;
let enable: u32 = if self.enable { 1u32 } else { 0u32 };
cur_var.set_value("ProxyEnable", &enable)?;
cur_var.set_value("ProxyServer", &self.server)?;
cur_var.set_value("ProxyOverride", &self.bypass)
}
#[cfg(target_os = "macos")]
/// Set the macos system proxy config /// Set the macos system proxy config
pub fn set_sys(&self) -> io::Result<()> { pub fn set_sys(&self) -> Result<()> {
use std::process::Command;
let enable = self.enable; let enable = self.enable;
let server = self.server.as_str(); let server = self.server.as_str();
let bypass = self.bypass.clone();
macproxy::set_proxy("-setwebproxy", MACOS_SERVICE, enable, server)?; macproxy::set_proxy("-setwebproxy", MACOS_SERVICE, enable, server)?;
macproxy::set_proxy("-setsecurewebproxy", MACOS_SERVICE, enable, server)?; macproxy::set_proxy("-setsecurewebproxy", MACOS_SERVICE, enable, server)?;
macproxy::set_proxy("-setsocksfirewallproxy", MACOS_SERVICE, enable, server) macproxy::set_proxy("-setsocksfirewallproxy", MACOS_SERVICE, enable, server)?;
let domains = bypass.split(",").collect::<Vec<_>>();
Command::new("networksetup")
.args([["-setproxybypassdomains", MACOS_SERVICE].to_vec(), domains].concat())
.status()?;
Ok(())
} }
} }
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
mod macproxy { mod macproxy {
use super::*; use super::*;
use anyhow::bail;
use std::process::Command; use std::process::Command;
/// use networksetup /// use networksetup
/// get the target proxy config /// get the target proxy config
pub(super) fn get_proxy(args: &[&str; 2]) -> io::Result<(String, String)> { pub(super) fn get_proxy(args: &[&str; 2]) -> Result<(String, String)> {
let output = Command::new("networksetup").args(args).output()?; let output = Command::new("networksetup").args(args).output()?;
match std::str::from_utf8(&output.stdout) {
Ok(stdout) => { let stdout = std::str::from_utf8(&output.stdout)?;
let enable = parse(stdout, "Enabled:"); let enable = parse(stdout, "Enabled:");
let server = parse(stdout, "Server:"); let server = parse(stdout, "Server:");
let port = parse(stdout, "Port:"); let port = parse(stdout, "Port:");
let server = format!("{}:{}", server, port); let server = format!("{server}:{port}");
Ok((enable.into(), server)) Ok((enable.into(), server))
}
Err(_) => Err(io::Error::from_raw_os_error(1)),
}
} }
/// use networksetup /// use networksetup
@@ -148,17 +169,17 @@ mod macproxy {
device: &str, device: &str,
enable: bool, enable: bool,
server: &str, server: &str,
) -> io::Result<()> { ) -> Result<()> {
let mut split = server.split(":"); let mut split = server.split(":");
let domain = split.next(); let host = split.next();
let port = split.next(); let port = split.next();
// can not parse the field // can not parse the field
if domain.is_none() || port.is_none() { if host.is_none() || port.is_none() {
return Err(io::Error::from_raw_os_error(1)); bail!("failed to parse the server into host:port");
} }
let args = vec![target, device, domain.unwrap(), port.unwrap()]; let args = vec![target, device, host.unwrap(), port.unwrap()];
Command::new("networksetup").args(&args).status()?; Command::new("networksetup").args(&args).status()?;
let target_state = String::from(target) + "state"; let target_state = String::from(target) + "state";
@@ -169,7 +190,7 @@ mod macproxy {
} }
/// parse the networksetup output /// parse the networksetup output
pub(super) fn parse<'a>(target: &'a str, key: &'a str) -> &'a str { fn parse<'a>(target: &'a str, key: &'a str) -> &'a str {
match target.find(key) { match target.find(key) {
Some(idx) => { Some(idx) => {
let idx = idx + key.len(); let idx = idx + key.len();
@@ -209,3 +230,137 @@ mod macproxy {
dbg!(sysproxy.set_sys().unwrap()); dbg!(sysproxy.set_sys().unwrap());
} }
} }
///
/// Linux Desktop System Proxy Supports
/// by using `gsettings`
#[cfg(target_os = "linux")]
impl SysProxyConfig {
/// Get the system proxy config [http/https/socks]
pub fn get_sys() -> Result<Self> {
use std::process::Command;
let schema = "org.gnome.system.proxy";
// get enable
let mode = Command::new("gsettings")
.args(["get", schema, "mode"])
.output()?;
let mode = std::str::from_utf8(&mode.stdout)?;
let enable = mode == "manual";
// get bypass
// Todo: parse the ignore-hosts
// ['aaa', 'bbb'] -> aaa,bbb
let ignore = Command::new("gsettings")
.args(["get", schema, "ignore-hosts"])
.output()?;
let ignore = std::str::from_utf8(&ignore.stdout)?;
let bypass = ignore.to_string();
let http = Self::get_proxy("http")?;
let https = Self::get_proxy("https")?;
let socks = Self::get_proxy("socks")?;
let mut server = "".into();
if socks.len() > 0 {
server = socks;
}
if https.len() > 0 {
server = https;
}
if http.len() > 0 {
server = http;
}
Ok(SysProxyConfig {
enable,
server,
bypass,
})
}
/// Get the system proxy config [http/https/socks]
pub fn set_sys(&self) -> Result<()> {
use anyhow::bail;
use std::process::Command;
let enable = self.enable;
let server = self.server.as_str();
let bypass = self.bypass.clone();
let schema = "org.gnome.system.proxy";
if enable {
let mut split = server.split(":");
let host = split.next();
let port = split.next();
if port.is_none() {
bail!("failed to parse the port");
}
let host = format!("'{}'", host.unwrap_or("127.0.0.1"));
let host = host.as_str();
let port = port.unwrap();
let http = format!("{schema}.http");
Command::new("gsettings")
.args(["set", http.as_str(), "host", host])
.status()?;
Command::new("gsettings")
.args(["set", http.as_str(), "port", port])
.status()?;
let https = format!("{schema}.https");
Command::new("gsettings")
.args(["set", https.as_str(), "host", host])
.status()?;
Command::new("gsettings")
.args(["set", https.as_str(), "port", port])
.status()?;
let socks = format!("{schema}.socks");
Command::new("gsettings")
.args(["set", socks.as_str(), "host", host])
.status()?;
Command::new("gsettings")
.args(["set", socks.as_str(), "port", port])
.status()?;
// set bypass
// Todo: parse the ignore-hosts
// aaa,bbb,cccc -> ['aaa', 'bbb', 'ccc']
Command::new("gsettings")
.args(["set", schema, "ignore-hosts", bypass.as_str()]) // todo
.status()?;
}
let mode = if enable { "'manual'" } else { "'none'" };
Command::new("gsettings")
.args(["set", schema, "mode", mode])
.status()?;
Ok(())
}
/// help function
fn get_proxy(typ: &str) -> Result<String> {
use std::process::Command;
let schema = format!("org.gnome.system.proxy.{typ}");
let schema = schema.as_str();
let host = Command::new("gsettings")
.args(["get", schema, "host"])
.output()?;
let host = std::str::from_utf8(&host.stdout)?;
let port = Command::new("gsettings")
.args(["get", schema, "port"])
.output()?;
let port = std::str::from_utf8(&port.stdout)?;
Ok(format!("{host}:{port}"))
}
}

View File

@@ -0,0 +1,70 @@
///! Some config file template
/// template for clash core `config.yaml`
pub const CLASH_CONFIG: &[u8] = br#"# Default Config For Clash Core
mixed-port: 7890
log-level: info
allow-lan: false
external-controller: 127.0.0.1:9090
mode: rule
secret: ""
"#;
/// template for `profiles.yaml`
pub const PROFILES_CONFIG: &[u8] = b"# Profiles Config for Clash Verge
current: ~
items: ~
";
/// template for `verge.yaml`
pub const VERGE_CONFIG: &[u8] = b"# Defaulf Config For Clash Verge
language: en
theme_mode: light
theme_blur: false
traffic_graph: true
enable_self_startup: false
enable_system_proxy: false
enable_proxy_guard: false
proxy_guard_duration: 10
system_proxy_bypass: localhost;127.*;10.*;192.168.*;<local>
";
/// template for new a profile item
pub const ITEM_LOCAL: &str = "# Profile Template for clash verge
proxies:
proxy-groups:
rules:
";
/// enhanced profile
pub const ITEM_MERGE: &str = "# Merge Template for clash verge
# The `Merge` format used to enhance profile
prepend-rules:
prepend-proxies:
prepend-proxy-groups:
append-rules:
append-proxies:
append-proxy-groups:
";
/// enhanced profile
pub const ITEM_SCRIPT: &str = "// Should define the `main` function
// The argument to this function is the clash config
// or the result of the previous handler
// so you should return the config after processing
function main(params) {
return params;
}
";

View File

@@ -1,7 +1,7 @@
{ {
"package": { "package": {
"productName": "clash-verge", "productName": "Clash Verge",
"version": "0.0.13" "version": "0.0.25"
}, },
"build": { "build": {
"distDir": "../dist", "distDir": "../dist",
@@ -27,7 +27,7 @@
], ],
"resources": ["resources"], "resources": ["resources"],
"externalBin": ["sidecar/clash"], "externalBin": ["sidecar/clash"],
"copyright": "© 2021 zzzgydi All Rights Reserved", "copyright": "© 2022 zzzgydi All Rights Reserved",
"category": "DeveloperTool", "category": "DeveloperTool",
"shortDescription": "A Clash GUI based on tauri.", "shortDescription": "A Clash GUI based on tauri.",
"longDescription": "A Clash GUI based on tauri.", "longDescription": "A Clash GUI based on tauri.",
@@ -52,12 +52,22 @@
"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"
}, },
"allowlist": { "allowlist": {
"all": true "shell": {
"all": true
},
"window": {
"all": true
},
"process": {
"all": true
}
}, },
"windows": [ "windows": [
{ {

View File

@@ -4,6 +4,7 @@ body {
"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
sans-serif; sans-serif;
-webkit-font-smoothing: antialiased; -webkit-font-smoothing: antialiased;
user-select: none;
} }
:root { :root {

View File

@@ -20,8 +20,8 @@
position: relative; position: relative;
flex: 0 1 180px; flex: 0 1 180px;
width: 100%; width: 100%;
max-width: 180px; max-width: 168px;
max-height: 180px; max-height: 168px;
margin: 0 auto; margin: 0 auto;
padding: 0 8px; padding: 0 8px;
text-align: center; text-align: center;
@@ -72,10 +72,20 @@
.the-content { .the-content {
position: absolute; position: absolute;
top: 30px; top: 0;
left: 0; left: 0;
right: 2px; right: 2px;
bottom: 10px; bottom: 10px;
} }
} }
} }
.linux,
.windows,
.unknown {
&.layout {
.layout__right .the-content {
top: 30px;
}
}
}

View File

@@ -12,8 +12,8 @@ const BasePage: React.FC<Props> = (props) => {
return ( return (
<div className="base-page" data-windrag> <div className="base-page" data-windrag>
<header data-windrag> <header data-windrag style={{ userSelect: "none" }}>
<Typography variant="h4" component="h1"> <Typography variant="h4" component="h1" data-windrag>
{title} {title}
</Typography> </Typography>

View File

@@ -1,13 +0,0 @@
import { ApiType } from "../services/types";
interface Props {
value: ApiType.ConnectionsItem;
}
const ConnectionItem = (props: Props) => {
const { value } = props;
return <div>{value.metadata.host || value.metadata.destinationIP}</div>;
};
export default ConnectionItem;

View File

@@ -0,0 +1,56 @@
import dayjs from "dayjs";
import { useLockFn } from "ahooks";
import { styled, Box, ListItem, IconButton, ListItemText } from "@mui/material";
import { CloseRounded } from "@mui/icons-material";
import { ApiType } from "../../services/types";
import { deleteConnection } from "../../services/api";
const Tag = styled(Box)(({ 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 {
value: ApiType.ConnectionsItem;
}
const ConnectionItem = (props: Props) => {
const { value } = props;
const onDelete = useLockFn(async () => deleteConnection(value.id));
return (
<ListItem
dense
secondaryAction={
<IconButton edge="end" onClick={onDelete}>
<CloseRounded />
</IconButton>
}
>
<ListItemText
primary={value.metadata.host || value.metadata.destinationIP}
secondary={
<Box>
<Tag sx={{ textTransform: "uppercase", color: "success" }}>
{value.metadata.network}
</Tag>
<Tag>{value.metadata.type}</Tag>
{value.chains.length > 0 && (
<Tag>{value.chains[value.chains.length - 1]}</Tag>
)}
<Tag>{dayjs(value.start).fromNow()}</Tag>
</Box>
}
/>
</ListItem>
);
};
export default ConnectionItem;

View File

@@ -1,15 +1,41 @@
import useSWR from "swr";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { useRecoilValue } from "recoil"; import { useRecoilValue } from "recoil";
import { Box, Typography } from "@mui/material"; import { Box, Typography } from "@mui/material";
import { ArrowDownward, ArrowUpward } from "@mui/icons-material"; import { ArrowDownward, ArrowUpward } from "@mui/icons-material";
import { getInfomation } from "../services/api"; import { listen } from "@tauri-apps/api/event";
import { ApiType } from "../services/types"; import { ApiType } from "../../services/types";
import { atomClashPort } from "../states/setting"; import { getInfomation } from "../../services/api";
import parseTraffic from "../utils/parse-traffic"; import { getVergeConfig } from "../../services/cmds";
import { atomClashPort } from "../../services/states";
import useLogSetup from "./use-log-setup";
import useTrafficGraph from "./use-traffic-graph";
import parseTraffic from "../../utils/parse-traffic";
const Traffic = () => { // setup the traffic
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 });
const { canvasRef, appendData, toggleStyle } = useTrafficGraph();
const [refresh, setRefresh] = useState({});
// whether hide traffic graph
const { data } = useSWR("getVergeConfig", getVergeConfig);
const trafficGraph = data?.traffic_graph ?? true;
// setup log ws during layout
useLogSetup();
useEffect(() => {
// should reconnect the traffic ws
const unlisten = listen("verge://refresh-clash-config", () =>
setRefresh({})
);
return () => {
unlisten.then((fn) => fn());
};
}, []);
useEffect(() => { useEffect(() => {
let ws: WebSocket | null = null; let ws: WebSocket | null = null;
@@ -19,12 +45,14 @@ const Traffic = () => {
ws = new WebSocket(`ws://${server}/traffic?token=${secret}`); ws = new WebSocket(`ws://${server}/traffic?token=${secret}`);
ws.addEventListener("message", (event) => { ws.addEventListener("message", (event) => {
setTraffic(JSON.parse(event.data) as ApiType.TrafficItem); const data = JSON.parse(event.data) as ApiType.TrafficItem;
appendData(data);
setTraffic(data);
}); });
}); });
return () => ws?.close(); return () => ws?.close();
}, [portValue]); }, [portValue, refresh]);
const [up, upUnit] = parseTraffic(traffic.up); const [up, upUnit] = parseTraffic(traffic.up);
const [down, downUnit] = parseTraffic(traffic.down); const [down, downUnit] = parseTraffic(traffic.down);
@@ -44,7 +72,14 @@ const Traffic = () => {
}; };
return ( return (
<Box width="110px"> <Box width="110px" position="relative" onClick={toggleStyle}>
{trafficGraph && (
<canvas
ref={canvasRef}
style={{ width: "100%", height: 60, marginBottom: 6 }}
/>
)}
<Box mb={1.5} display="flex" alignItems="center" whiteSpace="nowrap"> <Box mb={1.5} display="flex" alignItems="center" whiteSpace="nowrap">
<ArrowUpward <ArrowUpward
fontSize="small" fontSize="small"
@@ -66,4 +101,4 @@ const Traffic = () => {
); );
}; };
export default Traffic; export default LayoutTraffic;

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,22 +1,30 @@
import useSWR from "swr"; import useSWR from "swr";
import { useState } from "react"; import snarkdown from "snarkdown";
import { checkUpdate, installUpdate } from "@tauri-apps/api/updater"; import { useMemo } from "react";
import { relaunch } from "@tauri-apps/api/process"; 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 { checkUpdate, installUpdate } from "@tauri-apps/api/updater";
import { killSidecars, restartSidecar } from "../../services/cmds";
import { atomUpdateState } from "../../services/states";
import Notice from "../base/base-notice";
interface Props { interface Props {
open: boolean; open: boolean;
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;
@@ -25,36 +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 () => {
if (updateState) return;
setUpdateState(true);
try { try {
setUploading(true); await killSidecars();
uploadingState = true;
await installUpdate(); await installUpdate();
await relaunch(); await relaunch();
} catch (error) { } catch (err: any) {
console.log(error); await restartSidecar();
window.alert("Failed to upload, please try again."); Notice.error(err?.message || err.toString());
} finally { } finally {
setUploading(true); setUpdateState(false);
uploadingState = true;
} }
}; };
// 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,43 @@
import dayjs from "dayjs";
import { useEffect, useState } from "react";
import { useSetRecoilState } from "recoil";
import { listen } from "@tauri-apps/api/event";
import { ApiType } from "../../services/types";
import { getInfomation } from "../../services/api";
import { atomLogData } from "../../services/states";
const MAX_LOG_NUM = 1000;
// setup the log websocket
export default function useLogSetup() {
const [refresh, setRefresh] = useState({});
const setLogData = useSetRecoilState(atomLogData);
useEffect(() => {
let ws: WebSocket = null!;
const handler = (event: MessageEvent<any>) => {
const data = JSON.parse(event.data) as ApiType.LogItem;
const time = dayjs().format("MM-DD HH:mm:ss");
setLogData((l) => {
if (l.length >= MAX_LOG_NUM) l.shift();
return [...l, { ...data, time }];
});
};
getInfomation().then((info) => {
const { server = "", secret = "" } = info;
ws = new WebSocket(`ws://${server}/logs?token=${secret}`);
ws.addEventListener("message", handler);
});
const unlisten = listen("verge://refresh-clash-config", () =>
setRefresh({})
);
return () => {
ws?.close();
unlisten?.then((fn) => fn());
};
}, [refresh]);
}

View File

@@ -0,0 +1,146 @@
import { useRef } from "react";
const minPoint = 10;
const maxPoint = 36;
const refLineAlpha = 0.5;
const refLineWidth = 2;
const refLineColor = "#ccc";
const upLineAlpha = 0.6;
const upLineWidth = 4;
const upLineColor = "#9c27b0";
const downLineAlpha = 1;
const downLineWidth = 4;
const downLineColor = "#5b5c9d";
/**
* draw the traffic graph
*/
export default function useTrafficGraph() {
type TrafficData = { up: number; down: number };
const listRef = useRef<TrafficData[]>([]);
const styleRef = useRef(true);
const canvasRef = useRef<HTMLCanvasElement>(null!);
const drawGraph = () => {
const canvas = canvasRef.current!;
if (!canvas) return;
const context = canvas.getContext("2d")!;
const width = canvas.width;
const height = canvas.height;
const l1 = height * 0.2;
const l2 = height * 0.6;
const dl = height * 0.4;
context.clearRect(0, 0, width, height);
// Reference lines
context.beginPath();
context.globalAlpha = refLineAlpha;
context.lineWidth = refLineWidth;
context.strokeStyle = refLineColor;
context.moveTo(0, l1);
context.lineTo(width, l1);
context.moveTo(0, l2);
context.lineTo(width, l2);
context.stroke();
context.closePath();
const countY = (value: number) => {
let v = value;
if (v < 1024) v = (v / 1024) * dl;
else if (v < 1048576) v = dl + (v / 1048576) * dl;
else v = 2 * dl + (v / 10485760) * l1;
return height - v;
};
const drawBezier = (list: number[]) => {
const len = list.length;
const size = Math.min(Math.max(len, minPoint), maxPoint);
const axis = width / size;
let lx = 0;
let ly = height;
let llx = 0;
let lly = height;
list.forEach((val, index) => {
const x = (axis * index) | 0;
const y = countY(val);
const s = 0.25;
if (index === 0) context.moveTo(x, y);
else {
let nx = (axis * (index + 1)) | 0;
let ny = index < len - 1 ? countY(list[index + 1]) | 0 : 0;
const ax = (lx + (x - llx) * s) | 0;
const ay = (ly + (y - lly) * s) | 0;
const bx = (x - (nx - lx) * s) | 0;
const by = (y - (ny - ly) * s) | 0;
context.bezierCurveTo(ax, ay, bx, by, x, y);
}
llx = lx;
lly = ly;
lx = x;
ly = y;
});
};
const drawLine = (list: number[]) => {
const len = list.length;
const size = Math.min(Math.max(len, minPoint), maxPoint);
const axis = width / size;
list.forEach((val, index) => {
const x = (axis * index) | 0;
const y = countY(val);
if (index === 0) context.moveTo(x, y);
else context.lineTo(x, y);
});
};
const listUp = listRef.current.map((v) => v.up);
const listDown = listRef.current.map((v) => v.down);
const lineStyle = styleRef.current;
context.beginPath();
context.globalAlpha = upLineAlpha;
context.lineWidth = upLineWidth;
context.strokeStyle = upLineColor;
lineStyle ? drawLine(listUp) : drawBezier(listUp);
context.stroke();
context.closePath();
context.beginPath();
context.globalAlpha = downLineAlpha;
context.lineWidth = downLineWidth;
context.strokeStyle = downLineColor;
lineStyle ? drawLine(listDown) : drawBezier(listDown);
context.stroke();
context.closePath();
};
const appendData = (data: TrafficData) => {
const list = listRef.current;
if (list.length > maxPoint) list.shift();
list.push(data);
drawGraph();
};
const toggleStyle = () => {
styleRef.current = !styleRef.current;
drawGraph();
};
return {
canvasRef,
appendData,
toggleStyle,
};
}

View File

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

View File

@@ -1,241 +0,0 @@
import React, { useRef, useState } from "react";
import dayjs from "dayjs";
import {
alpha,
Box,
styled,
Typography,
LinearProgress,
IconButton,
keyframes,
MenuItem,
Menu,
} from "@mui/material";
import { useSWRConfig } from "swr";
import { RefreshRounded } from "@mui/icons-material";
import { CmdType } from "../services/types";
import { updateProfile, deleteProfile, viewProfile } from "../services/cmds";
import Notice from "./notice";
import parseTraffic from "../utils/parse-traffic";
import relativeTime from "dayjs/plugin/relativeTime";
dayjs.extend(relativeTime);
const Wrapper = styled(Box)(({ theme }) => ({
width: "100%",
display: "block",
cursor: "pointer",
textAlign: "left",
borderRadius: theme.shape.borderRadius,
boxShadow: theme.shadows[2],
padding: "8px 16px",
boxSizing: "border-box",
}));
const round = keyframes`
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
`;
interface Props {
index: number;
selected: boolean;
itemData: CmdType.ProfileItem;
onSelect: (force: boolean) => void;
}
const ProfileItem: React.FC<Props> = (props) => {
const { index, selected, itemData, onSelect } = props;
const { mutate } = useSWRConfig();
const [loading, setLoading] = useState(false);
const [anchorEl, setAnchorEl] = useState<any>(null);
const [position, setPosition] = useState({ left: 0, top: 0 });
const { name = "Profile", extra, updated = 0 } = itemData;
const { upload = 0, download = 0, total = 0 } = extra ?? {};
const from = parseUrl(itemData.url);
const expire = parseExpire(extra?.expire);
const progress = Math.round(((download + upload) * 100) / (total + 0.1));
const fromnow = updated > 0 ? dayjs(updated * 1000).fromNow() : "";
const onView = async () => {
setAnchorEl(null);
try {
await viewProfile(index);
} catch (err: any) {
Notice.error(err.toString());
}
};
const onForceSelect = () => {
setAnchorEl(null);
onSelect(true);
};
const onUpdateWrapper = (withProxy: boolean) => async () => {
setAnchorEl(null);
if (loading) return;
setLoading(true);
try {
await updateProfile(index, withProxy);
mutate("getProfiles");
} catch (err: any) {
Notice.error(err.toString());
} finally {
setLoading(false);
}
};
const deleteRef = useRef(false);
const onDelete = async () => {
setAnchorEl(null);
if (deleteRef.current) return;
deleteRef.current = true;
try {
await deleteProfile(index);
mutate("getProfiles");
} catch (err: any) {
Notice.error(err.toString());
} finally {
deleteRef.current = false;
}
};
const handleContextMenu = (
event: React.MouseEvent<HTMLDivElement, MouseEvent>
) => {
const { clientX, clientY } = event;
setPosition({ top: clientY, left: clientX });
setAnchorEl(event.currentTarget);
event.preventDefault();
};
return (
<>
<Wrapper
sx={({ palette }) => {
const { mode, primary, text, grey } = palette;
const key = `${mode}-${selected}`;
const bgcolor = {
"light-true": alpha(primary.main, 0.15),
"light-false": palette.background.paper,
"dark-true": alpha(primary.main, 0.35),
"dark-false": alpha(grey[700], 0.35),
}[key]!;
const color = {
"light-true": text.secondary,
"light-false": text.secondary,
"dark-true": alpha(text.secondary, 0.6),
"dark-false": alpha(text.secondary, 0.6),
}[key]!;
const h2color = {
"light-true": primary.main,
"light-false": text.primary,
"dark-true": primary.light,
"dark-false": text.primary,
}[key]!;
return { bgcolor, color, "& h2": { color: h2color } };
}}
onClick={() => onSelect(false)}
onContextMenu={handleContextMenu}
>
<Box display="flex" justifyContent="space-between">
<Typography
width="calc(100% - 40px)"
variant="h6"
component="h2"
noWrap
title={name}
>
{name}
</Typography>
<IconButton
sx={{
width: 30,
height: 30,
animation: loading ? `1s linear infinite ${round}` : "none",
}}
color="inherit"
disabled={loading}
onClick={(e) => {
e.stopPropagation();
onUpdateWrapper(false)();
}}
>
<RefreshRounded />
</IconButton>
</Box>
<Box display="flex" justifyContent="space-between" alignItems="center">
<Typography noWrap title={`From: ${from}`}>
{from}
</Typography>
<Typography
noWrap
flex="1 0 auto"
fontSize={14}
textAlign="right"
title="updated time"
>
{fromnow}
</Typography>
</Box>
<Box
sx={{
my: 0.5,
fontSize: 14,
display: "flex",
justifyContent: "space-between",
}}
>
<span title="used / total">
{parseTraffic(upload + download)} / {parseTraffic(total)}
</span>
<span title="expire time">{expire}</span>
</Box>
<LinearProgress
variant="determinate"
value={progress}
color="inherit"
/>
</Wrapper>
<Menu
open={!!anchorEl}
anchorEl={anchorEl}
onClose={() => setAnchorEl(null)}
anchorPosition={position}
anchorReference="anchorPosition"
>
<MenuItem onClick={onForceSelect}>Select</MenuItem>
<MenuItem onClick={onView}>View</MenuItem>
<MenuItem onClick={onUpdateWrapper(false)}>Update</MenuItem>
<MenuItem onClick={onUpdateWrapper(true)}>Update(Proxy)</MenuItem>
<MenuItem onClick={onDelete}>Delete</MenuItem>
</Menu>
</>
);
};
function parseUrl(url?: string) {
if (!url) return "";
const regex = /https?:\/\/(.+?)\//;
const result = url.match(regex);
return result ? result[1] : "local file";
}
function parseExpire(expire?: number) {
if (!expire) return "-";
return dayjs(expire * 1000).format("YYYY-MM-DD");
}
export default ProfileItem;

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

@@ -0,0 +1,137 @@
import { mutate } from "swr";
import { useEffect, useState } from "react";
import { useLockFn, useSetState } from "ahooks";
import {
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
IconButton,
TextField,
} from "@mui/material";
import { Settings } from "@mui/icons-material";
import { CmdType } from "../../services/types";
import { patchProfile } from "../../services/cmds";
import Notice from "../base/base-notice";
interface Props {
open: boolean;
itemData: CmdType.ProfileItem;
onClose: () => void;
}
// edit the profile item
// remote / local file / merge / script
const ProfileEdit = (props: Props) => {
const { open, itemData, onClose } = props;
const [form, setForm] = useSetState({ ...itemData });
const [option, setOption] = useSetState(itemData.option ?? {});
const [showOpt, setShowOpt] = useState(!!itemData.option);
useEffect(() => {
if (itemData) {
setForm({ ...itemData });
setOption(itemData.option ?? {});
setShowOpt(!!itemData.option?.user_agent);
}
}, [itemData]);
const onUpdate = useLockFn(async () => {
try {
const { uid } = itemData;
const { name, desc, url } = form;
const option_ = itemData.type === "remote" ? option : undefined;
if (itemData.type === "remote" && !url) {
throw new Error("Remote URL should not be null");
}
await patchProfile(uid, { uid, name, desc, url, option: option_ });
setShowOpt(false);
mutate("getProfiles");
onClose();
} catch (err: any) {
Notice.error(err?.message || err.toString());
}
});
const textFieldProps = {
fullWidth: true,
size: "small",
margin: "normal",
variant: "outlined",
} as const;
const type =
form.type ||
(form.url ? "remote" : form.file?.endsWith("js") ? "script" : "local");
return (
<Dialog open={open} onClose={onClose}>
<DialogTitle sx={{ pb: 0.5 }}>Edit Profile</DialogTitle>
<DialogContent sx={{ width: 336, pb: 1 }}>
<TextField
{...textFieldProps}
disabled
label="Type"
value={type}
sx={{ input: { textTransform: "capitalize" } }}
/>
<TextField
{...textFieldProps}
autoFocus
label="Name"
value={form.name}
onChange={(e) => setForm({ name: e.target.value })}
/>
<TextField
{...textFieldProps}
label="Descriptions"
value={form.desc}
onChange={(e) => setForm({ desc: e.target.value })}
/>
{type === "remote" && (
<TextField
{...textFieldProps}
label="Subscription Url"
value={form.url}
onChange={(e) => setForm({ url: e.target.value })}
/>
)}
{showOpt && (
<TextField
{...textFieldProps}
label="User Agent"
value={option.user_agent}
onChange={(e) => setOption({ user_agent: e.target.value })}
/>
)}
</DialogContent>
<DialogActions sx={{ px: 2, pb: 2, position: "relative" }}>
{form.type === "remote" && (
<IconButton
size="small"
sx={{ position: "absolute", left: 18 }}
onClick={() => setShowOpt((o) => !o)}
>
<Settings />
</IconButton>
)}
<Button onClick={onClose}>Cancel</Button>
<Button onClick={onUpdate} variant="contained">
Update
</Button>
</DialogActions>
</Dialog>
);
};
export default ProfileEdit;

View File

@@ -0,0 +1,298 @@
import dayjs from "dayjs";
import { useState } from "react";
import { useLockFn } from "ahooks";
import { useSWRConfig } from "swr";
import { useRecoilState } from "recoil";
import { useTranslation } from "react-i18next";
import {
alpha,
Box,
styled,
Typography,
LinearProgress,
IconButton,
keyframes,
MenuItem,
Menu,
} from "@mui/material";
import { RefreshRounded } from "@mui/icons-material";
import { CmdType } from "../../services/types";
import { atomLoadingCache } from "../../services/states";
import { updateProfile, deleteProfile, viewProfile } from "../../services/cmds";
import parseTraffic from "../../utils/parse-traffic";
import ProfileEdit from "./profile-edit";
import Notice from "../base/base-notice";
const Wrapper = styled(Box)(({ theme }) => ({
width: "100%",
display: "block",
cursor: "pointer",
textAlign: "left",
borderRadius: theme.shape.borderRadius,
boxShadow: theme.shadows[2],
padding: "8px 16px",
boxSizing: "border-box",
}));
const round = keyframes`
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
`;
interface Props {
selected: boolean;
itemData: CmdType.ProfileItem;
onSelect: (force: boolean) => void;
}
const ProfileItem = (props: Props) => {
const { selected, itemData, onSelect } = props;
const { t } = useTranslation();
const { mutate } = useSWRConfig();
const [anchorEl, setAnchorEl] = useState<any>(null);
const [position, setPosition] = useState({ left: 0, top: 0 });
const [loadingCache, setLoadingCache] = useRecoilState(atomLoadingCache);
const { name = "Profile", extra, updated = 0 } = itemData;
const { upload = 0, download = 0, total = 0 } = extra ?? {};
const from = parseUrl(itemData.url);
const expire = parseExpire(extra?.expire);
const progress = Math.round(((download + upload) * 100) / (total + 0.1));
const fromnow = updated > 0 ? dayjs(updated * 1000).fromNow() : "";
// local file mode
// remote file mode
// subscription url mode
const hasUrl = !!itemData.url;
const hasExtra = !!extra; // only subscription url has extra info
const loading = loadingCache[itemData.uid] ?? false;
const [editOpen, setEditOpen] = useState(false);
const onEdit = () => {
setAnchorEl(null);
setEditOpen(true);
};
const onView = async () => {
setAnchorEl(null);
try {
await viewProfile(itemData.uid);
} catch (err: any) {
Notice.error(err?.message || err.toString());
}
};
const onForceSelect = () => {
setAnchorEl(null);
onSelect(true);
};
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 () => {
setAnchorEl(null);
try {
await deleteProfile(itemData.uid);
mutate("getProfiles");
} catch (err: any) {
Notice.error(err?.message || err.toString());
}
});
const boxStyle = {
height: 26,
display: "flex",
alignItems: "center",
justifyContent: "space-between",
};
const urlModeMenu = [
{ label: "Select", handler: onForceSelect },
{ label: "Edit", handler: onEdit },
{ label: "File", handler: onView },
{ label: "Update", handler: () => onUpdate(false) },
{ label: "Update(Proxy)", handler: () => onUpdate(true) },
{ label: "Delete", handler: onDelete },
];
const fileModeMenu = [
{ label: "Select", handler: onForceSelect },
{ label: "Edit", handler: onEdit },
{ label: "File", handler: onView },
{ label: "Delete", handler: onDelete },
];
return (
<>
<Wrapper
sx={({ palette }) => {
const { mode, primary, text, grey } = palette;
const key = `${mode}-${selected}`;
const bgcolor = {
"light-true": alpha(primary.main, 0.15),
"light-false": palette.background.paper,
"dark-true": alpha(primary.main, 0.35),
"dark-false": alpha(grey[700], 0.35),
}[key]!;
const color = {
"light-true": text.secondary,
"light-false": text.secondary,
"dark-true": alpha(text.secondary, 0.6),
"dark-false": alpha(text.secondary, 0.6),
}[key]!;
const h2color = {
"light-true": primary.main,
"light-false": text.primary,
"dark-true": primary.light,
"dark-false": text.primary,
}[key]!;
return { bgcolor, color, "& h2": { color: h2color } };
}}
onClick={() => onSelect(false)}
onContextMenu={(event) => {
const { clientX, clientY } = event;
setPosition({ top: clientY, left: clientX });
setAnchorEl(event.currentTarget);
event.preventDefault();
}}
>
<Box display="flex" justifyContent="space-between">
<Typography
width="calc(100% - 40px)"
variant="h6"
component="h2"
noWrap
title={name}
>
{name}
</Typography>
{/* only if has url can it be updated */}
{hasUrl && (
<IconButton
sx={{
width: 26,
height: 26,
animation: loading ? `1s linear infinite ${round}` : "none",
}}
color="inherit"
disabled={loading}
onClick={(e) => {
e.stopPropagation();
onUpdate(false);
}}
>
<RefreshRounded />
</IconButton>
)}
</Box>
{/* the second line show url's info or description */}
{hasUrl ? (
<Box sx={boxStyle}>
<Typography noWrap title={`From: ${from}`}>
{from}
</Typography>
<Typography
noWrap
flex="1 0 auto"
fontSize={14}
textAlign="right"
title="updated time"
>
{fromnow}
</Typography>
</Box>
) : (
<Box sx={boxStyle}>
<Typography noWrap title={itemData.desc}>
{itemData.desc}
</Typography>
</Box>
)}
{/* the third line show extra info or last updated time */}
{hasExtra ? (
<Box sx={{ ...boxStyle, fontSize: 14 }}>
<span title="used / total">
{parseTraffic(upload + download)} / {parseTraffic(total)}
</span>
<span title="expire time">{expire}</span>
</Box>
) : (
<Box sx={{ ...boxStyle, fontSize: 14, justifyContent: "flex-end" }}>
<span title="updated time">{parseExpire(updated)}</span>
</Box>
)}
<LinearProgress
variant="determinate"
value={progress}
color="inherit"
/>
</Wrapper>
<Menu
open={!!anchorEl}
anchorEl={anchorEl}
onClose={() => setAnchorEl(null)}
anchorPosition={position}
anchorReference="anchorPosition"
onContextMenu={(e) => {
setAnchorEl(null);
e.preventDefault();
}}
>
{(hasUrl ? urlModeMenu : fileModeMenu).map((item) => (
<MenuItem
key={item.label}
onClick={item.handler}
sx={{ minWidth: 133 }}
>
{t(item.label)}
</MenuItem>
))}
</Menu>
{editOpen && (
<ProfileEdit
open={editOpen}
itemData={itemData}
onClose={() => setEditOpen(false)}
/>
)}
</>
);
};
function parseUrl(url?: string) {
if (!url) return "";
const regex = /https?:\/\/(.+?)\//;
const result = url.match(regex);
return result ? result[1] : "local file";
}
function parseExpire(expire?: number) {
if (!expire) return "-";
return dayjs(expire * 1000).format("YYYY-MM-DD");
}
export default ProfileItem;

View File

@@ -0,0 +1,245 @@
import dayjs from "dayjs";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import {
alpha,
Box,
Chip,
styled,
Typography,
MenuItem,
Menu,
} from "@mui/material";
import { CmdType } from "../../services/types";
import { viewProfile } from "../../services/cmds";
import ProfileEdit from "./profile-edit";
import Notice from "../base/base-notice";
import enhance from "../../services/enhance";
const Wrapper = styled(Box)(({ theme }) => ({
width: "100%",
display: "block",
cursor: "pointer",
textAlign: "left",
borderRadius: theme.shape.borderRadius,
boxShadow: theme.shadows[2],
padding: "8px 16px",
boxSizing: "border-box",
}));
interface Props {
selected: boolean;
itemData: CmdType.ProfileItem;
onEnable: () => void;
onDisable: () => void;
onMoveTop: () => void;
onMoveEnd: () => void;
onDelete: () => void;
onEnhance: () => void;
}
// profile enhanced item
const ProfileMore = (props: Props) => {
const {
selected,
itemData,
onEnable,
onDisable,
onMoveTop,
onMoveEnd,
onDelete,
onEnhance,
} = props;
const { uid, type } = itemData;
const { t } = useTranslation();
const [anchorEl, setAnchorEl] = useState<any>(null);
const [position, setPosition] = useState({ left: 0, top: 0 });
const [editOpen, setEditOpen] = useState(false);
const [status, setStatus] = useState(enhance.status(uid));
// unlisten when unmount
useEffect(() => enhance.listen(uid, setStatus), [uid]);
// error during enhanced mode
const hasError = selected && status?.status === "error";
const onEdit = () => {
setAnchorEl(null);
setEditOpen(true);
};
const onView = async () => {
setAnchorEl(null);
try {
await viewProfile(itemData.uid);
} catch (err: any) {
Notice.error(err?.message || err.toString());
}
};
const closeWrapper = (fn: () => void) => () => {
setAnchorEl(null);
return fn();
};
const enableMenu = [
{ label: "Disable", handler: closeWrapper(onDisable) },
{ label: "Refresh", handler: closeWrapper(onEnhance) },
{ label: "Edit", handler: onEdit },
{ label: "File", handler: onView },
{ label: "To Top", show: !hasError, handler: closeWrapper(onMoveTop) },
{ label: "To End", show: !hasError, handler: closeWrapper(onMoveEnd) },
{ label: "Delete", handler: closeWrapper(onDelete) },
];
const disableMenu = [
{ label: "Enable", handler: closeWrapper(onEnable) },
{ label: "Edit", handler: onEdit },
{ label: "File", handler: onView },
{ label: "Delete", handler: closeWrapper(onDelete) },
];
const boxStyle = {
height: 26,
display: "flex",
alignItems: "center",
justifyContent: "space-between",
lineHeight: 1,
};
return (
<>
<Wrapper
sx={({ palette }) => {
// todo
// 区分 selected 和 error 和 mode 下各种颜色的排列组合
const { mode, primary, text, grey, error } = palette;
const key = `${mode}-${selected}`;
const bgkey = hasError ? `${mode}-err` : key;
const bgcolor = {
"light-true": alpha(primary.main, 0.15),
"light-false": palette.background.paper,
"dark-true": alpha(primary.main, 0.35),
"dark-false": alpha(grey[700], 0.35),
"light-err": alpha(error.main, 0.12),
"dark-err": alpha(error.main, 0.3),
}[bgkey]!;
const color = {
"light-true": text.secondary,
"light-false": text.secondary,
"dark-true": alpha(text.secondary, 0.6),
"dark-false": alpha(text.secondary, 0.6),
}[key]!;
const h2color = {
"light-true": primary.main,
"light-false": text.primary,
"dark-true": primary.light,
"dark-false": text.primary,
}[key]!;
return { bgcolor, color, "& h2": { color: h2color } };
}}
// onClick={() => onSelect(false)}
onContextMenu={(event) => {
const { clientX, clientY } = event;
setPosition({ top: clientY, left: clientX });
setAnchorEl(event.currentTarget);
event.preventDefault();
}}
>
<Box display="flex" justifyContent="space-between" alignItems="center">
<Typography
width="calc(100% - 52px)"
variant="h6"
component="h2"
noWrap
title={itemData.name}
>
{itemData.name}
</Typography>
<Chip
label={type}
color="primary"
size="small"
variant="outlined"
sx={{ textTransform: "capitalize" }}
/>
</Box>
<Box sx={boxStyle}>
{hasError ? (
<Typography
noWrap
color="error"
sx={{ width: "calc(100% - 75px)" }}
title={status.message}
>
{status.message}
</Typography>
) : (
<Typography
noWrap
title={itemData.desc}
sx={{ width: "calc(100% - 75px)" }}
>
{itemData.desc}
</Typography>
)}
<Typography
component="span"
title="updated time"
style={{ fontSize: 14 }}
>
{parseExpire(itemData.updated)}
</Typography>
</Box>
</Wrapper>
<Menu
open={!!anchorEl}
anchorEl={anchorEl}
onClose={() => setAnchorEl(null)}
anchorPosition={position}
anchorReference="anchorPosition"
onContextMenu={(e) => {
setAnchorEl(null);
e.preventDefault();
}}
>
{(selected ? enableMenu : disableMenu)
.filter((item: any) => item.show !== false)
.map((item) => (
<MenuItem
key={item.label}
onClick={item.handler}
sx={{ minWidth: 133 }}
>
{t(item.label)}
</MenuItem>
))}
</Menu>
{editOpen && (
<ProfileEdit
open={editOpen}
itemData={itemData}
onClose={() => setEditOpen(false)}
/>
)}
</>
);
};
function parseExpire(expire?: number) {
if (!expire) return "-";
return dayjs(expire * 1000).format("YYYY-MM-DD");
}
export default ProfileMore;

View File

@@ -0,0 +1,165 @@
import { useRef, useState } from "react";
import { useSWRConfig } from "swr";
import { useLockFn, useSetState } from "ahooks";
import {
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
FormControl,
IconButton,
InputLabel,
MenuItem,
Select,
TextField,
} from "@mui/material";
import { Settings } from "@mui/icons-material";
import { createProfile } from "../../services/cmds";
import Notice from "../base/base-notice";
import FileInput from "./file-input";
interface Props {
open: boolean;
onClose: () => void;
}
// create a new profile
// remote / local file / merge / script
const ProfileNew = (props: Props) => {
const { open, onClose } = props;
const { mutate } = useSWRConfig();
const [form, setForm] = useSetState({
type: "remote",
name: "",
desc: "",
url: "",
});
const [showOpt, setShowOpt] = useState(false);
// can add more option
const [option, setOption] = useSetState({ user_agent: "" });
// file input
const fileDataRef = useRef<string | null>(null);
const onCreate = useLockFn(async () => {
if (!form.type) {
Notice.error("`Type` should not be null");
return;
}
try {
const name = form.name || `${form.type} file`;
if (form.type === "remote" && !form.url) {
throw new Error("The URL should not be null");
}
const option_ = form.type === "remote" ? option : undefined;
const item = { ...form, name, option: option_ };
const fileData = form.type === "local" ? fileDataRef.current : null;
await createProfile(item, fileData);
setForm({ type: "remote", name: "", desc: "", url: "" });
setOption({ user_agent: "" });
setShowOpt(false);
fileDataRef.current = null;
mutate("getProfiles");
onClose();
} catch (err: any) {
Notice.error(err.message || err.toString());
}
});
const textFieldProps = {
fullWidth: true,
size: "small",
margin: "normal",
variant: "outlined",
} as const;
return (
<Dialog open={open} onClose={onClose}>
<DialogTitle sx={{ pb: 0.5 }}>Create Profile</DialogTitle>
<DialogContent sx={{ width: 336, pb: 1 }}>
<FormControl size="small" fullWidth sx={{ mt: 2, mb: 1 }}>
<InputLabel>Type</InputLabel>
<Select
autoFocus
label="Type"
value={form.type}
onChange={(e) => setForm({ type: e.target.value })}
>
<MenuItem value="remote">Remote</MenuItem>
<MenuItem value="local">Local</MenuItem>
<MenuItem value="script">Script</MenuItem>
<MenuItem value="merge">Merge</MenuItem>
</Select>
</FormControl>
<TextField
{...textFieldProps}
label="Name"
autoComplete="off"
value={form.name}
onChange={(e) => setForm({ name: e.target.value })}
/>
<TextField
{...textFieldProps}
label="Descriptions"
autoComplete="off"
value={form.desc}
onChange={(e) => setForm({ desc: e.target.value })}
/>
{form.type === "remote" && (
<TextField
{...textFieldProps}
label="Subscription Url"
autoComplete="off"
value={form.url}
onChange={(e) => setForm({ url: e.target.value })}
/>
)}
{form.type === "local" && (
<FileInput onChange={(val) => (fileDataRef.current = val)} />
)}
{showOpt && (
<TextField
{...textFieldProps}
label="User Agent"
autoComplete="off"
value={option.user_agent}
onChange={(e) => setOption({ user_agent: e.target.value })}
/>
)}
</DialogContent>
<DialogActions sx={{ px: 2, pb: 2, position: "relative" }}>
{form.type === "remote" && (
<IconButton
size="small"
sx={{ position: "absolute", left: 18 }}
onClick={() => setShowOpt((o) => !o)}
>
<Settings />
</IconButton>
)}
<Button onClick={onClose}>Cancel</Button>
<Button onClick={onCreate} variant="contained">
Create
</Button>
</DialogActions>
</Dialog>
);
};
export default ProfileNew;

View File

@@ -1,136 +0,0 @@
import { useState } from "react";
import { Virtuoso } from "react-virtuoso";
import {
Box,
Collapse,
Divider,
IconButton,
List,
ListItem,
ListItemText,
} from "@mui/material";
import {
SendRounded,
ExpandLessRounded,
ExpandMoreRounded,
MyLocationRounded,
NetworkCheckRounded,
} from "@mui/icons-material";
import { updateProxy } from "../services/api";
import { ApiType } from "../services/types";
import { getProfiles, patchProfile } from "../services/cmds";
import ProxyItem from "./proxy-item";
interface Props {
group: ApiType.ProxyGroupItem;
}
const ProxyGroup = ({ group }: Props) => {
const [open, setOpen] = useState(false);
const [now, setNow] = useState(group.now);
const proxies = group.all ?? [];
const onUpdate = async (name: string) => {
// can not call update
if (group.type !== "Selector") {
// Todo
// error Tips
return;
}
const oldValue = now;
try {
setNow(name);
await updateProxy(group.name, name);
const profiles = await getProfiles().catch(console.error);
if (!profiles) return;
const profile = profiles.items![profiles.current!]!;
if (!profile) return;
if (!profile.selected) profile.selected = [];
const index = profile.selected.findIndex(
(item) => item.name === group.name
);
if (index < 0) {
profile.selected.push({ name: group.name, now: name });
} else {
profile.selected[index] = { name: group.name, now: name };
}
patchProfile(profiles.current!, profile).catch(console.error);
} catch {
setNow(oldValue);
// Todo
// error tips
}
};
return (
<>
<ListItem button onClick={() => setOpen(!open)} dense>
<ListItemText
primary={group.name}
secondary={
<>
<SendRounded color="primary" sx={{ mr: 1, fontSize: 14 }} />
<span>{now}</span>
</>
}
secondaryTypographyProps={{
sx: { display: "flex", alignItems: "center" },
}}
/>
{open ? <ExpandLessRounded /> : <ExpandMoreRounded />}
</ListItem>
<Collapse in={open} timeout="auto" unmountOnExit>
<Box sx={{ pl: 4, pr: 3, my: 0.5 }}>
<IconButton size="small" title="location">
<MyLocationRounded />
</IconButton>
<IconButton size="small" title="check">
<NetworkCheckRounded />
</IconButton>
</Box>
{proxies.length >= 10 ? (
<Virtuoso
style={{ height: "320px", marginBottom: "4px" }}
totalCount={proxies.length}
itemContent={(index) => (
<ProxyItem
proxy={proxies[index]}
selected={proxies[index].name === now}
sx={{ py: 0, pl: 4 }}
onClick={onUpdate}
/>
)}
/>
) : (
<List
component="div"
disablePadding
sx={{ maxHeight: "320px", overflow: "auto", mb: "4px" }}
>
{proxies.map((proxy) => (
<ProxyItem
key={proxy.name}
proxy={proxy}
selected={proxy.name === now}
sx={{ py: 0, pl: 4 }}
onClick={onUpdate}
/>
))}
</List>
)}
<Divider variant="middle" />
</Collapse>
</>
);
};
export default ProxyGroup;

View File

@@ -1,58 +0,0 @@
import { CheckCircleOutlineRounded } from "@mui/icons-material";
import {
alpha,
ListItem,
ListItemButton,
ListItemIcon,
ListItemText,
SxProps,
Theme,
} from "@mui/material";
import { ApiType } from "../services/types";
interface Props {
proxy: ApiType.ProxyItem;
selected: boolean;
sx?: SxProps<Theme>;
onClick?: (name: string) => void;
}
const ProxyItem = (props: Props) => {
const { proxy, selected, sx, onClick } = props;
return (
<ListItem sx={sx}>
<ListItemButton
dense
selected={selected}
onClick={() => onClick?.(proxy.name)}
sx={[
{
borderRadius: 1,
},
({ palette: { mode, primary } }) => {
const bgcolor =
mode === "light"
? alpha(primary.main, 0.15)
: alpha(primary.main, 0.35);
const color = mode === "light" ? primary.main : primary.light;
return {
"&.Mui-selected": { bgcolor },
"&.Mui-selected .MuiListItemText-secondary": { color },
};
},
]}
>
<ListItemText title={proxy.name} secondary={proxy.name} />
<ListItemIcon
sx={{ justifyContent: "flex-end", color: "primary.main" }}
>
{selected && <CheckCircleOutlineRounded sx={{ fontSize: 16 }} />}
</ListItemIcon>
</ListItemButton>
</ListItem>
);
};
export default ProxyItem;

View File

@@ -0,0 +1,150 @@
import { useEffect, useRef, useState } from "react";
import { useSWRConfig } from "swr";
import { useLockFn } from "ahooks";
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 { updateProxy } from "../../services/api";
import delayManager from "../../services/delay";
import useFilterProxy from "./use-filter-proxy";
import ProxyItem from "./proxy-item";
interface Props {
groupName: string;
curProxy?: string;
proxies: ApiType.ProxyItem[];
}
const ProxyGlobal = (props: Props) => {
const { groupName, curProxy, proxies } = props;
const { mutate } = useSWRConfig();
const [now, setNow] = useState(curProxy || "DIRECT");
const [showType, setShowType] = useState(true);
const [showFilter, setShowFilter] = useState(false);
const [filterText, setFilterText] = useState("");
const virtuosoRef = useRef<any>();
const filterProxies = useFilterProxy(proxies, groupName, filterText);
const onChangeProxy = useLockFn(async (name: string) => {
await updateProxy("GLOBAL", name);
mutate("getProxies");
setNow(name);
});
const onLocation = (smooth = true) => {
const index = filterProxies.findIndex((p) => p.name === now);
if (index >= 0) {
virtuosoRef.current?.scrollToIndex?.({
index,
align: "center",
behavior: smooth ? "smooth" : "auto",
});
}
};
const onCheckAll = useLockFn(async () => {
const names = filterProxies.map((p) => p.name);
await delayManager.checkListDelay(
{ names, groupName, skipNum: 8, maxTimeout: 600 },
() => mutate("getProxies")
);
mutate("getProxies");
});
useEffect(() => onLocation(false), [groupName]);
useEffect(() => {
if (!showFilter) setFilterText("");
}, [showFilter]);
useEffect(() => {
if (groupName === "DIRECT") setNow("DIRECT");
if (groupName === "GLOBAL") setNow(curProxy || "DIRECT");
}, [groupName, curProxy]);
return (
<>
<Box
sx={{
px: 3,
my: 0.5,
display: "flex",
alignItems: "center",
button: { mr: 0.5 },
}}
>
<IconButton
size="small"
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
ref={virtuosoRef}
style={{ height: "calc(100% - 40px)" }}
totalCount={filterProxies.length}
itemContent={(index) => (
<ProxyItem
groupName={groupName}
proxy={filterProxies[index]}
selected={filterProxies[index].name === now}
showType={showType}
onClick={onChangeProxy}
sx={{ py: 0, px: 2 }}
/>
)}
/>
</>
);
};
export default ProxyGlobal;

View File

@@ -0,0 +1,246 @@
import useSWR, { useSWRConfig } from "swr";
import { useEffect, useRef, useState } from "react";
import { useLockFn } from "ahooks";
import { Virtuoso } from "react-virtuoso";
import {
Box,
Collapse,
Divider,
IconButton,
List,
ListItem,
ListItemText,
TextField,
} from "@mui/material";
import {
SendRounded,
ExpandLessRounded,
ExpandMoreRounded,
MyLocationRounded,
NetworkCheckRounded,
FilterAltRounded,
FilterAltOffRounded,
VisibilityRounded,
VisibilityOffRounded,
} from "@mui/icons-material";
import { ApiType } from "../../services/types";
import { updateProxy } from "../../services/api";
import { getProfiles, patchProfile } from "../../services/cmds";
import delayManager from "../../services/delay";
import useFilterProxy from "./use-filter-proxy";
import ProxyItem from "./proxy-item";
interface Props {
group: ApiType.ProxyGroupItem;
}
const ProxyGroup = ({ group }: Props) => {
const { mutate } = useSWRConfig();
const [open, setOpen] = useState(false);
const [now, setNow] = useState(group.now);
const [showType, setShowType] = useState(false);
const [showFilter, setShowFilter] = useState(false);
const [filterText, setFilterText] = useState("");
const proxies = group.all ?? [];
const virtuosoRef = useRef<any>();
const filterProxies = useFilterProxy(proxies, group.name, filterText);
const { data: profiles } = useSWR("getProfiles", getProfiles);
const onChangeProxy = useLockFn(async (name: string) => {
// Todo: support another proxy group type
if (group.type !== "Selector") return;
const oldValue = now;
try {
setNow(name);
await updateProxy(group.name, name);
} catch {
setNow(oldValue);
return; // do not update profile
}
try {
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 === group.name
);
if (index < 0) {
profile.selected.push({ name: group.name, now: name });
} else {
profile.selected[index] = { name: group.name, now: name };
}
await patchProfile(profiles!.current!, { selected: profile.selected });
} catch (err) {
console.error(err);
}
});
const onLocation = (smooth = true) => {
const index = filterProxies.findIndex((p) => p.name === now);
if (index >= 0) {
virtuosoRef.current?.scrollToIndex?.({
index,
align: "center",
behavior: smooth ? "smooth" : "auto",
});
}
};
const onCheckAll = useLockFn(async () => {
const names = filterProxies.map((p) => p.name);
const groupName = group.name;
await delayManager.checkListDelay(
{ names, groupName, skipNum: 8, maxTimeout: 600 },
() => mutate("getProxies")
);
mutate("getProxies");
});
useEffect(() => {
if (!showFilter) setFilterText("");
}, [showFilter]);
// auto scroll to current index
useEffect(() => {
if (open) {
setTimeout(() => onLocation(false), 5);
}
}, [open]);
return (
<>
<ListItem button onClick={() => setOpen(!open)} dense>
<ListItemText
primary={group.name}
secondary={
<>
<SendRounded color="primary" sx={{ mr: 1, fontSize: 14 }} />
<span>{now}</span>
</>
}
secondaryTypographyProps={{
sx: { display: "flex", alignItems: "center" },
}}
/>
{open ? <ExpandLessRounded /> : <ExpandMoreRounded />}
</ListItem>
<Collapse in={open} timeout="auto" unmountOnExit>
<Box
sx={{
pl: 4,
pr: 3,
my: 0.5,
display: "flex",
alignItems: "center",
button: { mr: 0.5 },
}}
>
<IconButton
size="small"
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>
{!filterProxies.length && (
<Box
sx={{
py: 3,
fontSize: 18,
textAlign: "center",
color: "text.secondary",
}}
>
Empty
</Box>
)}
{filterProxies.length >= 10 ? (
<Virtuoso
ref={virtuosoRef}
style={{ height: "320px", marginBottom: "4px" }}
totalCount={filterProxies.length}
itemContent={(index) => (
<ProxyItem
groupName={group.name}
proxy={filterProxies[index]}
selected={filterProxies[index].name === now}
showType={showType}
sx={{ py: 0, pl: 4 }}
onClick={onChangeProxy}
/>
)}
/>
) : (
<List
component="div"
disablePadding
sx={{ maxHeight: "320px", overflow: "auto", mb: "4px" }}
>
{filterProxies.map((proxy) => (
<ProxyItem
key={proxy.name}
groupName={group.name}
proxy={proxy}
selected={proxy.name === now}
showType={showType}
sx={{ py: 0, pl: 4 }}
onClick={onChangeProxy}
/>
))}
</List>
)}
<Divider variant="middle" />
</Collapse>
</>
);
};
export default ProxyGroup;

View File

@@ -0,0 +1,142 @@
import { useEffect, useRef, useState } from "react";
import { CheckCircleOutlineRounded } from "@mui/icons-material";
import {
alpha,
Box,
ListItem,
ListItemButton,
ListItemIcon,
ListItemText,
styled,
SxProps,
Theme,
} from "@mui/material";
import { ApiType } from "../../services/types";
import delayManager from "../../services/delay";
interface Props {
groupName: string;
proxy: ApiType.ProxyItem;
selected: boolean;
showType?: boolean;
sx?: SxProps<Theme>;
onClick?: (name: string) => void;
}
const Widget = styled(Box)(() => ({
padding: "4px 6px",
fontSize: 14,
}));
const TypeBox = styled(Box)(({ theme }) => ({
display: "inline-block",
border: "1px solid #ccc",
borderColor: alpha(theme.palette.text.secondary, 0.36),
color: alpha(theme.palette.text.secondary, 0.42),
borderRadius: 4,
fontSize: 10,
marginLeft: 4,
padding: "0 2px",
lineHeight: 1.25,
}));
const ProxyItem = (props: Props) => {
const { groupName, proxy, selected, showType = true, sx, onClick } = props;
const [delay, setDelay] = useState(-1);
useEffect(() => {
if (proxy) {
setDelay(delayManager.getDelay(proxy.name, groupName));
}
}, [proxy]);
const delayRef = useRef(false);
const onDelay = (e: any) => {
e.preventDefault();
e.stopPropagation();
if (delayRef.current) return;
delayRef.current = true;
delayManager
.checkDelay(proxy.name, groupName)
.then((result) => setDelay(result))
.catch(() => setDelay(1e6))
.finally(() => (delayRef.current = false));
};
return (
<ListItem sx={sx}>
<ListItemButton
dense
selected={selected}
onClick={() => onClick?.(proxy.name)}
sx={[
{ borderRadius: 1 },
({ palette: { mode, primary } }) => {
const bgcolor =
mode === "light"
? alpha(primary.main, 0.15)
: alpha(primary.main, 0.35);
const color = mode === "light" ? primary.main : primary.light;
const showDelay = delay > 0;
const showIcon = !showDelay && selected;
return {
".the-check": { display: "none" },
".the-delay": { display: showDelay ? "block" : "none" },
".the-icon": { display: showIcon ? "block" : "none" },
"&:hover .the-check": { display: !showDelay ? "block" : "none" },
"&:hover .the-delay": { display: showDelay ? "block" : "none" },
"&:hover .the-icon": { display: "none" },
"&.Mui-selected": { bgcolor },
"&.Mui-selected .MuiListItemText-secondary": { color },
};
},
]}
>
<ListItemText
title={proxy.name}
secondary={
<>
{proxy.name}
{showType && <TypeBox component="span">{proxy.type}</TypeBox>}
{showType && proxy.udp && <TypeBox component="span">UDP</TypeBox>}
</>
}
/>
<ListItemIcon
sx={{ justifyContent: "flex-end", color: "primary.main" }}
>
<Widget className="the-check" onClick={onDelay}>
Check
</Widget>
<Widget
className="the-delay"
onClick={onDelay}
color={
delay > 500
? "error.main"
: delay < 100
? "success.main"
: "text.secondary"
}
>
{delay > 1e5 ? "Error" : delay > 3000 ? "Timeout" : `${delay}ms`}
</Widget>
<CheckCircleOutlineRounded
className="the-icon"
sx={{ fontSize: 16 }}
/>
</ListItemIcon>
</ListItemButton>
</ListItem>
);
};
export default ProxyItem;

View File

@@ -0,0 +1,49 @@
import { useMemo } from "react";
import { ApiType } from "../../services/types";
import delayManager from "../../services/delay";
const regex1 = /delay([=<>])(\d+|timeout|error)/i;
const regex2 = /type=(.*)/i;
/**
* filter the proxy
* according to the regular conditions
*/
export default function useFilterProxy(
proxies: ApiType.ProxyItem[],
groupName: string,
filterText: string
) {
return useMemo(() => {
if (!filterText) return proxies;
const res1 = regex1.exec(filterText);
if (res1) {
const symbol = res1[1];
const symbol2 = res1[2].toLowerCase();
const value =
symbol2 === "error" ? 1e5 : symbol2 === "timeout" ? 3000 : +symbol2;
return proxies.filter((p) => {
const delay = delayManager.getDelay(p.name, groupName);
if (delay < 0) return false;
if (symbol === "=" && symbol2 === "error") return delay >= 1e5;
if (symbol === "=" && symbol2 === "timeout")
return delay < 1e5 && delay >= 3000;
if (symbol === "=") return delay == value;
if (symbol === "<") return delay <= value;
if (symbol === ">") return delay >= value;
return false;
});
}
const res2 = regex2.exec(filterText);
if (res2) {
const type = res2[1].toLowerCase();
return proxies.filter((p) => p.type.toLowerCase().includes(type));
}
return proxies.filter((p) => p.name.includes(filterText.trim()));
}, [proxies, groupName, filterText]);
}

View File

@@ -5,6 +5,7 @@ interface Props<Value> {
value?: Value; value?: Value;
valueProps?: string; valueProps?: string;
onChangeProps?: string; onChangeProps?: string;
waitTime?: number;
onChange?: (value: Value) => void; onChange?: (value: Value) => void;
onFormat?: (...args: any[]) => Value; onFormat?: (...args: any[]) => Value;
onGuard?: (value: Value, oldValue: Value) => Promise<void>; onGuard?: (value: Value, oldValue: Value) => Promise<void>;
@@ -18,6 +19,7 @@ function GuardState<T>(props: Props<T>) {
children, children,
valueProps = "value", valueProps = "value",
onChangeProps = "onChange", onChangeProps = "onChange",
waitTime = 0, // debounce wait time default 0
onGuard = noop, onGuard = noop,
onCatch = noop, onCatch = noop,
onChange = noop, onChange = noop,
@@ -25,34 +27,61 @@ function GuardState<T>(props: Props<T>) {
} = props; } = props;
const lockRef = useRef(false); const lockRef = useRef(false);
const saveRef = useRef(value);
const lastRef = useRef(0);
const timeRef = useRef<any>();
if (isValidElement(children)) { if (!isValidElement(children)) {
const childProps = { ...children.props }; return children as any;
childProps[valueProps] = value;
childProps[onChangeProps] = async (...args: any[]) => {
// 多次操作无效
if (lockRef.current) return;
lockRef.current = true;
const oldValue = value;
try {
const newValue = (onFormat as any)(...args);
// 先在ui上响应操作
onChange(newValue);
await onGuard(newValue, oldValue!);
} catch (err: any) {
// 状态回退
onChange(oldValue!);
onCatch(err);
}
lockRef.current = false;
};
return cloneElement(children, childProps);
} }
return children as any; const childProps = { ...children.props };
childProps[valueProps] = value;
childProps[onChangeProps] = async (...args: any[]) => {
// 多次操作无效
if (lockRef.current) return;
lockRef.current = true;
try {
const newValue = (onFormat as any)(...args);
// 先在ui上响应操作
onChange(newValue);
const now = Date.now();
// save the old value
if (waitTime <= 0 || now - lastRef.current >= waitTime) {
saveRef.current = value;
}
lastRef.current = now;
if (waitTime <= 0) {
await onGuard(newValue, value!);
} else {
// debounce guard
clearTimeout(timeRef.current);
timeRef.current = setTimeout(async () => {
try {
await onGuard(newValue, saveRef.current!);
} catch (err: any) {
// 状态回退
onChange(saveRef.current!);
onCatch(err);
}
}, waitTime);
}
} catch (err: any) {
// 状态回退
onChange(saveRef.current!);
onCatch(err);
}
lockRef.current = false;
};
return cloneElement(children, childProps);
} }
export default GuardState; export default GuardState;

View File

@@ -1,41 +1,40 @@
import { useEffect, useState } from "react";
import { useDebounceFn } from "ahooks";
import { useSetRecoilState } from "recoil";
import useSWR, { useSWRConfig } from "swr"; import useSWR, { useSWRConfig } from "swr";
import { useSetRecoilState } from "recoil";
import { useTranslation } from "react-i18next";
import { import {
ListItemText, ListItemText,
TextField, TextField,
Switch, Switch,
Select, Select,
MenuItem, MenuItem,
Typography,
} from "@mui/material"; } from "@mui/material";
import { getClashConfig, updateConfigs } from "../../services/api";
import { SettingList, SettingItem } from "./setting";
import { patchClashConfig } from "../../services/cmds";
import { atomClashPort } from "../../states/setting";
import { ApiType } from "../../services/types"; import { ApiType } from "../../services/types";
import { atomClashPort } from "../../services/states";
import { patchClashConfig } from "../../services/cmds";
import { SettingList, SettingItem } from "./setting";
import { getClashConfig, getVersion, updateConfigs } from "../../services/api";
import Notice from "../base/base-notice";
import GuardState from "./guard-state"; import GuardState from "./guard-state";
import Notice from "../notice";
interface Props { interface Props {
onError: (err: Error) => void; onError: (err: Error) => void;
} }
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 { const {
ipv6 = false, ipv6,
"allow-lan": allowLan = false, "allow-lan": allowLan,
"log-level": logLevel = "silent", "log-level": logLevel,
"mixed-port": thePort = 0, "mixed-port": mixedPort,
} = clashConfig ?? {}; } = clashConfig ?? {};
const setPort = useSetRecoilState(atomClashPort); const setGlobalClashPort = useSetRecoilState(atomClashPort);
const [mixedPort, setMixedPort] = useState(thePort);
useEffect(() => setMixedPort(thePort), [thePort]);
const onSwitchFormat = (_e: any, value: boolean) => value; const onSwitchFormat = (_e: any, value: boolean) => value;
const onChangeData = (patch: Partial<ApiType.ConfigData>) => { const onChangeData = (patch: Partial<ApiType.ConfigData>) => {
@@ -46,34 +45,32 @@ const SettingClash = ({ onError }: Props) => {
await patchClashConfig(patch); await patchClashConfig(patch);
}; };
// restart clash when port is changed const onUpdatePort = async (port: number) => {
const { run: onUpdatePort } = useDebounceFn( if (port < 1000) {
async (port: number) => { throw new Error("The port should not < 1000");
(async () => { }
if (port < 1000) { if (port > 65536) {
throw new Error("The port should not < 1000"); throw new Error("The port should not > 65536");
} }
if (port > 65536) { await patchClashConfig({ "mixed-port": port });
throw new Error("The port should not > 65536"); setGlobalClashPort(port);
} Notice.success("Change Clash port successfully!");
await patchClashConfig({ "mixed-port": port });
onChangeData({ "mixed-port": port }); // update the config
setPort(port); mutate("getClashConfig");
Notice.success("Change Clash port successfully!"); };
})().catch((err: any) => {
setMixedPort(thePort); // back to old port value // get clash core version
Notice.error(err.message ?? err.toString()); const clashVer = versionData?.premium
}); ? `${versionData.version} Premium`
}, : versionData?.version || "-";
{ wait: 1000 }
);
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}
@@ -85,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}
@@ -99,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 })}
@@ -118,16 +115,23 @@ 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}
onFormat={(e: any) => +e.target.value?.replace(/\D+/, "")} onFormat={(e: any) => +e.target.value?.replace(/\D+/, "")}
onChange={setMixedPort} onChange={(e) => onChangeData({ "mixed-port": e })}
onGuard={onUpdatePort} onGuard={onUpdatePort}
waitTime={800}
> >
<TextField autoComplete="off" size="small" sx={{ width: 120 }} /> <TextField autoComplete="off" size="small" sx={{ width: 120 }} />
</GuardState> </GuardState>
</SettingItem> </SettingItem>
<SettingItem>
<ListItemText primary={t("Clash core")} />
<Typography sx={{ py: 1 }}>{clashVer}</Typography>
</SettingItem>
</SettingList> </SettingList>
); );
}; };

View File

@@ -1,5 +1,6 @@
import useSWR, { useSWRConfig } from "swr"; import useSWR, { useSWRConfig } from "swr";
import { Box, ListItemText, Switch } from "@mui/material"; import { useTranslation } from "react-i18next";
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";
import { CmdType } from "../../services/types"; import { CmdType } from "../../services/types";
@@ -11,12 +12,16 @@ 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_auto_launch: startup = false, enable_tun_mode,
enable_system_proxy: proxy = false, enable_auto_launch,
enable_system_proxy,
system_proxy_bypass,
enable_proxy_guard,
} = vergeConfig ?? {}; } = vergeConfig ?? {};
const onSwitchFormat = (_e: any, value: boolean) => value; const onSwitchFormat = (_e: any, value: boolean) => value;
@@ -25,11 +30,25 @@ const SettingSystem = ({ onError }: Props) => {
}; };
return ( return (
<SettingList title="System Setting"> <SettingList title={t("System Setting")}>
<SettingItem> <SettingItem>
<ListItemText primary="Auto Launch" /> <ListItemText primary={t("Tun Mode")} />
<GuardState <GuardState
value={startup} value={enable_tun_mode ?? false}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_tun_mode: e })}
onGuard={(e) => patchVergeConfig({ enable_tun_mode: e })}
>
<Switch edge="end" />
</GuardState>
</SettingItem>
<SettingItem>
<ListItemText primary={t("Auto Launch")} />
<GuardState
value={enable_auto_launch ?? false}
valueProps="checked" valueProps="checked"
onCatch={onError} onCatch={onError}
onFormat={onSwitchFormat} onFormat={onSwitchFormat}
@@ -44,22 +63,57 @@ const SettingSystem = ({ onError }: Props) => {
<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={proxy} value={enable_system_proxy ?? false}
valueProps="checked" valueProps="checked"
onCatch={onError} onCatch={onError}
onFormat={onSwitchFormat} onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_system_proxy: e })} onChange={(e) => onChangeData({ enable_system_proxy: e })}
onGuard={(e) => patchVergeConfig({ enable_system_proxy: e })} onGuard={async (e) => {
await patchVergeConfig({ enable_system_proxy: e });
mutate("getVergeConfig"); // update bypass value
}}
> >
<Switch edge="end" /> <Switch edge="end" />
</GuardState> </GuardState>
</SettingItem> </SettingItem>
{enable_system_proxy && (
<SettingItem>
<ListItemText primary={t("Proxy Guard")} />
<GuardState
value={enable_proxy_guard ?? false}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_proxy_guard: e })}
onGuard={(e) => patchVergeConfig({ enable_proxy_guard: e })}
>
<Switch edge="end" />
</GuardState>
</SettingItem>
)}
{enable_system_proxy && (
<SettingItem>
<ListItemText primary={t("Proxy Bypass")} />
<GuardState
value={system_proxy_bypass ?? ""}
onCatch={onError}
onFormat={(e: any) => e.target.value}
onChange={(e) => onChangeData({ system_proxy_bypass: e })}
onGuard={(e) => patchVergeConfig({ system_proxy_bypass: e })}
waitTime={1000}
>
<TextField autoComplete="off" size="small" sx={{ width: 120 }} />
</GuardState>
</SettingItem>
)}
</SettingList> </SettingList>
); );
}; };

View File

@@ -1,22 +1,36 @@
import useSWR, { useSWRConfig } from "swr"; import useSWR, { useSWRConfig } from "swr";
import { ListItemText, Switch, Typography } from "@mui/material"; import { useTranslation } from "react-i18next";
import { getVergeConfig, patchVergeConfig } from "../../services/cmds"; import {
IconButton,
ListItemText,
MenuItem,
Select,
Switch,
Typography,
} from "@mui/material";
import {
getVergeConfig,
openAppDir,
openLogsDir,
patchVergeConfig,
} from "../../services/cmds";
import { ArrowForward } from "@mui/icons-material";
import { SettingList, SettingItem } from "./setting"; import { SettingList, SettingItem } from "./setting";
import { CmdType } from "../../services/types"; import { CmdType } from "../../services/types";
import { version } from "../../../package.json"; import { version } from "../../../package.json";
import GuardState from "./guard-state";
import PaletteSwitch from "./palette-switch"; import PaletteSwitch from "./palette-switch";
import GuardState from "./guard-state";
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: mode = "light", theme_blur: blur = false } = const { theme_mode, theme_blur, traffic_graph, language } = vergeConfig ?? {};
vergeConfig ?? {};
const onSwitchFormat = (_e: any, value: boolean) => value; const onSwitchFormat = (_e: any, value: boolean) => value;
const onChangeData = (patch: Partial<CmdType.VergeConfig>) => { const onChangeData = (patch: Partial<CmdType.VergeConfig>) => {
@@ -24,17 +38,17 @@ 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={mode === "dark"} value={theme_mode === "dark"}
valueProps="checked" valueProps="checked"
onCatch={onError} onCatch={onError}
onFormat={onSwitchFormat} onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ theme_mode: e ? "dark" : "light" })} onChange={(e) => onChangeData({ theme_mode: e ? "dark" : "light" })}
onGuard={(c) => onGuard={(e) =>
patchVergeConfig({ theme_mode: c ? "dark" : "light" }) patchVergeConfig({ theme_mode: e ? "dark" : "light" })
} }
> >
<PaletteSwitch edge="end" /> <PaletteSwitch edge="end" />
@@ -42,9 +56,9 @@ const SettingVerge = ({ onError }: Props) => {
</SettingItem> </SettingItem>
<SettingItem> <SettingItem>
<ListItemText primary="Theme Blur" /> <ListItemText primary={t("Theme Blur")} />
<GuardState <GuardState
value={blur} value={theme_blur ?? false}
valueProps="checked" valueProps="checked"
onCatch={onError} onCatch={onError}
onFormat={onSwitchFormat} onFormat={onSwitchFormat}
@@ -56,7 +70,51 @@ const SettingVerge = ({ onError }: Props) => {
</SettingItem> </SettingItem>
<SettingItem> <SettingItem>
<ListItemText primary="Version" /> <ListItemText primary={t("Traffic Graph")} />
<GuardState
value={traffic_graph ?? true}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ traffic_graph: e })}
onGuard={(e) => patchVergeConfig({ traffic_graph: e })}
>
<Switch edge="end" />
</GuardState>
</SettingItem>
<SettingItem>
<ListItemText primary={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("Open App Dir")} />
<IconButton color="inherit" size="small" onClick={openAppDir}>
<ArrowForward />
</IconButton>
</SettingItem>
<SettingItem>
<ListItemText primary={t("Open Logs Dir")} />
<IconButton color="inherit" size="small" onClick={openLogsDir}>
<ArrowForward />
</IconButton>
</SettingItem>
<SettingItem>
<ListItemText primary={t("Version")} />
<Typography sx={{ py: "6px" }}>v{version}</Typography> <Typography sx={{ py: "6px" }}>v{version}</Typography>
</SettingItem> </SettingItem>
</SettingList> </SettingList>

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

@@ -0,0 +1,54 @@
{
"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": "Edit",
"File": "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",
"System Proxy": "System Proxy",
"Proxy Guard": "Proxy Guard",
"Proxy Bypass": "Proxy Bypass",
"Theme Mode": "Theme Mode",
"Theme Blur": "Theme Blur",
"Traffic Graph": "Traffic Graph",
"Language": "Language",
"Open App Dir": "Open App Dir",
"Open Logs Dir": "Open Logs Dir",
"Version": "Version"
}

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

@@ -0,0 +1,54 @@
{
"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": "编辑信息",
"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": "开机自启",
"System Proxy": "系统代理",
"Proxy Guard": "系统代理守卫",
"Proxy Bypass": "Proxy Bypass",
"Theme Mode": "暗夜模式",
"Theme Blur": "背景模糊",
"Traffic Graph": "流量图显",
"Language": "语言设置",
"Open App Dir": "应用目录",
"Open Logs Dir": "日志目录",
"Version": "版本"
}

View File

@@ -6,6 +6,10 @@ import ReactDOM from "react-dom";
import { RecoilRoot } from "recoil"; 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 "./services/i18n";
enhance.setup();
ReactDOM.render( ReactDOM.render(
<React.StrictMode> <React.StrictMode>

View File

@@ -1,46 +1,58 @@
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, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { Route, Routes } from "react-router-dom"; import { Route, Routes } from "react-router-dom";
import { useRecoilState } from "recoil";
import { alpha, createTheme, List, Paper, ThemeProvider } from "@mui/material"; import { alpha, createTheme, 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 { atomPaletteMode, atomThemeBlur } from "../states/setting";
import { getVergeConfig } from "../services/cmds";
import { getAxios } from "../services/api";
import { routers } from "./_routers"; import { routers } from "./_routers";
import { getAxios } from "../services/api";
import { getVergeConfig } from "../services/cmds";
import LogoSvg from "../assets/image/logo.svg"; import LogoSvg from "../assets/image/logo.svg";
import Traffic from "../components/traffic"; import LayoutItem from "../components/layout/layout-item";
import LayoutItem from "../components/layout-item"; import LayoutControl from "../components/layout/layout-control";
import UpdateButton from "../components/update-button"; import LayoutTraffic from "../components/layout/layout-traffic";
import LayoutControl from "../components/layout-control"; import UpdateButton from "../components/layout/update-button";
import getSystem from "../utils/get-system";
import "dayjs/locale/zh-cn";
dayjs.extend(relativeTime);
const OS = getSystem();
const Layout = () => { const Layout = () => {
const { t } = useTranslation();
const { mutate } = useSWRConfig(); const { mutate } = useSWRConfig();
const [mode, setMode] = useRecoilState(atomPaletteMode); const { data } = useSWR("getVergeConfig", getVergeConfig);
const [blur, setBlur] = useRecoilState(atomThemeBlur);
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig); const blur = !!data?.theme_blur;
const mode = data?.theme_mode ?? "light";
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"));
}, []); }, []);
useEffect(() => { useEffect(() => {
if (!vergeConfig) return; if (data?.language) {
setBlur(!!vergeConfig.theme_blur); dayjs.locale(data.language === "zh" ? "zh-cn" : data.language);
setMode(vergeConfig.theme_mode ?? "light"); i18next.changeLanguage(data.language);
}, [vergeConfig]); }
}, [data?.language]);
const theme = useMemo(() => { const theme = useMemo(() => {
// const background = mode === "light" ? "#f5f5f5" : "#000"; // const background = mode === "light" ? "#f5f5f5" : "#000";
@@ -74,8 +86,12 @@ const Layout = () => {
<Paper <Paper
square square
elevation={0} elevation={0}
className="layout" className={`${OS} layout`}
onPointerDown={onDragging} onPointerDown={onDragging}
onContextMenu={(e) => {
// only prevent it on Windows
if (OS === "windows") e.preventDefault();
}}
sx={[ sx={[
(theme) => ({ (theme) => ({
bgcolor: alpha(theme.palette.background.paper, blur ? 0.85 : 1), bgcolor: alpha(theme.palette.background.paper, blur ? 0.85 : 1),
@@ -92,20 +108,22 @@ 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>
<div className="the-traffic" data-windrag> <div className="the-traffic" data-windrag>
<Traffic /> <LayoutTraffic />
</div> </div>
</div> </div>
<div className="layout__right" data-windrag> <div className="layout__right" data-windrag>
<div className="the-bar"> {OS === "windows" && (
<LayoutControl /> <div className="the-bar">
</div> <LayoutControl />
</div>
)}
<div className="the-content"> <div className="the-content">
<Routes> <Routes>

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,
}, },

View File

@@ -1,13 +1,17 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { Paper } from "@mui/material"; import { useLockFn } from "ahooks";
import { Button, Paper } 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-page"; import BasePage from "../components/base/base-page";
import ConnectionItem from "../components/connection-item"; import ConnectionItem from "../components/connection/connection-item";
const ConnectionsPage = () => { const ConnectionsPage = () => {
const initConn = { uploadTotal: 0, downloadTotal: 0, connections: [] }; const initConn = { uploadTotal: 0, downloadTotal: 0, connections: [] };
const { t } = useTranslation();
const [conn, setConn] = useState<ApiType.Connections>(initConn); const [conn, setConn] = useState<ApiType.Connections>(initConn);
useEffect(() => { useEffect(() => {
@@ -26,10 +30,26 @@ const ConnectionsPage = () => {
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 <Virtuoso
initialTopMostItemIndex={999}
data={conn.connections} data={conn.connections}
itemContent={(index, item) => <ConnectionItem value={item} />} itemContent={(index, item) => <ConnectionItem value={item} />}
/> />

View File

@@ -1,51 +1,27 @@
import dayjs from "dayjs"; import { useRecoilState } from "recoil";
import { useEffect, useState } from "react";
import { Button, Paper } from "@mui/material"; import { Button, Paper } from "@mui/material";
import { Virtuoso } from "react-virtuoso"; import { Virtuoso } from "react-virtuoso";
import { ApiType } from "../services/types"; import { useTranslation } from "react-i18next";
import { getInfomation } from "../services/api"; import { atomLogData } from "../services/states";
import BasePage from "../components/base-page"; import BasePage from "../components/base/base-page";
import LogItem from "../components/log-item"; import LogItem from "../components/log/log-item";
let logCache: ApiType.LogItem[] = [];
const LogPage = () => { const LogPage = () => {
const [logData, setLogData] = useState(logCache); const { t } = useTranslation();
const [logData, setLogData] = useRecoilState(atomLogData);
useEffect(() => {
let ws: WebSocket | null = null;
getInfomation().then((result) => {
const { server = "", secret = "" } = result;
ws = new WebSocket(`ws://${server}/logs?token=${secret}`);
ws.addEventListener("message", (event) => {
const data = JSON.parse(event.data) as ApiType.LogItem;
const time = dayjs().format("MM-DD HH:mm:ss");
setLogData((l) => (logCache = [...l, { ...data, time }]));
});
});
return () => ws?.close();
}, []);
const onClear = () => {
setLogData([]);
logCache = [];
};
return ( return (
<BasePage <BasePage
title="Logs" title={t("Logs")}
contentStyle={{ height: "100%" }} contentStyle={{ height: "100%" }}
header={ header={
<Button <Button
size="small" size="small"
sx={{ mt: 1 }} sx={{ mt: 1 }}
variant="contained" variant="contained"
onClick={onClear} onClick={() => setLogData([])}
> >
Clear {t("Clear")}
</Button> </Button>
} }
> >

View File

@@ -1,31 +1,58 @@
import useSWR, { useSWRConfig } from "swr"; import useSWR, { useSWRConfig } from "swr";
import { useEffect, useRef, useState } from "react"; import { useLockFn } from "ahooks";
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,
selectProfile,
patchProfile, patchProfile,
deleteProfile,
selectProfile,
importProfile, importProfile,
enhanceProfiles,
changeProfileChain,
} from "../services/cmds"; } from "../services/cmds";
import { getProxies, updateProxy } from "../services/api"; import { getProxies, updateProxy } from "../services/api";
import noop from "../utils/noop"; import Notice from "../components/base/base-notice";
import Notice from "../components/notice"; import BasePage from "../components/base/base-page";
import BasePage from "../components/base-page"; import ProfileNew from "../components/profile/profile-new";
import ProfileItem from "../components/profile-item"; import ProfileItem from "../components/profile/profile-item";
import ProfileMore from "../components/profile/profile-more";
const ProfilePage = () => { const ProfilePage = () => {
const { t } = useTranslation();
const { mutate } = useSWRConfig();
const [url, setUrl] = useState(""); const [url, setUrl] = useState("");
const [disabled, setDisabled] = useState(false); const [disabled, setDisabled] = useState(false);
const [dialogOpen, setDialogOpen] = useState(false);
const { mutate } = useSWRConfig();
const { data: profiles = {} } = useSWR("getProfiles", getProfiles); const { data: profiles = {} } = useSWR("getProfiles", getProfiles);
const { regularItems, enhanceItems } = useMemo(() => {
const items = profiles.items || [];
const chain = profiles.chain || [];
const type1 = ["local", "remote"];
const type2 = ["merge", "script"];
const regularItems = items.filter((i) => type1.includes(i.type!));
const restItems = items.filter((i) => type2.includes(i.type!));
const restMap = Object.fromEntries(restItems.map((i) => [i.uid, i]));
const enhanceItems = chain
.map((i) => restMap[i]!)
.concat(restItems.filter((i) => !chain.includes(i.uid)));
return { regularItems, enhanceItems };
}, [profiles]);
useEffect(() => { useEffect(() => {
if (profiles.current == null) return; if (profiles.current == null) return;
if (!profiles.items) profiles.items = [];
const current = profiles.current; const current = profiles.current;
const profile = profiles.items![current]; const profile = regularItems.find((p) => p.uid === current);
if (!profile) return; if (!profile) return;
setTimeout(async () => { setTimeout(async () => {
@@ -56,11 +83,14 @@ const ProfilePage = () => {
name, name,
now, now,
})); }));
patchProfile(current!, profile).catch(console.error);
patchProfile(current!, { selected: profile.selected }).catch(
console.error
);
// update proxies cache // update proxies cache
if (hasChange) mutate("getProxies", getProxies()); if (hasChange) mutate("getProxies", getProxies());
}, 100); }, 100);
}, [profiles]); }, [profiles, regularItems]);
const onImport = async () => { const onImport = async () => {
if (!url) return; if (!url) return;
@@ -69,9 +99,17 @@ const ProfilePage = () => {
try { try {
await importProfile(url); await importProfile(url);
mutate("getProfiles", getProfiles());
if (!profiles.items?.length) selectProfile(0).catch(noop);
Notice.success("Successfully import profile."); Notice.success("Successfully import profile.");
getProfiles().then((newProfiles) => {
mutate("getProfiles", newProfiles);
if (!newProfiles.current && newProfiles.items?.length) {
const current = newProfiles.items[0].uid;
selectProfile(current);
mutate("getProfiles", { ...newProfiles, current }, true);
}
});
} catch { } catch {
Notice.error("Failed to import profile."); Notice.error("Failed to import profile.");
} finally { } finally {
@@ -79,55 +117,121 @@ const ProfilePage = () => {
} }
}; };
const lockRef = useRef(false); const onSelect = useLockFn(async (uid: string, force: boolean) => {
const onSelect = async (index: number, force: boolean) => { if (!force && uid === profiles.current) return;
if (lockRef.current) return;
if (!force && index === profiles.current) return;
lockRef.current = true;
try { try {
await selectProfile(index); await selectProfile(uid);
mutate("getProfiles", { ...profiles, current: index }, true); mutate("getProfiles", { ...profiles, current: uid }, true);
} catch (err: any) { } catch (err: any) {
err && Notice.error(err.toString()); Notice.error(err?.message || err.toString());
} finally {
lockRef.current = false;
} }
}; });
/** 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: 3 }}> <Box sx={{ display: "flex", mb: 2.5 }}>
<TextField <TextField
id="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}
onChange={(e) => setUrl(e.target.value)} onChange={(e) => setUrl(e.target.value)}
sx={{ mr: 2 }} sx={{ mr: 1 }}
/> />
<Button <Button
disabled={!url || disabled} disabled={!url || disabled}
variant="contained" variant="contained"
onClick={onImport} onClick={onImport}
sx={{ mr: 1 }}
> >
Import {t("Import")}
</Button>
<Button variant="contained" onClick={() => setDialogOpen(true)}>
{t("New")}
</Button> </Button>
</Box> </Box>
<Grid container spacing={3}> <Grid container spacing={2}>
{profiles?.items?.map((item, idx) => ( {regularItems.map((item) => (
<Grid item xs={12} sm={6} key={item.file}> <Grid item xs={12} sm={6} key={item.file}>
<ProfileItem <ProfileItem
index={idx} selected={profiles.current === item.uid}
selected={profiles.current === idx}
itemData={item} itemData={item}
onSelect={(f) => onSelect(idx, f)} onSelect={(f) => onSelect(item.uid, f)}
/> />
</Grid> </Grid>
))} ))}
</Grid> </Grid>
<Grid container spacing={2} sx={{ mt: 3 }}>
{enhanceItems.map((item) => (
<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)} />
</BasePage> </BasePage>
); );
}; };

View File

@@ -1,90 +1,53 @@
import useSWR, { useSWRConfig } from "swr"; import useSWR, { useSWRConfig } from "swr";
import { useEffect, useMemo, useRef, useState } from "react"; import { useEffect } from "react";
import { Virtuoso } from "react-virtuoso"; 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, updateProxy } from "../services/api"; import { getClashConfig, updateConfigs } from "../services/api";
import { patchClashConfig } from "../services/cmds"; import { patchClashConfig } from "../services/cmds";
import { getProxies } from "../services/api"; import { getProxies } from "../services/api";
import BasePage from "../components/base-page"; import BasePage from "../components/base/base-page";
import ProxyItem from "../components/proxy-item"; import ProxyGroup from "../components/proxy/proxy-group";
import ProxyGroup from "../components/proxy-group"; 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 [curProxy, setCurProxy] = useState<string>("DIRECT");
const curMode = clashConfig?.mode.toLowerCase();
// proxy groups
const { groups = [] } = proxiesData ?? {};
// proxies and sorted
const filterProxies = useMemo(() => {
if (!proxiesData?.proxies) return [];
const list = Object.values(proxiesData.proxies);
const retList = list.filter(
(p) => !p.all?.length && p.name !== "DIRECT" && p.name !== "REJECT"
);
const direct = list.filter((p) => p.name === "DIRECT");
const reject = list.filter((p) => p.name === "REJECT");
return direct.concat(retList).concat(reject);
}, [proxiesData]);
const modeList = ["rule", "global", "direct"]; const modeList = ["rule", "global", "direct"];
const asGroup = curMode === "rule" || !groups.length; const curMode = clashConfig?.mode.toLowerCase() ?? "direct";
const { groups = [], proxies = [] } = proxiesData ?? {};
// make sure that fetch the proxies successfully // make sure that fetch the proxies successfully
useEffect(() => { useEffect(() => {
if ( if (
(curMode === "rule" && !groups.length) || (curMode === "rule" && !groups.length) ||
(curMode === "global" && filterProxies.length < 4) (curMode === "global" && proxies.length < 2)
) { ) {
setTimeout(() => mutate("getProxies"), 500); setTimeout(() => mutate("getProxies"), 500);
} }
}, [groups, filterProxies, curMode]); }, [groups, proxies, curMode]);
// update the current proxy const onChangeMode = useLockFn(async (mode: string) => {
useEffect(() => { // switch rapidly
if (curMode === "direct") setCurProxy("DIRECT"); await updateConfigs({ mode });
if (curMode === "global") { await patchClashConfig({ mode });
const globalNow = proxiesData?.proxies?.GLOBAL?.now; mutate("getClashConfig");
setCurProxy(globalNow || "DIRECT"); });
}
}, [curMode, proxiesData]);
const changeLockRef = useRef(false);
const onChangeMode = async (mode: string) => {
if (changeLockRef.current) return;
changeLockRef.current = true;
try {
// switch rapidly
await updateConfigs({ mode });
await patchClashConfig({ mode });
mutate("getClashConfig");
} finally {
changeLockRef.current = false;
}
};
const onChangeProxy = async (name: string) => {
if (curMode !== "global") return;
await updateProxy("GLOBAL", name);
setCurProxy(name);
};
// difference style // difference style
const pageStyle = asGroup ? {} : { height: "100%" }; const showGroup = curMode === "rule" && !!groups.length;
const paperStyle: any = asGroup const pageStyle = showGroup ? {} : { height: "100%" };
const paperStyle: any = showGroup
? { mb: 0.5 } ? { mb: 0.5 }
: { py: 1, height: "100%", boxSizing: "border-box" }; : { py: 1, height: "100%", boxSizing: "border-box" };
return ( return (
<BasePage <BasePage
contentStyle={pageStyle} contentStyle={pageStyle}
title={asGroup ? "Proxy Groups" : "Proxies"} title={showGroup ? t("Proxy Groups") : t("Proxies")}
header={ header={
<ButtonGroup size="small"> <ButtonGroup size="small">
{modeList.map((mode) => ( {modeList.map((mode) => (
@@ -94,32 +57,32 @@ const ProxyPage = () => {
onClick={() => onChangeMode(mode)} onClick={() => onChangeMode(mode)}
sx={{ textTransform: "capitalize" }} sx={{ textTransform: "capitalize" }}
> >
{mode} {t(mode)}
</Button> </Button>
))} ))}
</ButtonGroup> </ButtonGroup>
} }
> >
<Paper sx={{ borderRadius: 1, boxShadow: 2, ...paperStyle }}> <Paper sx={{ borderRadius: 1, boxShadow: 2, ...paperStyle }}>
{asGroup ? ( {curMode === "rule" && !!groups.length && (
<List> <List>
{groups.map((group) => ( {groups.map((group) => (
<ProxyGroup key={group.name} group={group} /> <ProxyGroup key={group.name} group={group} />
))} ))}
</List> </List>
) : ( )}
// virtual list {((curMode === "rule" && !groups.length) || curMode === "global") && (
<Virtuoso <ProxyGlobal
style={{ height: "100%" }} groupName="GLOBAL"
totalCount={filterProxies.length} curProxy={proxiesData?.global?.now}
itemContent={(index) => ( proxies={proxies}
<ProxyItem />
proxy={filterProxies[index]} )}
selected={filterProxies[index].name === curProxy} {curMode === "direct" && (
onClick={onChangeProxy} <ProxyGlobal
sx={{ py: 0, px: 2 }} groupName="DIRECT"
/> curProxy="DIRECT"
)} proxies={[proxiesData?.direct!].filter(Boolean)}
/> />
)} )}
</Paper> </Paper>

View File

@@ -1,17 +1,20 @@
import { Paper } from "@mui/material"; import { Paper } from "@mui/material";
import BasePage from "../components/base-page"; import { useTranslation } from "react-i18next";
import Notice from "../components/base/base-notice";
import BasePage from "../components/base/base-page";
import SettingVerge from "../components/setting/setting-verge"; import SettingVerge from "../components/setting/setting-verge";
import SettingClash from "../components/setting/setting-clash"; import SettingClash from "../components/setting/setting-clash";
import SettingSystem from "../components/setting/setting-system"; import SettingSystem from "../components/setting/setting-system";
import Notice from "../components/notice";
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

@@ -14,7 +14,13 @@ export async function getAxios(force: boolean = false) {
try { try {
const info = await getClashInfo(); const info = await getClashInfo();
if (info?.server) server = info?.server; if (info?.server) {
server = info.server;
// compatible width `external-controller`
if (server.startsWith(":")) server = `127.0.0.1${server}`;
else if (/^\d+$/.test(server)) server = `127.0.0.1:${server}`;
}
if (info?.secret) secret = info?.secret; if (info?.secret) secret = info?.secret;
} catch {} } catch {}
@@ -60,43 +66,90 @@ export async function getRules() {
return instance.get("/rules") as Promise<ApiType.RuleItem[]>; return instance.get("/rules") as Promise<ApiType.RuleItem[]>;
} }
/// Get Proxy delay
export async function getProxyDelay(
name: string,
url?: string
): Promise<{ delay: number }> {
const params = {
timeout: 3000,
url: url || "http://www.gstatic.com/generate_204",
};
const instance = await getAxios();
return instance.get(`/proxies/${encodeURIComponent(name)}/delay`, { params });
}
/// Update the Proxy Choose /// Update the Proxy Choose
export async function updateProxy(group: string, proxy: string) { export async function updateProxy(group: string, proxy: string) {
const instance = await getAxios(); const instance = await getAxios();
return instance.put(`/proxies/${group}`, { name: proxy }); return instance.put(`/proxies/${encodeURIComponent(group)}`, { name: proxy });
} }
/// Get the Proxy infomation /// Get the Proxy infomation
export async function getProxies() { export async function getProxies() {
const instance = await getAxios(); const instance = await getAxios();
const response = await instance.get<any, any>("/proxies"); const response = await instance.get<any, any>("/proxies");
const proxies = (response?.proxies ?? {}) as Record< const records = (response?.proxies ?? {}) as Record<
string, string,
ApiType.ProxyItem ApiType.ProxyItem
>; >;
const global = proxies["GLOBAL"]; const global = records["GLOBAL"];
const direct = records["DIRECT"];
const reject = records["REJECT"];
const order = global?.all; const order = global?.all;
let groups: ApiType.ProxyGroupItem[] = []; let groups: ApiType.ProxyGroupItem[] = [];
// compatible with proxy-providers
const generateItem = (name: string) => {
if (records[name]) return records[name];
return { name, type: "unknown", udp: false, history: [] };
};
if (order) { if (order) {
groups = order groups = order
.filter((name) => proxies[name]?.all) .filter((name) => records[name]?.all)
.map((name) => proxies[name]) .map((name) => records[name])
.map((each) => ({ .map((each) => ({
...each, ...each,
all: each.all!.map((item) => proxies[item]), all: each.all!.map((item) => generateItem(item)),
})); }));
} else { } else {
groups = Object.values(proxies) groups = Object.values(records)
.filter((each) => each.name !== "GLOBAL" && each.all) .filter((each) => each.name !== "GLOBAL" && each.all)
.map((each) => ({ .map((each) => ({
...each, ...each,
all: each.all!.map((item) => proxies[item]), all: each.all!.map((item) => generateItem(item)),
})); }));
groups.sort((a, b) => b.name.localeCompare(a.name)); groups.sort((a, b) => b.name.localeCompare(a.name));
} }
return { global, groups, proxies }; const proxies = [direct, reject].concat(
Object.values(records).filter(
(p) => !p.all?.length && p.name !== "DIRECT" && p.name !== "REJECT"
)
);
return { global, direct, groups, records, proxies };
}
// todo: get proxy providers
export async function getProviders() {
const instance = await getAxios();
const response = await instance.get<any, any>("/providers/proxies");
return response.providers as any;
}
// 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");
@@ -9,35 +10,52 @@ export async function syncProfiles() {
return invoke<void>("sync_profiles"); return invoke<void>("sync_profiles");
} }
export async function viewProfile(index: number) { export async function enhanceProfiles() {
return invoke<void>("enhance_profiles");
}
export async function createProfile(
item: Partial<CmdType.ProfileItem>,
fileData?: string | null
) {
return invoke<void>("create_profile", { item, fileData });
}
export async function viewProfile(index: string) {
return invoke<void>("view_profile", { index }); return invoke<void>("view_profile", { index });
} }
export async function importProfile(url: string) { export async function importProfile(url: string) {
return invoke<void>("import_profile", { url, withProxy: true }); return invoke<void>("import_profile", {
url,
option: { with_proxy: true },
});
} }
export async function updateProfile(index: number, withProxy: boolean) { export async function updateProfile(
return invoke<void>("update_profile", { index, withProxy }); index: string,
option?: CmdType.ProfileOption
) {
return invoke<void>("update_profile", { index, option });
} }
export async function deleteProfile(index: number) { export async function deleteProfile(index: string) {
return invoke<void>("delete_profile", { index }); return invoke<void>("delete_profile", { index });
} }
export async function patchProfile( export async function patchProfile(
index: number, index: string,
profile: CmdType.ProfileItem profile: Partial<CmdType.ProfileItem>
) { ) {
return invoke<void>("patch_profile", { index, profile }); return invoke<void>("patch_profile", { index, profile });
} }
export async function selectProfile(index: number) { export async function selectProfile(index: string) {
return invoke<void>("select_profile", { index }); return invoke<void>("select_profile", { index });
} }
export async function restartSidecar() { export async function changeProfileChain(chain?: string[]) {
return invoke<void>("restart_sidecar"); return invoke<void>("change_profile_chain", { chain });
} }
export async function getClashInfo() { export async function getClashInfo() {
@@ -59,3 +77,23 @@ export async function patchVergeConfig(payload: CmdType.VergeConfig) {
export async function getSystemProxy() { export async function getSystemProxy() {
return invoke<any>("get_sys_proxy"); return invoke<any>("get_sys_proxy");
} }
export async function restartSidecar() {
return invoke<void>("restart_sidecar");
}
export async function killSidecars() {
return invoke<any>("kill_sidecars");
}
export async function openAppDir() {
return invoke<void>("open_app_dir").catch((err) =>
Notice.error(err?.message || err.toString(), 1500)
);
}
export async function openLogsDir() {
return invoke<void>("open_logs_dir").catch((err) =>
Notice.error(err?.message || err.toString(), 1500)
);
}

70
src/services/delay.ts Normal file
View File

@@ -0,0 +1,70 @@
import { getProxyDelay } from "./api";
const hashKey = (name: string, group: string) => `${group ?? ""}::${name}`;
class DelayManager {
private cache = new Map<string, [number, number]>();
setDelay(name: string, group: string, delay: number) {
this.cache.set(hashKey(name, group), [Date.now(), delay]);
}
getDelay(name: string, group: string) {
if (!name) return -1;
const result = this.cache.get(hashKey(name, group));
if (result && Date.now() - result[0] <= 18e5) {
return result[1];
}
return -1;
}
async checkDelay(name: string, group: string) {
let delay = -1;
try {
const result = await getProxyDelay(name);
delay = result.delay;
} catch {
delay = 1e6; // error
}
this.setDelay(name, group, delay);
return delay;
}
async checkListDelay(
options: {
names: readonly string[];
groupName: string;
skipNum: number;
maxTimeout: number;
},
callback: Function
) {
let names = [...options.names];
const { groupName, skipNum, maxTimeout } = options;
while (names.length) {
const list = names.slice(0, skipNum);
names = names.slice(skipNum);
let called = false;
setTimeout(() => {
if (!called) {
called = true;
callback();
}
}, maxTimeout);
await Promise.all(list.map((n) => this.checkDelay(n, groupName)));
if (!called) {
called = true;
callback();
}
}
}
}
export default new DelayManager();

173
src/services/enhance.ts Normal file
View File

@@ -0,0 +1,173 @@
import { emit, listen } from "@tauri-apps/api/event";
import { CmdType } from "./types";
/**
* process the merge mode
*/
function toMerge(
merge: CmdType.ProfileMerge,
data: CmdType.ProfileData
): CmdType.ProfileData {
if (!merge) return data;
const newData = { ...data };
// rules
if (Array.isArray(merge["prepend-rules"])) {
if (!newData.rules) newData.rules = [];
newData.rules.unshift(...merge["prepend-rules"]);
}
if (Array.isArray(merge["append-rules"])) {
if (!newData.rules) newData.rules = [];
newData.rules.push(...merge["append-rules"]);
}
// proxies
if (Array.isArray(merge["prepend-proxies"])) {
if (!newData.proxies) newData.proxies = [];
newData.proxies.unshift(...merge["prepend-proxies"]);
}
if (Array.isArray(merge["append-proxies"])) {
if (!newData.proxies) newData.proxies = [];
newData.proxies.push(...merge["append-proxies"]);
}
// proxy-groups
if (Array.isArray(merge["prepend-proxy-groups"])) {
if (!newData["proxy-groups"]) newData["proxy-groups"] = [];
newData["proxy-groups"].unshift(...merge["prepend-proxy-groups"]);
}
if (Array.isArray(merge["append-proxy-groups"])) {
if (!newData["proxy-groups"]) newData["proxy-groups"] = [];
newData["proxy-groups"].push(...merge["append-proxy-groups"]);
}
return newData;
}
/**
* process the script mode
*/
function toScript(
script: string,
data: CmdType.ProfileData
): Promise<CmdType.ProfileData> {
if (!script) {
throw new Error("miss the main function");
}
const paramsName = `__verge${Math.floor(Math.random() * 1000)}`;
const code = `'use strict';${script};return main(${paramsName});`;
const func = new Function(paramsName, code);
return func(data);
}
export type EStatus = { status: "ok" | "error"; message?: string };
export type EListener = (status: EStatus) => void;
export type EUnlistener = () => void;
/**
* The service helps to
* implement enhanced profiles
*/
class Enhance {
private isSetup = false;
private listenMap: Map<string, EListener>;
private resultMap: Map<string, EStatus>;
constructor() {
this.listenMap = new Map();
this.resultMap = new Map();
}
// setup some listener
// for the enhanced running status
listen(uid: string, cb: EListener): EUnlistener {
this.listenMap.set(uid, cb);
return () => this.listenMap.delete(uid);
}
// get the running status
status(uid: string): EStatus | undefined {
return this.resultMap.get(uid);
}
// setup the handler
setup() {
if (this.isSetup) return;
this.isSetup = true;
listen("script-handler", async (event) => {
const payload = event.payload as CmdType.EnhancedPayload;
let pdata = payload.current || {};
let hasScript = false;
for (const each of payload.chain) {
const { uid, type = "" } = each.item;
try {
// process script
if (type === "script") {
// support async main function
pdata = await toScript(each.script!, { ...pdata });
hasScript = true;
}
// 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);
}
}
// If script is never used
// filter other fields
if (!hasScript) {
const validKeys = [
"proxies",
"proxy-providers",
"proxy-groups",
"rule-providers",
"rules",
];
// to lowercase
const newData: any = {};
Object.keys(pdata).forEach((key) => {
const newKey = key.toLowerCase();
if (validKeys.includes(newKey)) {
newData[newKey] = (pdata as any)[key];
}
});
pdata = newData;
}
const result = { data: pdata, status: "ok" };
emit(payload.callback, JSON.stringify(result)).catch(console.error);
});
}
// exec the listener
private exec(uid: string, status: EStatus) {
this.resultMap.set(uid, status);
this.listenMap.get(uid)?.(status);
}
}
export default new Enhance();

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,
},
});

24
src/services/states.ts Normal file
View File

@@ -0,0 +1,24 @@
import { atom } from "recoil";
import { ApiType } from "./types";
export const atomClashPort = atom<number>({
key: "atomClashPort",
default: 0,
});
export const atomLogData = atom<ApiType.LogItem[]>({
key: "atomLogData",
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

@@ -78,6 +78,8 @@ export namespace ApiType {
* Some interface for command * Some interface for command
*/ */
export namespace CmdType { export namespace CmdType {
export type ProfileType = "local" | "remote" | "merge" | "script";
export interface ClashInfo { export interface ClashInfo {
status: string; status: string;
port?: string; port?: string;
@@ -86,9 +88,11 @@ export namespace CmdType {
} }
export interface ProfileItem { export interface ProfileItem {
uid: string;
type?: ProfileType | string;
name?: string; name?: string;
desc?: string;
file?: string; file?: string;
mode?: string;
url?: string; url?: string;
updated?: number; updated?: number;
selected?: { selected?: {
@@ -101,17 +105,58 @@ export namespace CmdType {
total: number; total: number;
expire: number; expire: number;
}; };
option?: ProfileOption;
}
export interface ProfileOption {
user_agent?: string;
with_proxy?: boolean;
} }
export interface ProfilesConfig { export interface ProfilesConfig {
current?: number; current?: string;
chain?: 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;
enable_tun_mode?: boolean;
enable_auto_launch?: boolean; enable_auto_launch?: boolean;
enable_system_proxy?: boolean; enable_system_proxy?: boolean;
enable_proxy_guard?: boolean;
system_proxy_bypass?: string;
}
export type ProfileMerge = Record<string, any>;
// partial of the clash config
export type ProfileData = Partial<{
rules: any[];
proxies: any[];
"proxy-groups": any[];
"proxy-providers": any[];
"rule-providers": any[];
}>;
export interface ChainItem {
item: ProfileItem;
merge?: ProfileMerge;
script?: string;
}
export interface EnhancedPayload {
chain: ChainItem[];
current: ProfileData;
callback: string;
}
export interface EnhancedResult {
data: ProfileData;
status: string;
error?: string;
} }
} }

View File

@@ -1,16 +0,0 @@
import { atom } from "recoil";
export const atomPaletteMode = atom<"light" | "dark">({
key: "atomPaletteMode",
default: "light",
});
export const atomThemeBlur = atom<boolean>({
key: "atomThemeBlur",
default: false,
});
export const atomClashPort = atom<number>({
key: "atomClashPort",
default: 0,
});

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";
}

3957
yarn.lock

File diff suppressed because it is too large Load Diff