Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ead15e78e | ||
|
|
aa0740ff94 | ||
|
|
6d3f837820 | ||
|
|
359b82c29c | ||
|
|
b54171bc2c | ||
|
|
936b2131e0 | ||
|
|
aaef6a9e9c | ||
|
|
9327006e61 | ||
|
|
5225c841ae | ||
|
|
8464e319fd | ||
|
|
98b8bd90ea | ||
|
|
ae94993b09 | ||
|
|
72f10aaed1 | ||
|
|
4a74bae8c7 | ||
|
|
5164aec37b | ||
|
|
1581e9b1cd | ||
|
|
536e3ffb11 | ||
|
|
d6103191ba | ||
|
|
49e37a19a5 | ||
|
|
d02431e260 | ||
|
|
f24f6ead92 | ||
|
|
b7bdb7ae50 | ||
|
|
2dcf8ac96f | ||
|
|
5421c94853 | ||
|
|
10f6bc092a | ||
|
|
be9ea4ea8e | ||
|
|
f5c6fa842a | ||
|
|
e0943ce905 | ||
|
|
61e7df77a7 | ||
|
|
a5434360bc | ||
|
|
ba29c66e3b | ||
|
|
b3a72d55ae | ||
|
|
c382ad1cc8 | ||
|
|
363e28f323 | ||
|
|
d695656b8c | ||
|
|
31c6cbc0a2 | ||
|
|
b93284bc2f | ||
|
|
99c855b01b | ||
|
|
c2eaedc959 | ||
|
|
a631cd67ec | ||
|
|
66fccd3c68 | ||
|
|
9a4ebf4daa | ||
|
|
91c14211c6 | ||
|
|
1ea07c458b | ||
|
|
591add6e0c | ||
|
|
b99fff66df | ||
|
|
f54ba05b00 | ||
|
|
6596fb00c7 | ||
|
|
df0b5a80dc | ||
|
|
8cdbb31dbe | ||
|
|
0be4b1222d | ||
|
|
18a6bfd73a | ||
|
|
5e2271b237 | ||
|
|
798999d490 | ||
|
|
0e68c5e8bc | ||
|
|
9694af82f4 | ||
|
|
28a4386975 | ||
|
|
a238f7beba | ||
|
|
75ba16281b | ||
|
|
ad65a278d4 | ||
|
|
a2320b3f8d | ||
|
|
ae12853ad0 | ||
|
|
68adf6dc2f | ||
|
|
f88989bd4b | ||
|
|
77ef3847ce | ||
|
|
b8291837fc | ||
|
|
423a7f951a | ||
|
|
557f5fe364 | ||
|
|
5308970ad8 | ||
|
|
6b368953f4 | ||
|
|
2d0b63c29d | ||
|
|
34e941c8cb | ||
|
|
76cf007fff | ||
|
|
321963be83 | ||
|
|
c733bda6c3 | ||
|
|
e67b50b976 | ||
|
|
9e3c080909 | ||
|
|
cb661aaebd | ||
|
|
573571978c | ||
|
|
dc492a2a0a | ||
|
|
e47747dd0e | ||
|
|
4de944b41e | ||
|
|
5f7a1fa5cd | ||
|
|
b8ad328cde | ||
|
|
3076fd19c1 | ||
|
|
fac437b8c1 | ||
|
|
697c25015e | ||
|
|
d83b404fc3 | ||
|
|
ab7313cbc4 | ||
|
|
1b8d70322b | ||
|
|
844ffab4ed | ||
|
|
f5d0513d1f | ||
|
|
557abd4285 | ||
|
|
f4f1a0fbc6 | ||
|
|
74e10dc012 | ||
|
|
359812b7ed | ||
|
|
c2449e53c4 | ||
|
|
1a91249da2 | ||
|
|
b9162f9576 | ||
|
|
f726e8a7b3 | ||
|
|
2f284cfdc9 | ||
|
|
b74696adba | ||
|
|
c8ccba0192 | ||
|
|
41b0e05f62 | ||
|
|
847d5f1b3b | ||
|
|
0445f9dfc2 | ||
|
|
3001c780bd | ||
|
|
68ad5e2320 | ||
|
|
b5e229b19c | ||
|
|
453d798fcf | ||
|
|
451afdb660 | ||
|
|
d298bda92c | ||
|
|
fd99ba6255 | ||
|
|
6ade0b2b1a | ||
|
|
9902003da9 | ||
|
|
0ff2fcac11 | ||
|
|
e80be8e7b6 | ||
|
|
fe0ad0f5cb | ||
|
|
cb8e162f4e | ||
|
|
ae8c30fe57 | ||
|
|
ab82db9e22 | ||
|
|
cb9d3098de | ||
|
|
c927419c99 | ||
|
|
c009026961 | ||
|
|
51cf442fa5 | ||
|
|
954e3553ee | ||
|
|
cde17385b4 | ||
|
|
5b9e078061 | ||
|
|
0290d9ddfc | ||
|
|
eab671d102 | ||
|
|
f9a96ff914 | ||
|
|
3ec2b46d28 | ||
|
|
aec30b89e0 | ||
|
|
309c33e190 | ||
|
|
9c0276f97b | ||
|
|
0a3402ff43 | ||
|
|
bd82308024 | ||
|
|
db3b634e62 | ||
|
|
40bcb22977 | ||
|
|
4bd94092f1 | ||
|
|
cac1ce6895 |
@@ -0,0 +1,84 @@
|
|||||||
|
name: Alpha CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [alpha]
|
||||||
|
|
||||||
|
env:
|
||||||
|
CARGO_INCREMENTAL: 0
|
||||||
|
RUST_BACKTRACE: short
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
release:
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
os: [windows-latest, ubuntu-latest, macos-latest]
|
||||||
|
runs-on: ${{ matrix.os }}
|
||||||
|
if: startsWith(github.repository, 'zzzgydi')
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
|
||||||
|
- name: Install Rust
|
||||||
|
uses: actions-rs/toolchain@v1
|
||||||
|
with:
|
||||||
|
toolchain: stable
|
||||||
|
profile: minimal
|
||||||
|
override: true
|
||||||
|
|
||||||
|
- name: Rust Cache
|
||||||
|
uses: Swatinem/rust-cache@ce325b60658c1b38465c06cc965b79baf32c1e72
|
||||||
|
with:
|
||||||
|
working-directory: src-tauri
|
||||||
|
|
||||||
|
- name: Install Node
|
||||||
|
uses: actions/setup-node@v1
|
||||||
|
with:
|
||||||
|
node-version: 14
|
||||||
|
|
||||||
|
- name: Install Dependencies (ubuntu only)
|
||||||
|
if: matrix.os == 'ubuntu-latest'
|
||||||
|
run: |
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get install -y libwebkit2gtk-4.0-dev build-essential curl wget libssl-dev libgtk-3-dev libappindicator3-dev librsvg2-dev libayatana-appindicator3-dev
|
||||||
|
|
||||||
|
- name: Get yarn cache dir path
|
||||||
|
id: yarn-cache-dir-path
|
||||||
|
run: echo "::set-output name=dir::$(yarn cache dir)"
|
||||||
|
|
||||||
|
- name: Yarn Cache
|
||||||
|
uses: actions/cache@v2
|
||||||
|
id: yarn-cache
|
||||||
|
with:
|
||||||
|
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
|
||||||
|
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
|
||||||
|
restore-keys: |
|
||||||
|
${{ runner.os }}-yarn-
|
||||||
|
|
||||||
|
- name: Yarn install and check
|
||||||
|
run: |
|
||||||
|
yarn install --network-timeout 1000000
|
||||||
|
yarn run check
|
||||||
|
|
||||||
|
- name: Tauri build
|
||||||
|
uses: tauri-apps/tauri-action@743a37fd53cbdd122910b818b9bef7b7aa019134
|
||||||
|
# enable cache even though failed
|
||||||
|
continue-on-error: true
|
||||||
|
env:
|
||||||
|
VITE_MULTI_CORE: 1
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
|
||||||
|
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
|
||||||
|
with:
|
||||||
|
tagName: alpha
|
||||||
|
releaseName: "Clash Verge Alpha"
|
||||||
|
releaseBody: "Alpha Version"
|
||||||
|
releaseDraft: true
|
||||||
|
prerelease: true
|
||||||
|
|
||||||
|
- name: Portable Bundle
|
||||||
|
if: matrix.os == 'windows-latest'
|
||||||
|
run: |
|
||||||
|
yarn run portable
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
@@ -28,6 +28,8 @@ jobs:
|
|||||||
|
|
||||||
- name: Rust Cache
|
- name: Rust Cache
|
||||||
uses: Swatinem/rust-cache@ce325b60658c1b38465c06cc965b79baf32c1e72
|
uses: Swatinem/rust-cache@ce325b60658c1b38465c06cc965b79baf32c1e72
|
||||||
|
with:
|
||||||
|
working-directory: src-tauri
|
||||||
|
|
||||||
- name: Install Node
|
- name: Install Node
|
||||||
uses: actions/setup-node@v1
|
uses: actions/setup-node@v1
|
||||||
@@ -38,7 +40,7 @@ jobs:
|
|||||||
if: matrix.os == 'ubuntu-latest'
|
if: matrix.os == 'ubuntu-latest'
|
||||||
run: |
|
run: |
|
||||||
sudo apt-get update
|
sudo apt-get update
|
||||||
sudo apt-get install -y libgtk-3-dev webkit2gtk-4.0 libappindicator3-dev librsvg2-dev patchelf
|
sudo apt-get install -y libwebkit2gtk-4.0-dev build-essential curl wget libssl-dev libgtk-3-dev libappindicator3-dev librsvg2-dev libayatana-appindicator3-dev
|
||||||
|
|
||||||
- name: Get yarn cache dir path
|
- name: Get yarn cache dir path
|
||||||
id: yarn-cache-dir-path
|
id: yarn-cache-dir-path
|
||||||
@@ -73,10 +75,10 @@ jobs:
|
|||||||
releaseDraft: false
|
releaseDraft: false
|
||||||
prerelease: true
|
prerelease: true
|
||||||
|
|
||||||
- name: Green zip bundle
|
- name: Portable Bundle
|
||||||
if: matrix.os == 'windows-latest'
|
if: matrix.os == 'windows-latest'
|
||||||
run: |
|
run: |
|
||||||
yarn run green
|
yarn run portable
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
@@ -106,7 +108,7 @@ jobs:
|
|||||||
- name: Yarn install
|
- name: Yarn install
|
||||||
run: yarn install
|
run: yarn install
|
||||||
|
|
||||||
- name: Release update.json
|
- name: Release updater file
|
||||||
run: yarn run release
|
run: yarn run updater
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
name: Test CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
os:
|
||||||
|
description: "Runs on OS"
|
||||||
|
required: true
|
||||||
|
default: windows-latest
|
||||||
|
type: choice
|
||||||
|
options:
|
||||||
|
- windows-latest
|
||||||
|
- ubuntu-latest
|
||||||
|
- macos-latest
|
||||||
|
|
||||||
|
env:
|
||||||
|
CARGO_INCREMENTAL: 0
|
||||||
|
RUST_BACKTRACE: short
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
release:
|
||||||
|
runs-on: ${{ github.event.inputs.os }}
|
||||||
|
if: startsWith(github.repository, 'zzzgydi')
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
|
||||||
|
- name: Install Rust
|
||||||
|
uses: actions-rs/toolchain@v1
|
||||||
|
with:
|
||||||
|
toolchain: stable
|
||||||
|
profile: minimal
|
||||||
|
override: true
|
||||||
|
|
||||||
|
- name: Rust Cache
|
||||||
|
uses: Swatinem/rust-cache@v1
|
||||||
|
with:
|
||||||
|
working-directory: src-tauri
|
||||||
|
|
||||||
|
- name: Install Node
|
||||||
|
uses: actions/setup-node@v1
|
||||||
|
with:
|
||||||
|
node-version: 14
|
||||||
|
|
||||||
|
- name: Install Dependencies (ubuntu only)
|
||||||
|
if: github.event.inputs.os == 'ubuntu-latest'
|
||||||
|
run: |
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get install -y libwebkit2gtk-4.0-dev build-essential curl wget libssl-dev libgtk-3-dev libappindicator3-dev librsvg2-dev libayatana-appindicator3-dev
|
||||||
|
|
||||||
|
- name: Get yarn cache dir path
|
||||||
|
id: yarn-cache-dir-path
|
||||||
|
run: echo "::set-output name=dir::$(yarn cache dir)"
|
||||||
|
|
||||||
|
- name: Yarn Cache
|
||||||
|
uses: actions/cache@v2
|
||||||
|
id: yarn-cache
|
||||||
|
with:
|
||||||
|
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
|
||||||
|
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
|
||||||
|
restore-keys: |
|
||||||
|
${{ runner.os }}-yarn-
|
||||||
|
|
||||||
|
- name: Yarn install and check
|
||||||
|
run: |
|
||||||
|
yarn install --network-timeout 1000000
|
||||||
|
yarn run check
|
||||||
|
|
||||||
|
- name: Tauri build
|
||||||
|
uses: tauri-apps/tauri-action@0e558392ccadcb49bcc89e7df15a400e8f0c954d
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
|
||||||
|
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
name: Updater CI
|
||||||
|
|
||||||
|
on: workflow_dispatch
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
release-update:
|
||||||
|
runs-on: macos-latest
|
||||||
|
if: startsWith(github.repository, 'zzzgydi')
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
|
||||||
|
- name: Get yarn cache dir path
|
||||||
|
id: yarn-cache-dir-path
|
||||||
|
run: echo "::set-output name=dir::$(yarn cache dir)"
|
||||||
|
|
||||||
|
- name: Yarn Cache
|
||||||
|
uses: actions/cache@v2
|
||||||
|
id: yarn-cache
|
||||||
|
with:
|
||||||
|
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
|
||||||
|
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
|
||||||
|
restore-keys: |
|
||||||
|
${{ runner.os }}-yarn-
|
||||||
|
|
||||||
|
- name: Yarn install
|
||||||
|
run: yarn install
|
||||||
|
|
||||||
|
- name: Release updater file
|
||||||
|
run: yarn run updater
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
@@ -12,7 +12,8 @@ A <a href="https://github.com/Dreamacro/clash">Clash</a> GUI based on <a href="h
|
|||||||
## Features
|
## Features
|
||||||
|
|
||||||
- Full `clash` config supported, Partial `clash premium` config supported.
|
- Full `clash` config supported, Partial `clash premium` config supported.
|
||||||
- Profiles management and enhancement (by yaml and Javascript).
|
- Profiles management and enhancement (by yaml and Javascript). [Doc](https://github.com/zzzgydi/clash-verge/issues/12)
|
||||||
|
- Simple UI and supports custom theme color.
|
||||||
- System proxy setting and guard.
|
- System proxy setting and guard.
|
||||||
|
|
||||||
## Install
|
## Install
|
||||||
@@ -64,6 +65,17 @@ yarn build
|
|||||||
<img src="./docs/demo6.png" alt="demo6" width="32%" />
|
<img src="./docs/demo6.png" alt="demo6" width="32%" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
### Custom Theme
|
||||||
|
|
||||||
|
<div align="center">
|
||||||
|
<img src="./docs/color1.png" alt="demo1" width="16%" />
|
||||||
|
<img src="./docs/color2.png" alt="demo2" width="16%" />
|
||||||
|
<img src="./docs/color3.png" alt="demo3" width="16%" />
|
||||||
|
<img src="./docs/color4.png" alt="demo4" width="16%" />
|
||||||
|
<img src="./docs/color5.png" alt="demo5" width="16%" />
|
||||||
|
<img src="./docs/color6.png" alt="demo6" width="16%" />
|
||||||
|
</div>
|
||||||
|
|
||||||
## Disclaimer
|
## Disclaimer
|
||||||
|
|
||||||
This is a learning project for Rust practice.
|
This is a learning project for Rust practice.
|
||||||
|
|||||||
@@ -1,3 +1,90 @@
|
|||||||
|
## v1.0.2
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- supports for switching clash core
|
||||||
|
- supports release UI processes
|
||||||
|
- supports script mode setting
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
- fix service mode bug (Windows)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## v1.0.1
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- adjust default theme settings
|
||||||
|
- reduce gpu usage of traffic graph when hidden
|
||||||
|
- supports more remote profile response header setting
|
||||||
|
- check remote profile data format when imported
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
- service mode install and start issue (Windows)
|
||||||
|
- fix launch panic (Some Windows)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## v1.0.0
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- update clash core
|
||||||
|
- optimize traffic graph animation
|
||||||
|
- supports interval update profiles
|
||||||
|
- supports service mode (Windows)
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
- reset system proxy when exit from dock (macOS)
|
||||||
|
- adjust clash dns config process strategy
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## v0.0.29
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- sort proxy node
|
||||||
|
- custom proxy test url
|
||||||
|
- logs page filter
|
||||||
|
- connections page filter
|
||||||
|
- default user agent for subscription
|
||||||
|
- system tray add tun mode toggle
|
||||||
|
- enable to change the config dir (Windows only)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## v0.0.28
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- enable to use clash config fields (UI)
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
- remove the character
|
||||||
|
- fix some icon color
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## v0.0.27
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- supports custom theme color
|
||||||
|
- tun mode setting control the final config
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
- fix transition flickers (macOS)
|
||||||
|
- reduce proxy page render
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## v0.0.26
|
## v0.0.26
|
||||||
|
|
||||||
### Features
|
### Features
|
||||||
|
|||||||
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 30 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 31 KiB |
@@ -1,57 +1,62 @@
|
|||||||
{
|
{
|
||||||
"name": "clash-verge",
|
"name": "clash-verge",
|
||||||
"version": "0.0.26",
|
"version": "1.0.2",
|
||||||
"license": "GPL-3.0",
|
"license": "GPL-3.0",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "tauri dev",
|
"dev": "tauri dev",
|
||||||
|
"dev:diff": "tauri dev -f verge-dev",
|
||||||
"build": "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",
|
"updater": "node scripts/updater.mjs",
|
||||||
"publish": "node scripts/publish.mjs",
|
"publish": "node scripts/publish.mjs",
|
||||||
"release": "node scripts/release.mjs",
|
"portable": "node scripts/portable.mjs",
|
||||||
"prepare": "husky install"
|
"prepare": "husky install"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@emotion/react": "^11.8.1",
|
"@emotion/react": "^11.9.0",
|
||||||
"@emotion/styled": "^11.8.1",
|
"@emotion/styled": "^11.8.1",
|
||||||
"@mui/icons-material": "^5.4.4",
|
"@mui/icons-material": "^5.8.0",
|
||||||
"@mui/material": "^5.4.4",
|
"@mui/material": "^5.8.1",
|
||||||
"@tauri-apps/api": "^1.0.0-rc.2",
|
"@tauri-apps/api": "^1.0.0-rc.6",
|
||||||
"ahooks": "^3.1.13",
|
"ahooks": "^3.2.0",
|
||||||
"axios": "^0.26.0",
|
"axios": "^0.26.0",
|
||||||
"dayjs": "^1.10.8",
|
"dayjs": "^1.11.0",
|
||||||
"i18next": "^21.6.14",
|
"i18next": "^21.6.14",
|
||||||
"monaco-editor": "^0.33.0",
|
"monaco-editor": "^0.33.0",
|
||||||
"react": "^17.0.2",
|
"react": "^17.0.2",
|
||||||
"react-dom": "^17.0.2",
|
"react-dom": "^17.0.2",
|
||||||
"react-i18next": "^11.15.6",
|
"react-i18next": "^11.15.6",
|
||||||
"react-router-dom": "^6.2.2",
|
"react-router-dom": "^6.2.2",
|
||||||
"react-virtuoso": "^2.7.0",
|
"react-virtuoso": "~2.11.0",
|
||||||
"recoil": "^0.6.1",
|
"recoil": "^0.6.1",
|
||||||
"snarkdown": "^2.0.0",
|
"snarkdown": "^2.0.0",
|
||||||
"swr": "^1.2.1"
|
"swr": "^1.3.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@actions/github": "^5.0.0",
|
"@actions/github": "^5.0.0",
|
||||||
"@tauri-apps/cli": "^1.0.0-rc.7",
|
"@tauri-apps/cli": "^1.0.0-rc.13",
|
||||||
"@types/fs-extra": "^9.0.13",
|
"@types/fs-extra": "^9.0.13",
|
||||||
"@types/js-cookie": "^3.0.1",
|
"@types/js-cookie": "^3.0.1",
|
||||||
|
"@types/lodash": "^4.14.180",
|
||||||
"@types/react": "^17.0.0",
|
"@types/react": "^17.0.0",
|
||||||
"@types/react-dom": "^17.0.0",
|
"@types/react-dom": "^17.0.0",
|
||||||
"@vitejs/plugin-react": "^1.2.0",
|
"@vitejs/plugin-react": "^1.3.2",
|
||||||
"adm-zip": "^0.5.9",
|
"adm-zip": "^0.5.9",
|
||||||
|
"cross-env": "^7.0.3",
|
||||||
"fs-extra": "^10.0.0",
|
"fs-extra": "^10.0.0",
|
||||||
|
"https-proxy-agent": "^5.0.1",
|
||||||
"husky": "^7.0.0",
|
"husky": "^7.0.0",
|
||||||
"node-fetch": "^3.2.0",
|
"node-fetch": "^3.2.0",
|
||||||
"pretty-quick": "^3.1.3",
|
"pretty-quick": "^3.1.3",
|
||||||
"sass": "^1.49.7",
|
"sass": "^1.51.0",
|
||||||
"typescript": "^4.5.5",
|
"typescript": "^4.6.4",
|
||||||
"vite": "^2.8.6",
|
"vite": "^2.9.9",
|
||||||
"vite-plugin-monaco-editor": "^1.0.10"
|
"vite-plugin-monaco-editor": "^1.0.10",
|
||||||
|
"vite-plugin-svgr": "^2.1.0"
|
||||||
},
|
},
|
||||||
"prettier": {
|
"prettier": {
|
||||||
"tabWidth": 2,
|
"tabWidth": 2,
|
||||||
|
|||||||
@@ -3,10 +3,14 @@ import zlib from "zlib";
|
|||||||
import path from "path";
|
import path from "path";
|
||||||
import AdmZip from "adm-zip";
|
import AdmZip from "adm-zip";
|
||||||
import fetch from "node-fetch";
|
import fetch from "node-fetch";
|
||||||
|
import proxyAgent from "https-proxy-agent";
|
||||||
import { execSync } from "child_process";
|
import { execSync } from "child_process";
|
||||||
|
|
||||||
const cwd = process.cwd();
|
const cwd = process.cwd();
|
||||||
|
const TEMP_DIR = path.join(cwd, "node_modules/.verge");
|
||||||
|
|
||||||
const FORCE = process.argv.includes("--force");
|
const FORCE = process.argv.includes("--force");
|
||||||
|
const NO_META = process.argv.includes("--no-meta") || false;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* get the correct clash release infomation
|
* get the correct clash release infomation
|
||||||
@@ -16,7 +20,7 @@ function resolveClash() {
|
|||||||
|
|
||||||
const CLASH_URL_PREFIX =
|
const CLASH_URL_PREFIX =
|
||||||
"https://github.com/Dreamacro/clash/releases/download/premium/";
|
"https://github.com/Dreamacro/clash/releases/download/premium/";
|
||||||
const CLASH_LATEST_DATE = "2022.03.21";
|
const CLASH_LATEST_DATE = "2022.05.18";
|
||||||
|
|
||||||
// todo
|
// todo
|
||||||
const map = {
|
const map = {
|
||||||
@@ -41,55 +45,139 @@ function resolveClash() {
|
|||||||
return { url, zip, exefile, zipfile };
|
return { url, zip, exefile, zipfile };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* get the correct Clash.Meta release infomation
|
||||||
|
*/
|
||||||
|
async function resolveClashMeta() {
|
||||||
|
const { platform, arch } = process;
|
||||||
|
|
||||||
|
const urlPrefix = `https://github.com/MetaCubeX/Clash.Meta/releases/download/`;
|
||||||
|
const latestVersion = "v1.11.1";
|
||||||
|
|
||||||
|
const map = {
|
||||||
|
"win32-x64": "Clash.Meta-windows-amd64v3",
|
||||||
|
"darwin-x64": "Clash.Meta-darwin-amd64v3",
|
||||||
|
"darwin-arm64": "Clash.Meta-darwin-arm64",
|
||||||
|
"linux-x64": "Clash.Meta-linux-amd64v3",
|
||||||
|
};
|
||||||
|
|
||||||
|
const name = map[`${platform}-${arch}`];
|
||||||
|
|
||||||
|
if (!name) {
|
||||||
|
throw new Error(`unsupport platform "${platform}-${arch}"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const isWin = platform === "win32";
|
||||||
|
const ext = isWin ? "zip" : "gz";
|
||||||
|
const url = `${urlPrefix}${latestVersion}/${name}-${latestVersion}.${ext}`;
|
||||||
|
const exefile = `${name}${isWin ? ".exe" : ""}`;
|
||||||
|
const zipfile = `${name}-${latestVersion}.${ext}`;
|
||||||
|
|
||||||
|
return { url, zip: ext, exefile, zipfile };
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* get the sidecar bin
|
* get the sidecar bin
|
||||||
|
* clash and Clash Meta
|
||||||
*/
|
*/
|
||||||
async function resolveSidecar() {
|
async function resolveSidecar() {
|
||||||
const sidecarDir = path.join(cwd, "src-tauri", "sidecar");
|
const sidecarDir = path.join(cwd, "src-tauri", "sidecar");
|
||||||
|
|
||||||
const host = execSync("rustc -vV | grep host").toString().slice(6).trim();
|
const host = execSync("rustc -vV | grep host").toString().slice(6).trim();
|
||||||
const ext = process.platform === "win32" ? ".exe" : "";
|
const ext = process.platform === "win32" ? ".exe" : "";
|
||||||
const sidecarFile = `clash-${host}${ext}`;
|
|
||||||
const sidecarPath = path.join(sidecarDir, sidecarFile);
|
|
||||||
|
|
||||||
await fs.mkdirp(sidecarDir);
|
await clash();
|
||||||
if (!FORCE && (await fs.pathExists(sidecarPath))) return;
|
if (!NO_META) await clashMeta();
|
||||||
|
|
||||||
// download sidecar
|
async function clash() {
|
||||||
const binInfo = resolveClash();
|
const sidecarFile = `clash-${host}${ext}`;
|
||||||
const tempDir = path.join(cwd, "pre-dev-temp");
|
const sidecarPath = path.join(sidecarDir, sidecarFile);
|
||||||
const tempZip = path.join(tempDir, binInfo.zipfile);
|
|
||||||
const tempExe = path.join(tempDir, binInfo.exefile);
|
|
||||||
|
|
||||||
await fs.mkdirp(tempDir);
|
await fs.mkdirp(sidecarDir);
|
||||||
if (!(await fs.pathExists(tempZip))) await downloadFile(binInfo.url, tempZip);
|
if (!FORCE && (await fs.pathExists(sidecarPath))) return;
|
||||||
|
|
||||||
if (binInfo.zip === "zip") {
|
// download sidecar
|
||||||
const zip = new AdmZip(tempZip);
|
const binInfo = resolveClash();
|
||||||
zip.getEntries().forEach((entry) => {
|
const tempDir = path.join(TEMP_DIR, "clash");
|
||||||
console.log("[INFO]: entry name", entry.entryName);
|
const tempZip = path.join(tempDir, binInfo.zipfile);
|
||||||
});
|
const tempExe = path.join(tempDir, binInfo.exefile);
|
||||||
zip.extractAllTo(tempDir, true);
|
|
||||||
// save as sidecar
|
await fs.mkdirp(tempDir);
|
||||||
await fs.rename(tempExe, sidecarPath);
|
if (!(await fs.pathExists(tempZip)))
|
||||||
console.log(`[INFO]: unzip finished`);
|
await downloadFile(binInfo.url, tempZip);
|
||||||
} else {
|
|
||||||
// gz
|
if (binInfo.zip === "zip") {
|
||||||
const readStream = fs.createReadStream(tempZip);
|
const zip = new AdmZip(tempZip);
|
||||||
const writeStream = fs.createWriteStream(sidecarPath);
|
zip.getEntries().forEach((entry) => {
|
||||||
readStream
|
console.log("[INFO]: entry name", entry.entryName);
|
||||||
.pipe(zlib.createGunzip())
|
});
|
||||||
.pipe(writeStream)
|
zip.extractAllTo(tempDir, true);
|
||||||
.on("finish", () => {
|
// save as sidecar
|
||||||
console.log(`[INFO]: gunzip finished`);
|
await fs.rename(tempExe, sidecarPath);
|
||||||
execSync(`chmod 755 ${sidecarPath}`);
|
console.log(`[INFO]: unzip finished`);
|
||||||
console.log(`[INFO]: chmod binary finished`);
|
} else {
|
||||||
})
|
// gz
|
||||||
.on("error", (error) => console.error(error));
|
const readStream = fs.createReadStream(tempZip);
|
||||||
|
const writeStream = fs.createWriteStream(sidecarPath);
|
||||||
|
readStream
|
||||||
|
.pipe(zlib.createGunzip())
|
||||||
|
.pipe(writeStream)
|
||||||
|
.on("finish", () => {
|
||||||
|
console.log(`[INFO]: gunzip finished`);
|
||||||
|
execSync(`chmod 755 ${sidecarPath}`);
|
||||||
|
console.log(`[INFO]: chmod binary finished`);
|
||||||
|
})
|
||||||
|
.on("error", (error) => console.error(error));
|
||||||
|
}
|
||||||
|
|
||||||
|
// delete temp dir
|
||||||
|
await fs.remove(tempDir);
|
||||||
}
|
}
|
||||||
|
|
||||||
// delete temp dir
|
async function clashMeta() {
|
||||||
await fs.remove(tempDir);
|
const sidecarFile = `clash-meta-${host}${ext}`;
|
||||||
|
const sidecarPath = path.join(sidecarDir, sidecarFile);
|
||||||
|
|
||||||
|
await fs.mkdirp(sidecarDir);
|
||||||
|
if (!FORCE && (await fs.pathExists(sidecarPath))) return;
|
||||||
|
|
||||||
|
// download sidecar
|
||||||
|
const binInfo = await resolveClashMeta();
|
||||||
|
const tempDir = path.join(TEMP_DIR, "clash-meta");
|
||||||
|
const tempZip = path.join(tempDir, binInfo.zipfile);
|
||||||
|
const tempExe = path.join(tempDir, binInfo.exefile);
|
||||||
|
|
||||||
|
await fs.mkdirp(tempDir);
|
||||||
|
if (!(await fs.pathExists(tempZip)))
|
||||||
|
await downloadFile(binInfo.url, tempZip);
|
||||||
|
|
||||||
|
if (binInfo.zip === "zip") {
|
||||||
|
const zip = new AdmZip(tempZip);
|
||||||
|
zip.getEntries().forEach((entry) => {
|
||||||
|
console.log("[INFO]: entry name", entry.entryName);
|
||||||
|
});
|
||||||
|
zip.extractAllTo(tempDir, true);
|
||||||
|
// save as sidecar
|
||||||
|
await fs.rename(tempExe, sidecarPath);
|
||||||
|
console.log(`[INFO]: unzip finished`);
|
||||||
|
} else {
|
||||||
|
// gz
|
||||||
|
const readStream = fs.createReadStream(tempZip);
|
||||||
|
const writeStream = fs.createWriteStream(sidecarPath);
|
||||||
|
readStream
|
||||||
|
.pipe(zlib.createGunzip())
|
||||||
|
.pipe(writeStream)
|
||||||
|
.on("finish", () => {
|
||||||
|
console.log(`[INFO]: gunzip finished`);
|
||||||
|
execSync(`chmod 755 ${sidecarPath}`);
|
||||||
|
console.log(`[INFO]: chmod binary finished`);
|
||||||
|
})
|
||||||
|
.on("error", (error) => console.error(error));
|
||||||
|
}
|
||||||
|
|
||||||
|
// delete temp dir
|
||||||
|
await fs.remove(tempDir);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -103,7 +191,7 @@ async function resolveWintun() {
|
|||||||
|
|
||||||
const url = "https://www.wintun.net/builds/wintun-0.14.1.zip";
|
const url = "https://www.wintun.net/builds/wintun-0.14.1.zip";
|
||||||
|
|
||||||
const tempDir = path.join(cwd, "pre-dev-temp-1");
|
const tempDir = path.join(TEMP_DIR, "wintun");
|
||||||
const tempZip = path.join(tempDir, "wintun.zip");
|
const tempZip = path.join(tempDir, "wintun.zip");
|
||||||
|
|
||||||
const wintunPath = path.join(tempDir, "wintun/bin/amd64/wintun.dll");
|
const wintunPath = path.join(tempDir, "wintun/bin/amd64/wintun.dll");
|
||||||
@@ -125,24 +213,55 @@ async function resolveWintun() {
|
|||||||
throw new Error(`path not found "${wintunPath}"`);
|
throw new Error(`path not found "${wintunPath}"`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// move wintun.dll to resources
|
|
||||||
await fs.rename(wintunPath, targetPath);
|
await fs.rename(wintunPath, targetPath);
|
||||||
// delete temp dir
|
|
||||||
await fs.remove(tempDir);
|
await fs.remove(tempDir);
|
||||||
|
|
||||||
console.log(`[INFO]: resolve wintun.dll finished`);
|
console.log(`[INFO]: resolve wintun.dll finished`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* only Windows
|
||||||
|
* get the clash-verge-service.exe
|
||||||
|
*/
|
||||||
|
async function resolveService() {
|
||||||
|
const { platform } = process;
|
||||||
|
|
||||||
|
if (platform !== "win32") return;
|
||||||
|
|
||||||
|
const resDir = path.join(cwd, "src-tauri/resources");
|
||||||
|
|
||||||
|
const repo =
|
||||||
|
"https://github.com/zzzgydi/clash-verge-service/releases/download/latest";
|
||||||
|
|
||||||
|
async function help(bin) {
|
||||||
|
const targetPath = path.join(resDir, bin);
|
||||||
|
|
||||||
|
if (!FORCE && (await fs.pathExists(targetPath))) return;
|
||||||
|
|
||||||
|
const url = `${repo}/${bin}`;
|
||||||
|
await downloadFile(url, targetPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
await fs.mkdirp(resDir);
|
||||||
|
await help("clash-verge-service.exe");
|
||||||
|
await help("install-service.exe");
|
||||||
|
await help("uninstall-service.exe");
|
||||||
|
|
||||||
|
console.log(`[INFO]: resolve Service finished`);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* get the Country.mmdb (not required)
|
* get the Country.mmdb (not required)
|
||||||
*/
|
*/
|
||||||
async function resolveMmdb() {
|
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/download/20220512/Country.mmdb";
|
||||||
|
|
||||||
const resDir = path.join(cwd, "src-tauri", "resources");
|
const resDir = path.join(cwd, "src-tauri", "resources");
|
||||||
const resPath = path.join(resDir, "Country.mmdb");
|
const resPath = path.join(resDir, "Country.mmdb");
|
||||||
|
|
||||||
if (!FORCE && (await fs.pathExists(resPath))) return;
|
if (!FORCE && (await fs.pathExists(resPath))) return;
|
||||||
|
|
||||||
await fs.mkdirp(resDir);
|
await fs.mkdirp(resDir);
|
||||||
await downloadFile(url, resPath);
|
await downloadFile(url, resPath);
|
||||||
}
|
}
|
||||||
@@ -153,7 +272,20 @@ async function resolveMmdb() {
|
|||||||
async function downloadFile(url, path) {
|
async function downloadFile(url, path) {
|
||||||
console.log(`[INFO]: downloading from "${url}"`);
|
console.log(`[INFO]: downloading from "${url}"`);
|
||||||
|
|
||||||
|
const options = {};
|
||||||
|
|
||||||
|
const httpProxy =
|
||||||
|
process.env.HTTP_PROXY ||
|
||||||
|
process.env.http_proxy ||
|
||||||
|
process.env.HTTPS_PROXY ||
|
||||||
|
process.env.https_proxy;
|
||||||
|
|
||||||
|
if (httpProxy) {
|
||||||
|
options.agent = proxyAgent(httpProxy);
|
||||||
|
}
|
||||||
|
|
||||||
const response = await fetch(url, {
|
const response = await fetch(url, {
|
||||||
|
...options,
|
||||||
method: "GET",
|
method: "GET",
|
||||||
headers: { "Content-Type": "application/octet-stream" },
|
headers: { "Content-Type": "application/octet-stream" },
|
||||||
});
|
});
|
||||||
@@ -167,3 +299,4 @@ async function downloadFile(url, path) {
|
|||||||
resolveSidecar().catch(console.error);
|
resolveSidecar().catch(console.error);
|
||||||
resolveWintun().catch(console.error);
|
resolveWintun().catch(console.error);
|
||||||
resolveMmdb().catch(console.error);
|
resolveMmdb().catch(console.error);
|
||||||
|
resolveService().catch(console.error);
|
||||||
|
|||||||
@@ -1,56 +0,0 @@
|
|||||||
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);
|
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
import fs from "fs-extra";
|
||||||
|
import path from "path";
|
||||||
|
import AdmZip from "adm-zip";
|
||||||
|
import { createRequire } from "module";
|
||||||
|
import { getOctokit, context } from "@actions/github";
|
||||||
|
|
||||||
|
const META = process.argv.includes("--meta"); // use Clash.Meta
|
||||||
|
|
||||||
|
/// Script for ci
|
||||||
|
/// 打包绿色版/便携版 (only Windows)
|
||||||
|
async function resolvePortable() {
|
||||||
|
if (process.platform !== "win32") return;
|
||||||
|
|
||||||
|
const releaseDir = "./src-tauri/target/release";
|
||||||
|
|
||||||
|
if (!(await fs.pathExists(releaseDir))) {
|
||||||
|
throw new Error("could not found the release dir");
|
||||||
|
}
|
||||||
|
|
||||||
|
const zip = new AdmZip();
|
||||||
|
|
||||||
|
zip.addLocalFile(path.join(releaseDir, "Clash Verge.exe"));
|
||||||
|
zip.addLocalFile(path.join(releaseDir, "clash.exe"));
|
||||||
|
zip.addLocalFolder(path.join(releaseDir, "resources"), "resources");
|
||||||
|
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const packageJson = require("../package.json");
|
||||||
|
const { version } = packageJson;
|
||||||
|
|
||||||
|
const zipFile = `Clash.Verge_${version}_x64_portable.zip`;
|
||||||
|
zip.writeZip(zipFile);
|
||||||
|
|
||||||
|
console.log("[INFO]: create portable zip successfully");
|
||||||
|
|
||||||
|
// push release assets
|
||||||
|
if (process.env.GITHUB_TOKEN === undefined) {
|
||||||
|
throw new Error("GITHUB_TOKEN is required");
|
||||||
|
}
|
||||||
|
|
||||||
|
const options = { owner: context.repo.owner, repo: context.repo.repo };
|
||||||
|
const github = getOctokit(process.env.GITHUB_TOKEN);
|
||||||
|
|
||||||
|
const { data: release } = await github.rest.repos.getReleaseByTag({
|
||||||
|
...options,
|
||||||
|
tag: `v${version}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(release.name);
|
||||||
|
|
||||||
|
await github.rest.repos.uploadReleaseAsset({
|
||||||
|
...options,
|
||||||
|
release_id: release.id,
|
||||||
|
name: zipFile,
|
||||||
|
data: zip.toBuffer(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 打包包含Clash.Meta的 (only Windows)
|
||||||
|
async function resolvePortableMeta() {
|
||||||
|
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.addLocalFile(path.join(releaseDir, "clash-meta.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.Meta_${version}_x64_portable.zip`;
|
||||||
|
zip.writeZip(zipFile);
|
||||||
|
|
||||||
|
console.log("[INFO]: create portable zip successfully");
|
||||||
|
|
||||||
|
// push release assets
|
||||||
|
if (process.env.GITHUB_TOKEN === undefined) {
|
||||||
|
throw new Error("GITHUB_TOKEN is required");
|
||||||
|
}
|
||||||
|
|
||||||
|
const options = { owner: context.repo.owner, repo: context.repo.repo };
|
||||||
|
const github = getOctokit(process.env.GITHUB_TOKEN);
|
||||||
|
|
||||||
|
const { data: release } = await github.rest.repos.getReleaseByTag({
|
||||||
|
...options,
|
||||||
|
tag: `v${version}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(release.name);
|
||||||
|
|
||||||
|
await github.rest.repos.uploadReleaseAsset({
|
||||||
|
...options,
|
||||||
|
release_id: release.id,
|
||||||
|
name: zipFile,
|
||||||
|
data: zip.toBuffer(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (META) resolvePortableMeta().catch(console.error);
|
||||||
|
else resolvePortable().catch(console.error);
|
||||||
@@ -8,7 +8,7 @@ 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
|
||||||
async function resolveRelease() {
|
async function resolveUpdater() {
|
||||||
if (process.env.GITHUB_TOKEN === undefined) {
|
if (process.env.GITHUB_TOKEN === undefined) {
|
||||||
throw new Error("GITHUB_TOKEN is required");
|
throw new Error("GITHUB_TOKEN is required");
|
||||||
}
|
}
|
||||||
@@ -38,9 +38,14 @@ async function resolveRelease() {
|
|||||||
notes: await resolveUpdateLog(tag.name), // use updatelog.md
|
notes: await resolveUpdateLog(tag.name), // use updatelog.md
|
||||||
pub_date: new Date().toISOString(),
|
pub_date: new Date().toISOString(),
|
||||||
platforms: {
|
platforms: {
|
||||||
win64: { signature: "", url: "" },
|
win64: { signature: "", url: "" }, // compatible with older formats
|
||||||
linux: { signature: "", url: "" },
|
linux: { signature: "", url: "" }, // compatible with older formats
|
||||||
darwin: { signature: "", url: "" },
|
darwin: { signature: "", url: "" }, // compatible with older formats
|
||||||
|
"darwin-aarch64": { signature: "", url: "" },
|
||||||
|
"darwin-intel": { signature: "", url: "" },
|
||||||
|
"linux-x86_64": { signature: "", url: "" },
|
||||||
|
"windows-x86_64": { signature: "", url: "" },
|
||||||
|
"windows-i686": { signature: "", url: "" }, // no supported
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -48,36 +53,49 @@ async function resolveRelease() {
|
|||||||
const { name, browser_download_url } = asset;
|
const { name, browser_download_url } = asset;
|
||||||
|
|
||||||
// win64 url
|
// win64 url
|
||||||
if (/\.msi\.zip$/.test(name)) {
|
if (name.endsWith(".msi.zip")) {
|
||||||
updateData.platforms.win64.url = browser_download_url;
|
updateData.platforms.win64.url = browser_download_url;
|
||||||
|
updateData.platforms["windows-x86_64"].url = browser_download_url;
|
||||||
}
|
}
|
||||||
// win64 signature
|
// win64 signature
|
||||||
if (/\.msi\.zip\.sig$/.test(name)) {
|
if (name.endsWith(".msi.zip.sig")) {
|
||||||
updateData.platforms.win64.signature = await getSignature(
|
const sig = await getSignature(browser_download_url);
|
||||||
browser_download_url
|
updateData.platforms.win64.signature = sig;
|
||||||
);
|
updateData.platforms["windows-x86_64"].signature = sig;
|
||||||
}
|
}
|
||||||
|
|
||||||
// darwin url
|
// darwin url (intel)
|
||||||
if (/\.app\.tar\.gz$/.test(name)) {
|
if (name.endsWith(".app.tar.gz") && !name.includes("aarch")) {
|
||||||
updateData.platforms.darwin.url = browser_download_url;
|
updateData.platforms.darwin.url = browser_download_url;
|
||||||
|
updateData.platforms["darwin-intel"].url = browser_download_url;
|
||||||
}
|
}
|
||||||
// darwin signature
|
// darwin signature (intel)
|
||||||
if (/\.app\.tar\.gz\.sig$/.test(name)) {
|
if (name.endsWith(".app.tar.gz.sig") && !name.includes("aarch")) {
|
||||||
updateData.platforms.darwin.signature = await getSignature(
|
const sig = await getSignature(browser_download_url);
|
||||||
browser_download_url
|
updateData.platforms.darwin.signature = sig;
|
||||||
);
|
updateData.platforms["darwin-intel"].signature = sig;
|
||||||
|
}
|
||||||
|
|
||||||
|
// darwin url (aarch)
|
||||||
|
if (name.endsWith("aarch.app.tar.gz")) {
|
||||||
|
updateData.platforms["darwin-aarch64"].url = browser_download_url;
|
||||||
|
}
|
||||||
|
// darwin signature (aarch)
|
||||||
|
if (name.endsWith("aarch.app.tar.gz.sig")) {
|
||||||
|
const sig = await getSignature(browser_download_url);
|
||||||
|
updateData.platforms["darwin-aarch64"].signature = sig;
|
||||||
}
|
}
|
||||||
|
|
||||||
// linux url
|
// linux url
|
||||||
if (/\.AppImage\.tar\.gz$/.test(name)) {
|
if (name.endsWith(".AppImage.tar.gz")) {
|
||||||
updateData.platforms.linux.url = browser_download_url;
|
updateData.platforms.linux.url = browser_download_url;
|
||||||
|
updateData.platforms["linux-x86_64"].url = browser_download_url;
|
||||||
}
|
}
|
||||||
// linux signature
|
// linux signature
|
||||||
if (/\.AppImage\.tar\.gz\.sig$/.test(name)) {
|
if (name.endsWith(".AppImage.tar.gz.sig")) {
|
||||||
updateData.platforms.linux.signature = await getSignature(
|
const sig = await getSignature(browser_download_url);
|
||||||
browser_download_url
|
updateData.platforms.linux.signature = sig;
|
||||||
);
|
updateData.platforms["linux-x86_64"].signature = sig;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -85,29 +103,24 @@ async function resolveRelease() {
|
|||||||
console.log(updateData);
|
console.log(updateData);
|
||||||
|
|
||||||
// maybe should test the signature as well
|
// maybe should test the signature as well
|
||||||
const { darwin, win64, linux } = updateData.platforms;
|
// delete the null field
|
||||||
if (!darwin.url) {
|
Object.entries(updateData.platforms).forEach(([key, value]) => {
|
||||||
console.log(`[Error]: failed to parse release for darwin`);
|
if (!value.url) {
|
||||||
delete updateData.platforms.darwin;
|
console.log(`[Error]: failed to parse release for "${key}"`);
|
||||||
}
|
delete updateData.platforms[key];
|
||||||
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的更新文件
|
// 生成一个代理github的更新文件
|
||||||
// 使用 https://hub.fastgit.xyz/ 做github资源的加速
|
// 使用 https://hub.fastgit.xyz/ 做github资源的加速
|
||||||
const updateDataNew = JSON.parse(JSON.stringify(updateData));
|
const updateDataNew = JSON.parse(JSON.stringify(updateData));
|
||||||
|
|
||||||
Object.keys(updateDataNew.platforms).forEach((key) => {
|
Object.entries(updateDataNew.platforms).forEach(([key, value]) => {
|
||||||
if (updateDataNew.platforms[key]) {
|
if (value.url) {
|
||||||
updateDataNew.platforms[key].url = updateDataNew.platforms[
|
updateDataNew.platforms[key].url = value.url.replace(
|
||||||
key
|
"https://github.com/",
|
||||||
].url.replace("https://github.com/", "https://hub.fastgit.xyz/");
|
"https://hub.fastgit.xyz/"
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
console.log(`[Error]: updateDataNew.platforms.${key} is null`);
|
console.log(`[Error]: updateDataNew.platforms.${key} is null`);
|
||||||
}
|
}
|
||||||
@@ -135,7 +148,7 @@ async function resolveRelease() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// upload assets
|
// upload new assets
|
||||||
await github.rest.repos.uploadReleaseAsset({
|
await github.rest.repos.uploadReleaseAsset({
|
||||||
...options,
|
...options,
|
||||||
release_id: updateRelease.id,
|
release_id: updateRelease.id,
|
||||||
@@ -161,4 +174,4 @@ async function getSignature(url) {
|
|||||||
return response.text();
|
return response.text();
|
||||||
}
|
}
|
||||||
|
|
||||||
resolveRelease().catch(console.error);
|
resolveUpdater().catch(console.error);
|
||||||
@@ -10,38 +10,43 @@ edition = "2021"
|
|||||||
build = "build.rs"
|
build = "build.rs"
|
||||||
|
|
||||||
[build-dependencies]
|
[build-dependencies]
|
||||||
tauri-build = { version = "1.0.0-rc.4", features = [] }
|
tauri-build = { version = "1.0.0-rc.12", features = [] }
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
warp = "0.3"
|
||||||
|
which = "4.2.2"
|
||||||
anyhow = "1.0"
|
anyhow = "1.0"
|
||||||
dirs = "4.0.0"
|
dirs = "4.0.0"
|
||||||
open = "2.1.1"
|
open = "2.1.1"
|
||||||
|
log = "0.4.14"
|
||||||
dunce = "1.0.2"
|
dunce = "1.0.2"
|
||||||
|
log4rs = "1.0.0"
|
||||||
nanoid = "0.4.0"
|
nanoid = "0.4.0"
|
||||||
chrono = "0.4.19"
|
chrono = "0.4.19"
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
serde_yaml = "0.8"
|
serde_yaml = "0.8"
|
||||||
serde = { version = "1.0", features = ["derive"] }
|
|
||||||
tauri = { version = "1.0.0-rc.4", features = ["process-all", "shell-all", "system-tray", "updater", "window-all"] }
|
|
||||||
window-shadows = { git = "https://github.com/tauri-apps/window-shadows" }
|
|
||||||
window-vibrancy = { git = "https://github.com/tauri-apps/window-vibrancy" }
|
|
||||||
|
|
||||||
reqwest = { version = "0.11", features = ["json"] }
|
|
||||||
tokio = { version = "1", features = ["full"] }
|
|
||||||
log = "0.4.14"
|
|
||||||
log4rs = "1.0.0"
|
|
||||||
warp = "0.3"
|
|
||||||
which = "4.2.2"
|
|
||||||
auto-launch = "0.2"
|
auto-launch = "0.2"
|
||||||
port_scanner = "0.1.5"
|
port_scanner = "0.1.5"
|
||||||
|
delay_timer = "0.11.1"
|
||||||
|
parking_lot = "0.12.0"
|
||||||
|
tokio = { version = "1", features = ["full"] }
|
||||||
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
|
reqwest = { version = "0.11", features = ["json"] }
|
||||||
|
tauri = { version = "1.0.0-rc.14", features = ["process-all", "shell-all", "system-tray", "updater", "window-all"] }
|
||||||
|
window-shadows = { version = "0.1" }
|
||||||
|
window-vibrancy = { version = "0.1" }
|
||||||
|
|
||||||
[target.'cfg(windows)'.dependencies]
|
[target.'cfg(windows)'.dependencies]
|
||||||
|
runas = "0.2.1"
|
||||||
|
deelevate = "0.2.0"
|
||||||
winreg = { version = "0.10", features = ["transactions"] }
|
winreg = { version = "0.10", features = ["transactions"] }
|
||||||
|
windows-sys = { version = "0.36", features = ["Win32_System_LibraryLoader", "Win32_System_SystemInformation"] }
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = [ "custom-protocol" ]
|
default = ["custom-protocol", "tauri/ayatana-tray"]
|
||||||
custom-protocol = [ "tauri/custom-protocol" ]
|
custom-protocol = ["tauri/custom-protocol"]
|
||||||
verge-dev = []
|
verge-dev = []
|
||||||
|
debug-yml = []
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
panic = "abort"
|
panic = "abort"
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 33 KiB |
|
Before Width: | Height: | Size: 4.2 KiB After Width: | Height: | Size: 33 KiB |
|
After Width: | Height: | Size: 4.2 KiB |
|
After Width: | Height: | Size: 12 KiB |
@@ -1,26 +1,25 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
core::{ClashInfo, PrfItem, PrfOption, Profiles, VergeConfig},
|
core::{ClashInfo, Core, PrfItem, PrfOption, Profiles, Verge},
|
||||||
states::{ClashState, ProfilesState, VergeState},
|
utils::{dirs, help, sysopt::SysProxyConfig},
|
||||||
utils::{dirs, sysopt::SysProxyConfig},
|
|
||||||
};
|
};
|
||||||
use crate::{ret_err, wrap_err};
|
use crate::{log_if_err, ret_err, wrap_err};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use serde_yaml::Mapping;
|
use serde_yaml::Mapping;
|
||||||
use std::process::Command;
|
use tauri::{api, State};
|
||||||
use tauri::{api, Manager, State};
|
|
||||||
|
type CmdResult<T = ()> = Result<T, String>;
|
||||||
|
|
||||||
/// get all profiles from `profiles.yaml`
|
/// get all profiles from `profiles.yaml`
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn get_profiles<'a>(profiles_state: State<'_, ProfilesState>) -> Result<Profiles, String> {
|
pub fn get_profiles(core: State<'_, Core>) -> CmdResult<Profiles> {
|
||||||
let profiles = profiles_state.0.lock().unwrap();
|
let profiles = core.profiles.lock();
|
||||||
Ok(profiles.clone())
|
Ok(profiles.clone())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// synchronize data irregularly
|
/// manually exec enhanced profile
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn sync_profiles(profiles_state: State<'_, ProfilesState>) -> Result<(), String> {
|
pub fn enhance_profiles(core: State<'_, Core>) -> CmdResult {
|
||||||
let mut profiles = profiles_state.0.lock().unwrap();
|
wrap_err!(core.activate_enhanced(false))
|
||||||
wrap_err!(profiles.sync_file())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// import the profile from url
|
/// import the profile from url
|
||||||
@@ -29,11 +28,11 @@ pub fn sync_profiles(profiles_state: State<'_, ProfilesState>) -> Result<(), Str
|
|||||||
pub async fn import_profile(
|
pub async fn import_profile(
|
||||||
url: String,
|
url: String,
|
||||||
option: Option<PrfOption>,
|
option: Option<PrfOption>,
|
||||||
profiles_state: State<'_, ProfilesState>,
|
core: State<'_, Core>,
|
||||||
) -> Result<(), String> {
|
) -> CmdResult {
|
||||||
let item = wrap_err!(PrfItem::from_url(&url, None, None, option).await)?;
|
let item = wrap_err!(PrfItem::from_url(&url, None, None, option).await)?;
|
||||||
|
|
||||||
let mut profiles = profiles_state.0.lock().unwrap();
|
let mut profiles = core.profiles.lock();
|
||||||
wrap_err!(profiles.append_item(item))
|
wrap_err!(profiles.append_item(item))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -44,11 +43,11 @@ pub async fn import_profile(
|
|||||||
pub async fn create_profile(
|
pub async fn create_profile(
|
||||||
item: PrfItem, // partial
|
item: PrfItem, // partial
|
||||||
file_data: Option<String>,
|
file_data: Option<String>,
|
||||||
profiles_state: State<'_, ProfilesState>,
|
core: State<'_, Core>,
|
||||||
) -> Result<(), String> {
|
) -> CmdResult {
|
||||||
let item = wrap_err!(PrfItem::from(item, file_data).await)?;
|
let item = wrap_err!(PrfItem::from(item, file_data).await)?;
|
||||||
let mut profiles = profiles_state.0.lock().unwrap();
|
|
||||||
|
|
||||||
|
let mut profiles = core.profiles.lock();
|
||||||
wrap_err!(profiles.append_item(item))
|
wrap_err!(profiles.append_item(item))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,101 +56,53 @@ pub async fn create_profile(
|
|||||||
pub async fn update_profile(
|
pub async fn update_profile(
|
||||||
index: String,
|
index: String,
|
||||||
option: Option<PrfOption>,
|
option: Option<PrfOption>,
|
||||||
clash_state: State<'_, ClashState>,
|
core: State<'_, Core>,
|
||||||
profiles_state: State<'_, ProfilesState>,
|
) -> CmdResult {
|
||||||
) -> Result<(), String> {
|
wrap_err!(Core::update_profile_item(core.inner().clone(), index, option).await)
|
||||||
let (url, opt) = {
|
|
||||||
// must release the lock here
|
|
||||||
let profiles = profiles_state.0.lock().unwrap();
|
|
||||||
let item = wrap_err!(profiles.get_item(&index))?;
|
|
||||||
|
|
||||||
// check the profile type
|
|
||||||
if let Some(typ) = item.itype.as_ref() {
|
|
||||||
if *typ != "remote" {
|
|
||||||
ret_err!(format!("could not update the `{typ}` profile"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if item.url.is_none() {
|
|
||||||
ret_err!("failed to get the item url");
|
|
||||||
}
|
|
||||||
|
|
||||||
(item.url.clone().unwrap(), item.option.clone())
|
|
||||||
};
|
|
||||||
|
|
||||||
let fetch_opt = PrfOption::merge(opt, option);
|
|
||||||
let item = wrap_err!(PrfItem::from_url(&url, None, None, fetch_opt).await)?;
|
|
||||||
|
|
||||||
let mut profiles = profiles_state.0.lock().unwrap();
|
|
||||||
wrap_err!(profiles.update_item(index.clone(), item))?;
|
|
||||||
|
|
||||||
// reactivate the profile
|
|
||||||
if Some(index) == profiles.get_current() {
|
|
||||||
let clash = clash_state.0.lock().unwrap();
|
|
||||||
wrap_err!(clash.activate_enhanced(&profiles, false, false))?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// change the current profile
|
/// change the current profile
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn select_profile(
|
pub fn select_profile(index: String, core: State<'_, Core>) -> CmdResult {
|
||||||
index: String,
|
let mut profiles = core.profiles.lock();
|
||||||
clash_state: State<'_, ClashState>,
|
|
||||||
profiles_state: State<'_, ProfilesState>,
|
|
||||||
) -> Result<(), String> {
|
|
||||||
let mut profiles = profiles_state.0.lock().unwrap();
|
|
||||||
wrap_err!(profiles.put_current(index))?;
|
wrap_err!(profiles.put_current(index))?;
|
||||||
|
|
||||||
let clash = clash_state.0.lock().unwrap();
|
drop(profiles);
|
||||||
wrap_err!(clash.activate_enhanced(&profiles, false, false))
|
|
||||||
|
wrap_err!(core.activate_enhanced(false))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// change the profile chain
|
/// change the profile chain
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn change_profile_chain(
|
pub fn change_profile_chain(chain: Option<Vec<String>>, core: State<'_, Core>) -> CmdResult {
|
||||||
chain: Option<Vec<String>>,
|
let mut profiles = core.profiles.lock();
|
||||||
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);
|
profiles.put_chain(chain);
|
||||||
clash.set_window(app_handle.get_window("main"));
|
|
||||||
|
|
||||||
wrap_err!(clash.activate_enhanced(&profiles, false, false))
|
drop(profiles);
|
||||||
|
|
||||||
|
wrap_err!(core.activate_enhanced(false))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// manually exec enhanced profile
|
/// change the profile valid fields
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn enhance_profiles(
|
pub fn change_profile_valid(valid: Option<Vec<String>>, core: State<Core>) -> CmdResult {
|
||||||
app_handle: tauri::AppHandle,
|
let mut profiles = core.profiles.lock();
|
||||||
clash_state: State<'_, ClashState>,
|
profiles.put_valid(valid);
|
||||||
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"));
|
drop(profiles);
|
||||||
|
|
||||||
wrap_err!(clash.activate_enhanced(&profiles, false, false))
|
wrap_err!(core.activate_enhanced(false))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// delete profile item
|
/// delete profile item
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn delete_profile(
|
pub fn delete_profile(index: String, core: State<'_, Core>) -> CmdResult {
|
||||||
index: String,
|
let mut profiles = core.profiles.lock();
|
||||||
clash_state: State<'_, ClashState>,
|
|
||||||
profiles_state: State<'_, ProfilesState>,
|
|
||||||
) -> Result<(), String> {
|
|
||||||
let mut profiles = profiles_state.0.lock().unwrap();
|
|
||||||
|
|
||||||
if wrap_err!(profiles.delete_item(index))? {
|
if wrap_err!(profiles.delete_item(index))? {
|
||||||
let clash = clash_state.0.lock().unwrap();
|
drop(profiles);
|
||||||
wrap_err!(clash.activate_enhanced(&profiles, false, false))?;
|
|
||||||
|
log_if_err!(core.activate_enhanced(false));
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -159,19 +110,20 @@ pub fn delete_profile(
|
|||||||
|
|
||||||
/// patch the profile config
|
/// patch the profile config
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn patch_profile(
|
pub fn patch_profile(index: String, profile: PrfItem, core: State<'_, Core>) -> CmdResult {
|
||||||
index: String,
|
let mut profiles = core.profiles.lock();
|
||||||
profile: PrfItem,
|
wrap_err!(profiles.patch_item(index, profile))?;
|
||||||
profiles_state: State<'_, ProfilesState>,
|
drop(profiles);
|
||||||
) -> Result<(), String> {
|
|
||||||
let mut profiles = profiles_state.0.lock().unwrap();
|
// update cron task
|
||||||
wrap_err!(profiles.patch_item(index, profile))
|
let mut timer = core.timer.lock();
|
||||||
|
wrap_err!(timer.refresh())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// run vscode command to edit the profile
|
/// run vscode command to edit the profile
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn view_profile(index: String, profiles_state: State<'_, ProfilesState>) -> Result<(), String> {
|
pub fn view_profile(index: String, core: State<'_, Core>) -> CmdResult {
|
||||||
let profiles = profiles_state.0.lock().unwrap();
|
let profiles = core.profiles.lock();
|
||||||
let item = wrap_err!(profiles.get_item(&index))?;
|
let item = wrap_err!(profiles.get_item(&index))?;
|
||||||
|
|
||||||
let file = item.file.clone();
|
let file = item.file.clone();
|
||||||
@@ -184,41 +136,14 @@ pub fn view_profile(index: String, profiles_state: State<'_, ProfilesState>) ->
|
|||||||
ret_err!("the file not found");
|
ret_err!("the file not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
// use vscode first
|
wrap_err!(help::open_file(path))
|
||||||
if let Ok(code) = which::which("code") {
|
|
||||||
#[cfg(target_os = "windows")]
|
|
||||||
{
|
|
||||||
use std::os::windows::process::CommandExt;
|
|
||||||
|
|
||||||
if let Err(err) = Command::new(code)
|
|
||||||
.creation_flags(0x08000000)
|
|
||||||
.arg(path)
|
|
||||||
.spawn()
|
|
||||||
{
|
|
||||||
log::error!("failed to open file by VScode for {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!("failed to open file by VScode for {err}");
|
|
||||||
return Err("failed to open file by VScode".into());
|
|
||||||
}
|
|
||||||
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
wrap_err!(open::that(path))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// read the profile item file data
|
/// read the profile item file data
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn read_profile_file(
|
pub fn read_profile_file(index: String, core: State<'_, Core>) -> CmdResult<String> {
|
||||||
index: String,
|
let profiles = core.profiles.lock();
|
||||||
profiles_state: State<'_, ProfilesState>,
|
|
||||||
) -> Result<String, String> {
|
|
||||||
let profiles = profiles_state.0.lock().unwrap();
|
|
||||||
let item = wrap_err!(profiles.get_item(&index))?;
|
let item = wrap_err!(profiles.get_item(&index))?;
|
||||||
let data = wrap_err!(item.read_file())?;
|
let data = wrap_err!(item.read_file())?;
|
||||||
|
|
||||||
@@ -230,34 +155,22 @@ pub fn read_profile_file(
|
|||||||
pub fn save_profile_file(
|
pub fn save_profile_file(
|
||||||
index: String,
|
index: String,
|
||||||
file_data: Option<String>,
|
file_data: Option<String>,
|
||||||
profiles_state: State<'_, ProfilesState>,
|
core: State<'_, Core>,
|
||||||
) -> Result<(), String> {
|
) -> CmdResult {
|
||||||
if file_data.is_none() {
|
if file_data.is_none() {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
let profiles = profiles_state.0.lock().unwrap();
|
let profiles = core.profiles.lock();
|
||||||
let item = wrap_err!(profiles.get_item(&index))?;
|
let item = wrap_err!(profiles.get_item(&index))?;
|
||||||
wrap_err!(item.save_file(file_data.unwrap()))
|
wrap_err!(item.save_file(file_data.unwrap()))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// restart the sidecar
|
|
||||||
#[tauri::command]
|
|
||||||
pub fn restart_sidecar(
|
|
||||||
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();
|
|
||||||
|
|
||||||
wrap_err!(clash.restart_sidecar(&mut profiles))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 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(core: State<'_, Core>) -> CmdResult<ClashInfo> {
|
||||||
let clash = clash_state.0.lock().unwrap();
|
let clash = core.clash.lock();
|
||||||
Ok(clash.info.clone())
|
Ok(clash.info.clone())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -265,16 +178,44 @@ pub fn get_clash_info(clash_state: State<'_, ClashState>) -> Result<ClashInfo, S
|
|||||||
/// after putting the change to the clash core
|
/// after putting the change to the clash core
|
||||||
/// then we should save the latest config
|
/// then we should save the latest config
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn patch_clash_config(
|
pub fn patch_clash_config(payload: Mapping, core: State<'_, Core>) -> CmdResult {
|
||||||
payload: Mapping,
|
wrap_err!(core.patch_clash(payload))
|
||||||
clash_state: State<'_, ClashState>,
|
}
|
||||||
verge_state: State<'_, VergeState>,
|
|
||||||
profiles_state: State<'_, ProfilesState>,
|
/// get the verge config
|
||||||
) -> Result<(), String> {
|
#[tauri::command]
|
||||||
let mut clash = clash_state.0.lock().unwrap();
|
pub fn get_verge_config(core: State<'_, Core>) -> CmdResult<Verge> {
|
||||||
let mut verge = verge_state.0.lock().unwrap();
|
let verge = core.verge.lock();
|
||||||
let mut profiles = profiles_state.0.lock().unwrap();
|
Ok(verge.clone())
|
||||||
wrap_err!(clash.patch_config(payload, &mut verge, &mut profiles))
|
}
|
||||||
|
|
||||||
|
/// patch the verge config
|
||||||
|
/// this command only save the config and not responsible for other things
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn patch_verge_config(
|
||||||
|
payload: Verge,
|
||||||
|
app_handle: tauri::AppHandle,
|
||||||
|
core: State<'_, Core>,
|
||||||
|
) -> CmdResult {
|
||||||
|
wrap_err!(core.patch_verge(payload, &app_handle))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// change clash core
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn change_clash_core(core: State<'_, Core>, clash_core: Option<String>) -> CmdResult {
|
||||||
|
wrap_err!(core.change_core(clash_core))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// restart the sidecar
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn restart_sidecar(core: State<'_, Core>) -> CmdResult {
|
||||||
|
wrap_err!(core.restart_clash())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// kill all sidecars when update app
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn kill_sidecar() {
|
||||||
|
api::process::kill_children();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// get the system proxy
|
/// get the system proxy
|
||||||
@@ -286,66 +227,9 @@ pub fn get_sys_proxy() -> Result<SysProxyConfig, 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(core: State<'_, Core>) -> CmdResult<Option<SysProxyConfig>> {
|
||||||
let verge = verge_state.0.lock().unwrap();
|
let sysopt = core.sysopt.lock();
|
||||||
Ok(verge.cur_sysproxy.clone())
|
wrap_err!(sysopt.get_sysproxy())
|
||||||
}
|
|
||||||
|
|
||||||
/// get the verge config
|
|
||||||
#[tauri::command]
|
|
||||||
pub fn get_verge_config(verge_state: State<'_, VergeState>) -> Result<VergeConfig, String> {
|
|
||||||
let verge = verge_state.0.lock().unwrap();
|
|
||||||
let mut config = verge.config.clone();
|
|
||||||
|
|
||||||
if config.system_proxy_bypass.is_none() && verge.cur_sysproxy.is_some() {
|
|
||||||
config.system_proxy_bypass = Some(verge.cur_sysproxy.clone().unwrap().bypass)
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(config)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// patch the verge config
|
|
||||||
/// this command only save the config and not responsible for other things
|
|
||||||
#[tauri::command]
|
|
||||||
pub fn patch_verge_config(
|
|
||||||
payload: VergeConfig,
|
|
||||||
app_handle: tauri::AppHandle,
|
|
||||||
clash_state: State<'_, ClashState>,
|
|
||||||
verge_state: State<'_, VergeState>,
|
|
||||||
profiles_state: State<'_, ProfilesState>,
|
|
||||||
) -> 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_enhanced(&profiles, false, false))?;
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut verge = verge_state.0.lock().unwrap();
|
|
||||||
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
|
/// open app config dir
|
||||||
@@ -361,3 +245,68 @@ pub fn open_logs_dir() -> Result<(), String> {
|
|||||||
let log_dir = dirs::app_logs_dir();
|
let log_dir = dirs::app_logs_dir();
|
||||||
wrap_err!(open::that(log_dir))
|
wrap_err!(open::that(log_dir))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// service mode
|
||||||
|
#[cfg(windows)]
|
||||||
|
pub mod service {
|
||||||
|
use super::*;
|
||||||
|
use crate::core::win_service::JsonResponse;
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn start_service() -> Result<(), String> {
|
||||||
|
wrap_err!(crate::core::Service::start_service().await)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn stop_service() -> Result<(), String> {
|
||||||
|
wrap_err!(crate::core::Service::stop_service().await)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn check_service() -> Result<JsonResponse, String> {
|
||||||
|
// no log
|
||||||
|
match crate::core::Service::check_service().await {
|
||||||
|
Ok(res) => Ok(res),
|
||||||
|
Err(err) => Err(err.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn install_service() -> Result<(), String> {
|
||||||
|
wrap_err!(crate::core::Service::install_service().await)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn uninstall_service() -> Result<(), String> {
|
||||||
|
wrap_err!(crate::core::Service::uninstall_service().await)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
pub mod service {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn start_service() -> Result<(), String> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn stop_service() -> Result<(), String> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn check_service() -> Result<(), String> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn install_service() -> Result<(), String> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn uninstall_service() -> Result<(), String> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,14 +1,7 @@
|
|||||||
use super::{PrfEnhancedResult, Profiles, Verge};
|
use crate::utils::{config, dirs};
|
||||||
use crate::log_if_err;
|
use anyhow::Result;
|
||||||
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::Window;
|
|
||||||
use tokio::time::sleep;
|
|
||||||
|
|
||||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||||
pub struct ClashInfo {
|
pub struct ClashInfo {
|
||||||
@@ -25,56 +18,16 @@ pub struct ClashInfo {
|
|||||||
pub secret: Option<String>,
|
pub secret: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct Clash {
|
impl ClashInfo {
|
||||||
/// maintain the clash config
|
|
||||||
pub config: Mapping,
|
|
||||||
|
|
||||||
/// some info
|
|
||||||
pub info: ClashInfo,
|
|
||||||
|
|
||||||
/// clash sidecar
|
|
||||||
pub sidecar: Option<CommandChild>,
|
|
||||||
|
|
||||||
/// save the main window
|
|
||||||
pub window: Option<Window>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Clash {
|
|
||||||
pub fn new() -> Clash {
|
|
||||||
let config = Clash::read_config();
|
|
||||||
let info = Clash::get_info(&config);
|
|
||||||
|
|
||||||
Clash {
|
|
||||||
config,
|
|
||||||
info,
|
|
||||||
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 {
|
pub fn from(config: &Mapping) -> ClashInfo {
|
||||||
let key_port_1 = Value::String("port".to_string());
|
let key_port_1 = Value::from("port");
|
||||||
let key_port_2 = Value::String("mixed-port".to_string());
|
let key_port_2 = Value::from("mixed-port");
|
||||||
let key_server = Value::String("external-controller".to_string());
|
let key_server = Value::from("external-controller");
|
||||||
let key_secret = Value::String("secret".to_string());
|
let key_secret = Value::from("secret");
|
||||||
|
|
||||||
let port = match clash_config.get(&key_port_1) {
|
let port = match config.get(&key_port_1) {
|
||||||
Some(value) => match value {
|
Some(value) => match value {
|
||||||
Value::String(val_str) => Some(val_str.clone()),
|
Value::String(val_str) => Some(val_str.clone()),
|
||||||
Value::Number(val_num) => Some(val_num.to_string()),
|
Value::Number(val_num) => Some(val_num.to_string()),
|
||||||
@@ -84,7 +37,7 @@ impl Clash {
|
|||||||
};
|
};
|
||||||
let port = match port {
|
let port = match port {
|
||||||
Some(_) => port,
|
Some(_) => port,
|
||||||
None => match clash_config.get(&key_port_2) {
|
None => match config.get(&key_port_2) {
|
||||||
Some(value) => match value {
|
Some(value) => match value {
|
||||||
Value::String(val_str) => Some(val_str.clone()),
|
Value::String(val_str) => Some(val_str.clone()),
|
||||||
Value::Number(val_num) => Some(val_num.to_string()),
|
Value::Number(val_num) => Some(val_num.to_string()),
|
||||||
@@ -94,25 +47,21 @@ impl Clash {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
let server = match clash_config.get(&key_server) {
|
// `external-controller` could be
|
||||||
|
// "127.0.0.1:9090" or ":9090"
|
||||||
|
// "9090" or 9090 (clash do not support this)
|
||||||
|
let server = match config.get(&key_server) {
|
||||||
Some(value) => match value {
|
Some(value) => match value {
|
||||||
Value::String(val_str) => {
|
Value::String(val_str) => match val_str.starts_with(":") {
|
||||||
// `external-controller` could be
|
true => Some(format!("127.0.0.1{val_str}")),
|
||||||
// "127.0.0.1:9090" or ":9090"
|
false => Some(val_str.clone()),
|
||||||
// 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,
|
||||||
};
|
};
|
||||||
let secret = match clash_config.get(&key_secret) {
|
|
||||||
|
let secret = match config.get(&key_secret) {
|
||||||
Some(value) => match value {
|
Some(value) => match value {
|
||||||
Value::String(val_str) => Some(val_str.clone()),
|
Value::String(val_str) => Some(val_str.clone()),
|
||||||
Value::Bool(val_bool) => Some(val_bool.to_string()),
|
Value::Bool(val_bool) => Some(val_bool.to_string()),
|
||||||
@@ -129,111 +78,71 @@ impl Clash {
|
|||||||
secret,
|
secret,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// save the main window
|
pub struct Clash {
|
||||||
pub fn set_window(&mut self, win: Option<Window>) {
|
/// maintain the clash config
|
||||||
self.window = win;
|
pub config: Mapping,
|
||||||
|
|
||||||
|
/// some info
|
||||||
|
pub info: ClashInfo,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Clash {
|
||||||
|
pub fn new() -> Clash {
|
||||||
|
let config = Clash::read_config();
|
||||||
|
let info = ClashInfo::from(&config);
|
||||||
|
|
||||||
|
Clash { config, info }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// run clash sidecar
|
/// get clash config
|
||||||
pub fn run_sidecar(&mut self) -> Result<()> {
|
pub fn read_config() -> Mapping {
|
||||||
let app_dir = dirs::app_home_dir();
|
config::read_yaml::<Mapping>(dirs::clash_path())
|
||||||
let app_dir = app_dir.as_os_str().to_str().unwrap();
|
|
||||||
|
|
||||||
match Command::new_sidecar("clash") {
|
|
||||||
Ok(cmd) => match cmd.args(["-d", app_dir]).spawn() {
|
|
||||||
Ok((mut rx, cmd_child)) => {
|
|
||||||
self.sidecar = Some(cmd_child);
|
|
||||||
|
|
||||||
// clash log
|
|
||||||
tauri::async_runtime::spawn(async move {
|
|
||||||
while let Some(event) = rx.recv().await {
|
|
||||||
match event {
|
|
||||||
CommandEvent::Stdout(line) => log::info!("[clash]: {}", line),
|
|
||||||
CommandEvent::Stderr(err) => log::error!("[clash]: {}", err),
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
Err(err) => bail!(err.to_string()),
|
|
||||||
},
|
|
||||||
Err(err) => bail!(err.to_string()),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// drop clash sidecar
|
/// save the clash config
|
||||||
pub fn drop_sidecar(&mut self) -> Result<()> {
|
pub fn save_config(&self) -> Result<()> {
|
||||||
if let Some(sidecar) = self.sidecar.take() {
|
config::save_yaml(
|
||||||
sidecar.kill()?;
|
dirs::clash_path(),
|
||||||
}
|
&self.config,
|
||||||
Ok(())
|
Some("# Default Config For Clash Core\n\n"),
|
||||||
}
|
)
|
||||||
|
|
||||||
/// restart clash sidecar
|
|
||||||
/// should reactivate profile after restart
|
|
||||||
pub fn restart_sidecar(&mut self, profiles: &mut Profiles) -> Result<()> {
|
|
||||||
self.update_config();
|
|
||||||
self.drop_sidecar()?;
|
|
||||||
self.run_sidecar()?;
|
|
||||||
self.activate(profiles)?;
|
|
||||||
self.activate_enhanced(profiles, false, true)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// update the clash info
|
|
||||||
pub fn update_config(&mut self) {
|
|
||||||
self.config = Clash::read_config();
|
|
||||||
self.info = Clash::get_info(&self.config);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// patch update the clash config
|
/// patch update the clash config
|
||||||
pub fn patch_config(
|
/// if the port is changed then return true
|
||||||
&mut self,
|
pub fn patch_config(&mut self, patch: Mapping) -> Result<bool> {
|
||||||
patch: Mapping,
|
let port_key = Value::from("mixed-port");
|
||||||
verge: &mut Verge,
|
let server_key = Value::from("external-controller");
|
||||||
profiles: &mut Profiles,
|
let secret_key = Value::from("secret");
|
||||||
) -> Result<()> {
|
|
||||||
let mix_port_key = Value::from("mixed-port");
|
let mut change_port = false;
|
||||||
let mut port = None;
|
let mut change_info = false;
|
||||||
|
|
||||||
for (key, value) in patch.into_iter() {
|
for (key, value) in patch.into_iter() {
|
||||||
let value = value.clone();
|
if key == port_key {
|
||||||
|
change_port = true;
|
||||||
// check whether the mix_port is changed
|
|
||||||
if key == mix_port_key {
|
|
||||||
if value.is_number() {
|
|
||||||
port = value.as_i64().as_ref().map(|n| n.to_string());
|
|
||||||
} else {
|
|
||||||
port = value.as_str().as_ref().map(|s| s.to_string());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
self.config.insert(key.clone(), value);
|
if key == port_key || key == server_key || key == secret_key {
|
||||||
|
change_info = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.config.insert(key, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
if change_info {
|
||||||
|
self.info = ClashInfo::from(&self.config);
|
||||||
}
|
}
|
||||||
|
|
||||||
self.save_config()?;
|
self.save_config()?;
|
||||||
|
|
||||||
if let Some(port) = port {
|
Ok(change_port)
|
||||||
self.restart_sidecar(profiles)?;
|
|
||||||
verge.init_sysproxy(Some(port));
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// enable tun mode
|
/// revise the `tun` and `dns` config
|
||||||
/// only revise the config
|
pub fn _tun_mode(mut config: Mapping, enable: bool) -> Mapping {
|
||||||
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 {
|
macro_rules! revise {
|
||||||
($map: expr, $key: expr, $val: expr) => {
|
($map: expr, $key: expr, $val: expr) => {
|
||||||
let ret_key = Value::String($key.into());
|
let ret_key = Value::String($key.into());
|
||||||
@@ -252,7 +161,7 @@ impl Clash {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// tun config
|
// tun config
|
||||||
let tun_val = self.config.get(&Value::from("tun"));
|
let tun_val = config.get(&Value::from("tun"));
|
||||||
let mut new_tun = Mapping::new();
|
let mut new_tun = Mapping::new();
|
||||||
|
|
||||||
if tun_val.is_some() && tun_val.as_ref().unwrap().is_mapping() {
|
if tun_val.is_some() && tun_val.as_ref().unwrap().is_mapping() {
|
||||||
@@ -260,186 +169,55 @@ impl Clash {
|
|||||||
}
|
}
|
||||||
|
|
||||||
revise!(new_tun, "enable", enable);
|
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);
|
if enable {
|
||||||
|
append!(new_tun, "stack", "gvisor");
|
||||||
// dns config
|
append!(new_tun, "dns-hijack", vec!["198.18.0.2:53"]);
|
||||||
let dns_val = self.config.get(&Value::from("dns"));
|
append!(new_tun, "auto-route", true);
|
||||||
let mut new_dns = Mapping::new();
|
append!(new_tun, "auto-detect-interface", true);
|
||||||
|
|
||||||
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!(config, "tun", new_tun);
|
||||||
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")]
|
if enable {
|
||||||
append!(
|
// dns config
|
||||||
new_dns,
|
let dns_val = config.get(&Value::from("dns"));
|
||||||
"fake-ip-filter",
|
let mut new_dns = Mapping::new();
|
||||||
vec![
|
|
||||||
"dns.msftncsi.com",
|
|
||||||
"www.msftncsi.com",
|
|
||||||
"www.msftconnecttest.com"
|
|
||||||
]
|
|
||||||
);
|
|
||||||
|
|
||||||
revise!(self.config, "dns", new_dns);
|
if dns_val.is_some() && dns_val.as_ref().unwrap().is_mapping() {
|
||||||
|
new_dns = dns_val.as_ref().unwrap().as_mapping().unwrap().clone();
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
|
revise!(new_dns, "enable", enable);
|
||||||
|
|
||||||
let mut data = HashMap::new();
|
// 借鉴cfw的默认配置
|
||||||
data.insert("path", temp_path.as_os_str().to_str().unwrap());
|
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>);
|
||||||
|
|
||||||
// retry 5 times
|
#[cfg(target_os = "windows")]
|
||||||
for _ in 0..5 {
|
append!(
|
||||||
match reqwest::ClientBuilder::new().no_proxy().build() {
|
new_dns,
|
||||||
Ok(client) => {
|
"fake-ip-filter",
|
||||||
let builder = client.put(&server).headers(headers.clone()).json(&data);
|
vec![
|
||||||
|
"dns.msftncsi.com",
|
||||||
|
"www.msftncsi.com",
|
||||||
|
"www.msftconnecttest.com"
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
match builder.send().await {
|
revise!(config, "dns", new_dns);
|
||||||
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
|
|
||||||
/// - (sync) refresh config if enhance chain is null
|
|
||||||
/// - (async) enhanced config
|
|
||||||
pub fn activate_enhanced(&self, profiles: &Profiles, delay: bool, skip: bool) -> Result<()> {
|
|
||||||
if self.window.is_none() {
|
|
||||||
bail!("failed to get the main window");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let event_name = help::get_uid("e");
|
config
|
||||||
let event_name = format!("enhanced-cb-{event_name}");
|
|
||||||
|
|
||||||
// generate the payload
|
|
||||||
let payload = profiles.gen_enhanced(event_name.clone())?;
|
|
||||||
|
|
||||||
let info = self.info.clone();
|
|
||||||
|
|
||||||
// do not run enhanced
|
|
||||||
if payload.chain.len() == 0 {
|
|
||||||
if skip {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut config = self.config.clone();
|
|
||||||
let filter_data = Clash::strict_filter(payload.current);
|
|
||||||
|
|
||||||
for (key, value) in filter_data.into_iter() {
|
|
||||||
config.insert(key, value);
|
|
||||||
}
|
|
||||||
|
|
||||||
return Clash::_activate(info, config, self.window.clone());
|
|
||||||
}
|
|
||||||
|
|
||||||
let window = self.window.clone().unwrap();
|
|
||||||
let window_move = self.window.clone();
|
|
||||||
|
|
||||||
window.once(&event_name, move |event| {
|
|
||||||
if let Some(result) = event.payload() {
|
|
||||||
let result: PrfEnhancedResult = serde_json::from_str(result).unwrap();
|
|
||||||
|
|
||||||
if let Some(data) = result.data {
|
|
||||||
let mut config = Clash::read_config();
|
|
||||||
let filter_data = Clash::loose_filter(data); // loose filter
|
|
||||||
|
|
||||||
for (key, value) in filter_data.into_iter() {
|
|
||||||
config.insert(key, value);
|
|
||||||
}
|
|
||||||
|
|
||||||
log_if_err!(Clash::_activate(info, config, window_move));
|
|
||||||
log::info!("profile enhanced status {}", result.status);
|
|
||||||
}
|
|
||||||
|
|
||||||
result.error.map(|err| log::error!("{err}"));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
tauri::async_runtime::spawn(async move {
|
|
||||||
// wait the window setup during resolve app
|
|
||||||
if delay {
|
|
||||||
sleep(Duration::from_secs(2)).await;
|
|
||||||
}
|
|
||||||
window.emit("script-handler", payload).unwrap();
|
|
||||||
});
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// activate the profile
|
|
||||||
/// auto activate enhanced profile
|
|
||||||
pub fn activate(&self, profiles: &Profiles) -> Result<()> {
|
|
||||||
let data = profiles.gen_activate()?;
|
|
||||||
let data = Clash::strict_filter(data);
|
|
||||||
|
|
||||||
let info = self.info.clone();
|
|
||||||
let mut config = self.config.clone();
|
|
||||||
|
|
||||||
for (key, value) in data.into_iter() {
|
|
||||||
config.insert(key, value);
|
|
||||||
}
|
|
||||||
|
|
||||||
Clash::_activate(info, config, self.window.clone())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// only 5 default fields available (clash config fields)
|
/// only 5 default fields available (clash config fields)
|
||||||
/// convert to lowercase
|
/// convert to lowercase
|
||||||
fn strict_filter(config: Mapping) -> Mapping {
|
pub fn strict_filter(config: Mapping) -> Mapping {
|
||||||
// Only the following fields are allowed:
|
// Only the following fields are allowed:
|
||||||
// proxies/proxy-providers/proxy-groups/rule-providers/rules
|
// proxies/proxy-providers/proxy-groups/rule-providers/rules
|
||||||
let valid_keys = vec![
|
let valid_keys = vec![
|
||||||
@@ -470,7 +248,7 @@ impl Clash {
|
|||||||
|
|
||||||
/// more clash config fields available
|
/// more clash config fields available
|
||||||
/// convert to lowercase
|
/// convert to lowercase
|
||||||
fn loose_filter(config: Mapping) -> Mapping {
|
pub fn loose_filter(config: Mapping) -> Mapping {
|
||||||
// all of these can not be revised by script or merge
|
// all of these can not be revised by script or merge
|
||||||
// http/https/socks port should be under control
|
// http/https/socks port should be under control
|
||||||
let not_allow = vec![
|
let not_allow = vec![
|
||||||
@@ -508,11 +286,3 @@ impl Default for Clash {
|
|||||||
Clash::new()
|
Clash::new()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Drop for Clash {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
if let Err(err) = self.drop_sidecar() {
|
|
||||||
log::error!("{err}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
use super::prfitem::PrfItem;
|
||||||
|
use crate::utils::{config, dirs};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use serde_yaml::Mapping;
|
||||||
|
use std::fs;
|
||||||
|
|
||||||
|
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct PrfEnhanced {
|
||||||
|
pub current: Mapping,
|
||||||
|
|
||||||
|
pub chain: Vec<PrfData>,
|
||||||
|
|
||||||
|
pub valid: Vec<String>,
|
||||||
|
|
||||||
|
pub callback: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct PrfEnhancedResult {
|
||||||
|
pub data: Option<Mapping>,
|
||||||
|
|
||||||
|
pub status: String,
|
||||||
|
|
||||||
|
pub error: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct PrfData {
|
||||||
|
item: PrfItem,
|
||||||
|
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
merge: Option<Mapping>,
|
||||||
|
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
script: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PrfData {
|
||||||
|
pub fn from_item(item: &PrfItem) -> Option<PrfData> {
|
||||||
|
match item.itype.as_ref() {
|
||||||
|
Some(itype) => {
|
||||||
|
let file = item.file.clone()?;
|
||||||
|
let path = dirs::app_profiles_dir().join(file);
|
||||||
|
|
||||||
|
if !path.exists() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
match itype.as_str() {
|
||||||
|
"script" => Some(PrfData {
|
||||||
|
item: item.clone(),
|
||||||
|
script: Some(fs::read_to_string(path).unwrap_or("".into())),
|
||||||
|
merge: None,
|
||||||
|
}),
|
||||||
|
"merge" => Some(PrfData {
|
||||||
|
item: item.clone(),
|
||||||
|
merge: Some(config::read_yaml::<Mapping>(path)),
|
||||||
|
script: None,
|
||||||
|
}),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,454 @@
|
|||||||
|
use self::notice::Notice;
|
||||||
|
use self::sysopt::Sysopt;
|
||||||
|
use self::timer::Timer;
|
||||||
|
use crate::core::enhance::PrfEnhancedResult;
|
||||||
|
use crate::log_if_err;
|
||||||
|
use crate::utils::{dirs, help};
|
||||||
|
use anyhow::{bail, Result};
|
||||||
|
use parking_lot::Mutex;
|
||||||
|
use serde_yaml::Mapping;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::Duration;
|
||||||
|
use tauri::{AppHandle, Manager, Window};
|
||||||
|
use tokio::time::sleep;
|
||||||
|
|
||||||
mod clash;
|
mod clash;
|
||||||
|
mod enhance;
|
||||||
|
mod notice;
|
||||||
|
mod prfitem;
|
||||||
mod profiles;
|
mod profiles;
|
||||||
|
mod service;
|
||||||
|
mod sysopt;
|
||||||
|
mod timer;
|
||||||
mod verge;
|
mod verge;
|
||||||
|
|
||||||
pub use self::clash::*;
|
pub use self::clash::*;
|
||||||
|
pub use self::prfitem::*;
|
||||||
pub use self::profiles::*;
|
pub use self::profiles::*;
|
||||||
|
pub use self::service::*;
|
||||||
pub use self::verge::*;
|
pub use self::verge::*;
|
||||||
|
|
||||||
|
/// close the window for slient start
|
||||||
|
/// after enhance mode
|
||||||
|
static mut WINDOW_CLOSABLE: bool = true;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Core {
|
||||||
|
pub clash: Arc<Mutex<Clash>>,
|
||||||
|
|
||||||
|
pub verge: Arc<Mutex<Verge>>,
|
||||||
|
|
||||||
|
pub profiles: Arc<Mutex<Profiles>>,
|
||||||
|
|
||||||
|
pub service: Arc<Mutex<Service>>,
|
||||||
|
|
||||||
|
pub sysopt: Arc<Mutex<Sysopt>>,
|
||||||
|
|
||||||
|
pub timer: Arc<Mutex<Timer>>,
|
||||||
|
|
||||||
|
pub window: Arc<Mutex<Option<Window>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Core {
|
||||||
|
pub fn new() -> Core {
|
||||||
|
let clash = Clash::new();
|
||||||
|
let verge = Verge::new();
|
||||||
|
let profiles = Profiles::new();
|
||||||
|
let service = Service::new();
|
||||||
|
|
||||||
|
Core {
|
||||||
|
clash: Arc::new(Mutex::new(clash)),
|
||||||
|
verge: Arc::new(Mutex::new(verge)),
|
||||||
|
profiles: Arc::new(Mutex::new(profiles)),
|
||||||
|
service: Arc::new(Mutex::new(service)),
|
||||||
|
sysopt: Arc::new(Mutex::new(Sysopt::new())),
|
||||||
|
timer: Arc::new(Mutex::new(Timer::new())),
|
||||||
|
window: Arc::new(Mutex::new(None)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// initialize the core state
|
||||||
|
pub fn init(&self, app_handle: tauri::AppHandle) {
|
||||||
|
let verge = self.verge.lock();
|
||||||
|
let clash_core = verge.clash_core.clone();
|
||||||
|
|
||||||
|
let mut service = self.service.lock();
|
||||||
|
service.set_core(clash_core);
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
let enable = verge.enable_service_mode.clone();
|
||||||
|
service.set_mode(enable.unwrap_or(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
log_if_err!(service.start());
|
||||||
|
drop(verge);
|
||||||
|
drop(service);
|
||||||
|
|
||||||
|
log_if_err!(self.activate());
|
||||||
|
|
||||||
|
let clash = self.clash.lock();
|
||||||
|
let verge = self.verge.lock();
|
||||||
|
|
||||||
|
let silent_start = verge.enable_silent_start.clone();
|
||||||
|
let auto_launch = verge.enable_auto_launch.clone();
|
||||||
|
|
||||||
|
// silent start
|
||||||
|
if silent_start.unwrap_or(false) {
|
||||||
|
let window = self.window.lock();
|
||||||
|
window.as_ref().map(|win| {
|
||||||
|
win.hide().unwrap();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut sysopt = self.sysopt.lock();
|
||||||
|
|
||||||
|
sysopt.init_sysproxy(clash.info.port.clone(), &verge);
|
||||||
|
|
||||||
|
drop(clash);
|
||||||
|
drop(verge);
|
||||||
|
|
||||||
|
log_if_err!(sysopt.init_launch(auto_launch));
|
||||||
|
|
||||||
|
log_if_err!(self.update_systray(&app_handle));
|
||||||
|
|
||||||
|
// wait the window setup during resolve app
|
||||||
|
let core = self.clone();
|
||||||
|
tauri::async_runtime::spawn(async move {
|
||||||
|
sleep(Duration::from_secs(2)).await;
|
||||||
|
log_if_err!(core.activate_enhanced(true));
|
||||||
|
});
|
||||||
|
|
||||||
|
// timer initialize
|
||||||
|
let mut timer = self.timer.lock();
|
||||||
|
timer.set_core(self.clone());
|
||||||
|
log_if_err!(timer.refresh());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// save the window instance
|
||||||
|
pub fn set_win(&self, win: Option<Window>) {
|
||||||
|
let mut window = self.window.lock();
|
||||||
|
*window = win;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// restart the clash sidecar
|
||||||
|
pub fn restart_clash(&self) -> Result<()> {
|
||||||
|
let mut service = self.service.lock();
|
||||||
|
service.restart()?;
|
||||||
|
drop(service);
|
||||||
|
|
||||||
|
self.activate()?;
|
||||||
|
self.activate_enhanced(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// change the clash core
|
||||||
|
pub fn change_core(&self, clash_core: Option<String>) -> Result<()> {
|
||||||
|
let clash_core = clash_core.unwrap_or("clash".into());
|
||||||
|
|
||||||
|
if &clash_core != "clash" && &clash_core != "clash-meta" {
|
||||||
|
bail!("invalid clash core name \"{clash_core}\"");
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut verge = self.verge.lock();
|
||||||
|
verge.patch_config(Verge {
|
||||||
|
clash_core: Some(clash_core.clone()),
|
||||||
|
..Verge::default()
|
||||||
|
})?;
|
||||||
|
drop(verge);
|
||||||
|
|
||||||
|
let mut service = self.service.lock();
|
||||||
|
service.stop()?;
|
||||||
|
service.set_core(Some(clash_core));
|
||||||
|
service.start()?;
|
||||||
|
drop(service);
|
||||||
|
|
||||||
|
self.activate()?;
|
||||||
|
self.activate_enhanced(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Patch Clash
|
||||||
|
/// handle the clash config changed
|
||||||
|
pub fn patch_clash(&self, patch: Mapping) -> Result<()> {
|
||||||
|
let (changed, port) = {
|
||||||
|
let mut clash = self.clash.lock();
|
||||||
|
(clash.patch_config(patch)?, clash.info.port.clone())
|
||||||
|
};
|
||||||
|
|
||||||
|
// todo: port check
|
||||||
|
|
||||||
|
if changed {
|
||||||
|
let mut service = self.service.lock();
|
||||||
|
service.restart()?;
|
||||||
|
drop(service);
|
||||||
|
|
||||||
|
self.activate()?;
|
||||||
|
self.activate_enhanced(true)?;
|
||||||
|
|
||||||
|
let mut sysopt = self.sysopt.lock();
|
||||||
|
let verge = self.verge.lock();
|
||||||
|
sysopt.init_sysproxy(port, &verge);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Patch Verge
|
||||||
|
pub fn patch_verge(&self, patch: Verge, app_handle: &AppHandle) -> Result<()> {
|
||||||
|
let tun_mode = patch.enable_tun_mode.clone();
|
||||||
|
let auto_launch = patch.enable_auto_launch.clone();
|
||||||
|
let system_proxy = patch.enable_system_proxy.clone();
|
||||||
|
let proxy_bypass = patch.system_proxy_bypass.clone();
|
||||||
|
let proxy_guard = patch.enable_proxy_guard.clone();
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
let service_mode = patch.enable_service_mode.clone();
|
||||||
|
|
||||||
|
if service_mode.is_some() {
|
||||||
|
let service_mode = service_mode.unwrap();
|
||||||
|
|
||||||
|
let mut service = self.service.lock();
|
||||||
|
service.stop()?;
|
||||||
|
service.set_mode(service_mode);
|
||||||
|
service.start()?;
|
||||||
|
drop(service);
|
||||||
|
|
||||||
|
self.activate_enhanced(false)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if auto_launch.is_some() {
|
||||||
|
let mut sysopt = self.sysopt.lock();
|
||||||
|
sysopt.update_launch(auto_launch)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
if system_proxy.is_some() || proxy_bypass.is_some() {
|
||||||
|
let mut sysopt = self.sysopt.lock();
|
||||||
|
sysopt.update_sysproxy(system_proxy.clone(), proxy_bypass)?;
|
||||||
|
sysopt.guard_proxy();
|
||||||
|
}
|
||||||
|
|
||||||
|
if proxy_guard.unwrap_or(false) {
|
||||||
|
let sysopt = self.sysopt.lock();
|
||||||
|
sysopt.guard_proxy();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
if tun_mode.is_some() && *tun_mode.as_ref().unwrap_or(&false) {
|
||||||
|
let wintun_dll = dirs::app_home_dir().join("wintun.dll");
|
||||||
|
if !wintun_dll.exists() {
|
||||||
|
bail!("failed to enable TUN for missing `wintun.dll`");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// save the patch
|
||||||
|
let mut verge = self.verge.lock();
|
||||||
|
verge.patch_config(patch)?;
|
||||||
|
drop(verge);
|
||||||
|
|
||||||
|
if system_proxy.is_some() || tun_mode.is_some() {
|
||||||
|
self.update_systray(app_handle)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
if tun_mode.is_some() {
|
||||||
|
self.activate_enhanced(false)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// update the system tray state
|
||||||
|
pub fn update_systray(&self, app_handle: &AppHandle) -> Result<()> {
|
||||||
|
let verge = self.verge.lock();
|
||||||
|
let tray = app_handle.tray_handle();
|
||||||
|
|
||||||
|
let system_proxy = verge.enable_system_proxy.as_ref();
|
||||||
|
let tun_mode = verge.enable_tun_mode.as_ref();
|
||||||
|
|
||||||
|
tray
|
||||||
|
.get_item("system_proxy")
|
||||||
|
.set_selected(*system_proxy.unwrap_or(&false))?;
|
||||||
|
tray
|
||||||
|
.get_item("tun_mode")
|
||||||
|
.set_selected(*tun_mode.unwrap_or(&false))?;
|
||||||
|
|
||||||
|
// update verge config
|
||||||
|
let window = app_handle.get_window("main");
|
||||||
|
let notice = Notice::from(window);
|
||||||
|
notice.refresh_verge();
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// activate the profile
|
||||||
|
/// auto activate enhanced profile
|
||||||
|
pub fn activate(&self) -> Result<()> {
|
||||||
|
let data = {
|
||||||
|
let profiles = self.profiles.lock();
|
||||||
|
let data = profiles.gen_activate()?;
|
||||||
|
Clash::strict_filter(data)
|
||||||
|
};
|
||||||
|
|
||||||
|
let (mut config, info) = {
|
||||||
|
let clash = self.clash.lock();
|
||||||
|
let config = clash.config.clone();
|
||||||
|
let info = clash.info.clone();
|
||||||
|
(config, info)
|
||||||
|
};
|
||||||
|
|
||||||
|
for (key, value) in data.into_iter() {
|
||||||
|
config.insert(key, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
let config = {
|
||||||
|
let verge = self.verge.lock();
|
||||||
|
let tun_mode = verge.enable_tun_mode.unwrap_or(false);
|
||||||
|
Clash::_tun_mode(config, tun_mode)
|
||||||
|
};
|
||||||
|
|
||||||
|
let notice = {
|
||||||
|
let window = self.window.lock();
|
||||||
|
Notice::from(window.clone())
|
||||||
|
};
|
||||||
|
|
||||||
|
let service = self.service.lock();
|
||||||
|
service.set_config(info, config, notice)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Enhanced
|
||||||
|
/// enhanced profiles mode
|
||||||
|
pub fn activate_enhanced(&self, skip: bool) -> Result<()> {
|
||||||
|
let window = self.window.lock();
|
||||||
|
if window.is_none() {
|
||||||
|
bail!("failed to get the main window");
|
||||||
|
}
|
||||||
|
|
||||||
|
let event_name = help::get_uid("e");
|
||||||
|
let event_name = format!("enhanced-cb-{event_name}");
|
||||||
|
|
||||||
|
// generate the payload
|
||||||
|
let payload = {
|
||||||
|
let profiles = self.profiles.lock();
|
||||||
|
profiles.gen_enhanced(event_name.clone())?
|
||||||
|
};
|
||||||
|
|
||||||
|
// do not run enhanced
|
||||||
|
if payload.chain.len() == 0 {
|
||||||
|
if skip {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
drop(window);
|
||||||
|
return self.activate();
|
||||||
|
}
|
||||||
|
|
||||||
|
let tun_mode = {
|
||||||
|
let verge = self.verge.lock();
|
||||||
|
verge.enable_tun_mode.unwrap_or(false)
|
||||||
|
};
|
||||||
|
|
||||||
|
let info = {
|
||||||
|
let clash = self.clash.lock();
|
||||||
|
clash.info.clone()
|
||||||
|
};
|
||||||
|
|
||||||
|
let notice = Notice::from(window.clone());
|
||||||
|
let service = self.service.clone();
|
||||||
|
|
||||||
|
let window = window.clone().unwrap();
|
||||||
|
window.once(&event_name, move |event| {
|
||||||
|
let result = event.payload();
|
||||||
|
|
||||||
|
if result.is_none() {
|
||||||
|
log::warn!("event payload result is none");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let result = result.unwrap();
|
||||||
|
let result: PrfEnhancedResult = serde_json::from_str(result).unwrap();
|
||||||
|
|
||||||
|
if let Some(data) = result.data {
|
||||||
|
let mut config = Clash::read_config();
|
||||||
|
let filter_data = Clash::loose_filter(data); // loose filter
|
||||||
|
|
||||||
|
for (key, value) in filter_data.into_iter() {
|
||||||
|
config.insert(key, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
let config = Clash::_tun_mode(config, tun_mode);
|
||||||
|
|
||||||
|
let service = service.lock();
|
||||||
|
log_if_err!(service.set_config(info, config, notice));
|
||||||
|
|
||||||
|
log::info!("profile enhanced status {}", result.status);
|
||||||
|
}
|
||||||
|
|
||||||
|
result.error.map(|err| log::error!("{err}"));
|
||||||
|
});
|
||||||
|
|
||||||
|
let verge = self.verge.lock();
|
||||||
|
let silent_start = verge.enable_silent_start.clone();
|
||||||
|
|
||||||
|
let closable = unsafe { WINDOW_CLOSABLE };
|
||||||
|
|
||||||
|
if silent_start.unwrap_or(false) && closable {
|
||||||
|
unsafe {
|
||||||
|
WINDOW_CLOSABLE = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
window.emit("script-handler-close", payload).unwrap();
|
||||||
|
} else {
|
||||||
|
window.emit("script-handler", payload).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Core {
|
||||||
|
/// Static function
|
||||||
|
/// update profile item
|
||||||
|
pub async fn update_profile_item(
|
||||||
|
core: Core,
|
||||||
|
uid: String,
|
||||||
|
option: Option<PrfOption>,
|
||||||
|
) -> Result<()> {
|
||||||
|
let (url, opt) = {
|
||||||
|
let profiles = core.profiles.lock();
|
||||||
|
let item = profiles.get_item(&uid)?;
|
||||||
|
|
||||||
|
if let Some(typ) = item.itype.as_ref() {
|
||||||
|
// maybe only valid for `local` profile
|
||||||
|
if *typ != "remote" {
|
||||||
|
// reactivate the config
|
||||||
|
if Some(uid) == profiles.get_current() {
|
||||||
|
drop(profiles);
|
||||||
|
return core.activate_enhanced(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if item.url.is_none() {
|
||||||
|
bail!("failed to get the profile item url");
|
||||||
|
}
|
||||||
|
|
||||||
|
(item.url.clone().unwrap(), item.option.clone())
|
||||||
|
};
|
||||||
|
|
||||||
|
let merged_opt = PrfOption::merge(opt, option);
|
||||||
|
let item = PrfItem::from_url(&url, None, None, merged_opt).await?;
|
||||||
|
|
||||||
|
let mut profiles = core.profiles.lock();
|
||||||
|
profiles.update_item(uid.clone(), item)?;
|
||||||
|
|
||||||
|
// reactivate the profile
|
||||||
|
if Some(uid) == profiles.get_current() {
|
||||||
|
drop(profiles);
|
||||||
|
core.activate_enhanced(false)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
use crate::log_if_err;
|
||||||
|
use tauri::Window;
|
||||||
|
|
||||||
|
#[derive(Debug, Default, Clone)]
|
||||||
|
pub struct Notice {
|
||||||
|
win: Option<Window>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Notice {
|
||||||
|
pub fn from(win: Option<Window>) -> Notice {
|
||||||
|
Notice { win }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_win(&mut self, win: Option<Window>) {
|
||||||
|
self.win = win;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn refresh_clash(&self) {
|
||||||
|
if let Some(window) = self.win.as_ref() {
|
||||||
|
log_if_err!(window.emit("verge://refresh-clash-config", "yes"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn refresh_verge(&self) {
|
||||||
|
if let Some(window) = self.win.as_ref() {
|
||||||
|
log_if_err!(window.emit("verge://refresh-verge-config", "yes"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn refresh_profiles(&self) {
|
||||||
|
if let Some(window) = self.win.as_ref() {
|
||||||
|
log_if_err!(window.emit("verge://refresh-profiles-config", "yes"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,336 @@
|
|||||||
|
use crate::utils::{dirs, help, tmpl};
|
||||||
|
use anyhow::{bail, Context, Result};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use serde_yaml::Mapping;
|
||||||
|
use std::fs;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||||
|
pub struct PrfItem {
|
||||||
|
pub uid: Option<String>,
|
||||||
|
|
||||||
|
/// profile item type
|
||||||
|
/// enum value: remote | local | script | merge
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
pub itype: Option<String>,
|
||||||
|
|
||||||
|
/// profile name
|
||||||
|
pub name: Option<String>,
|
||||||
|
|
||||||
|
/// profile file
|
||||||
|
pub file: Option<String>,
|
||||||
|
|
||||||
|
/// profile description
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub desc: Option<String>,
|
||||||
|
|
||||||
|
/// source url
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub url: Option<String>,
|
||||||
|
|
||||||
|
/// selected infomation
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub selected: Option<Vec<PrfSelected>>,
|
||||||
|
|
||||||
|
/// subscription user info
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub extra: Option<PrfExtra>,
|
||||||
|
|
||||||
|
/// updated time
|
||||||
|
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)]
|
||||||
|
pub struct PrfSelected {
|
||||||
|
pub name: Option<String>,
|
||||||
|
pub now: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default, Debug, Clone, Copy, Deserialize, Serialize)]
|
||||||
|
pub struct PrfExtra {
|
||||||
|
pub upload: usize,
|
||||||
|
pub download: usize,
|
||||||
|
pub total: usize,
|
||||||
|
pub expire: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
|
||||||
|
pub struct PrfOption {
|
||||||
|
/// for `remote` profile's http request
|
||||||
|
/// see issue #13
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub user_agent: Option<String>,
|
||||||
|
|
||||||
|
/// for `remote` profile
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub with_proxy: Option<bool>,
|
||||||
|
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub update_interval: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PrfOption {
|
||||||
|
pub fn merge(one: Option<Self>, other: Option<Self>) -> Option<Self> {
|
||||||
|
if one.is_none() {
|
||||||
|
return other;
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(val) = other.update_interval {
|
||||||
|
one.update_interval = Some(val);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Some(one);
|
||||||
|
}
|
||||||
|
|
||||||
|
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 profile item 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();
|
||||||
|
}
|
||||||
|
|
||||||
|
builder = builder.user_agent(user_agent.unwrap_or("clash-verge/v1.0.0".into()));
|
||||||
|
|
||||||
|
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,
|
||||||
|
};
|
||||||
|
|
||||||
|
// parse the Content-Disposition
|
||||||
|
let filename = match header.get("Content-Disposition") {
|
||||||
|
Some(value) => {
|
||||||
|
let filename = value.to_str().unwrap_or("");
|
||||||
|
help::parse_str::<String>(filename, "filename=")
|
||||||
|
}
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
// parse the profile-update-interval
|
||||||
|
let option = match header.get("profile-update-interval") {
|
||||||
|
Some(value) => match value.to_str().unwrap_or("").parse::<u64>() {
|
||||||
|
Ok(val) => Some(PrfOption {
|
||||||
|
update_interval: Some(val * 60), // hour -> min
|
||||||
|
..PrfOption::default()
|
||||||
|
}),
|
||||||
|
Err(_) => None,
|
||||||
|
},
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
let uid = help::get_uid("r");
|
||||||
|
let file = format!("{uid}.yaml");
|
||||||
|
let name = name.unwrap_or(filename.unwrap_or("Remote File".into()));
|
||||||
|
let data = resp.text_with_charset("utf-8").await?;
|
||||||
|
|
||||||
|
// check the data whether the valid yaml format
|
||||||
|
if !serde_yaml::from_str::<Mapping>(&data).is_ok() {
|
||||||
|
bail!("the remote profile data is invalid yaml");
|
||||||
|
}
|
||||||
|
|
||||||
|
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()),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// get the file data
|
||||||
|
pub fn read_file(&self) -> Result<String> {
|
||||||
|
if self.file.is_none() {
|
||||||
|
bail!("could not find the file");
|
||||||
|
}
|
||||||
|
|
||||||
|
let file = self.file.clone().unwrap();
|
||||||
|
let path = dirs::app_profiles_dir().join(file);
|
||||||
|
fs::read_to_string(path).context("failed to read the file")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// save the file data
|
||||||
|
pub fn save_file(&self, data: String) -> Result<()> {
|
||||||
|
if self.file.is_none() {
|
||||||
|
bail!("could not find the file");
|
||||||
|
}
|
||||||
|
|
||||||
|
let file = self.file.clone().unwrap();
|
||||||
|
let path = dirs::app_profiles_dir().join(file);
|
||||||
|
fs::write(path, data.as_bytes()).context("failed to save the file")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,308 +1,11 @@
|
|||||||
use crate::utils::{config, dirs, help, tmpl};
|
use super::enhance::{PrfData, PrfEnhanced};
|
||||||
|
use super::prfitem::PrfItem;
|
||||||
|
use crate::utils::{config, dirs, help};
|
||||||
use anyhow::{bail, Context, Result};
|
use anyhow::{bail, Context, Result};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use serde_yaml::Mapping;
|
use serde_yaml::Mapping;
|
||||||
use std::{fs, io::Write};
|
use std::{fs, io::Write};
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
|
||||||
pub struct PrfItem {
|
|
||||||
pub uid: Option<String>,
|
|
||||||
|
|
||||||
/// profile item type
|
|
||||||
/// enum value: remote | local | script | merge
|
|
||||||
#[serde(rename = "type")]
|
|
||||||
pub itype: Option<String>,
|
|
||||||
|
|
||||||
/// profile name
|
|
||||||
pub name: Option<String>,
|
|
||||||
|
|
||||||
/// profile description
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
pub desc: Option<String>,
|
|
||||||
|
|
||||||
/// profile file
|
|
||||||
pub file: Option<String>,
|
|
||||||
|
|
||||||
/// source url
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
pub url: Option<String>,
|
|
||||||
|
|
||||||
/// selected infomation
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
pub selected: Option<Vec<PrfSelected>>,
|
|
||||||
|
|
||||||
/// subscription user info
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
pub extra: Option<PrfExtra>,
|
|
||||||
|
|
||||||
/// updated time
|
|
||||||
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)]
|
|
||||||
pub struct PrfSelected {
|
|
||||||
pub name: Option<String>,
|
|
||||||
pub now: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Default, Debug, Clone, Copy, Deserialize, Serialize)]
|
|
||||||
pub struct PrfExtra {
|
|
||||||
pub upload: usize,
|
|
||||||
pub download: usize,
|
|
||||||
pub total: usize,
|
|
||||||
pub expire: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
|
||||||
pub struct PrfOption {
|
|
||||||
/// for `remote` profile's http request
|
|
||||||
/// see issue #13
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
pub user_agent: Option<String>,
|
|
||||||
|
|
||||||
/// for `remote` profile
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
pub with_proxy: Option<bool>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PrfOption {
|
|
||||||
pub fn merge(one: Option<Self>, other: Option<Self>) -> Option<Self> {
|
|
||||||
if one.is_some() && other.is_some() {
|
|
||||||
let mut one = one.unwrap();
|
|
||||||
let other = other.unwrap();
|
|
||||||
|
|
||||||
if let Some(val) = other.user_agent {
|
|
||||||
one.user_agent = Some(val);
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(val) = other.with_proxy {
|
|
||||||
one.with_proxy = Some(val);
|
|
||||||
}
|
|
||||||
|
|
||||||
return Some(one);
|
|
||||||
}
|
|
||||||
|
|
||||||
if one.is_none() {
|
|
||||||
return other;
|
|
||||||
}
|
|
||||||
|
|
||||||
return one;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for PrfItem {
|
|
||||||
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()),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// get the file data
|
|
||||||
pub fn read_file(&self) -> Result<String> {
|
|
||||||
if self.file.is_none() {
|
|
||||||
bail!("could not find the file");
|
|
||||||
}
|
|
||||||
|
|
||||||
let file = self.file.clone().unwrap();
|
|
||||||
let path = dirs::app_profiles_dir().join(file);
|
|
||||||
fs::read_to_string(path).context("failed to read the file")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// save the file data
|
|
||||||
pub fn save_file(&self, data: String) -> Result<()> {
|
|
||||||
if self.file.is_none() {
|
|
||||||
bail!("could not find the file");
|
|
||||||
}
|
|
||||||
|
|
||||||
let file = self.file.clone().unwrap();
|
|
||||||
let path = dirs::app_profiles_dir().join(file);
|
|
||||||
fs::write(path, data.as_bytes()).context("failed to save the file")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
///
|
///
|
||||||
/// ## Profiles Config
|
/// ## Profiles Config
|
||||||
///
|
///
|
||||||
@@ -316,6 +19,9 @@ pub struct Profiles {
|
|||||||
/// same as PrfConfig.chain
|
/// same as PrfConfig.chain
|
||||||
chain: Option<Vec<String>>,
|
chain: Option<Vec<String>>,
|
||||||
|
|
||||||
|
/// record valid fields for clash
|
||||||
|
valid: Option<Vec<String>>,
|
||||||
|
|
||||||
/// profile list
|
/// profile list
|
||||||
items: Option<Vec<PrfItem>>,
|
items: Option<Vec<PrfItem>>,
|
||||||
}
|
}
|
||||||
@@ -329,6 +35,10 @@ macro_rules! patch {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Profiles {
|
impl Profiles {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Profiles::read_file()
|
||||||
|
}
|
||||||
|
|
||||||
/// read the config from the file
|
/// read the config from the file
|
||||||
pub fn read_file() -> Self {
|
pub fn read_file() -> Self {
|
||||||
let mut profiles = config::read_yaml::<Self>(dirs::profiles_path());
|
let mut profiles = config::read_yaml::<Self>(dirs::profiles_path());
|
||||||
@@ -337,6 +47,7 @@ impl Profiles {
|
|||||||
profiles.items = Some(vec![]);
|
profiles.items = Some(vec![]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// compatiable with the old old old version
|
||||||
profiles.items.as_mut().map(|items| {
|
profiles.items.as_mut().map(|items| {
|
||||||
for mut item in items.iter_mut() {
|
for mut item in items.iter_mut() {
|
||||||
if item.uid.is_none() {
|
if item.uid.is_none() {
|
||||||
@@ -357,19 +68,6 @@ impl Profiles {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// sync the config between file and memory
|
|
||||||
pub fn sync_file(&mut self) -> Result<()> {
|
|
||||||
let data = Self::read_file();
|
|
||||||
if data.current.is_none() && data.items.is_none() {
|
|
||||||
bail!("failed to read profiles.yaml");
|
|
||||||
}
|
|
||||||
|
|
||||||
self.current = data.current;
|
|
||||||
self.chain = data.chain;
|
|
||||||
self.items = data.items;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// get the current uid
|
/// get the current uid
|
||||||
pub fn get_current(&self) -> Option<String> {
|
pub fn get_current(&self) -> Option<String> {
|
||||||
self.current.clone()
|
self.current.clone()
|
||||||
@@ -384,11 +82,9 @@ impl Profiles {
|
|||||||
let items = self.items.as_ref().unwrap();
|
let items = self.items.as_ref().unwrap();
|
||||||
let some_uid = Some(uid.clone());
|
let some_uid = Some(uid.clone());
|
||||||
|
|
||||||
for each in items.iter() {
|
if items.iter().find(|&each| each.uid == some_uid).is_some() {
|
||||||
if each.uid == some_uid {
|
self.current = some_uid;
|
||||||
self.current = some_uid;
|
return self.save_file();
|
||||||
return self.save_file();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
bail!("invalid uid \"{uid}\"");
|
bail!("invalid uid \"{uid}\"");
|
||||||
@@ -399,6 +95,16 @@ impl Profiles {
|
|||||||
self.chain = chain;
|
self.chain = chain;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// just change the `field`
|
||||||
|
pub fn put_valid(&mut self, valid: Option<Vec<String>>) {
|
||||||
|
self.valid = valid;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// get items ref
|
||||||
|
pub fn get_items(&self) -> Option<&Vec<PrfItem>> {
|
||||||
|
self.items.as_ref()
|
||||||
|
}
|
||||||
|
|
||||||
/// find the item by the uid
|
/// find the item by the uid
|
||||||
pub fn get_item(&self, uid: &String) -> Result<&PrfItem> {
|
pub fn get_item(&self, uid: &String) -> Result<&PrfItem> {
|
||||||
if self.items.is_some() {
|
if self.items.is_some() {
|
||||||
@@ -447,7 +153,7 @@ impl Profiles {
|
|||||||
self.save_file()
|
self.save_file()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// update the item's value
|
/// update the item value
|
||||||
pub fn patch_item(&mut self, uid: String, item: PrfItem) -> Result<()> {
|
pub fn patch_item(&mut self, uid: String, item: PrfItem) -> Result<()> {
|
||||||
let mut items = self.items.take().unwrap_or(vec![]);
|
let mut items = self.items.take().unwrap_or(vec![]);
|
||||||
|
|
||||||
@@ -482,7 +188,7 @@ impl Profiles {
|
|||||||
// find the item
|
// find the item
|
||||||
let _ = self.get_item(&uid)?;
|
let _ = self.get_item(&uid)?;
|
||||||
|
|
||||||
self.items.as_mut().map(|items| {
|
if let Some(items) = self.items.as_mut() {
|
||||||
let some_uid = Some(uid.clone());
|
let some_uid = Some(uid.clone());
|
||||||
|
|
||||||
for mut each in items.iter_mut() {
|
for mut each in items.iter_mut() {
|
||||||
@@ -502,15 +208,15 @@ impl Profiles {
|
|||||||
let path = dirs::app_profiles_dir().join(&file);
|
let path = dirs::app_profiles_dir().join(&file);
|
||||||
|
|
||||||
fs::File::create(path)
|
fs::File::create(path)
|
||||||
.unwrap()
|
.context(format!("failed to create file \"{}\"", file))?
|
||||||
.write(file_data.as_bytes())
|
.write(file_data.as_bytes())
|
||||||
.unwrap();
|
.context(format!("failed to write to file \"{}\"", file))?;
|
||||||
}
|
}
|
||||||
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
}
|
||||||
|
|
||||||
self.save_file()
|
self.save_file()
|
||||||
}
|
}
|
||||||
@@ -599,69 +305,13 @@ impl Profiles {
|
|||||||
None => vec![],
|
None => vec![],
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let valid = self.valid.clone().unwrap_or(vec![]);
|
||||||
|
|
||||||
Ok(PrfEnhanced {
|
Ok(PrfEnhanced {
|
||||||
current,
|
current,
|
||||||
chain,
|
chain,
|
||||||
|
valid,
|
||||||
callback,
|
callback,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
|
|
||||||
pub struct PrfEnhanced {
|
|
||||||
pub current: Mapping,
|
|
||||||
|
|
||||||
pub chain: Vec<PrfData>,
|
|
||||||
|
|
||||||
pub callback: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
|
|
||||||
pub struct PrfEnhancedResult {
|
|
||||||
pub data: Option<Mapping>,
|
|
||||||
|
|
||||||
pub status: String,
|
|
||||||
|
|
||||||
pub error: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
|
|
||||||
pub struct PrfData {
|
|
||||||
item: PrfItem,
|
|
||||||
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
merge: Option<Mapping>,
|
|
||||||
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
script: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PrfData {
|
|
||||||
pub fn from_item(item: &PrfItem) -> Option<PrfData> {
|
|
||||||
match item.itype.as_ref() {
|
|
||||||
Some(itype) => {
|
|
||||||
let file = item.file.clone()?;
|
|
||||||
let path = dirs::app_profiles_dir().join(file);
|
|
||||||
|
|
||||||
if !path.exists() {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
match itype.as_str() {
|
|
||||||
"script" => Some(PrfData {
|
|
||||||
item: item.clone(),
|
|
||||||
script: Some(fs::read_to_string(path).unwrap_or("".into())),
|
|
||||||
merge: None,
|
|
||||||
}),
|
|
||||||
"merge" => Some(PrfData {
|
|
||||||
item: item.clone(),
|
|
||||||
merge: Some(config::read_yaml::<Mapping>(path)),
|
|
||||||
script: None,
|
|
||||||
}),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,409 @@
|
|||||||
|
use super::{notice::Notice, ClashInfo};
|
||||||
|
use crate::log_if_err;
|
||||||
|
use crate::utils::{config, dirs};
|
||||||
|
use anyhow::{bail, Result};
|
||||||
|
use reqwest::header::HeaderMap;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use serde_yaml::Mapping;
|
||||||
|
use std::{collections::HashMap, time::Duration};
|
||||||
|
use tauri::api::process::{Command, CommandChild, CommandEvent};
|
||||||
|
use tokio::time::sleep;
|
||||||
|
|
||||||
|
static mut CLASH_CORE: &str = "clash";
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Service {
|
||||||
|
sidecar: Option<CommandChild>,
|
||||||
|
|
||||||
|
#[allow(unused)]
|
||||||
|
service_mode: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Service {
|
||||||
|
pub fn new() -> Service {
|
||||||
|
Service {
|
||||||
|
sidecar: None,
|
||||||
|
service_mode: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_core(&mut self, clash_core: Option<String>) {
|
||||||
|
unsafe {
|
||||||
|
CLASH_CORE = Box::leak(clash_core.unwrap_or("clash".into()).into_boxed_str());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(unused)]
|
||||||
|
pub fn set_mode(&mut self, enable: bool) {
|
||||||
|
self.service_mode = enable;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
pub fn start(&mut self) -> Result<()> {
|
||||||
|
self.start_clash_by_sidecar()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
pub fn start(&mut self) -> Result<()> {
|
||||||
|
if !self.service_mode {
|
||||||
|
return self.start_clash_by_sidecar();
|
||||||
|
}
|
||||||
|
|
||||||
|
tauri::async_runtime::spawn(async move {
|
||||||
|
match Self::check_service().await {
|
||||||
|
Ok(status) => {
|
||||||
|
// 未启动clash
|
||||||
|
if status.code != 0 {
|
||||||
|
if let Err(err) = Self::start_clash_by_service().await {
|
||||||
|
log::error!("{err}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(err) => log::error!("{err}"),
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
pub fn stop(&mut self) -> Result<()> {
|
||||||
|
self.stop_clash_by_sidecar()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
pub fn stop(&mut self) -> Result<()> {
|
||||||
|
if !self.service_mode {
|
||||||
|
return self.stop_clash_by_sidecar();
|
||||||
|
}
|
||||||
|
|
||||||
|
tauri::async_runtime::spawn(async move {
|
||||||
|
if let Err(err) = Self::stop_clash_by_service().await {
|
||||||
|
log::error!("{err}");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn restart(&mut self) -> Result<()> {
|
||||||
|
self.stop()?;
|
||||||
|
self.start()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// start the clash sidecar
|
||||||
|
fn start_clash_by_sidecar(&mut self) -> Result<()> {
|
||||||
|
if self.sidecar.is_some() {
|
||||||
|
bail!("could not run clash sidecar twice");
|
||||||
|
}
|
||||||
|
|
||||||
|
let app_dir = dirs::app_home_dir();
|
||||||
|
let app_dir = app_dir.as_os_str().to_str().unwrap();
|
||||||
|
|
||||||
|
let clash_core = unsafe { CLASH_CORE };
|
||||||
|
let cmd = Command::new_sidecar(clash_core)?;
|
||||||
|
let (mut rx, cmd_child) = cmd.args(["-d", app_dir]).spawn()?;
|
||||||
|
|
||||||
|
self.sidecar = Some(cmd_child);
|
||||||
|
|
||||||
|
// clash log
|
||||||
|
tauri::async_runtime::spawn(async move {
|
||||||
|
while let Some(event) = rx.recv().await {
|
||||||
|
match event {
|
||||||
|
CommandEvent::Stdout(line) => log::info!("[clash]: {}", line),
|
||||||
|
CommandEvent::Stderr(err) => log::error!("[clash]: {}", err),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// stop the clash sidecar
|
||||||
|
fn stop_clash_by_sidecar(&mut self) -> Result<()> {
|
||||||
|
if let Some(sidecar) = self.sidecar.take() {
|
||||||
|
sidecar.kill()?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// update clash config
|
||||||
|
/// using PUT methods
|
||||||
|
pub fn set_config(&self, info: ClashInfo, config: Mapping, notice: Notice) -> Result<()> {
|
||||||
|
if !self.service_mode && self.sidecar.is_none() {
|
||||||
|
bail!("did not start sidecar");
|
||||||
|
}
|
||||||
|
|
||||||
|
let temp_path = dirs::profiles_temp_path();
|
||||||
|
config::save_yaml(temp_path.clone(), &config, Some("# Clash Verge Temp File"))?;
|
||||||
|
|
||||||
|
if info.server.is_none() {
|
||||||
|
bail!("failed to parse the server");
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
tauri::async_runtime::spawn(async move {
|
||||||
|
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 with status \"{}\"", resp.status());
|
||||||
|
}
|
||||||
|
|
||||||
|
notice.refresh_clash();
|
||||||
|
|
||||||
|
// 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(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Service {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
log_if_err!(self.stop());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// ### Service Mode
|
||||||
|
///
|
||||||
|
#[cfg(windows)]
|
||||||
|
pub mod win_service {
|
||||||
|
use super::*;
|
||||||
|
use anyhow::Context;
|
||||||
|
use deelevate::{PrivilegeLevel, Token};
|
||||||
|
use runas::Command as RunasCommand;
|
||||||
|
use std::os::windows::process::CommandExt;
|
||||||
|
use std::{env::current_exe, process::Command as StdCommand};
|
||||||
|
|
||||||
|
const SERVICE_NAME: &str = "clash_verge_service";
|
||||||
|
|
||||||
|
const SERVICE_URL: &str = "http://127.0.0.1:33211";
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||||
|
pub struct ResponseBody {
|
||||||
|
pub bin_path: String,
|
||||||
|
pub config_dir: String,
|
||||||
|
pub log_file: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||||
|
pub struct JsonResponse {
|
||||||
|
pub code: u64,
|
||||||
|
pub msg: String,
|
||||||
|
pub data: Option<ResponseBody>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Service {
|
||||||
|
/// Install the Clash Verge Service
|
||||||
|
/// 该函数应该在协程或者线程中执行,避免UAC弹窗阻塞主线程
|
||||||
|
pub async fn install_service() -> Result<()> {
|
||||||
|
let binary_path = dirs::service_path();
|
||||||
|
let install_path = binary_path.with_file_name("install-service.exe");
|
||||||
|
|
||||||
|
if !install_path.exists() {
|
||||||
|
bail!("installer exe not found");
|
||||||
|
}
|
||||||
|
|
||||||
|
let token = Token::with_current_process()?;
|
||||||
|
let level = token.privilege_level()?;
|
||||||
|
|
||||||
|
let status = match level {
|
||||||
|
PrivilegeLevel::NotPrivileged => RunasCommand::new(install_path).status()?,
|
||||||
|
_ => StdCommand::new(install_path)
|
||||||
|
.creation_flags(0x08000000)
|
||||||
|
.status()?,
|
||||||
|
};
|
||||||
|
|
||||||
|
if !status.success() {
|
||||||
|
bail!(
|
||||||
|
"failed to install service with status {}",
|
||||||
|
status.code().unwrap()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Uninstall the Clash Verge Service
|
||||||
|
/// 该函数应该在协程或者线程中执行,避免UAC弹窗阻塞主线程
|
||||||
|
pub async fn uninstall_service() -> Result<()> {
|
||||||
|
let binary_path = dirs::service_path();
|
||||||
|
let uninstall_path = binary_path.with_file_name("uninstall-service.exe");
|
||||||
|
|
||||||
|
if !uninstall_path.exists() {
|
||||||
|
bail!("uninstaller exe not found");
|
||||||
|
}
|
||||||
|
|
||||||
|
let token = Token::with_current_process()?;
|
||||||
|
let level = token.privilege_level()?;
|
||||||
|
|
||||||
|
let status = match level {
|
||||||
|
PrivilegeLevel::NotPrivileged => RunasCommand::new(uninstall_path).status()?,
|
||||||
|
_ => StdCommand::new(uninstall_path)
|
||||||
|
.creation_flags(0x08000000)
|
||||||
|
.status()?,
|
||||||
|
};
|
||||||
|
|
||||||
|
if !status.success() {
|
||||||
|
bail!(
|
||||||
|
"failed to uninstall service with status {}",
|
||||||
|
status.code().unwrap()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [deprecated]
|
||||||
|
/// start service
|
||||||
|
/// 该函数应该在协程或者线程中执行,避免UAC弹窗阻塞主线程
|
||||||
|
pub async fn start_service() -> Result<()> {
|
||||||
|
let token = Token::with_current_process()?;
|
||||||
|
let level = token.privilege_level()?;
|
||||||
|
|
||||||
|
let args = ["start", SERVICE_NAME];
|
||||||
|
|
||||||
|
let status = match level {
|
||||||
|
PrivilegeLevel::NotPrivileged => RunasCommand::new("sc").args(&args).status()?,
|
||||||
|
_ => StdCommand::new("sc").args(&args).status()?,
|
||||||
|
};
|
||||||
|
|
||||||
|
match status.success() {
|
||||||
|
true => Ok(()),
|
||||||
|
false => bail!(
|
||||||
|
"failed to start service with status {}",
|
||||||
|
status.code().unwrap()
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// stop service
|
||||||
|
pub async fn stop_service() -> Result<()> {
|
||||||
|
let url = format!("{SERVICE_URL}/stop_service");
|
||||||
|
let res = reqwest::ClientBuilder::new()
|
||||||
|
.no_proxy()
|
||||||
|
.build()?
|
||||||
|
.post(url)
|
||||||
|
.send()
|
||||||
|
.await?
|
||||||
|
.json::<JsonResponse>()
|
||||||
|
.await
|
||||||
|
.context("failed to connect to the Clash Verge Service")?;
|
||||||
|
|
||||||
|
if res.code != 0 {
|
||||||
|
bail!(res.msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// check the windows service status
|
||||||
|
pub async fn check_service() -> Result<JsonResponse> {
|
||||||
|
let url = format!("{SERVICE_URL}/get_clash");
|
||||||
|
let response = reqwest::ClientBuilder::new()
|
||||||
|
.no_proxy()
|
||||||
|
.build()?
|
||||||
|
.get(url)
|
||||||
|
.send()
|
||||||
|
.await?
|
||||||
|
.json::<JsonResponse>()
|
||||||
|
.await
|
||||||
|
.context("failed to connect to the Clash Verge Service")?;
|
||||||
|
|
||||||
|
Ok(response)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// start the clash by service
|
||||||
|
pub(super) async fn start_clash_by_service() -> Result<()> {
|
||||||
|
let status = Self::check_service().await?;
|
||||||
|
|
||||||
|
if status.code == 0 {
|
||||||
|
Self::stop_clash_by_service().await?;
|
||||||
|
sleep(Duration::from_secs(1)).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
let clash_core = unsafe { CLASH_CORE };
|
||||||
|
let clash_bin = format!("{clash_core}.exe");
|
||||||
|
let bin_path = current_exe().unwrap().with_file_name(clash_bin);
|
||||||
|
let bin_path = bin_path.as_os_str().to_str().unwrap();
|
||||||
|
|
||||||
|
let config_dir = dirs::app_home_dir();
|
||||||
|
let config_dir = config_dir.as_os_str().to_str().unwrap();
|
||||||
|
|
||||||
|
let log_path = dirs::service_log_file();
|
||||||
|
let log_path = log_path.as_os_str().to_str().unwrap();
|
||||||
|
|
||||||
|
let mut map = HashMap::new();
|
||||||
|
map.insert("bin_path", bin_path);
|
||||||
|
map.insert("config_dir", config_dir);
|
||||||
|
map.insert("log_file", log_path);
|
||||||
|
|
||||||
|
let url = format!("{SERVICE_URL}/start_clash");
|
||||||
|
let res = reqwest::ClientBuilder::new()
|
||||||
|
.no_proxy()
|
||||||
|
.build()?
|
||||||
|
.post(url)
|
||||||
|
.json(&map)
|
||||||
|
.send()
|
||||||
|
.await?
|
||||||
|
.json::<JsonResponse>()
|
||||||
|
.await
|
||||||
|
.context("failed to connect to the Clash Verge Service")?;
|
||||||
|
|
||||||
|
if res.code != 0 {
|
||||||
|
bail!(res.msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// stop the clash by service
|
||||||
|
pub(super) async fn stop_clash_by_service() -> Result<()> {
|
||||||
|
let url = format!("{SERVICE_URL}/stop_clash");
|
||||||
|
let res = reqwest::ClientBuilder::new()
|
||||||
|
.no_proxy()
|
||||||
|
.build()?
|
||||||
|
.post(url)
|
||||||
|
.send()
|
||||||
|
.await?
|
||||||
|
.json::<JsonResponse>()
|
||||||
|
.await
|
||||||
|
.context("failed to connect to the Clash Verge Service")?;
|
||||||
|
|
||||||
|
if res.code != 0 {
|
||||||
|
bail!(res.msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,205 @@
|
|||||||
|
use super::{Clash, Verge};
|
||||||
|
use crate::{log_if_err, utils::sysopt::SysProxyConfig};
|
||||||
|
use anyhow::{bail, Result};
|
||||||
|
use auto_launch::{AutoLaunch, AutoLaunchBuilder};
|
||||||
|
// use parking_lot::Mutex;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use tauri::{async_runtime::Mutex, utils::platform::current_exe};
|
||||||
|
|
||||||
|
pub struct Sysopt {
|
||||||
|
/// current system proxy setting
|
||||||
|
cur_sysproxy: Option<SysProxyConfig>,
|
||||||
|
|
||||||
|
/// 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 Sysopt {
|
||||||
|
pub fn new() -> Sysopt {
|
||||||
|
Sysopt {
|
||||||
|
cur_sysproxy: None,
|
||||||
|
old_sysproxy: None,
|
||||||
|
auto_launch: None,
|
||||||
|
guard_state: Arc::new(Mutex::new(false)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// init the sysproxy
|
||||||
|
pub fn init_sysproxy(&mut self, port: Option<String>, verge: &Verge) {
|
||||||
|
if let Some(port) = port {
|
||||||
|
let enable = verge.enable_system_proxy.clone().unwrap_or(false);
|
||||||
|
|
||||||
|
self.old_sysproxy = match SysProxyConfig::get_sys() {
|
||||||
|
Ok(proxy) => Some(proxy),
|
||||||
|
Err(_) => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
let bypass = verge.system_proxy_bypass.clone();
|
||||||
|
let sysproxy = SysProxyConfig::new(enable, port, bypass);
|
||||||
|
|
||||||
|
if enable {
|
||||||
|
if let Err(err) = sysproxy.set_sys() {
|
||||||
|
log::error!("failed to set system proxy for `{err}`");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
self.cur_sysproxy = Some(sysproxy);
|
||||||
|
}
|
||||||
|
|
||||||
|
// launchs the system proxy guard
|
||||||
|
self.guard_proxy();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// update the system proxy
|
||||||
|
/// when the verge config is changed
|
||||||
|
pub fn update_sysproxy(&mut self, enable: Option<bool>, bypass: Option<String>) -> Result<()> {
|
||||||
|
let sysproxy = self.cur_sysproxy.take();
|
||||||
|
|
||||||
|
if sysproxy.is_none() {
|
||||||
|
bail!("unhandle error for sysproxy is none");
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut sysproxy = sysproxy.unwrap();
|
||||||
|
|
||||||
|
if let Some(enable) = enable {
|
||||||
|
sysproxy.enable = enable;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(bypass) = bypass {
|
||||||
|
sysproxy.bypass = bypass;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.cur_sysproxy = Some(sysproxy);
|
||||||
|
|
||||||
|
if self.cur_sysproxy.as_ref().unwrap().set_sys().is_err() {
|
||||||
|
bail!("failed to set system proxy");
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// reset the sysproxy
|
||||||
|
pub fn reset_sysproxy(&mut self) {
|
||||||
|
if let Some(sysproxy) = self.old_sysproxy.take() {
|
||||||
|
match sysproxy.set_sys() {
|
||||||
|
Ok(_) => self.cur_sysproxy = None,
|
||||||
|
Err(_) => log::error!("failed to reset proxy"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// get current proxy
|
||||||
|
pub fn get_sysproxy(&self) -> Result<Option<SysProxyConfig>> {
|
||||||
|
Ok(self.cur_sysproxy.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// init the auto launch
|
||||||
|
pub fn init_launch(&mut self, enable: Option<bool>) -> Result<()> {
|
||||||
|
let app_exe = current_exe().unwrap();
|
||||||
|
let app_exe = dunce::canonicalize(app_exe).unwrap();
|
||||||
|
let app_name = app_exe.file_stem().unwrap().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()
|
||||||
|
.set_app_name(app_name)
|
||||||
|
.set_app_path(app_path)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
if let Some(enable) = enable {
|
||||||
|
// fix issue #26
|
||||||
|
if enable {
|
||||||
|
auto.enable()?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
self.auto_launch = Some(auto);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// update the startup
|
||||||
|
pub fn update_launch(&mut self, enable: Option<bool>) -> Result<()> {
|
||||||
|
if enable.is_none() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
let enable = enable.unwrap();
|
||||||
|
let auto_launch = self.auto_launch.as_ref().unwrap();
|
||||||
|
|
||||||
|
match enable {
|
||||||
|
true => auto_launch.enable()?,
|
||||||
|
false => auto_launch.disable()?,
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// launch a system proxy guard
|
||||||
|
/// read config from file directly
|
||||||
|
pub fn guard_proxy(&self) {
|
||||||
|
use tokio::time::{sleep, Duration};
|
||||||
|
|
||||||
|
let guard_state = self.guard_state.clone();
|
||||||
|
|
||||||
|
tauri::async_runtime::spawn(async move {
|
||||||
|
// if it is running, exit
|
||||||
|
let mut state = guard_state.lock().await;
|
||||||
|
if *state {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
*state = true;
|
||||||
|
drop(state);
|
||||||
|
|
||||||
|
// default duration is 10s
|
||||||
|
let mut wait_secs = 10u64;
|
||||||
|
|
||||||
|
loop {
|
||||||
|
sleep(Duration::from_secs(wait_secs)).await;
|
||||||
|
|
||||||
|
let verge = Verge::new();
|
||||||
|
|
||||||
|
let enable_proxy = verge.enable_system_proxy.unwrap_or(false);
|
||||||
|
let enable_guard = verge.enable_proxy_guard.unwrap_or(false);
|
||||||
|
let guard_duration = verge.proxy_guard_duration.unwrap_or(10);
|
||||||
|
|
||||||
|
// update duration
|
||||||
|
wait_secs = guard_duration;
|
||||||
|
|
||||||
|
// stop loop
|
||||||
|
if !enable_guard || !enable_proxy {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
log::debug!("try to guard the system proxy");
|
||||||
|
|
||||||
|
let clash = Clash::new();
|
||||||
|
|
||||||
|
match &clash.info.port {
|
||||||
|
Some(port) => {
|
||||||
|
let bypass = verge.system_proxy_bypass.clone();
|
||||||
|
let sysproxy = SysProxyConfig::new(true, port.clone(), bypass);
|
||||||
|
|
||||||
|
log_if_err!(sysproxy.set_sys());
|
||||||
|
}
|
||||||
|
None => log::error!("failed to parse clash port"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut state = guard_state.lock().await;
|
||||||
|
*state = false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
use super::Core;
|
||||||
|
use crate::log_if_err;
|
||||||
|
use anyhow::{bail, Context, Result};
|
||||||
|
use delay_timer::prelude::{DelayTimer, DelayTimerBuilder, TaskBuilder};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
type TaskID = u64;
|
||||||
|
|
||||||
|
pub struct Timer {
|
||||||
|
/// cron manager
|
||||||
|
delay_timer: DelayTimer,
|
||||||
|
|
||||||
|
/// save the current state
|
||||||
|
timer_map: HashMap<String, (TaskID, u64)>,
|
||||||
|
|
||||||
|
/// increment id
|
||||||
|
timer_count: TaskID,
|
||||||
|
|
||||||
|
/// save the instance of the app
|
||||||
|
core: Option<Core>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Timer {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Timer {
|
||||||
|
delay_timer: DelayTimerBuilder::default().build(),
|
||||||
|
timer_map: HashMap::new(),
|
||||||
|
timer_count: 1,
|
||||||
|
core: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_core(&mut self, core: Core) {
|
||||||
|
self.core = Some(core);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Correctly update all cron tasks
|
||||||
|
pub fn refresh(&mut self) -> Result<()> {
|
||||||
|
if self.core.is_none() {
|
||||||
|
bail!("unhandle error for core is none");
|
||||||
|
}
|
||||||
|
|
||||||
|
let diff_map = self.gen_diff();
|
||||||
|
|
||||||
|
for (uid, diff) in diff_map.into_iter() {
|
||||||
|
match diff {
|
||||||
|
DiffFlag::Del(tid) => {
|
||||||
|
let _ = self.timer_map.remove(&uid);
|
||||||
|
log_if_err!(self.delay_timer.remove_task(tid));
|
||||||
|
}
|
||||||
|
DiffFlag::Add(tid, val) => {
|
||||||
|
let _ = self.timer_map.insert(uid.clone(), (tid, val));
|
||||||
|
log_if_err!(self.add_task(uid, tid, val));
|
||||||
|
}
|
||||||
|
DiffFlag::Mod(tid, val) => {
|
||||||
|
let _ = self.timer_map.insert(uid.clone(), (tid, val));
|
||||||
|
log_if_err!(self.delay_timer.remove_task(tid));
|
||||||
|
log_if_err!(self.add_task(uid, tid, val));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// generate a uid -> update_interval map
|
||||||
|
fn gen_map(&self) -> HashMap<String, u64> {
|
||||||
|
let profiles = self.core.as_ref().unwrap().profiles.lock();
|
||||||
|
|
||||||
|
let mut new_map = HashMap::new();
|
||||||
|
|
||||||
|
if let Some(items) = profiles.get_items() {
|
||||||
|
for item in items.iter() {
|
||||||
|
if item.option.is_some() {
|
||||||
|
let option = item.option.as_ref().unwrap();
|
||||||
|
let interval = option.update_interval.unwrap_or(0);
|
||||||
|
|
||||||
|
if interval > 0 {
|
||||||
|
new_map.insert(item.uid.clone().unwrap(), interval);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
new_map
|
||||||
|
}
|
||||||
|
|
||||||
|
/// generate the diff map for refresh
|
||||||
|
fn gen_diff(&mut self) -> HashMap<String, DiffFlag> {
|
||||||
|
let mut diff_map = HashMap::new();
|
||||||
|
|
||||||
|
let new_map = self.gen_map();
|
||||||
|
let cur_map = &self.timer_map;
|
||||||
|
|
||||||
|
cur_map.iter().for_each(|(uid, (tid, val))| {
|
||||||
|
let new_val = new_map.get(uid).unwrap_or(&0);
|
||||||
|
|
||||||
|
if *new_val == 0 {
|
||||||
|
diff_map.insert(uid.clone(), DiffFlag::Del(*tid));
|
||||||
|
} else if new_val != val {
|
||||||
|
diff_map.insert(uid.clone(), DiffFlag::Mod(*tid, *new_val));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let mut count = self.timer_count;
|
||||||
|
|
||||||
|
new_map.iter().for_each(|(uid, val)| {
|
||||||
|
if cur_map.get(uid).is_none() {
|
||||||
|
diff_map.insert(uid.clone(), DiffFlag::Add(count, *val));
|
||||||
|
|
||||||
|
count += 1;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
self.timer_count = count;
|
||||||
|
|
||||||
|
diff_map
|
||||||
|
}
|
||||||
|
|
||||||
|
/// add a cron task
|
||||||
|
fn add_task(&self, uid: String, tid: TaskID, minutes: u64) -> Result<()> {
|
||||||
|
let core = self.core.clone().unwrap();
|
||||||
|
|
||||||
|
let task = TaskBuilder::default()
|
||||||
|
.set_task_id(tid)
|
||||||
|
.set_maximum_parallel_runnable_num(1)
|
||||||
|
.set_frequency_repeated_by_minutes(minutes)
|
||||||
|
// .set_frequency_repeated_by_seconds(minutes) // for test
|
||||||
|
.spawn_async_routine(move || Self::async_task(core.clone(), uid.clone()))
|
||||||
|
.context("failed to create timer task")?;
|
||||||
|
|
||||||
|
self
|
||||||
|
.delay_timer
|
||||||
|
.add_task(task)
|
||||||
|
.context("failed to add timer task")?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// the task runner
|
||||||
|
async fn async_task(core: Core, uid: String) {
|
||||||
|
log::info!("running timer task `{uid}`");
|
||||||
|
log_if_err!(Core::update_profile_item(core, uid, None).await);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
enum DiffFlag {
|
||||||
|
Del(TaskID),
|
||||||
|
Add(TaskID, u64),
|
||||||
|
Mod(TaskID, u64),
|
||||||
|
}
|
||||||
@@ -1,17 +1,10 @@
|
|||||||
use crate::log_if_err;
|
use crate::utils::{config, dirs};
|
||||||
use crate::{
|
use anyhow::Result;
|
||||||
core::Clash,
|
|
||||||
utils::{config, dirs, sysopt::SysProxyConfig},
|
|
||||||
};
|
|
||||||
use anyhow::{bail, Result};
|
|
||||||
use auto_launch::{AutoLaunch, AutoLaunchBuilder};
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
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 Verge {
|
||||||
// i18n
|
// i18n
|
||||||
pub language: Option<String>,
|
pub language: Option<String>,
|
||||||
|
|
||||||
@@ -28,6 +21,10 @@ pub struct VergeConfig {
|
|||||||
/// clash tun mode
|
/// clash tun mode
|
||||||
pub enable_tun_mode: Option<bool>,
|
pub enable_tun_mode: Option<bool>,
|
||||||
|
|
||||||
|
/// windows service mode
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub enable_service_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>,
|
||||||
|
|
||||||
@@ -45,11 +42,34 @@ pub struct VergeConfig {
|
|||||||
|
|
||||||
/// proxy guard duration
|
/// proxy guard duration
|
||||||
pub proxy_guard_duration: Option<u64>,
|
pub proxy_guard_duration: Option<u64>,
|
||||||
|
|
||||||
|
/// theme setting
|
||||||
|
pub theme_setting: Option<VergeTheme>,
|
||||||
|
|
||||||
|
/// clash core path
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub clash_core: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl VergeConfig {
|
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||||
|
pub struct VergeTheme {
|
||||||
|
pub primary_color: Option<String>,
|
||||||
|
pub secondary_color: Option<String>,
|
||||||
|
pub primary_text: Option<String>,
|
||||||
|
pub secondary_text: Option<String>,
|
||||||
|
|
||||||
|
pub info_color: Option<String>,
|
||||||
|
pub error_color: Option<String>,
|
||||||
|
pub warning_color: Option<String>,
|
||||||
|
pub success_color: Option<String>,
|
||||||
|
|
||||||
|
pub font_family: Option<String>,
|
||||||
|
pub css_injection: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Verge {
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
config::read_yaml::<VergeConfig>(dirs::verge_path())
|
config::read_yaml::<Verge>(dirs::verge_path())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Save Verge App Config
|
/// Save Verge App Config
|
||||||
@@ -60,273 +80,60 @@ impl VergeConfig {
|
|||||||
Some("# The Config for Clash Verge App\n\n"),
|
Some("# The Config for Clash Verge App\n\n"),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// Verge App abilities
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct Verge {
|
|
||||||
/// manage the verge config
|
|
||||||
pub config: VergeConfig,
|
|
||||||
|
|
||||||
/// current system proxy setting
|
|
||||||
pub cur_sysproxy: Option<SysProxyConfig>,
|
|
||||||
|
|
||||||
/// 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 {
|
|
||||||
fn default() -> Self {
|
|
||||||
Verge::new()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Verge {
|
|
||||||
pub fn new() -> Self {
|
|
||||||
Verge {
|
|
||||||
config: VergeConfig::new(),
|
|
||||||
old_sysproxy: None,
|
|
||||||
cur_sysproxy: None,
|
|
||||||
auto_launch: None,
|
|
||||||
guard_state: Arc::new(Mutex::new(false)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// init the sysproxy
|
|
||||||
pub fn init_sysproxy(&mut self, port: Option<String>) {
|
|
||||||
if let Some(port) = port {
|
|
||||||
let enable = self.config.enable_system_proxy.clone().unwrap_or(false);
|
|
||||||
|
|
||||||
self.old_sysproxy = match SysProxyConfig::get_sys() {
|
|
||||||
Ok(proxy) => Some(proxy),
|
|
||||||
Err(_) => None,
|
|
||||||
};
|
|
||||||
|
|
||||||
let bypass = self.config.system_proxy_bypass.clone();
|
|
||||||
let sysproxy = SysProxyConfig::new(enable, port, bypass);
|
|
||||||
|
|
||||||
if enable {
|
|
||||||
if sysproxy.set_sys().is_err() {
|
|
||||||
log::error!("failed to set system proxy");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
self.cur_sysproxy = Some(sysproxy);
|
|
||||||
}
|
|
||||||
|
|
||||||
// launchs the system proxy guard
|
|
||||||
Verge::guard_proxy(self.guard_state.clone());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// reset the sysproxy
|
|
||||||
pub fn reset_sysproxy(&mut self) {
|
|
||||||
if let Some(sysproxy) = self.old_sysproxy.take() {
|
|
||||||
match sysproxy.set_sys() {
|
|
||||||
Ok(_) => self.cur_sysproxy = None,
|
|
||||||
Err(_) => log::error!("failed to reset proxy for"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// init the auto launch
|
|
||||||
pub fn init_launch(&mut self) -> Result<()> {
|
|
||||||
let app_exe = current_exe().unwrap();
|
|
||||||
let app_exe = dunce::canonicalize(app_exe).unwrap();
|
|
||||||
let app_name = app_exe.file_stem().unwrap().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()
|
|
||||||
.set_app_name(app_name)
|
|
||||||
.set_app_path(app_path)
|
|
||||||
.build();
|
|
||||||
|
|
||||||
if let Some(enable) = self.config.enable_auto_launch.as_ref() {
|
|
||||||
// fix issue #26
|
|
||||||
if *enable {
|
|
||||||
auto.enable()?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
self.auto_launch = Some(auto);
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// update the startup
|
|
||||||
fn update_launch(&mut self, enable: bool) -> Result<()> {
|
|
||||||
let conf_enable = self.config.enable_auto_launch.clone().unwrap_or(false);
|
|
||||||
|
|
||||||
if enable == conf_enable {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
let auto_launch = self.auto_launch.clone().unwrap();
|
|
||||||
|
|
||||||
match enable {
|
|
||||||
true => auto_launch.enable()?,
|
|
||||||
false => auto_launch.disable()?,
|
|
||||||
};
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// patch verge config
|
/// patch verge config
|
||||||
/// There should be only one update at a time here
|
/// only save to file
|
||||||
/// so call the save_file at the end is savely
|
pub fn patch_config(&mut self, patch: Verge) -> Result<()> {
|
||||||
pub fn patch_config(&mut self, patch: VergeConfig) -> Result<()> {
|
|
||||||
// only change it
|
// only change it
|
||||||
if patch.language.is_some() {
|
if patch.language.is_some() {
|
||||||
self.config.language = patch.language;
|
self.language = patch.language;
|
||||||
}
|
}
|
||||||
if patch.theme_mode.is_some() {
|
if patch.theme_mode.is_some() {
|
||||||
self.config.theme_mode = patch.theme_mode;
|
self.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.theme_blur = patch.theme_blur;
|
||||||
|
}
|
||||||
|
if patch.theme_setting.is_some() {
|
||||||
|
self.theme_setting = patch.theme_setting;
|
||||||
}
|
}
|
||||||
if patch.traffic_graph.is_some() {
|
if patch.traffic_graph.is_some() {
|
||||||
self.config.traffic_graph = patch.traffic_graph;
|
self.traffic_graph = patch.traffic_graph;
|
||||||
}
|
}
|
||||||
|
if patch.clash_core.is_some() {
|
||||||
|
self.clash_core = patch.clash_core;
|
||||||
|
}
|
||||||
|
|
||||||
|
// system setting
|
||||||
if patch.enable_silent_start.is_some() {
|
if patch.enable_silent_start.is_some() {
|
||||||
self.config.enable_silent_start = patch.enable_silent_start;
|
self.enable_silent_start = patch.enable_silent_start;
|
||||||
}
|
}
|
||||||
|
|
||||||
// should update system startup
|
|
||||||
if patch.enable_auto_launch.is_some() {
|
if patch.enable_auto_launch.is_some() {
|
||||||
let enable = patch.enable_auto_launch.unwrap();
|
self.enable_auto_launch = patch.enable_auto_launch;
|
||||||
self.update_launch(enable)?;
|
|
||||||
self.config.enable_auto_launch = Some(enable);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// should update system proxy
|
// proxy
|
||||||
if patch.enable_system_proxy.is_some() {
|
if patch.enable_system_proxy.is_some() {
|
||||||
let enable = patch.enable_system_proxy.unwrap();
|
self.enable_system_proxy = patch.enable_system_proxy;
|
||||||
|
|
||||||
if let Some(mut sysproxy) = self.cur_sysproxy.take() {
|
|
||||||
sysproxy.enable = enable;
|
|
||||||
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.enable_system_proxy = Some(enable);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// should update system proxy too
|
|
||||||
if patch.system_proxy_bypass.is_some() {
|
if patch.system_proxy_bypass.is_some() {
|
||||||
let bypass = patch.system_proxy_bypass.unwrap();
|
self.system_proxy_bypass = patch.system_proxy_bypass;
|
||||||
|
|
||||||
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() {
|
if patch.enable_proxy_guard.is_some() {
|
||||||
self.config.enable_proxy_guard = patch.enable_proxy_guard;
|
self.enable_proxy_guard = patch.enable_proxy_guard;
|
||||||
}
|
}
|
||||||
if patch.proxy_guard_duration.is_some() {
|
if patch.proxy_guard_duration.is_some() {
|
||||||
self.config.proxy_guard_duration = patch.proxy_guard_duration;
|
self.proxy_guard_duration = patch.proxy_guard_duration;
|
||||||
}
|
}
|
||||||
|
|
||||||
// relaunch the guard
|
// tun mode
|
||||||
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() {
|
if patch.enable_tun_mode.is_some() {
|
||||||
self.config.enable_tun_mode = patch.enable_tun_mode;
|
self.enable_tun_mode = patch.enable_tun_mode;
|
||||||
|
}
|
||||||
|
if patch.enable_service_mode.is_some() {
|
||||||
|
self.enable_service_mode = patch.enable_service_mode;
|
||||||
}
|
}
|
||||||
|
|
||||||
self.config.save_file()
|
self.save_file()
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Verge {
|
|
||||||
/// launch a system proxy guard
|
|
||||||
/// read config from file directly
|
|
||||||
pub fn guard_proxy(guard_state: Arc<Mutex<bool>>) {
|
|
||||||
use tokio::time::{sleep, Duration};
|
|
||||||
|
|
||||||
tauri::async_runtime::spawn(async move {
|
|
||||||
// if it is running, exit
|
|
||||||
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;
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,11 +5,10 @@
|
|||||||
|
|
||||||
mod cmds;
|
mod cmds;
|
||||||
mod core;
|
mod core;
|
||||||
mod states;
|
|
||||||
mod utils;
|
mod utils;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
core::VergeConfig,
|
core::Verge,
|
||||||
utils::{resolve, server},
|
utils::{resolve, server},
|
||||||
};
|
};
|
||||||
use tauri::{
|
use tauri::{
|
||||||
@@ -22,88 +21,89 @@ fn main() -> std::io::Result<()> {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
unsafe {
|
||||||
|
use crate::utils::dirs;
|
||||||
|
|
||||||
|
dirs::init_portable_flag();
|
||||||
|
}
|
||||||
|
|
||||||
let tray_menu = SystemTrayMenu::new()
|
let tray_menu = SystemTrayMenu::new()
|
||||||
.add_item(CustomMenuItem::new("open_window", "Show"))
|
.add_item(CustomMenuItem::new("open_window", "Show"))
|
||||||
.add_item(CustomMenuItem::new("system_proxy", "System Proxy"))
|
.add_item(CustomMenuItem::new("system_proxy", "System Proxy"))
|
||||||
|
.add_item(CustomMenuItem::new("tun_mode", "Tun Mode"))
|
||||||
.add_item(CustomMenuItem::new("restart_clash", "Restart Clash"))
|
.add_item(CustomMenuItem::new("restart_clash", "Restart Clash"))
|
||||||
.add_native_item(SystemTrayMenuItem::Separator)
|
.add_native_item(SystemTrayMenuItem::Separator)
|
||||||
.add_item(CustomMenuItem::new("quit", "Quit").accelerator("CmdOrControl+Q"));
|
.add_item(CustomMenuItem::new("quit", "Quit").accelerator("CmdOrControl+Q"));
|
||||||
|
|
||||||
#[allow(unused_mut)]
|
#[allow(unused_mut)]
|
||||||
let mut builder = tauri::Builder::default()
|
let mut builder = tauri::Builder::default()
|
||||||
.manage(states::VergeState::default())
|
.manage(core::Core::new())
|
||||||
.manage(states::ClashState::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(tray_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" => {
|
||||||
let window = app_handle.get_window("main").unwrap();
|
resolve::create_window(app_handle);
|
||||||
window.unminimize().unwrap();
|
|
||||||
window.show().unwrap();
|
|
||||||
window.set_focus().unwrap();
|
|
||||||
}
|
}
|
||||||
"system_proxy" => {
|
"system_proxy" => {
|
||||||
let verge_state = app_handle.state::<states::VergeState>();
|
let core = app_handle.state::<core::Core>();
|
||||||
let mut verge = verge_state.0.lock().unwrap();
|
|
||||||
|
|
||||||
let old_value = verge.config.enable_system_proxy.clone().unwrap_or(false);
|
let new_value = {
|
||||||
let new_value = !old_value;
|
let verge = core.verge.lock();
|
||||||
|
!verge.enable_system_proxy.clone().unwrap_or(false)
|
||||||
|
};
|
||||||
|
|
||||||
match verge.patch_config(VergeConfig {
|
let patch = Verge {
|
||||||
enable_system_proxy: Some(new_value),
|
enable_system_proxy: Some(new_value),
|
||||||
..VergeConfig::default()
|
..Verge::default()
|
||||||
}) {
|
};
|
||||||
Ok(_) => {
|
|
||||||
app_handle
|
|
||||||
.tray_handle()
|
|
||||||
.get_item(id.as_str())
|
|
||||||
.set_selected(new_value)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
// update verge config
|
crate::log_if_err!(core.patch_verge(patch, app_handle));
|
||||||
let window = app_handle.get_window("main").unwrap();
|
}
|
||||||
window.emit("verge://refresh-verge-config", "yes").unwrap();
|
"tun_mode" => {
|
||||||
}
|
let core = app_handle.state::<core::Core>();
|
||||||
Err(err) => log::error!("{err}"),
|
|
||||||
}
|
let new_value = {
|
||||||
|
let verge = core.verge.lock();
|
||||||
|
!verge.enable_tun_mode.clone().unwrap_or(false)
|
||||||
|
};
|
||||||
|
|
||||||
|
let patch = Verge {
|
||||||
|
enable_tun_mode: Some(new_value),
|
||||||
|
..Verge::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
crate::log_if_err!(core.patch_verge(patch, app_handle));
|
||||||
}
|
}
|
||||||
"restart_clash" => {
|
"restart_clash" => {
|
||||||
let clash_state = app_handle.state::<states::ClashState>();
|
let core = app_handle.state::<core::Core>();
|
||||||
let profiles_state = app_handle.state::<states::ProfilesState>();
|
crate::log_if_err!(core.restart_clash());
|
||||||
let mut clash = clash_state.0.lock().unwrap();
|
|
||||||
let mut profiles = profiles_state.0.lock().unwrap();
|
|
||||||
|
|
||||||
crate::log_if_err!(clash.restart_sidecar(&mut profiles));
|
|
||||||
}
|
}
|
||||||
"quit" => {
|
"quit" => {
|
||||||
resolve::resolve_reset(app_handle);
|
resolve::resolve_reset(app_handle);
|
||||||
api::process::kill_children();
|
app_handle.exit(0);
|
||||||
std::process::exit(0);
|
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
},
|
},
|
||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
SystemTrayEvent::LeftClick { .. } => {
|
SystemTrayEvent::LeftClick { .. } => {
|
||||||
let window = app_handle.get_window("main").unwrap();
|
resolve::create_window(app_handle);
|
||||||
window.unminimize().unwrap();
|
|
||||||
window.show().unwrap();
|
|
||||||
window.set_focus().unwrap();
|
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
})
|
})
|
||||||
.invoke_handler(tauri::generate_handler![
|
.invoke_handler(tauri::generate_handler![
|
||||||
// common
|
// common
|
||||||
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_app_dir,
|
||||||
cmds::open_logs_dir,
|
cmds::open_logs_dir,
|
||||||
|
cmds::kill_sidecar,
|
||||||
|
cmds::restart_sidecar,
|
||||||
// clash
|
// clash
|
||||||
cmds::get_clash_info,
|
cmds::get_clash_info,
|
||||||
cmds::patch_clash_config,
|
cmds::patch_clash_config,
|
||||||
|
cmds::change_clash_core,
|
||||||
// verge
|
// verge
|
||||||
cmds::get_verge_config,
|
cmds::get_verge_config,
|
||||||
cmds::patch_verge_config,
|
cmds::patch_verge_config,
|
||||||
@@ -116,11 +116,17 @@ fn main() -> std::io::Result<()> {
|
|||||||
cmds::delete_profile,
|
cmds::delete_profile,
|
||||||
cmds::select_profile,
|
cmds::select_profile,
|
||||||
cmds::get_profiles,
|
cmds::get_profiles,
|
||||||
cmds::sync_profiles,
|
|
||||||
cmds::enhance_profiles,
|
cmds::enhance_profiles,
|
||||||
cmds::change_profile_chain,
|
cmds::change_profile_chain,
|
||||||
|
cmds::change_profile_valid,
|
||||||
cmds::read_profile_file,
|
cmds::read_profile_file,
|
||||||
cmds::save_profile_file
|
cmds::save_profile_file,
|
||||||
|
// service mode
|
||||||
|
cmds::service::start_service,
|
||||||
|
cmds::service::stop_service,
|
||||||
|
cmds::service::check_service,
|
||||||
|
cmds::service::install_service,
|
||||||
|
cmds::service::uninstall_service,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
@@ -144,12 +150,10 @@ fn main() -> std::io::Result<()> {
|
|||||||
.build(tauri::generate_context!())
|
.build(tauri::generate_context!())
|
||||||
.expect("error while running tauri application")
|
.expect("error while running tauri application")
|
||||||
.run(|app_handle, e| match e {
|
.run(|app_handle, e| match e {
|
||||||
tauri::RunEvent::CloseRequested { label, api, .. } => {
|
tauri::RunEvent::ExitRequested { api, .. } => {
|
||||||
let app_handle = app_handle.clone();
|
api.prevent_exit();
|
||||||
api.prevent_close();
|
|
||||||
app_handle.get_window(&label).unwrap().hide().unwrap();
|
|
||||||
}
|
}
|
||||||
tauri::RunEvent::ExitRequested { .. } => {
|
tauri::RunEvent::Exit => {
|
||||||
resolve::resolve_reset(app_handle);
|
resolve::resolve_reset(app_handle);
|
||||||
api::process::kill_children();
|
api::process::kill_children();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
use crate::core::{Clash, Profiles, Verge};
|
// use crate::core::{Clash, Profiles, Verge};
|
||||||
use std::sync::{Arc, Mutex};
|
// use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
#[derive(Default)]
|
// #[derive(Default)]
|
||||||
pub struct ProfilesState(pub Arc<Mutex<Profiles>>);
|
// pub struct ProfilesState(pub Arc<Mutex<Profiles>>);
|
||||||
|
|
||||||
#[derive(Default)]
|
// #[derive(Default)]
|
||||||
pub struct ClashState(pub Arc<Mutex<Clash>>);
|
// pub struct ClashState(pub Arc<Mutex<Clash>>);
|
||||||
|
|
||||||
#[derive(Default)]
|
// #[derive(Default)]
|
||||||
pub struct VergeState(pub Arc<Mutex<Verge>>);
|
// pub struct VergeState(pub Arc<Mutex<Verge>>);
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use std::env::temp_dir;
|
use std::env::temp_dir;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::PathBuf;
|
||||||
use tauri::{
|
use tauri::{
|
||||||
api::path::{home_dir, resource_dir},
|
api::path::{home_dir, resource_dir},
|
||||||
Env, PackageInfo,
|
Env, PackageInfo,
|
||||||
@@ -15,19 +15,62 @@ static VERGE_CONFIG: &str = "verge.yaml";
|
|||||||
static PROFILE_YAML: &str = "profiles.yaml";
|
static PROFILE_YAML: &str = "profiles.yaml";
|
||||||
static PROFILE_TEMP: &str = "clash-verge-runtime.yaml";
|
static PROFILE_TEMP: &str = "clash-verge-runtime.yaml";
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
static mut RESOURCE_DIR: Option<PathBuf> = None;
|
||||||
|
|
||||||
|
/// portable flag
|
||||||
|
#[allow(unused)]
|
||||||
|
static mut PORTABLE_FLAG: bool = false;
|
||||||
|
|
||||||
|
/// initialize portable flag
|
||||||
|
#[allow(unused)]
|
||||||
|
pub unsafe fn init_portable_flag() {
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
{
|
||||||
|
use tauri::utils::platform::current_exe;
|
||||||
|
|
||||||
|
let exe = current_exe().unwrap();
|
||||||
|
let dir = exe.parent().unwrap();
|
||||||
|
let dir = PathBuf::from(dir).join(".config/PORTABLE");
|
||||||
|
|
||||||
|
if dir.exists() {
|
||||||
|
PORTABLE_FLAG = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// get the verge app home dir
|
/// get the verge app home dir
|
||||||
pub fn app_home_dir() -> PathBuf {
|
pub fn app_home_dir() -> PathBuf {
|
||||||
home_dir()
|
#[cfg(target_os = "windows")]
|
||||||
.unwrap()
|
unsafe {
|
||||||
.join(Path::new(".config"))
|
use tauri::utils::platform::current_exe;
|
||||||
.join(Path::new(APP_DIR))
|
|
||||||
|
if !PORTABLE_FLAG {
|
||||||
|
home_dir().unwrap().join(".config").join(APP_DIR)
|
||||||
|
} else {
|
||||||
|
let app_exe = current_exe().unwrap();
|
||||||
|
let app_exe = dunce::canonicalize(app_exe).unwrap();
|
||||||
|
let app_dir = app_exe.parent().unwrap();
|
||||||
|
PathBuf::from(app_dir).join(".config").join(APP_DIR)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(target_os = "windows"))]
|
||||||
|
home_dir().unwrap().join(".config").join(APP_DIR)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// get the resources dir
|
/// get the resources dir
|
||||||
pub fn app_resources_dir(package_info: &PackageInfo) -> PathBuf {
|
pub fn app_resources_dir(package_info: &PackageInfo) -> PathBuf {
|
||||||
resource_dir(package_info, &Env::default())
|
let res_dir = resource_dir(package_info, &Env::default())
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.join("resources")
|
.join("resources");
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
unsafe {
|
||||||
|
RESOURCE_DIR = Some(res_dir.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
res_dir
|
||||||
}
|
}
|
||||||
|
|
||||||
/// profiles dir
|
/// profiles dir
|
||||||
@@ -53,5 +96,35 @@ pub fn profiles_path() -> PathBuf {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn profiles_temp_path() -> PathBuf {
|
pub fn profiles_temp_path() -> PathBuf {
|
||||||
temp_dir().join(PROFILE_TEMP)
|
#[cfg(not(feature = "debug-yml"))]
|
||||||
|
return temp_dir().join(PROFILE_TEMP);
|
||||||
|
|
||||||
|
#[cfg(feature = "debug-yml")]
|
||||||
|
return app_home_dir().join(PROFILE_TEMP);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
static SERVICE_PATH: &str = "clash-verge-service.exe";
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
pub fn service_path() -> PathBuf {
|
||||||
|
unsafe {
|
||||||
|
let res_dir = RESOURCE_DIR.clone().unwrap();
|
||||||
|
res_dir.join(SERVICE_PATH)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
pub fn service_log_file() -> PathBuf {
|
||||||
|
use chrono::Local;
|
||||||
|
|
||||||
|
let log_dir = app_logs_dir().join("service");
|
||||||
|
|
||||||
|
let local_time = Local::now().format("%Y-%m-%d-%H%M%S").to_string();
|
||||||
|
let log_file = format!("{}.log", local_time);
|
||||||
|
let log_file = log_dir.join(log_file);
|
||||||
|
|
||||||
|
std::fs::create_dir_all(&log_dir).unwrap();
|
||||||
|
|
||||||
|
log_file
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
|
use anyhow::{bail, Result};
|
||||||
use nanoid::nanoid;
|
use nanoid::nanoid;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::process::Command;
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
use std::time::{SystemTime, UNIX_EPOCH};
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
@@ -41,6 +44,38 @@ pub fn parse_str<T: FromStr>(target: &str, key: &str) -> Option<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// open file
|
||||||
|
/// use vscode by default
|
||||||
|
pub fn open_file(path: PathBuf) -> Result<()> {
|
||||||
|
// use vscode first
|
||||||
|
if let Ok(code) = which::which("code") {
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
{
|
||||||
|
use std::os::windows::process::CommandExt;
|
||||||
|
|
||||||
|
if let Err(err) = Command::new(code)
|
||||||
|
.creation_flags(0x08000000)
|
||||||
|
.arg(path)
|
||||||
|
.spawn()
|
||||||
|
{
|
||||||
|
bail!(format!("failed to open file by VScode for `{err}`"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(target_os = "windows"))]
|
||||||
|
if let Err(err) = Command::new(code).arg(path).spawn() {
|
||||||
|
bail!(format!("failed to open file by VScode for `{err}`"));
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
match open::that(path) {
|
||||||
|
Ok(_) => Ok(()),
|
||||||
|
Err(err) => bail!(format!("failed to open file for `{err}`")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[macro_export]
|
#[macro_export]
|
||||||
macro_rules! log_if_err {
|
macro_rules! log_if_err {
|
||||||
($result: expr) => {
|
($result: expr) => {
|
||||||
|
|||||||
@@ -6,3 +6,4 @@ pub mod resolve;
|
|||||||
pub mod server;
|
pub mod server;
|
||||||
pub mod sysopt;
|
pub mod sysopt;
|
||||||
pub mod tmpl;
|
pub mod tmpl;
|
||||||
|
mod winhelp;
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
use super::{init, server};
|
use crate::{core::Core, utils::init, utils::server};
|
||||||
use crate::{core::Profiles, log_if_err, states};
|
|
||||||
use tauri::{App, AppHandle, Manager};
|
use tauri::{App, AppHandle, Manager};
|
||||||
|
|
||||||
/// handle something when start app
|
/// handle something when start app
|
||||||
@@ -11,86 +10,113 @@ pub fn resolve_setup(app: &App) {
|
|||||||
init::init_app(app.package_info());
|
init::init_app(app.package_info());
|
||||||
|
|
||||||
// init states
|
// init states
|
||||||
let clash_state = app.state::<states::ClashState>();
|
let core = app.state::<Core>();
|
||||||
let verge_state = app.state::<states::VergeState>();
|
|
||||||
let profiles_state = app.state::<states::ProfilesState>();
|
|
||||||
|
|
||||||
let mut clash = clash_state.0.lock().unwrap();
|
core.set_win(app.get_window("main"));
|
||||||
let mut verge = verge_state.0.lock().unwrap();
|
core.init(app.app_handle());
|
||||||
let mut profiles = profiles_state.0.lock().unwrap();
|
|
||||||
|
|
||||||
log_if_err!(clash.run_sidecar());
|
resolve_window(app);
|
||||||
|
|
||||||
*profiles = Profiles::read_file();
|
|
||||||
|
|
||||||
clash.set_window(app.get_window("main"));
|
|
||||||
log_if_err!(clash.activate(&profiles));
|
|
||||||
log_if_err!(clash.activate_enhanced(&profiles, true, true));
|
|
||||||
|
|
||||||
verge.init_sysproxy(clash.info.port.clone());
|
|
||||||
// enable tun mode
|
|
||||||
if verge.config.enable_tun_mode.clone().unwrap_or(false)
|
|
||||||
&& verge.cur_sysproxy.is_some()
|
|
||||||
&& verge.cur_sysproxy.as_ref().unwrap().enable
|
|
||||||
{
|
|
||||||
log::info!("enable tun mode");
|
|
||||||
clash.tun_mode(true).unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
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));
|
|
||||||
});
|
|
||||||
|
|
||||||
resolve_window(app, verge.config.enable_silent_start.clone());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// reset system proxy
|
/// reset system proxy
|
||||||
pub fn resolve_reset(app_handle: &AppHandle) {
|
pub fn resolve_reset(app_handle: &AppHandle) {
|
||||||
let verge_state = app_handle.state::<states::VergeState>();
|
let core = app_handle.state::<Core>();
|
||||||
let mut verge = verge_state.0.lock().unwrap();
|
let mut sysopt = core.sysopt.lock();
|
||||||
|
sysopt.reset_sysproxy();
|
||||||
|
drop(sysopt);
|
||||||
|
|
||||||
verge.reset_sysproxy();
|
let mut service = core.service.lock();
|
||||||
|
crate::log_if_err!(service.stop());
|
||||||
}
|
}
|
||||||
|
|
||||||
/// customize the window theme
|
/// customize the window theme
|
||||||
fn resolve_window(app: &App, hide: Option<bool>) {
|
fn resolve_window(app: &App) {
|
||||||
let window = app.get_window("main").unwrap();
|
let window = app.get_window("main").unwrap();
|
||||||
|
|
||||||
// silent start
|
|
||||||
hide.map(|hide| {
|
|
||||||
if hide {
|
|
||||||
window.hide().unwrap();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
{
|
{
|
||||||
|
use crate::utils::winhelp;
|
||||||
use window_shadows::set_shadow;
|
use window_shadows::set_shadow;
|
||||||
use window_vibrancy::apply_blur;
|
use window_vibrancy::apply_blur;
|
||||||
|
|
||||||
window.set_decorations(false).unwrap();
|
let _ = window.set_decorations(false);
|
||||||
set_shadow(&window, true).unwrap();
|
let _ = set_shadow(&window, true);
|
||||||
apply_blur(&window, None).unwrap();
|
|
||||||
|
// todo
|
||||||
|
// win11 disable this feature temporarily due to lag
|
||||||
|
if !winhelp::is_win11() {
|
||||||
|
let _ = apply_blur(&window, None);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
{
|
{
|
||||||
use tauri::LogicalSize;
|
use tauri::LogicalSize;
|
||||||
use tauri::Size::Logical;
|
use tauri::Size::Logical;
|
||||||
window.set_decorations(true).unwrap();
|
|
||||||
window
|
let _ = window.set_decorations(true);
|
||||||
.set_size(Logical(LogicalSize {
|
let _ = window.set_size(Logical(LogicalSize {
|
||||||
width: 800.0,
|
width: 800.0,
|
||||||
height: 610.0,
|
height: 620.0,
|
||||||
}))
|
}));
|
||||||
.unwrap();
|
|
||||||
// use tauri_plugin_vibrancy::MacOSVibrancy;
|
|
||||||
// #[allow(deprecated)]
|
|
||||||
// window.apply_vibrancy(MacOSVibrancy::AppearanceBased);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// create main window
|
||||||
|
pub fn create_window(app_handle: &AppHandle) {
|
||||||
|
if let Some(window) = app_handle.get_window("main") {
|
||||||
|
let _ = window.unminimize();
|
||||||
|
let _ = window.show();
|
||||||
|
let _ = window.set_focus();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let builder = tauri::window::WindowBuilder::new(
|
||||||
|
app_handle,
|
||||||
|
"main".to_string(),
|
||||||
|
tauri::WindowUrl::App("index.html".into()),
|
||||||
|
)
|
||||||
|
.title("Clash Verge")
|
||||||
|
.center()
|
||||||
|
.fullscreen(false)
|
||||||
|
.min_inner_size(600.0, 520.0);
|
||||||
|
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
{
|
||||||
|
use crate::utils::winhelp;
|
||||||
|
use window_shadows::set_shadow;
|
||||||
|
use window_vibrancy::apply_blur;
|
||||||
|
|
||||||
|
match builder
|
||||||
|
.decorations(false)
|
||||||
|
.transparent(true)
|
||||||
|
.inner_size(800.0, 636.0)
|
||||||
|
.build()
|
||||||
|
{
|
||||||
|
Ok(_) => {
|
||||||
|
let app_handle = app_handle.clone();
|
||||||
|
|
||||||
|
tauri::async_runtime::spawn(async move {
|
||||||
|
if let Some(window) = app_handle.get_window("main") {
|
||||||
|
let _ = set_shadow(&window, true);
|
||||||
|
|
||||||
|
if !winhelp::is_win11() {
|
||||||
|
let _ = apply_blur(&window, None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Err(err) => log::error!("{err}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
crate::log_if_err!(builder.decorations(true).inner_size(800.0, 620.0).build());
|
||||||
|
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
crate::log_if_err!(builder
|
||||||
|
.decorations(false)
|
||||||
|
.transparent(true)
|
||||||
|
.inner_size(800.0, 636.0)
|
||||||
|
.build());
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,69 @@
|
|||||||
|
#![cfg(target_os = "windows")]
|
||||||
|
#![allow(non_snake_case)]
|
||||||
|
#![allow(non_camel_case_types)]
|
||||||
|
|
||||||
|
//!
|
||||||
|
//! From https://github.com/tauri-apps/window-vibrancy/blob/dev/src/windows.rs
|
||||||
|
//!
|
||||||
|
|
||||||
|
use windows_sys::Win32::{
|
||||||
|
Foundation::*,
|
||||||
|
System::{LibraryLoader::*, SystemInformation::*},
|
||||||
|
};
|
||||||
|
|
||||||
|
fn get_function_impl(library: &str, function: &str) -> Option<FARPROC> {
|
||||||
|
assert_eq!(library.chars().last(), Some('\0'));
|
||||||
|
assert_eq!(function.chars().last(), Some('\0'));
|
||||||
|
|
||||||
|
let module = unsafe { LoadLibraryA(library.as_ptr()) };
|
||||||
|
if module == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(unsafe { GetProcAddress(module, function.as_ptr()) })
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! get_function {
|
||||||
|
($lib:expr, $func:ident) => {
|
||||||
|
get_function_impl(concat!($lib, '\0'), concat!(stringify!($func), '\0')).map(|f| unsafe {
|
||||||
|
std::mem::transmute::<::windows_sys::Win32::Foundation::FARPROC, $func>(f)
|
||||||
|
})
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns a tuple of (major, minor, buildnumber)
|
||||||
|
fn get_windows_ver() -> Option<(u32, u32, u32)> {
|
||||||
|
type RtlGetVersion = unsafe extern "system" fn(*mut OSVERSIONINFOW) -> i32;
|
||||||
|
let handle = get_function!("ntdll.dll", RtlGetVersion);
|
||||||
|
if let Some(rtl_get_version) = handle {
|
||||||
|
unsafe {
|
||||||
|
let mut vi = OSVERSIONINFOW {
|
||||||
|
dwOSVersionInfoSize: 0,
|
||||||
|
dwMajorVersion: 0,
|
||||||
|
dwMinorVersion: 0,
|
||||||
|
dwBuildNumber: 0,
|
||||||
|
dwPlatformId: 0,
|
||||||
|
szCSDVersion: [0; 128],
|
||||||
|
};
|
||||||
|
|
||||||
|
let status = (rtl_get_version)(&mut vi as _);
|
||||||
|
|
||||||
|
if status >= 0 {
|
||||||
|
Some((vi.dwMajorVersion, vi.dwMinorVersion, vi.dwBuildNumber))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_win11() -> bool {
|
||||||
|
let v = get_windows_ver().unwrap_or_default();
|
||||||
|
v.2 >= 22000
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_version() {
|
||||||
|
dbg!(get_windows_ver().unwrap_or_default());
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"package": {
|
"package": {
|
||||||
"productName": "Clash Verge",
|
"productName": "Clash Verge",
|
||||||
"version": "0.0.26"
|
"version": "1.0.2"
|
||||||
},
|
},
|
||||||
"build": {
|
"build": {
|
||||||
"distDir": "../dist",
|
"distDir": "../dist",
|
||||||
@@ -11,7 +11,7 @@
|
|||||||
},
|
},
|
||||||
"tauri": {
|
"tauri": {
|
||||||
"systemTray": {
|
"systemTray": {
|
||||||
"iconPath": "icons/icon.png",
|
"iconPath": "icons/tray-icon.png",
|
||||||
"iconAsTemplate": true
|
"iconAsTemplate": true
|
||||||
},
|
},
|
||||||
"bundle": {
|
"bundle": {
|
||||||
@@ -26,19 +26,17 @@
|
|||||||
"icons/icon.ico"
|
"icons/icon.ico"
|
||||||
],
|
],
|
||||||
"resources": ["resources"],
|
"resources": ["resources"],
|
||||||
"externalBin": ["sidecar/clash"],
|
"externalBin": ["sidecar/clash", "sidecar/clash-meta"],
|
||||||
"copyright": "© 2022 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.",
|
||||||
"deb": {
|
"deb": {
|
||||||
"depends": [],
|
"depends": []
|
||||||
"useBootstrapper": false
|
|
||||||
},
|
},
|
||||||
"macOS": {
|
"macOS": {
|
||||||
"frameworks": [],
|
"frameworks": [],
|
||||||
"minimumSystemVersion": "",
|
"minimumSystemVersion": "",
|
||||||
"useBootstrapper": false,
|
|
||||||
"exceptionDomain": "",
|
"exceptionDomain": "",
|
||||||
"signingIdentity": null,
|
"signingIdentity": null,
|
||||||
"entitlements": null
|
"entitlements": null
|
||||||
@@ -46,7 +44,10 @@
|
|||||||
"windows": {
|
"windows": {
|
||||||
"certificateThumbprint": null,
|
"certificateThumbprint": null,
|
||||||
"digestAlgorithm": "sha256",
|
"digestAlgorithm": "sha256",
|
||||||
"timestampUrl": ""
|
"timestampUrl": "",
|
||||||
|
"wix": {
|
||||||
|
"language": ["zh-CN", "en-US"]
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"updater": {
|
"updater": {
|
||||||
@@ -73,7 +74,7 @@
|
|||||||
{
|
{
|
||||||
"title": "Clash Verge",
|
"title": "Clash Verge",
|
||||||
"width": 800,
|
"width": 800,
|
||||||
"height": 600,
|
"height": 636,
|
||||||
"resizable": true,
|
"resizable": true,
|
||||||
"fullscreen": false,
|
"fullscreen": false,
|
||||||
"decorations": false,
|
"decorations": false,
|
||||||
@@ -83,7 +84,7 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"security": {
|
"security": {
|
||||||
"csp": "script-src 'unsafe-eval' 'self'; default-src blob: data: filesystem: ws: wss: http: https: tauri: 'unsafe-eval' 'unsafe-inline' 'self'; img-src 'self';"
|
"csp": "script-src 'unsafe-eval' 'self'; default-src blob: data: filesystem: ws: wss: http: https: tauri: 'unsafe-eval' 'unsafe-inline' 'self'; img-src data: 'self';"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ body {
|
|||||||
--primary-main: #5b5c9d;
|
--primary-main: #5b5c9d;
|
||||||
--text-primary: #637381;
|
--text-primary: #637381;
|
||||||
--selection-color: #f5f5f5;
|
--selection-color: #f5f5f5;
|
||||||
|
--scroller-color: #90939980;
|
||||||
}
|
}
|
||||||
|
|
||||||
::selection {
|
::selection {
|
||||||
@@ -25,7 +26,7 @@ body {
|
|||||||
}
|
}
|
||||||
*::-webkit-scrollbar-thumb {
|
*::-webkit-scrollbar-thumb {
|
||||||
border-radius: 6px;
|
border-radius: 6px;
|
||||||
background-color: rgba(#909399, 0.5);
|
background-color: var(--scroller-color);
|
||||||
}
|
}
|
||||||
|
|
||||||
@import "./layout.scss";
|
@import "./layout.scss";
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
height: 100%;
|
height: 100%;
|
||||||
max-width: 225px;
|
max-width: 225px;
|
||||||
min-width: 125px;
|
min-width: 125px;
|
||||||
padding: 8px 0;
|
padding: 16px 0 8px;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
user-select: none;
|
user-select: none;
|
||||||
@@ -18,17 +18,20 @@
|
|||||||
|
|
||||||
.the-logo {
|
.the-logo {
|
||||||
position: relative;
|
position: relative;
|
||||||
flex: 0 1 180px;
|
flex: 0 1 168px;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
max-width: 168px;
|
max-width: 168px;
|
||||||
max-height: 168px;
|
max-height: 168px;
|
||||||
margin: 0 auto;
|
margin: 0 auto;
|
||||||
padding: 0 8px;
|
padding: 0 16px;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
|
|
||||||
img {
|
img,
|
||||||
width: 100%;
|
svg {
|
||||||
|
width: 96%;
|
||||||
|
height: 96%;
|
||||||
|
pointer-events: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.the-newbtn {
|
.the-newbtn {
|
||||||
@@ -40,7 +43,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.the-menu {
|
.the-menu {
|
||||||
flex: 1 1 75%;
|
flex: 1 1 80%;
|
||||||
overflow-y: auto;
|
overflow-y: auto;
|
||||||
margin-bottom: 8px;
|
margin-bottom: 8px;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ interface InnerProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const NoticeInner = (props: InnerProps) => {
|
const NoticeInner = (props: InnerProps) => {
|
||||||
const { type, message, duration = 2000, onClose } = props;
|
const { type, message, duration = 1500, onClose } = props;
|
||||||
const [visible, setVisible] = useState(true);
|
const [visible, setVisible] = useState(true);
|
||||||
|
|
||||||
const onBtnClose = () => {
|
const onBtnClose = () => {
|
||||||
@@ -79,14 +79,16 @@ const Notice: NoticeInstance = (props) => {
|
|||||||
|
|
||||||
const onUnmount = () => {
|
const onUnmount = () => {
|
||||||
const result = ReactDOM.unmountComponentAtNode(container);
|
const result = ReactDOM.unmountComponentAtNode(container);
|
||||||
if (result && parent) parent.removeChild(container);
|
if (result && parent) setTimeout(() => parent.removeChild(container), 300);
|
||||||
};
|
};
|
||||||
|
|
||||||
ReactDOM.render(<NoticeInner {...props} onClose={onUnmount} />, container);
|
ReactDOM.render(<NoticeInner {...props} onClose={onUnmount} />, container);
|
||||||
};
|
};
|
||||||
|
|
||||||
(["info", "error", "success"] as const).forEach((type) => {
|
(["info", "error", "success"] as const).forEach((type) => {
|
||||||
Notice[type] = (message, duration) => Notice({ type, message, duration });
|
Notice[type] = (message, duration) => {
|
||||||
|
setTimeout(() => Notice({ type, message, duration }), 0);
|
||||||
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
export default Notice;
|
export default Notice;
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { styled, ListItem, IconButton, ListItemText } from "@mui/material";
|
|||||||
import { CloseRounded } from "@mui/icons-material";
|
import { CloseRounded } from "@mui/icons-material";
|
||||||
import { ApiType } from "../../services/types";
|
import { ApiType } from "../../services/types";
|
||||||
import { deleteConnection } from "../../services/api";
|
import { deleteConnection } from "../../services/api";
|
||||||
|
import parseTraffic from "../../utils/parse-traffic";
|
||||||
|
|
||||||
const Tag = styled("span")(({ theme }) => ({
|
const Tag = styled("span")(({ theme }) => ({
|
||||||
display: "inline-block",
|
display: "inline-block",
|
||||||
@@ -23,32 +24,39 @@ interface Props {
|
|||||||
const ConnectionItem = (props: Props) => {
|
const ConnectionItem = (props: Props) => {
|
||||||
const { value } = props;
|
const { value } = props;
|
||||||
|
|
||||||
const onDelete = useLockFn(async () => deleteConnection(value.id));
|
const { id, metadata, chains, start, curUpload, curDownload } = value;
|
||||||
|
|
||||||
|
const onDelete = useLockFn(async () => deleteConnection(id));
|
||||||
|
const showTraffic = curUpload! > 1024 || curDownload! > 1024;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ListItem
|
<ListItem
|
||||||
dense
|
dense
|
||||||
secondaryAction={
|
secondaryAction={
|
||||||
<IconButton edge="end" onClick={onDelete}>
|
<IconButton edge="end" color="inherit" onClick={onDelete}>
|
||||||
<CloseRounded />
|
<CloseRounded />
|
||||||
</IconButton>
|
</IconButton>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<ListItemText
|
<ListItemText
|
||||||
primary={value.metadata.host || value.metadata.destinationIP}
|
primary={metadata.host || metadata.destinationIP}
|
||||||
secondary={
|
secondary={
|
||||||
<>
|
<>
|
||||||
<Tag sx={{ textTransform: "uppercase", color: "success" }}>
|
<Tag sx={{ textTransform: "uppercase", color: "success" }}>
|
||||||
{value.metadata.network}
|
{metadata.network}
|
||||||
</Tag>
|
</Tag>
|
||||||
|
|
||||||
<Tag>{value.metadata.type}</Tag>
|
<Tag>{metadata.type}</Tag>
|
||||||
|
|
||||||
{value.chains.length > 0 && (
|
{chains.length > 0 && <Tag>{chains[value.chains.length - 1]}</Tag>}
|
||||||
<Tag>{value.chains[value.chains.length - 1]}</Tag>
|
|
||||||
|
<Tag>{dayjs(start).fromNow()}</Tag>
|
||||||
|
|
||||||
|
{showTraffic && (
|
||||||
|
<Tag>
|
||||||
|
{parseTraffic(curUpload!)} / {parseTraffic(curDownload!)}
|
||||||
|
</Tag>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<Tag>{dayjs(value.start).fromNow()}</Tag>
|
|
||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ const LayoutControl = () => {
|
|||||||
<Button
|
<Button
|
||||||
size="small"
|
size="small"
|
||||||
sx={{ minWidth, svg: { transform: "scale(1.05)" } }}
|
sx={{ minWidth, svg: { transform: "scale(1.05)" } }}
|
||||||
onClick={() => appWindow.hide()}
|
onClick={() => appWindow.close()}
|
||||||
>
|
>
|
||||||
<CloseRounded fontSize="small" />
|
<CloseRounded fontSize="small" />
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -1,24 +1,25 @@
|
|||||||
import useSWR from "swr";
|
import useSWR from "swr";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useRef, 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 { listen } from "@tauri-apps/api/event";
|
import { listen } from "@tauri-apps/api/event";
|
||||||
import { ApiType } from "../../services/types";
|
import { ApiType } from "../../services/types";
|
||||||
import { getInfomation } from "../../services/api";
|
import { getInformation } from "../../services/api";
|
||||||
import { getVergeConfig } from "../../services/cmds";
|
import { getVergeConfig } from "../../services/cmds";
|
||||||
import { atomClashPort } from "../../services/states";
|
import { atomClashPort } from "../../services/states";
|
||||||
|
import TrafficGraph from "./traffic-graph";
|
||||||
import useLogSetup from "./use-log-setup";
|
import useLogSetup from "./use-log-setup";
|
||||||
import useTrafficGraph from "./use-traffic-graph";
|
|
||||||
import parseTraffic from "../../utils/parse-traffic";
|
import parseTraffic from "../../utils/parse-traffic";
|
||||||
|
|
||||||
// setup the traffic
|
// setup the traffic
|
||||||
const LayoutTraffic = () => {
|
const LayoutTraffic = () => {
|
||||||
const portValue = useRecoilValue(atomClashPort);
|
const portValue = useRecoilValue(atomClashPort);
|
||||||
const [traffic, setTraffic] = useState({ up: 0, down: 0 });
|
const [traffic, setTraffic] = useState({ up: 0, down: 0 });
|
||||||
const { canvasRef, appendData, toggleStyle } = useTrafficGraph();
|
|
||||||
const [refresh, setRefresh] = useState({});
|
const [refresh, setRefresh] = useState({});
|
||||||
|
|
||||||
|
const trafficRef = useRef<any>();
|
||||||
|
|
||||||
// whether hide traffic graph
|
// whether hide traffic graph
|
||||||
const { data } = useSWR("getVergeConfig", getVergeConfig);
|
const { data } = useSWR("getVergeConfig", getVergeConfig);
|
||||||
const trafficGraph = data?.traffic_graph ?? true;
|
const trafficGraph = data?.traffic_graph ?? true;
|
||||||
@@ -40,13 +41,13 @@ const LayoutTraffic = () => {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let ws: WebSocket | null = null;
|
let ws: WebSocket | null = null;
|
||||||
|
|
||||||
getInfomation().then((result) => {
|
getInformation().then((result) => {
|
||||||
const { server = "", secret = "" } = result;
|
const { server = "", secret = "" } = result;
|
||||||
ws = new WebSocket(`ws://${server}/traffic?token=${secret}`);
|
ws = new WebSocket(`ws://${server}/traffic?token=${secret}`);
|
||||||
|
|
||||||
ws.addEventListener("message", (event) => {
|
ws.addEventListener("message", (event) => {
|
||||||
const data = JSON.parse(event.data) as ApiType.TrafficItem;
|
const data = JSON.parse(event.data) as ApiType.TrafficItem;
|
||||||
appendData(data);
|
trafficRef.current?.appendData(data);
|
||||||
setTraffic(data);
|
setTraffic(data);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -72,12 +73,15 @@ const LayoutTraffic = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box width="110px" position="relative" onClick={toggleStyle}>
|
<Box
|
||||||
|
width="110px"
|
||||||
|
position="relative"
|
||||||
|
onClick={trafficRef.current?.toggleStyle}
|
||||||
|
>
|
||||||
{trafficGraph && (
|
{trafficGraph && (
|
||||||
<canvas
|
<div style={{ width: "100%", height: 60, marginBottom: 6 }}>
|
||||||
ref={canvasRef}
|
<TrafficGraph instance={trafficRef} />
|
||||||
style={{ width: "100%", height: 60, marginBottom: 6 }}
|
</div>
|
||||||
/>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<Box mb={1.5} display="flex" alignItems="center" whiteSpace="nowrap">
|
<Box mb={1.5} display="flex" alignItems="center" whiteSpace="nowrap">
|
||||||
|
|||||||
@@ -0,0 +1,224 @@
|
|||||||
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
import { useTheme } from "@mui/material";
|
||||||
|
import { listen } from "@tauri-apps/api/event";
|
||||||
|
import { appWindow } from "@tauri-apps/api/window";
|
||||||
|
|
||||||
|
const maxPoint = 30;
|
||||||
|
|
||||||
|
const refLineAlpha = 1;
|
||||||
|
const refLineWidth = 2;
|
||||||
|
|
||||||
|
const upLineAlpha = 0.6;
|
||||||
|
const upLineWidth = 4;
|
||||||
|
|
||||||
|
const downLineAlpha = 1;
|
||||||
|
const downLineWidth = 4;
|
||||||
|
|
||||||
|
const defaultList = Array(maxPoint + 2).fill({ up: 0, down: 0 });
|
||||||
|
|
||||||
|
type TrafficData = { up: number; down: number };
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
instance: React.MutableRefObject<{
|
||||||
|
appendData: (data: TrafficData) => void;
|
||||||
|
toggleStyle: () => void;
|
||||||
|
}>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* draw the traffic graph
|
||||||
|
*/
|
||||||
|
const TrafficGraph = (props: Props) => {
|
||||||
|
const { instance } = props;
|
||||||
|
|
||||||
|
const countRef = useRef(0);
|
||||||
|
const styleRef = useRef(true);
|
||||||
|
const listRef = useRef<TrafficData[]>(defaultList);
|
||||||
|
const canvasRef = useRef<HTMLCanvasElement>(null!);
|
||||||
|
|
||||||
|
const { palette } = useTheme();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let timer: any;
|
||||||
|
let cache: TrafficData | null = null;
|
||||||
|
const zero = { up: 0, down: 0 };
|
||||||
|
|
||||||
|
const handleData = () => {
|
||||||
|
const data = cache ? cache : zero;
|
||||||
|
cache = null;
|
||||||
|
|
||||||
|
const list = listRef.current;
|
||||||
|
if (list.length > maxPoint + 2) list.shift();
|
||||||
|
list.push(data);
|
||||||
|
countRef.current = 0;
|
||||||
|
|
||||||
|
timer = setTimeout(handleData, 1000);
|
||||||
|
};
|
||||||
|
|
||||||
|
instance.current = {
|
||||||
|
appendData: (data: TrafficData) => {
|
||||||
|
cache = data;
|
||||||
|
},
|
||||||
|
toggleStyle: () => {
|
||||||
|
styleRef.current = !styleRef.current;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
handleData();
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
instance.current = null!;
|
||||||
|
if (timer) clearTimeout(timer);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// reduce the GPU usage when hidden
|
||||||
|
const [enablePaint, setEnablePaint] = useState(true);
|
||||||
|
useEffect(() => {
|
||||||
|
appWindow.isVisible().then(setEnablePaint);
|
||||||
|
|
||||||
|
const unlistenBlur = listen("tauri://blur", async () => {
|
||||||
|
setEnablePaint(await appWindow.isVisible());
|
||||||
|
});
|
||||||
|
|
||||||
|
const unlistenFocus = listen("tauri://focus", async () => {
|
||||||
|
setEnablePaint(await appWindow.isVisible());
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
unlistenBlur.then((fn) => fn());
|
||||||
|
unlistenFocus.then((fn) => fn());
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!enablePaint) return;
|
||||||
|
|
||||||
|
let raf = 0;
|
||||||
|
const canvas = canvasRef.current!;
|
||||||
|
|
||||||
|
if (!canvas) return;
|
||||||
|
|
||||||
|
const context = canvas.getContext("2d")!;
|
||||||
|
|
||||||
|
if (!context) return;
|
||||||
|
|
||||||
|
const { primary, secondary, divider } = palette;
|
||||||
|
const refLineColor = divider || "rgba(0, 0, 0, 0.12)";
|
||||||
|
const upLineColor = secondary.main || "#9c27b0";
|
||||||
|
const downLineColor = primary.main || "#5b5c9d";
|
||||||
|
|
||||||
|
const width = canvas.width;
|
||||||
|
const height = canvas.height;
|
||||||
|
const dx = width / maxPoint;
|
||||||
|
const dy = height / 7;
|
||||||
|
const l1 = dy;
|
||||||
|
const l2 = dy * 4;
|
||||||
|
|
||||||
|
const countY = (v: number) => {
|
||||||
|
const h = height;
|
||||||
|
|
||||||
|
if (v == 0) return h - 1;
|
||||||
|
if (v <= 10) return h - (v / 10) * dy;
|
||||||
|
if (v <= 100) return h - (v / 100 + 1) * dy;
|
||||||
|
if (v <= 1024) return h - (v / 1024 + 2) * dy;
|
||||||
|
if (v <= 10240) return h - (v / 10240 + 3) * dy;
|
||||||
|
if (v <= 102400) return h - (v / 102400 + 4) * dy;
|
||||||
|
if (v <= 1048576) return h - (v / 1048576 + 5) * dy;
|
||||||
|
if (v <= 10485760) return h - (v / 10485760 + 6) * dy;
|
||||||
|
return 1;
|
||||||
|
};
|
||||||
|
|
||||||
|
const drawBezier = (list: number[], offset: number) => {
|
||||||
|
const points = list.map((y, i) => [
|
||||||
|
(dx * (i - 1) - offset + 3) | 0,
|
||||||
|
countY(y),
|
||||||
|
]);
|
||||||
|
|
||||||
|
let x = points[0][0];
|
||||||
|
let y = points[0][1];
|
||||||
|
|
||||||
|
context.moveTo(x, y);
|
||||||
|
|
||||||
|
for (let i = 1; i < points.length; i++) {
|
||||||
|
const p1 = points[i];
|
||||||
|
const p2 = points[i + 1] || p1;
|
||||||
|
|
||||||
|
const x1 = (p1[0] + p2[0]) / 2;
|
||||||
|
const y1 = (p1[1] + p2[1]) / 2;
|
||||||
|
|
||||||
|
context.quadraticCurveTo(p1[0], p1[1], x1, y1);
|
||||||
|
x = x1;
|
||||||
|
y = y1;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const drawLine = (list: number[], offset: number) => {
|
||||||
|
const points = list.map((y, i) => [
|
||||||
|
(dx * (i - 1) - offset) | 0,
|
||||||
|
countY(y),
|
||||||
|
]);
|
||||||
|
|
||||||
|
context.moveTo(points[0][0], points[0][1]);
|
||||||
|
|
||||||
|
for (let i = 1; i < points.length; i++) {
|
||||||
|
const p = points[i];
|
||||||
|
context.lineTo(p[0], p[1]);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const drawGraph = (lastTime: number) => {
|
||||||
|
const listUp = listRef.current.map((v) => v.up);
|
||||||
|
const listDown = listRef.current.map((v) => v.down);
|
||||||
|
const lineStyle = styleRef.current;
|
||||||
|
|
||||||
|
const now = Date.now();
|
||||||
|
const diff = now - lastTime;
|
||||||
|
const temp = Math.min((diff / 1000) * dx + countRef.current, dx);
|
||||||
|
const offset = countRef.current === 0 ? 0 : temp;
|
||||||
|
countRef.current = temp;
|
||||||
|
|
||||||
|
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();
|
||||||
|
|
||||||
|
context.beginPath();
|
||||||
|
context.globalAlpha = upLineAlpha;
|
||||||
|
context.lineWidth = upLineWidth;
|
||||||
|
context.strokeStyle = upLineColor;
|
||||||
|
lineStyle ? drawBezier(listUp, offset) : drawLine(listUp, offset);
|
||||||
|
context.stroke();
|
||||||
|
context.closePath();
|
||||||
|
|
||||||
|
context.beginPath();
|
||||||
|
context.globalAlpha = downLineAlpha;
|
||||||
|
context.lineWidth = downLineWidth;
|
||||||
|
context.strokeStyle = downLineColor;
|
||||||
|
lineStyle ? drawBezier(listDown, offset) : drawLine(listDown, offset);
|
||||||
|
context.stroke();
|
||||||
|
context.closePath();
|
||||||
|
|
||||||
|
raf = requestAnimationFrame(() => drawGraph(now));
|
||||||
|
};
|
||||||
|
|
||||||
|
drawGraph(Date.now());
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
cancelAnimationFrame(raf);
|
||||||
|
};
|
||||||
|
}, [enablePaint, palette]);
|
||||||
|
|
||||||
|
return <canvas ref={canvasRef} style={{ width: "100%", height: "100%" }} />;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default TrafficGraph;
|
||||||
@@ -13,7 +13,7 @@ import {
|
|||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import { relaunch } from "@tauri-apps/api/process";
|
import { relaunch } from "@tauri-apps/api/process";
|
||||||
import { checkUpdate, installUpdate } from "@tauri-apps/api/updater";
|
import { checkUpdate, installUpdate } from "@tauri-apps/api/updater";
|
||||||
import { killSidecars, restartSidecar } from "../../services/cmds";
|
import { killSidecar, restartSidecar } from "../../services/cmds";
|
||||||
import { atomUpdateState } from "../../services/states";
|
import { atomUpdateState } from "../../services/states";
|
||||||
import Notice from "../base/base-notice";
|
import Notice from "../base/base-notice";
|
||||||
|
|
||||||
@@ -41,7 +41,7 @@ const UpdateDialog = (props: Props) => {
|
|||||||
setUpdateState(true);
|
setUpdateState(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await killSidecars();
|
await killSidecar();
|
||||||
await installUpdate();
|
await installUpdate();
|
||||||
await relaunch();
|
await relaunch();
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
|
|||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import useSWR from "swr";
|
||||||
|
import { useMemo } from "react";
|
||||||
|
import { createTheme } from "@mui/material";
|
||||||
|
import { getVergeConfig } from "../../services/cmds";
|
||||||
|
import { defaultTheme, defaultDarkTheme } from "../../pages/_theme";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* custome theme
|
||||||
|
*/
|
||||||
|
export default function useCustomTheme() {
|
||||||
|
const { data } = useSWR("getVergeConfig", getVergeConfig);
|
||||||
|
const { theme_mode, theme_setting } = data ?? {};
|
||||||
|
|
||||||
|
const theme = useMemo(() => {
|
||||||
|
const mode = theme_mode ?? "light";
|
||||||
|
|
||||||
|
const setting = theme_setting || {};
|
||||||
|
const dt = mode === "light" ? defaultTheme : defaultDarkTheme;
|
||||||
|
|
||||||
|
const theme = createTheme({
|
||||||
|
breakpoints: {
|
||||||
|
values: { xs: 0, sm: 650, md: 900, lg: 1200, xl: 1536 },
|
||||||
|
},
|
||||||
|
palette: {
|
||||||
|
mode,
|
||||||
|
primary: { main: setting.primary_color || dt.primary_color },
|
||||||
|
secondary: { main: setting.secondary_color || dt.secondary_color },
|
||||||
|
info: { main: setting.info_color || dt.info_color },
|
||||||
|
error: { main: setting.error_color || dt.error_color },
|
||||||
|
warning: { main: setting.warning_color || dt.warning_color },
|
||||||
|
success: { main: setting.success_color || dt.success_color },
|
||||||
|
text: {
|
||||||
|
primary: setting.primary_text || dt.primary_text,
|
||||||
|
secondary: setting.secondary_text || dt.secondary_text,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
typography: {
|
||||||
|
// todo
|
||||||
|
fontFamily: setting.font_family
|
||||||
|
? `${setting.font_family}, ${dt.font_family}`
|
||||||
|
: dt.font_family,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// css
|
||||||
|
const selectColor = mode === "light" ? "#f5f5f5" : "#d5d5d5";
|
||||||
|
const scrollColor = mode === "light" ? "#90939980" : "#54545480";
|
||||||
|
|
||||||
|
const rootEle = document.documentElement;
|
||||||
|
rootEle.style.background = "transparent";
|
||||||
|
rootEle.style.setProperty("--selection-color", selectColor);
|
||||||
|
rootEle.style.setProperty("--scroller-color", scrollColor);
|
||||||
|
rootEle.style.setProperty("--primary-main", theme.palette.primary.main);
|
||||||
|
|
||||||
|
// inject css
|
||||||
|
let style = document.querySelector("style#verge-theme");
|
||||||
|
if (!style) {
|
||||||
|
style = document.createElement("style");
|
||||||
|
style.id = "verge-theme";
|
||||||
|
document.head.appendChild(style!);
|
||||||
|
}
|
||||||
|
if (style) {
|
||||||
|
style.innerHTML = setting.css_injection || "";
|
||||||
|
}
|
||||||
|
|
||||||
|
// update svg icon
|
||||||
|
const { palette } = theme;
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
const dom = document.querySelector("#Gradient2");
|
||||||
|
if (dom) {
|
||||||
|
dom.innerHTML = `
|
||||||
|
<stop offset="0%" stop-color="${palette.primary.main}" />
|
||||||
|
<stop offset="80%" stop-color="${palette.primary.dark}" />
|
||||||
|
<stop offset="100%" stop-color="${palette.primary.dark}" />
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
}, 0);
|
||||||
|
|
||||||
|
return theme;
|
||||||
|
}, [theme_mode, theme_setting]);
|
||||||
|
|
||||||
|
return { theme };
|
||||||
|
}
|
||||||
@@ -3,7 +3,7 @@ import { useEffect, useState } from "react";
|
|||||||
import { useSetRecoilState } from "recoil";
|
import { useSetRecoilState } from "recoil";
|
||||||
import { listen } from "@tauri-apps/api/event";
|
import { listen } from "@tauri-apps/api/event";
|
||||||
import { ApiType } from "../../services/types";
|
import { ApiType } from "../../services/types";
|
||||||
import { getInfomation } from "../../services/api";
|
import { getInformation } from "../../services/api";
|
||||||
import { atomLogData } from "../../services/states";
|
import { atomLogData } from "../../services/states";
|
||||||
|
|
||||||
const MAX_LOG_NUM = 1000;
|
const MAX_LOG_NUM = 1000;
|
||||||
@@ -25,7 +25,7 @@ export default function useLogSetup() {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
getInfomation().then((info) => {
|
getInformation().then((info) => {
|
||||||
const { server = "", secret = "" } = info;
|
const { server = "", secret = "" } = info;
|
||||||
ws = new WebSocket(`ws://${server}/logs?token=${secret}`);
|
ws = new WebSocket(`ws://${server}/logs?token=${secret}`);
|
||||||
ws.addEventListener("message", handler);
|
ws.addEventListener("message", handler);
|
||||||
|
|||||||
@@ -1,146 +0,0 @@
|
|||||||
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,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
import useSWR from "swr";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useLockFn } from "ahooks";
|
||||||
|
import {
|
||||||
|
Box,
|
||||||
|
Divider,
|
||||||
|
Grid,
|
||||||
|
IconButton,
|
||||||
|
ListItemIcon,
|
||||||
|
ListItemText,
|
||||||
|
Menu,
|
||||||
|
MenuItem,
|
||||||
|
Stack,
|
||||||
|
} from "@mui/material";
|
||||||
|
import {
|
||||||
|
AddchartRounded,
|
||||||
|
CheckRounded,
|
||||||
|
MenuRounded,
|
||||||
|
RestartAltRounded,
|
||||||
|
} from "@mui/icons-material";
|
||||||
|
import {
|
||||||
|
getProfiles,
|
||||||
|
deleteProfile,
|
||||||
|
enhanceProfiles,
|
||||||
|
changeProfileChain,
|
||||||
|
changeProfileValid,
|
||||||
|
} from "../../services/cmds";
|
||||||
|
import { CmdType } from "../../services/types";
|
||||||
|
import getSystem from "../../utils/get-system";
|
||||||
|
import ProfileMore from "./profile-more";
|
||||||
|
import Notice from "../base/base-notice";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
items: CmdType.ProfileItem[];
|
||||||
|
chain: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const OS = getSystem();
|
||||||
|
|
||||||
|
const EnhancedMode = (props: Props) => {
|
||||||
|
const { items, chain } = props;
|
||||||
|
|
||||||
|
const { data, mutate } = useSWR("getProfiles", getProfiles);
|
||||||
|
const valid = data?.valid || [];
|
||||||
|
|
||||||
|
const [anchorEl, setAnchorEl] = useState<any>(null);
|
||||||
|
|
||||||
|
// handler
|
||||||
|
const onEnhance = useLockFn(async () => {
|
||||||
|
try {
|
||||||
|
await enhanceProfiles();
|
||||||
|
Notice.success("Refresh clash config", 1000);
|
||||||
|
} catch (err: any) {
|
||||||
|
Notice.error(err.message || err.toString());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const onEnhanceEnable = useLockFn(async (uid: string) => {
|
||||||
|
if (chain.includes(uid)) return;
|
||||||
|
|
||||||
|
const newChain = [...chain, uid];
|
||||||
|
await changeProfileChain(newChain);
|
||||||
|
mutate((conf = {}) => ({ ...conf, chain: newChain }), true);
|
||||||
|
});
|
||||||
|
|
||||||
|
const onEnhanceDisable = useLockFn(async (uid: string) => {
|
||||||
|
if (!chain.includes(uid)) return;
|
||||||
|
|
||||||
|
const newChain = chain.filter((i) => i !== uid);
|
||||||
|
await changeProfileChain(newChain);
|
||||||
|
mutate((conf = {}) => ({ ...conf, chain: newChain }), true);
|
||||||
|
});
|
||||||
|
|
||||||
|
const onEnhanceDelete = useLockFn(async (uid: string) => {
|
||||||
|
try {
|
||||||
|
await onEnhanceDisable(uid);
|
||||||
|
await deleteProfile(uid);
|
||||||
|
mutate();
|
||||||
|
} catch (err: any) {
|
||||||
|
Notice.error(err?.message || err.toString());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const onMoveTop = useLockFn(async (uid: string) => {
|
||||||
|
if (!chain.includes(uid)) return;
|
||||||
|
|
||||||
|
const newChain = [uid].concat(chain.filter((i) => i !== uid));
|
||||||
|
await changeProfileChain(newChain);
|
||||||
|
mutate((conf = {}) => ({ ...conf, chain: newChain }), true);
|
||||||
|
});
|
||||||
|
|
||||||
|
const onMoveEnd = useLockFn(async (uid: string) => {
|
||||||
|
if (!chain.includes(uid)) return;
|
||||||
|
|
||||||
|
const newChain = chain.filter((i) => i !== uid).concat([uid]);
|
||||||
|
await changeProfileChain(newChain);
|
||||||
|
mutate((conf = {}) => ({ ...conf, chain: newChain }), true);
|
||||||
|
});
|
||||||
|
|
||||||
|
// update valid list
|
||||||
|
const onToggleValid = useLockFn(async (key: string) => {
|
||||||
|
try {
|
||||||
|
const newValid = valid.includes(key)
|
||||||
|
? valid.filter((i) => i !== key)
|
||||||
|
: valid.concat(key);
|
||||||
|
await changeProfileValid(newValid);
|
||||||
|
mutate();
|
||||||
|
} catch (err: any) {
|
||||||
|
Notice.error(err.message || err.toString());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box sx={{ mt: 4 }}>
|
||||||
|
<Stack
|
||||||
|
spacing={1}
|
||||||
|
direction="row"
|
||||||
|
alignItems="center"
|
||||||
|
justifyContent="flex-end"
|
||||||
|
sx={{ mb: 0.5 }}
|
||||||
|
>
|
||||||
|
<IconButton
|
||||||
|
size="small"
|
||||||
|
color="inherit"
|
||||||
|
title="refresh enhanced profiles"
|
||||||
|
onClick={onEnhance}
|
||||||
|
>
|
||||||
|
<RestartAltRounded />
|
||||||
|
</IconButton>
|
||||||
|
|
||||||
|
<IconButton
|
||||||
|
size="small"
|
||||||
|
color="inherit"
|
||||||
|
id="profile-use-button"
|
||||||
|
title="enable clash fields"
|
||||||
|
aria-controls={!!anchorEl ? "profile-use-menu" : undefined}
|
||||||
|
aria-haspopup="true"
|
||||||
|
aria-expanded={!!anchorEl ? "true" : undefined}
|
||||||
|
onClick={(e) => setAnchorEl(e.currentTarget)}
|
||||||
|
>
|
||||||
|
<MenuRounded />
|
||||||
|
</IconButton>
|
||||||
|
|
||||||
|
<Menu
|
||||||
|
id="profile-use-menu"
|
||||||
|
open={!!anchorEl}
|
||||||
|
anchorEl={anchorEl}
|
||||||
|
onClose={() => setAnchorEl(null)}
|
||||||
|
transitionDuration={225}
|
||||||
|
TransitionProps={
|
||||||
|
OS === "macos" ? { style: { transitionDuration: "225ms" } } : {}
|
||||||
|
}
|
||||||
|
MenuListProps={{
|
||||||
|
dense: true,
|
||||||
|
"aria-labelledby": "profile-use-button",
|
||||||
|
}}
|
||||||
|
onContextMenu={(e) => {
|
||||||
|
setAnchorEl(null);
|
||||||
|
e.preventDefault();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<MenuItem>
|
||||||
|
<ListItemIcon color="inherit">
|
||||||
|
<AddchartRounded />
|
||||||
|
</ListItemIcon>
|
||||||
|
Use Clash Fields
|
||||||
|
</MenuItem>
|
||||||
|
|
||||||
|
<Divider />
|
||||||
|
|
||||||
|
{[
|
||||||
|
"tun",
|
||||||
|
"dns",
|
||||||
|
"hosts",
|
||||||
|
"script",
|
||||||
|
"profile",
|
||||||
|
"payload",
|
||||||
|
"interface-name",
|
||||||
|
"routing-mark",
|
||||||
|
].map((key) => {
|
||||||
|
const has = valid.includes(key);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<MenuItem
|
||||||
|
key={key}
|
||||||
|
sx={{ width: 180 }}
|
||||||
|
onClick={() => onToggleValid(key)}
|
||||||
|
>
|
||||||
|
{has && (
|
||||||
|
<ListItemIcon color="inherit">
|
||||||
|
<CheckRounded />
|
||||||
|
</ListItemIcon>
|
||||||
|
)}
|
||||||
|
<ListItemText inset={!has}>{key}</ListItemText>
|
||||||
|
</MenuItem>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</Menu>
|
||||||
|
</Stack>
|
||||||
|
|
||||||
|
<Grid container spacing={2}>
|
||||||
|
{items.map((item) => (
|
||||||
|
<Grid item xs={12} sm={6} key={item.file}>
|
||||||
|
<ProfileMore
|
||||||
|
selected={!!chain.includes(item.uid)}
|
||||||
|
itemData={item}
|
||||||
|
enableNum={chain.length}
|
||||||
|
onEnable={() => onEnhanceEnable(item.uid)}
|
||||||
|
onDisable={() => onEnhanceDisable(item.uid)}
|
||||||
|
onDelete={() => onEnhanceDelete(item.uid)}
|
||||||
|
onMoveTop={() => onMoveTop(item.uid)}
|
||||||
|
onMoveEnd={() => onMoveEnd(item.uid)}
|
||||||
|
/>
|
||||||
|
</Grid>
|
||||||
|
))}
|
||||||
|
</Grid>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default EnhancedMode;
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { mutate } from "swr";
|
import { mutate } from "swr";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { useLockFn, useSetState } from "ahooks";
|
import { useLockFn, useSetState } from "ahooks";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
import {
|
import {
|
||||||
Button,
|
Button,
|
||||||
Dialog,
|
Dialog,
|
||||||
@@ -25,6 +26,8 @@ interface Props {
|
|||||||
// remote / local file / merge / script
|
// remote / local file / merge / script
|
||||||
const ProfileEdit = (props: Props) => {
|
const ProfileEdit = (props: Props) => {
|
||||||
const { open, itemData, onClose } = props;
|
const { open, itemData, onClose } = props;
|
||||||
|
|
||||||
|
const { t } = useTranslation();
|
||||||
const [form, setForm] = useSetState({ ...itemData });
|
const [form, setForm] = useSetState({ ...itemData });
|
||||||
const [option, setOption] = useSetState(itemData.option ?? {});
|
const [option, setOption] = useSetState(itemData.option ?? {});
|
||||||
const [showOpt, setShowOpt] = useState(!!itemData.option);
|
const [showOpt, setShowOpt] = useState(!!itemData.option);
|
||||||
@@ -33,7 +36,10 @@ const ProfileEdit = (props: Props) => {
|
|||||||
if (itemData) {
|
if (itemData) {
|
||||||
setForm({ ...itemData });
|
setForm({ ...itemData });
|
||||||
setOption(itemData.option ?? {});
|
setOption(itemData.option ?? {});
|
||||||
setShowOpt(!!itemData.option?.user_agent);
|
setShowOpt(
|
||||||
|
itemData.type === "remote" &&
|
||||||
|
(!!itemData.option?.user_agent || !!itemData.option?.update_interval)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}, [itemData]);
|
}, [itemData]);
|
||||||
|
|
||||||
@@ -41,7 +47,10 @@ const ProfileEdit = (props: Props) => {
|
|||||||
try {
|
try {
|
||||||
const { uid } = itemData;
|
const { uid } = itemData;
|
||||||
const { name, desc, url } = form;
|
const { name, desc, url } = form;
|
||||||
const option_ = itemData.type === "remote" ? option : undefined;
|
const option_ =
|
||||||
|
itemData.type === "remote" || itemData.type === "local"
|
||||||
|
? option
|
||||||
|
: undefined;
|
||||||
|
|
||||||
if (itemData.type === "remote" && !url) {
|
if (itemData.type === "remote" && !url) {
|
||||||
throw new Error("Remote URL should not be null");
|
throw new Error("Remote URL should not be null");
|
||||||
@@ -65,11 +74,11 @@ const ProfileEdit = (props: Props) => {
|
|||||||
|
|
||||||
const type =
|
const type =
|
||||||
form.type ||
|
form.type ||
|
||||||
(form.url ? "remote" : form.file?.endsWith("js") ? "script" : "local");
|
(form.url ? "remote" : form.file?.endsWith(".js") ? "script" : "local");
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog open={open} onClose={onClose}>
|
<Dialog open={open} onClose={onClose}>
|
||||||
<DialogTitle sx={{ pb: 0.5 }}>Edit Profile</DialogTitle>
|
<DialogTitle sx={{ pb: 0.5 }}>{t("Edit Info")}</DialogTitle>
|
||||||
|
|
||||||
<DialogContent sx={{ width: 336, pb: 1 }}>
|
<DialogContent sx={{ width: 336, pb: 1 }}>
|
||||||
<TextField
|
<TextField
|
||||||
@@ -86,6 +95,7 @@ const ProfileEdit = (props: Props) => {
|
|||||||
label="Name"
|
label="Name"
|
||||||
value={form.name}
|
value={form.name}
|
||||||
onChange={(e) => setForm({ name: e.target.value })}
|
onChange={(e) => setForm({ name: e.target.value })}
|
||||||
|
onKeyDown={(e) => e.key === "Enter" && onUpdate()}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<TextField
|
<TextField
|
||||||
@@ -93,14 +103,16 @@ const ProfileEdit = (props: Props) => {
|
|||||||
label="Descriptions"
|
label="Descriptions"
|
||||||
value={form.desc}
|
value={form.desc}
|
||||||
onChange={(e) => setForm({ desc: e.target.value })}
|
onChange={(e) => setForm({ desc: e.target.value })}
|
||||||
|
onKeyDown={(e) => e.key === "Enter" && onUpdate()}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{type === "remote" && (
|
{type === "remote" && (
|
||||||
<TextField
|
<TextField
|
||||||
{...textFieldProps}
|
{...textFieldProps}
|
||||||
label="Subscription Url"
|
label="Subscription URL"
|
||||||
value={form.url}
|
value={form.url}
|
||||||
onChange={(e) => setForm({ url: e.target.value })}
|
onChange={(e) => setForm({ url: e.target.value })}
|
||||||
|
onKeyDown={(e) => e.key === "Enter" && onUpdate()}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -109,7 +121,22 @@ const ProfileEdit = (props: Props) => {
|
|||||||
{...textFieldProps}
|
{...textFieldProps}
|
||||||
label="User Agent"
|
label="User Agent"
|
||||||
value={option.user_agent}
|
value={option.user_agent}
|
||||||
|
placeholder="clash-verge/v1.0.0"
|
||||||
onChange={(e) => setOption({ user_agent: e.target.value })}
|
onChange={(e) => setOption({ user_agent: e.target.value })}
|
||||||
|
onKeyDown={(e) => e.key === "Enter" && onUpdate()}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{((type === "remote" && showOpt) || type === "local") && (
|
||||||
|
<TextField
|
||||||
|
{...textFieldProps}
|
||||||
|
label="Update Interval (mins)"
|
||||||
|
value={option.update_interval}
|
||||||
|
onChange={(e) => {
|
||||||
|
const str = e.target.value?.replace(/\D/, "");
|
||||||
|
setOption({ update_interval: str != null ? +str : str });
|
||||||
|
}}
|
||||||
|
onKeyDown={(e) => e.key === "Enter" && onUpdate()}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import dayjs from "dayjs";
|
import dayjs from "dayjs";
|
||||||
import { useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { useLockFn } from "ahooks";
|
import { useLockFn } from "ahooks";
|
||||||
import { useSWRConfig } from "swr";
|
import { useSWRConfig } from "swr";
|
||||||
import { useRecoilState } from "recoil";
|
import { useRecoilState } from "recoil";
|
||||||
@@ -20,6 +20,7 @@ import { CmdType } from "../../services/types";
|
|||||||
import { atomLoadingCache } from "../../services/states";
|
import { atomLoadingCache } from "../../services/states";
|
||||||
import { updateProfile, deleteProfile, viewProfile } from "../../services/cmds";
|
import { updateProfile, deleteProfile, viewProfile } from "../../services/cmds";
|
||||||
import parseTraffic from "../../utils/parse-traffic";
|
import parseTraffic from "../../utils/parse-traffic";
|
||||||
|
import getSystem from "../../utils/get-system";
|
||||||
import ProfileEdit from "./profile-edit";
|
import ProfileEdit from "./profile-edit";
|
||||||
import FileEditor from "./file-editor";
|
import FileEditor from "./file-editor";
|
||||||
import Notice from "../base/base-notice";
|
import Notice from "../base/base-notice";
|
||||||
@@ -40,6 +41,8 @@ const round = keyframes`
|
|||||||
to { transform: rotate(360deg); }
|
to { transform: rotate(360deg); }
|
||||||
`;
|
`;
|
||||||
|
|
||||||
|
const OS = getSystem();
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
selected: boolean;
|
selected: boolean;
|
||||||
itemData: CmdType.ProfileItem;
|
itemData: CmdType.ProfileItem;
|
||||||
@@ -56,11 +59,6 @@ const ProfileItem = (props: Props) => {
|
|||||||
const [loadingCache, setLoadingCache] = useRecoilState(atomLoadingCache);
|
const [loadingCache, setLoadingCache] = useRecoilState(atomLoadingCache);
|
||||||
|
|
||||||
const { uid, name = "Profile", extra, updated = 0 } = itemData;
|
const { uid, 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
|
// local file mode
|
||||||
// remote file mode
|
// remote file mode
|
||||||
@@ -68,8 +66,42 @@ const ProfileItem = (props: Props) => {
|
|||||||
const hasUrl = !!itemData.url;
|
const hasUrl = !!itemData.url;
|
||||||
const hasExtra = !!extra; // only subscription url has extra info
|
const hasExtra = !!extra; // only subscription url has extra info
|
||||||
|
|
||||||
|
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 loading = loadingCache[itemData.uid] ?? false;
|
const loading = loadingCache[itemData.uid] ?? false;
|
||||||
|
|
||||||
|
// interval update from now field
|
||||||
|
const [, setRefresh] = useState({});
|
||||||
|
useEffect(() => {
|
||||||
|
if (!hasUrl) return;
|
||||||
|
|
||||||
|
let timer: any = null;
|
||||||
|
|
||||||
|
const handler = () => {
|
||||||
|
const now = Date.now();
|
||||||
|
const lastUpdate = updated * 1000;
|
||||||
|
|
||||||
|
// 大于一天的不管
|
||||||
|
if (now - lastUpdate >= 24 * 36e5) return;
|
||||||
|
|
||||||
|
const wait = now - lastUpdate >= 36e5 ? 30e5 : 5e4;
|
||||||
|
|
||||||
|
timer = setTimeout(() => {
|
||||||
|
setRefresh({});
|
||||||
|
handler();
|
||||||
|
}, wait);
|
||||||
|
};
|
||||||
|
|
||||||
|
handler();
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
if (timer) clearTimeout(timer);
|
||||||
|
};
|
||||||
|
}, [hasUrl, updated]);
|
||||||
|
|
||||||
const [editOpen, setEditOpen] = useState(false);
|
const [editOpen, setEditOpen] = useState(false);
|
||||||
const [fileOpen, setFileOpen] = useState(false);
|
const [fileOpen, setFileOpen] = useState(false);
|
||||||
|
|
||||||
@@ -162,8 +194,8 @@ const ProfileItem = (props: Props) => {
|
|||||||
const color = {
|
const color = {
|
||||||
"light-true": text.secondary,
|
"light-true": text.secondary,
|
||||||
"light-false": text.secondary,
|
"light-false": text.secondary,
|
||||||
"dark-true": alpha(text.secondary, 0.6),
|
"dark-true": alpha(text.secondary, 0.75),
|
||||||
"dark-false": alpha(text.secondary, 0.6),
|
"dark-false": alpha(text.secondary, 0.75),
|
||||||
}[key]!;
|
}[key]!;
|
||||||
|
|
||||||
const h2color = {
|
const h2color = {
|
||||||
@@ -228,7 +260,7 @@ const ProfileItem = (props: Props) => {
|
|||||||
textAlign="right"
|
textAlign="right"
|
||||||
title="updated time"
|
title="updated time"
|
||||||
>
|
>
|
||||||
{fromnow}
|
{updated > 0 ? dayjs(updated * 1000).fromNow() : ""}
|
||||||
</Typography>
|
</Typography>
|
||||||
</Box>
|
</Box>
|
||||||
) : (
|
) : (
|
||||||
@@ -267,6 +299,9 @@ const ProfileItem = (props: Props) => {
|
|||||||
anchorPosition={position}
|
anchorPosition={position}
|
||||||
anchorReference="anchorPosition"
|
anchorReference="anchorPosition"
|
||||||
transitionDuration={225}
|
transitionDuration={225}
|
||||||
|
TransitionProps={
|
||||||
|
OS === "macos" ? { style: { transitionDuration: "225ms" } } : {}
|
||||||
|
}
|
||||||
onContextMenu={(e) => {
|
onContextMenu={(e) => {
|
||||||
setAnchorEl(null);
|
setAnchorEl(null);
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import {
|
|||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import { CmdType } from "../../services/types";
|
import { CmdType } from "../../services/types";
|
||||||
import { viewProfile } from "../../services/cmds";
|
import { viewProfile } from "../../services/cmds";
|
||||||
|
import getSystem from "../../utils/get-system";
|
||||||
import enhance from "../../services/enhance";
|
import enhance from "../../services/enhance";
|
||||||
import ProfileEdit from "./profile-edit";
|
import ProfileEdit from "./profile-edit";
|
||||||
import FileEditor from "./file-editor";
|
import FileEditor from "./file-editor";
|
||||||
@@ -29,15 +30,17 @@ const Wrapper = styled(Box)(({ theme }) => ({
|
|||||||
boxSizing: "border-box",
|
boxSizing: "border-box",
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
const OS = getSystem();
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
selected: boolean;
|
selected: boolean;
|
||||||
itemData: CmdType.ProfileItem;
|
itemData: CmdType.ProfileItem;
|
||||||
|
enableNum: number;
|
||||||
onEnable: () => void;
|
onEnable: () => void;
|
||||||
onDisable: () => void;
|
onDisable: () => void;
|
||||||
onMoveTop: () => void;
|
onMoveTop: () => void;
|
||||||
onMoveEnd: () => void;
|
onMoveEnd: () => void;
|
||||||
onDelete: () => void;
|
onDelete: () => void;
|
||||||
onEnhance: () => void;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// profile enhanced item
|
// profile enhanced item
|
||||||
@@ -45,12 +48,12 @@ const ProfileMore = (props: Props) => {
|
|||||||
const {
|
const {
|
||||||
selected,
|
selected,
|
||||||
itemData,
|
itemData,
|
||||||
|
enableNum,
|
||||||
onEnable,
|
onEnable,
|
||||||
onDisable,
|
onDisable,
|
||||||
onMoveTop,
|
onMoveTop,
|
||||||
onMoveEnd,
|
onMoveEnd,
|
||||||
onDelete,
|
onDelete,
|
||||||
onEnhance,
|
|
||||||
} = props;
|
} = props;
|
||||||
|
|
||||||
const { uid, type } = itemData;
|
const { uid, type } = itemData;
|
||||||
@@ -92,14 +95,15 @@ const ProfileMore = (props: Props) => {
|
|||||||
return fn();
|
return fn();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const showMove = enableNum > 1 && !hasError;
|
||||||
|
|
||||||
const enableMenu = [
|
const enableMenu = [
|
||||||
{ label: "Disable", handler: fnWrapper(onDisable) },
|
{ label: "Disable", handler: fnWrapper(onDisable) },
|
||||||
{ label: "Refresh", handler: fnWrapper(onEnhance) },
|
|
||||||
{ label: "Edit Info", handler: onEditInfo },
|
{ label: "Edit Info", handler: onEditInfo },
|
||||||
{ label: "Edit File", handler: onEditFile },
|
{ label: "Edit File", handler: onEditFile },
|
||||||
{ label: "Open File", handler: onOpenFile },
|
{ label: "Open File", handler: onOpenFile },
|
||||||
{ label: "To Top", show: !hasError, handler: fnWrapper(onMoveTop) },
|
{ label: "To Top", show: showMove, handler: fnWrapper(onMoveTop) },
|
||||||
{ label: "To End", show: !hasError, handler: fnWrapper(onMoveEnd) },
|
{ label: "To End", show: showMove, handler: fnWrapper(onMoveEnd) },
|
||||||
{ label: "Delete", handler: fnWrapper(onDelete) },
|
{ label: "Delete", handler: fnWrapper(onDelete) },
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -219,6 +223,9 @@ const ProfileMore = (props: Props) => {
|
|||||||
anchorPosition={position}
|
anchorPosition={position}
|
||||||
anchorReference="anchorPosition"
|
anchorReference="anchorPosition"
|
||||||
transitionDuration={225}
|
transitionDuration={225}
|
||||||
|
TransitionProps={
|
||||||
|
OS === "macos" ? { style: { transitionDuration: "225ms" } } : {}
|
||||||
|
}
|
||||||
onContextMenu={(e) => {
|
onContextMenu={(e) => {
|
||||||
setAnchorEl(null);
|
setAnchorEl(null);
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
|||||||
@@ -2,20 +2,13 @@ import useSWR, { useSWRConfig } from "swr";
|
|||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
import { useLockFn } from "ahooks";
|
import { useLockFn } from "ahooks";
|
||||||
import { Virtuoso } from "react-virtuoso";
|
import { Virtuoso } from "react-virtuoso";
|
||||||
import { Box, IconButton, TextField } from "@mui/material";
|
|
||||||
import {
|
|
||||||
MyLocationRounded,
|
|
||||||
NetworkCheckRounded,
|
|
||||||
FilterAltRounded,
|
|
||||||
FilterAltOffRounded,
|
|
||||||
VisibilityRounded,
|
|
||||||
VisibilityOffRounded,
|
|
||||||
} from "@mui/icons-material";
|
|
||||||
import { ApiType } from "../../services/types";
|
import { ApiType } from "../../services/types";
|
||||||
import { updateProxy } from "../../services/api";
|
import { updateProxy } from "../../services/api";
|
||||||
import { getProfiles, patchProfile } from "../../services/cmds";
|
import { getProfiles, patchProfile } from "../../services/cmds";
|
||||||
import delayManager from "../../services/delay";
|
import useSortProxy, { ProxySortType } from "./use-sort-proxy";
|
||||||
import useFilterProxy from "./use-filter-proxy";
|
import useFilterProxy from "./use-filter-proxy";
|
||||||
|
import delayManager from "../../services/delay";
|
||||||
|
import ProxyHead from "./proxy-head";
|
||||||
import ProxyItem from "./proxy-item";
|
import ProxyItem from "./proxy-item";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
@@ -30,12 +23,14 @@ const ProxyGlobal = (props: Props) => {
|
|||||||
|
|
||||||
const { mutate } = useSWRConfig();
|
const { mutate } = useSWRConfig();
|
||||||
const [now, setNow] = useState(curProxy || "DIRECT");
|
const [now, setNow] = useState(curProxy || "DIRECT");
|
||||||
|
|
||||||
const [showType, setShowType] = useState(true);
|
const [showType, setShowType] = useState(true);
|
||||||
const [showFilter, setShowFilter] = useState(false);
|
const [sortType, setSortType] = useState<ProxySortType>(0);
|
||||||
const [filterText, setFilterText] = useState("");
|
const [filterText, setFilterText] = useState("");
|
||||||
|
|
||||||
const virtuosoRef = useRef<any>();
|
const virtuosoRef = useRef<any>();
|
||||||
const filterProxies = useFilterProxy(proxies, groupName, filterText);
|
const filterProxies = useFilterProxy(proxies, groupName, filterText);
|
||||||
|
const sortedProxies = useSortProxy(filterProxies, groupName, sortType);
|
||||||
|
|
||||||
const { data: profiles } = useSWR("getProfiles", getProfiles);
|
const { data: profiles } = useSWR("getProfiles", getProfiles);
|
||||||
|
|
||||||
@@ -61,7 +56,7 @@ const ProxyGlobal = (props: Props) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const onLocation = (smooth = true) => {
|
const onLocation = (smooth = true) => {
|
||||||
const index = filterProxies.findIndex((p) => p.name === now);
|
const index = sortedProxies.findIndex((p) => p.name === now);
|
||||||
|
|
||||||
if (index >= 0) {
|
if (index >= 0) {
|
||||||
virtuosoRef.current?.scrollToIndex?.({
|
virtuosoRef.current?.scrollToIndex?.({
|
||||||
@@ -73,22 +68,15 @@ const ProxyGlobal = (props: Props) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const onCheckAll = useLockFn(async () => {
|
const onCheckAll = useLockFn(async () => {
|
||||||
const names = filterProxies.map((p) => p.name);
|
const names = sortedProxies.map((p) => p.name);
|
||||||
|
|
||||||
await delayManager.checkListDelay(
|
await delayManager.checkListDelay({ names, groupName, skipNum: 8 }, () =>
|
||||||
{ names, groupName, skipNum: 8, maxTimeout: 600 },
|
mutate("getProxies")
|
||||||
() => mutate("getProxies")
|
|
||||||
);
|
);
|
||||||
|
|
||||||
mutate("getProxies");
|
|
||||||
});
|
});
|
||||||
|
|
||||||
useEffect(() => onLocation(false), [groupName]);
|
useEffect(() => onLocation(false), [groupName]);
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!showFilter) setFilterText("");
|
|
||||||
}, [showFilter]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (groupName === "DIRECT") setNow("DIRECT");
|
if (groupName === "DIRECT") setNow("DIRECT");
|
||||||
else if (groupName === "GLOBAL") {
|
else if (groupName === "GLOBAL") {
|
||||||
@@ -112,66 +100,28 @@ const ProxyGlobal = (props: Props) => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Box
|
<ProxyHead
|
||||||
sx={{
|
sx={{ px: 3, my: 0.5, button: { mr: 0.5 } }}
|
||||||
px: 3,
|
showType={showType}
|
||||||
my: 0.5,
|
sortType={sortType}
|
||||||
display: "flex",
|
groupName={groupName}
|
||||||
alignItems: "center",
|
filterText={filterText}
|
||||||
button: { mr: 0.5 },
|
onLocation={onLocation}
|
||||||
}}
|
onCheckDelay={onCheckAll}
|
||||||
>
|
onShowType={setShowType}
|
||||||
<IconButton
|
onSortType={setSortType}
|
||||||
size="small"
|
onFilterText={setFilterText}
|
||||||
title="location"
|
/>
|
||||||
onClick={() => onLocation(true)}
|
|
||||||
>
|
|
||||||
<MyLocationRounded />
|
|
||||||
</IconButton>
|
|
||||||
|
|
||||||
<IconButton size="small" title="check" onClick={onCheckAll}>
|
|
||||||
<NetworkCheckRounded />
|
|
||||||
</IconButton>
|
|
||||||
|
|
||||||
<IconButton
|
|
||||||
size="small"
|
|
||||||
title="check"
|
|
||||||
onClick={() => setShowType(!showType)}
|
|
||||||
>
|
|
||||||
{showType ? <VisibilityRounded /> : <VisibilityOffRounded />}
|
|
||||||
</IconButton>
|
|
||||||
|
|
||||||
<IconButton
|
|
||||||
size="small"
|
|
||||||
title="check"
|
|
||||||
onClick={() => setShowFilter(!showFilter)}
|
|
||||||
>
|
|
||||||
{showFilter ? <FilterAltRounded /> : <FilterAltOffRounded />}
|
|
||||||
</IconButton>
|
|
||||||
|
|
||||||
{showFilter && (
|
|
||||||
<TextField
|
|
||||||
autoFocus
|
|
||||||
hiddenLabel
|
|
||||||
value={filterText}
|
|
||||||
size="small"
|
|
||||||
variant="outlined"
|
|
||||||
placeholder="Filter conditions"
|
|
||||||
onChange={(e) => setFilterText(e.target.value)}
|
|
||||||
sx={{ ml: 0.5, flex: "1 1 auto", input: { py: 0.65, px: 1 } }}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Virtuoso
|
<Virtuoso
|
||||||
ref={virtuosoRef}
|
ref={virtuosoRef}
|
||||||
style={{ height: "calc(100% - 40px)" }}
|
style={{ height: "calc(100% - 40px)" }}
|
||||||
totalCount={filterProxies.length}
|
totalCount={sortedProxies.length}
|
||||||
itemContent={(index) => (
|
itemContent={(index) => (
|
||||||
<ProxyItem
|
<ProxyItem
|
||||||
groupName={groupName}
|
groupName={groupName}
|
||||||
proxy={filterProxies[index]}
|
proxy={sortedProxies[index]}
|
||||||
selected={filterProxies[index].name === now}
|
selected={sortedProxies[index].name === now}
|
||||||
showType={showType}
|
showType={showType}
|
||||||
onClick={onChangeProxy}
|
onClick={onChangeProxy}
|
||||||
sx={{ py: 0, px: 2 }}
|
sx={{ py: 0, px: 2 }}
|
||||||
|
|||||||
@@ -6,28 +6,22 @@ import {
|
|||||||
Box,
|
Box,
|
||||||
Collapse,
|
Collapse,
|
||||||
Divider,
|
Divider,
|
||||||
IconButton,
|
|
||||||
List,
|
List,
|
||||||
ListItem,
|
ListItem,
|
||||||
ListItemText,
|
ListItemText,
|
||||||
TextField,
|
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import {
|
import {
|
||||||
SendRounded,
|
SendRounded,
|
||||||
ExpandLessRounded,
|
ExpandLessRounded,
|
||||||
ExpandMoreRounded,
|
ExpandMoreRounded,
|
||||||
MyLocationRounded,
|
|
||||||
NetworkCheckRounded,
|
|
||||||
FilterAltRounded,
|
|
||||||
FilterAltOffRounded,
|
|
||||||
VisibilityRounded,
|
|
||||||
VisibilityOffRounded,
|
|
||||||
} from "@mui/icons-material";
|
} from "@mui/icons-material";
|
||||||
import { ApiType } from "../../services/types";
|
import { ApiType } from "../../services/types";
|
||||||
import { updateProxy } from "../../services/api";
|
import { updateProxy } from "../../services/api";
|
||||||
import { getProfiles, patchProfile } from "../../services/cmds";
|
import { getProfiles, patchProfile } from "../../services/cmds";
|
||||||
import delayManager from "../../services/delay";
|
import useSortProxy, { ProxySortType } from "./use-sort-proxy";
|
||||||
import useFilterProxy from "./use-filter-proxy";
|
import useFilterProxy from "./use-filter-proxy";
|
||||||
|
import delayManager from "../../services/delay";
|
||||||
|
import ProxyHead from "./proxy-head";
|
||||||
import ProxyItem from "./proxy-item";
|
import ProxyItem from "./proxy-item";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
@@ -38,13 +32,14 @@ const ProxyGroup = ({ group }: Props) => {
|
|||||||
const { mutate } = useSWRConfig();
|
const { mutate } = useSWRConfig();
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const [now, setNow] = useState(group.now);
|
const [now, setNow] = useState(group.now);
|
||||||
|
|
||||||
const [showType, setShowType] = useState(false);
|
const [showType, setShowType] = useState(false);
|
||||||
const [showFilter, setShowFilter] = useState(false);
|
const [sortType, setSortType] = useState<ProxySortType>(0);
|
||||||
const [filterText, setFilterText] = useState("");
|
const [filterText, setFilterText] = useState("");
|
||||||
|
|
||||||
const proxies = group.all ?? [];
|
|
||||||
const virtuosoRef = useRef<any>();
|
const virtuosoRef = useRef<any>();
|
||||||
const filterProxies = useFilterProxy(proxies, group.name, filterText);
|
const filterProxies = useFilterProxy(group.all, group.name, filterText);
|
||||||
|
const sortedProxies = useSortProxy(filterProxies, group.name, sortType);
|
||||||
|
|
||||||
const { data: profiles } = useSWR("getProfiles", getProfiles);
|
const { data: profiles } = useSWR("getProfiles", getProfiles);
|
||||||
|
|
||||||
@@ -82,7 +77,7 @@ const ProxyGroup = ({ group }: Props) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const onLocation = (smooth = true) => {
|
const onLocation = (smooth = true) => {
|
||||||
const index = filterProxies.findIndex((p) => p.name === now);
|
const index = sortedProxies.findIndex((p) => p.name === now);
|
||||||
|
|
||||||
if (index >= 0) {
|
if (index >= 0) {
|
||||||
virtuosoRef.current?.scrollToIndex?.({
|
virtuosoRef.current?.scrollToIndex?.({
|
||||||
@@ -94,21 +89,14 @@ const ProxyGroup = ({ group }: Props) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const onCheckAll = useLockFn(async () => {
|
const onCheckAll = useLockFn(async () => {
|
||||||
const names = filterProxies.map((p) => p.name);
|
const names = sortedProxies.map((p) => p.name);
|
||||||
const groupName = group.name;
|
const groupName = group.name;
|
||||||
|
|
||||||
await delayManager.checkListDelay(
|
await delayManager.checkListDelay({ names, groupName, skipNum: 8 }, () =>
|
||||||
{ names, groupName, skipNum: 8, maxTimeout: 600 },
|
mutate("getProxies")
|
||||||
() => mutate("getProxies")
|
|
||||||
);
|
);
|
||||||
|
|
||||||
mutate("getProxies");
|
|
||||||
});
|
});
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!showFilter) setFilterText("");
|
|
||||||
}, [showFilter]);
|
|
||||||
|
|
||||||
// auto scroll to current index
|
// auto scroll to current index
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (open) {
|
if (open) {
|
||||||
@@ -136,59 +124,20 @@ const ProxyGroup = ({ group }: Props) => {
|
|||||||
</ListItem>
|
</ListItem>
|
||||||
|
|
||||||
<Collapse in={open} timeout="auto" unmountOnExit>
|
<Collapse in={open} timeout="auto" unmountOnExit>
|
||||||
<Box
|
<ProxyHead
|
||||||
sx={{
|
sx={{ pl: 4, pr: 3, my: 0.5, button: { mr: 0.5 } }}
|
||||||
pl: 4,
|
showType={showType}
|
||||||
pr: 3,
|
sortType={sortType}
|
||||||
my: 0.5,
|
groupName={group.name}
|
||||||
display: "flex",
|
filterText={filterText}
|
||||||
alignItems: "center",
|
onLocation={onLocation}
|
||||||
button: { mr: 0.5 },
|
onCheckDelay={onCheckAll}
|
||||||
}}
|
onShowType={setShowType}
|
||||||
>
|
onSortType={setSortType}
|
||||||
<IconButton
|
onFilterText={setFilterText}
|
||||||
size="small"
|
/>
|
||||||
title="location"
|
|
||||||
onClick={() => onLocation(true)}
|
|
||||||
>
|
|
||||||
<MyLocationRounded />
|
|
||||||
</IconButton>
|
|
||||||
|
|
||||||
<IconButton size="small" title="check" onClick={onCheckAll}>
|
{!sortedProxies.length && (
|
||||||
<NetworkCheckRounded />
|
|
||||||
</IconButton>
|
|
||||||
|
|
||||||
<IconButton
|
|
||||||
size="small"
|
|
||||||
title="check"
|
|
||||||
onClick={() => setShowType(!showType)}
|
|
||||||
>
|
|
||||||
{showType ? <VisibilityRounded /> : <VisibilityOffRounded />}
|
|
||||||
</IconButton>
|
|
||||||
|
|
||||||
<IconButton
|
|
||||||
size="small"
|
|
||||||
title="check"
|
|
||||||
onClick={() => setShowFilter(!showFilter)}
|
|
||||||
>
|
|
||||||
{showFilter ? <FilterAltRounded /> : <FilterAltOffRounded />}
|
|
||||||
</IconButton>
|
|
||||||
|
|
||||||
{showFilter && (
|
|
||||||
<TextField
|
|
||||||
autoFocus
|
|
||||||
hiddenLabel
|
|
||||||
value={filterText}
|
|
||||||
size="small"
|
|
||||||
variant="outlined"
|
|
||||||
placeholder="Filter conditions"
|
|
||||||
onChange={(e) => setFilterText(e.target.value)}
|
|
||||||
sx={{ ml: 0.5, flex: "1 1 auto", input: { py: 0.65, px: 1 } }}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
{!filterProxies.length && (
|
|
||||||
<Box
|
<Box
|
||||||
sx={{
|
sx={{
|
||||||
py: 3,
|
py: 3,
|
||||||
@@ -201,16 +150,16 @@ const ProxyGroup = ({ group }: Props) => {
|
|||||||
</Box>
|
</Box>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{filterProxies.length >= 10 ? (
|
{sortedProxies.length >= 10 ? (
|
||||||
<Virtuoso
|
<Virtuoso
|
||||||
ref={virtuosoRef}
|
ref={virtuosoRef}
|
||||||
style={{ height: "320px", marginBottom: "4px" }}
|
style={{ height: "320px", marginBottom: "4px" }}
|
||||||
totalCount={filterProxies.length}
|
totalCount={sortedProxies.length}
|
||||||
itemContent={(index) => (
|
itemContent={(index) => (
|
||||||
<ProxyItem
|
<ProxyItem
|
||||||
groupName={group.name}
|
groupName={group.name}
|
||||||
proxy={filterProxies[index]}
|
proxy={sortedProxies[index]}
|
||||||
selected={filterProxies[index].name === now}
|
selected={sortedProxies[index].name === now}
|
||||||
showType={showType}
|
showType={showType}
|
||||||
sx={{ py: 0, pl: 4 }}
|
sx={{ py: 0, pl: 4 }}
|
||||||
onClick={onChangeProxy}
|
onClick={onChangeProxy}
|
||||||
@@ -223,7 +172,7 @@ const ProxyGroup = ({ group }: Props) => {
|
|||||||
disablePadding
|
disablePadding
|
||||||
sx={{ maxHeight: "320px", overflow: "auto", mb: "4px" }}
|
sx={{ maxHeight: "320px", overflow: "auto", mb: "4px" }}
|
||||||
>
|
>
|
||||||
{filterProxies.map((proxy) => (
|
{sortedProxies.map((proxy) => (
|
||||||
<ProxyItem
|
<ProxyItem
|
||||||
key={proxy.name}
|
key={proxy.name}
|
||||||
groupName={group.name}
|
groupName={group.name}
|
||||||
|
|||||||
@@ -0,0 +1,147 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { Box, IconButton, TextField, SxProps } from "@mui/material";
|
||||||
|
import {
|
||||||
|
AccessTimeRounded,
|
||||||
|
MyLocationRounded,
|
||||||
|
NetworkCheckRounded,
|
||||||
|
FilterAltRounded,
|
||||||
|
FilterAltOffRounded,
|
||||||
|
VisibilityRounded,
|
||||||
|
VisibilityOffRounded,
|
||||||
|
WifiTetheringRounded,
|
||||||
|
WifiTetheringOffRounded,
|
||||||
|
SortByAlphaRounded,
|
||||||
|
SortRounded,
|
||||||
|
} from "@mui/icons-material";
|
||||||
|
import delayManager from "../../services/delay";
|
||||||
|
import type { ProxySortType } from "./use-sort-proxy";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
sx?: SxProps;
|
||||||
|
groupName: string;
|
||||||
|
showType: boolean;
|
||||||
|
sortType: ProxySortType;
|
||||||
|
filterText: string;
|
||||||
|
onLocation: () => void;
|
||||||
|
onCheckDelay: () => void;
|
||||||
|
onShowType: (val: boolean) => void;
|
||||||
|
onSortType: (val: ProxySortType) => void;
|
||||||
|
onFilterText: (val: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ProxyHead = (props: Props) => {
|
||||||
|
const { sx = {}, groupName, showType, sortType, filterText } = props;
|
||||||
|
|
||||||
|
const [textState, setTextState] = useState<"url" | "filter" | null>(null);
|
||||||
|
|
||||||
|
const [testUrl, setTestUrl] = useState(delayManager.getUrl(groupName) || "");
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box sx={{ display: "flex", alignItems: "center", ...sx }}>
|
||||||
|
<IconButton
|
||||||
|
size="small"
|
||||||
|
title="location"
|
||||||
|
color="inherit"
|
||||||
|
onClick={props.onLocation}
|
||||||
|
>
|
||||||
|
<MyLocationRounded />
|
||||||
|
</IconButton>
|
||||||
|
|
||||||
|
<IconButton
|
||||||
|
size="small"
|
||||||
|
color="inherit"
|
||||||
|
title="delay check"
|
||||||
|
onClick={() => {
|
||||||
|
// Remind the user that it is custom test url
|
||||||
|
if (testUrl?.trim() && textState !== "filter") {
|
||||||
|
setTextState("url");
|
||||||
|
}
|
||||||
|
props.onCheckDelay();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<NetworkCheckRounded />
|
||||||
|
</IconButton>
|
||||||
|
|
||||||
|
<IconButton
|
||||||
|
size="small"
|
||||||
|
color="inherit"
|
||||||
|
title={["sort by default", "sort by delay", "sort by name"][sortType]}
|
||||||
|
onClick={() => props.onSortType(((sortType + 1) % 3) as ProxySortType)}
|
||||||
|
>
|
||||||
|
{sortType === 0 && <SortRounded />}
|
||||||
|
{sortType === 1 && <AccessTimeRounded />}
|
||||||
|
{sortType === 2 && <SortByAlphaRounded />}
|
||||||
|
</IconButton>
|
||||||
|
|
||||||
|
<IconButton
|
||||||
|
size="small"
|
||||||
|
color="inherit"
|
||||||
|
title="edit test url"
|
||||||
|
onClick={() => setTextState((ts) => (ts === "url" ? null : "url"))}
|
||||||
|
>
|
||||||
|
{textState === "url" ? (
|
||||||
|
<WifiTetheringRounded />
|
||||||
|
) : (
|
||||||
|
<WifiTetheringOffRounded />
|
||||||
|
)}
|
||||||
|
</IconButton>
|
||||||
|
|
||||||
|
<IconButton
|
||||||
|
size="small"
|
||||||
|
color="inherit"
|
||||||
|
title="proxy detail"
|
||||||
|
onClick={() => props.onShowType(!showType)}
|
||||||
|
>
|
||||||
|
{showType ? <VisibilityRounded /> : <VisibilityOffRounded />}
|
||||||
|
</IconButton>
|
||||||
|
|
||||||
|
<IconButton
|
||||||
|
size="small"
|
||||||
|
color="inherit"
|
||||||
|
title="filter"
|
||||||
|
onClick={() =>
|
||||||
|
setTextState((ts) => (ts === "filter" ? null : "filter"))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{textState === "filter" ? (
|
||||||
|
<FilterAltRounded />
|
||||||
|
) : (
|
||||||
|
<FilterAltOffRounded />
|
||||||
|
)}
|
||||||
|
</IconButton>
|
||||||
|
|
||||||
|
{textState === "filter" && (
|
||||||
|
<TextField
|
||||||
|
autoFocus
|
||||||
|
hiddenLabel
|
||||||
|
value={filterText}
|
||||||
|
size="small"
|
||||||
|
variant="outlined"
|
||||||
|
placeholder="Filter conditions"
|
||||||
|
onChange={(e) => props.onFilterText(e.target.value)}
|
||||||
|
sx={{ ml: 0.5, flex: "1 1 auto", input: { py: 0.65, px: 1 } }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{textState === "url" && (
|
||||||
|
<TextField
|
||||||
|
autoFocus
|
||||||
|
hiddenLabel
|
||||||
|
autoSave="off"
|
||||||
|
autoComplete="off"
|
||||||
|
value={testUrl}
|
||||||
|
size="small"
|
||||||
|
variant="outlined"
|
||||||
|
placeholder="Test url"
|
||||||
|
onChange={(e) => {
|
||||||
|
setTestUrl(e.target.value);
|
||||||
|
delayManager.setUrl(groupName, e.target.value);
|
||||||
|
}}
|
||||||
|
sx={{ ml: 0.5, flex: "1 1 auto", input: { py: 0.65, px: 1 } }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default ProxyHead;
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
|
import { useLockFn } from "ahooks";
|
||||||
import { CheckCircleOutlineRounded } from "@mui/icons-material";
|
import { CheckCircleOutlineRounded } from "@mui/icons-material";
|
||||||
import {
|
import {
|
||||||
alpha,
|
alpha,
|
||||||
@@ -24,8 +25,9 @@ interface Props {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const Widget = styled(Box)(() => ({
|
const Widget = styled(Box)(() => ({
|
||||||
padding: "4px 6px",
|
padding: "3px 6px",
|
||||||
fontSize: 14,
|
fontSize: 14,
|
||||||
|
borderRadius: "4px",
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const TypeBox = styled(Box)(({ theme }) => ({
|
const TypeBox = styled(Box)(({ theme }) => ({
|
||||||
@@ -50,20 +52,12 @@ const ProxyItem = (props: Props) => {
|
|||||||
}
|
}
|
||||||
}, [proxy]);
|
}, [proxy]);
|
||||||
|
|
||||||
const delayRef = useRef(false);
|
const onDelay = useLockFn(async () => {
|
||||||
const onDelay = (e: any) => {
|
return delayManager
|
||||||
e.preventDefault();
|
|
||||||
e.stopPropagation();
|
|
||||||
|
|
||||||
if (delayRef.current) return;
|
|
||||||
delayRef.current = true;
|
|
||||||
|
|
||||||
delayManager
|
|
||||||
.checkDelay(proxy.name, groupName)
|
.checkDelay(proxy.name, groupName)
|
||||||
.then((result) => setDelay(result))
|
.then((result) => setDelay(result))
|
||||||
.catch(() => setDelay(1e6))
|
.catch(() => setDelay(1e6));
|
||||||
.finally(() => (delayRef.current = false));
|
});
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ListItem sx={sx}>
|
<ListItem sx={sx}>
|
||||||
@@ -111,13 +105,27 @@ const ProxyItem = (props: Props) => {
|
|||||||
<ListItemIcon
|
<ListItemIcon
|
||||||
sx={{ justifyContent: "flex-end", color: "primary.main" }}
|
sx={{ justifyContent: "flex-end", color: "primary.main" }}
|
||||||
>
|
>
|
||||||
<Widget className="the-check" onClick={onDelay}>
|
<Widget
|
||||||
|
className="the-check"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
onDelay();
|
||||||
|
}}
|
||||||
|
sx={(theme) => ({
|
||||||
|
":hover": { bgcolor: alpha(theme.palette.primary.main, 0.15) },
|
||||||
|
})}
|
||||||
|
>
|
||||||
Check
|
Check
|
||||||
</Widget>
|
</Widget>
|
||||||
|
|
||||||
<Widget
|
<Widget
|
||||||
className="the-delay"
|
className="the-delay"
|
||||||
onClick={onDelay}
|
onClick={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
onDelay();
|
||||||
|
}}
|
||||||
color={
|
color={
|
||||||
delay > 500
|
delay > 500
|
||||||
? "error.main"
|
? "error.main"
|
||||||
@@ -125,6 +133,9 @@ const ProxyItem = (props: Props) => {
|
|||||||
? "success.main"
|
? "success.main"
|
||||||
: "text.secondary"
|
: "text.secondary"
|
||||||
}
|
}
|
||||||
|
sx={(theme) => ({
|
||||||
|
":hover": { bgcolor: alpha(theme.palette.primary.main, 0.15) },
|
||||||
|
})}
|
||||||
>
|
>
|
||||||
{delay > 1e5 ? "Error" : delay > 3000 ? "Timeout" : `${delay}ms`}
|
{delay > 1e5 ? "Error" : delay > 3000 ? "Timeout" : `${delay}ms`}
|
||||||
</Widget>
|
</Widget>
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ export default function useFilterProxy(
|
|||||||
filterText: string
|
filterText: string
|
||||||
) {
|
) {
|
||||||
return useMemo(() => {
|
return useMemo(() => {
|
||||||
|
if (!proxies) return [];
|
||||||
if (!filterText) return proxies;
|
if (!filterText) return proxies;
|
||||||
|
|
||||||
const res1 = regex1.exec(filterText);
|
const res1 = regex1.exec(filterText);
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { useMemo } from "react";
|
||||||
|
import { ApiType } from "../../services/types";
|
||||||
|
import delayManager from "../../services/delay";
|
||||||
|
|
||||||
|
// default | delay | alpha
|
||||||
|
export type ProxySortType = 0 | 1 | 2;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* sort the proxy
|
||||||
|
*/
|
||||||
|
export default function useSortProxy(
|
||||||
|
proxies: ApiType.ProxyItem[],
|
||||||
|
groupName: string,
|
||||||
|
sortType: ProxySortType
|
||||||
|
) {
|
||||||
|
return useMemo(() => {
|
||||||
|
if (!proxies) return [];
|
||||||
|
if (sortType === 0) return proxies;
|
||||||
|
|
||||||
|
const list = proxies.slice();
|
||||||
|
|
||||||
|
if (sortType === 1) {
|
||||||
|
list.sort((a, b) => {
|
||||||
|
const ad = delayManager.getDelay(a.name, groupName);
|
||||||
|
const bd = delayManager.getDelay(b.name, groupName);
|
||||||
|
|
||||||
|
if (ad === -1) return 1;
|
||||||
|
if (bd === -1) return -1;
|
||||||
|
|
||||||
|
return ad - bd;
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
list.sort((a, b) => a.name.localeCompare(b.name));
|
||||||
|
}
|
||||||
|
|
||||||
|
return list;
|
||||||
|
}, [proxies, groupName, sortType]);
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import useSWR, { useSWRConfig } from "swr";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useLockFn } from "ahooks";
|
||||||
|
import { Menu, MenuItem } from "@mui/material";
|
||||||
|
import { Settings } from "@mui/icons-material";
|
||||||
|
import { changeClashCore, getVergeConfig } from "../../services/cmds";
|
||||||
|
import getSystem from "../../utils/get-system";
|
||||||
|
import Notice from "../base/base-notice";
|
||||||
|
|
||||||
|
const OS = getSystem();
|
||||||
|
|
||||||
|
const VALID_CORE = [
|
||||||
|
{ name: "Clash", core: "clash" },
|
||||||
|
{ name: "Clash Meta", core: "clash-meta" },
|
||||||
|
];
|
||||||
|
|
||||||
|
const CoreSwitch = () => {
|
||||||
|
const { mutate } = useSWRConfig();
|
||||||
|
|
||||||
|
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
|
||||||
|
|
||||||
|
const [anchorEl, setAnchorEl] = useState<any>(null);
|
||||||
|
const [position, setPosition] = useState({ left: 0, top: 0 });
|
||||||
|
|
||||||
|
const { clash_core = "clash" } = vergeConfig ?? {};
|
||||||
|
|
||||||
|
const onCoreChange = useLockFn(async (core: string) => {
|
||||||
|
if (core === clash_core) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await changeClashCore(core);
|
||||||
|
mutate("getVergeConfig");
|
||||||
|
mutate("getClashConfig");
|
||||||
|
mutate("getVersion");
|
||||||
|
setAnchorEl(null);
|
||||||
|
Notice.success(`Successfully switch to ${core}`, 1000);
|
||||||
|
} catch (err: any) {
|
||||||
|
Notice.error(err?.message || err.toString());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Settings
|
||||||
|
fontSize="small"
|
||||||
|
style={{ cursor: "pointer" }}
|
||||||
|
onClick={(event) => {
|
||||||
|
const { clientX, clientY } = event;
|
||||||
|
setPosition({ top: clientY, left: clientX });
|
||||||
|
setAnchorEl(event.currentTarget);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Menu
|
||||||
|
open={!!anchorEl}
|
||||||
|
anchorEl={anchorEl}
|
||||||
|
onClose={() => setAnchorEl(null)}
|
||||||
|
anchorPosition={position}
|
||||||
|
anchorReference="anchorPosition"
|
||||||
|
transitionDuration={225}
|
||||||
|
TransitionProps={
|
||||||
|
OS === "macos" ? { style: { transitionDuration: "225ms" } } : {}
|
||||||
|
}
|
||||||
|
onContextMenu={(e) => {
|
||||||
|
setAnchorEl(null);
|
||||||
|
e.preventDefault();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{VALID_CORE.map((each) => (
|
||||||
|
<MenuItem
|
||||||
|
key={each.core}
|
||||||
|
sx={{ minWidth: 125 }}
|
||||||
|
selected={each.core === clash_core}
|
||||||
|
onClick={() => onCoreChange(each.core)}
|
||||||
|
>
|
||||||
|
{each.name}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</Menu>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default CoreSwitch;
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
import useSWR, { useSWRConfig } from "swr";
|
||||||
|
import { useLockFn } from "ahooks";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import {
|
||||||
|
Button,
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogTitle,
|
||||||
|
Stack,
|
||||||
|
Typography,
|
||||||
|
} from "@mui/material";
|
||||||
|
import {
|
||||||
|
checkService,
|
||||||
|
installService,
|
||||||
|
uninstallService,
|
||||||
|
patchVergeConfig,
|
||||||
|
} from "../../services/cmds";
|
||||||
|
import Notice from "../base/base-notice";
|
||||||
|
import noop from "../../utils/noop";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
open: boolean;
|
||||||
|
enable: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
onError?: (err: Error) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ServiceMode = (props: Props) => {
|
||||||
|
const { open, enable, onClose, onError = noop } = props;
|
||||||
|
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const { mutate } = useSWRConfig();
|
||||||
|
const { data: status } = useSWR("checkService", checkService, {
|
||||||
|
revalidateIfStale: true,
|
||||||
|
shouldRetryOnError: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
const state = status != null ? status : "pending";
|
||||||
|
|
||||||
|
const onInstall = useLockFn(async () => {
|
||||||
|
try {
|
||||||
|
await installService();
|
||||||
|
mutate("checkService");
|
||||||
|
onClose();
|
||||||
|
Notice.success("Service installed successfully");
|
||||||
|
} catch (err: any) {
|
||||||
|
mutate("checkService");
|
||||||
|
onError(err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const onUninstall = useLockFn(async () => {
|
||||||
|
try {
|
||||||
|
if (state === "active" && enable) {
|
||||||
|
await patchVergeConfig({ enable_service_mode: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
await uninstallService();
|
||||||
|
mutate("checkService");
|
||||||
|
onClose();
|
||||||
|
Notice.success("Service uninstalled successfully");
|
||||||
|
} catch (err: any) {
|
||||||
|
mutate("checkService");
|
||||||
|
onError(err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// fix unhandle error of the service mode
|
||||||
|
const onDisable = useLockFn(async () => {
|
||||||
|
await patchVergeConfig({ enable_service_mode: false });
|
||||||
|
mutate("checkService");
|
||||||
|
onClose();
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onClose={onClose}>
|
||||||
|
<DialogTitle>{t("Service Mode")}</DialogTitle>
|
||||||
|
|
||||||
|
<DialogContent sx={{ width: 360, userSelect: "text" }}>
|
||||||
|
<Typography>Current State: {state}</Typography>
|
||||||
|
|
||||||
|
{(state === "unknown" || state === "uninstall") && (
|
||||||
|
<Typography>
|
||||||
|
Infomation: Please make sure the Clash Verge Service is installed
|
||||||
|
and enabled
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Stack
|
||||||
|
direction="row"
|
||||||
|
spacing={1}
|
||||||
|
sx={{ mt: 4, justifyContent: "flex-end" }}
|
||||||
|
>
|
||||||
|
{state === "uninstall" && enable && (
|
||||||
|
<Button variant="contained" onClick={onDisable}>
|
||||||
|
Disable Service Mode
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{state === "uninstall" && (
|
||||||
|
<Button variant="contained" onClick={onInstall}>
|
||||||
|
Install
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{(state === "active" || state === "installed") && (
|
||||||
|
<Button variant="outlined" onClick={onUninstall}>
|
||||||
|
Uninstall
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default ServiceMode;
|
||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
Select,
|
Select,
|
||||||
MenuItem,
|
MenuItem,
|
||||||
Typography,
|
Typography,
|
||||||
|
Box,
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import { ApiType } from "../../services/types";
|
import { ApiType } from "../../services/types";
|
||||||
import { atomClashPort } from "../../services/states";
|
import { atomClashPort } from "../../services/states";
|
||||||
@@ -16,11 +17,15 @@ import { SettingList, SettingItem } from "./setting";
|
|||||||
import { getClashConfig, getVersion, updateConfigs } from "../../services/api";
|
import { getClashConfig, getVersion, updateConfigs } from "../../services/api";
|
||||||
import Notice from "../base/base-notice";
|
import Notice from "../base/base-notice";
|
||||||
import GuardState from "./guard-state";
|
import GuardState from "./guard-state";
|
||||||
|
import CoreSwitch from "./core-switch";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
onError: (err: Error) => void;
|
onError: (err: Error) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// const MULTI_CORE = !!import.meta.env.VITE_MULTI_CORE;
|
||||||
|
const MULTI_CORE = true;
|
||||||
|
|
||||||
const SettingClash = ({ onError }: Props) => {
|
const SettingClash = ({ onError }: Props) => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const { mutate } = useSWRConfig();
|
const { mutate } = useSWRConfig();
|
||||||
@@ -54,7 +59,7 @@ const SettingClash = ({ onError }: Props) => {
|
|||||||
}
|
}
|
||||||
await patchClashConfig({ "mixed-port": port });
|
await patchClashConfig({ "mixed-port": port });
|
||||||
setGlobalClashPort(port);
|
setGlobalClashPort(port);
|
||||||
Notice.success("Change Clash port successfully!");
|
Notice.success("Change Clash port successfully!", 1000);
|
||||||
|
|
||||||
// update the config
|
// update the config
|
||||||
mutate("getClashConfig");
|
mutate("getClashConfig");
|
||||||
@@ -122,14 +127,25 @@ const SettingClash = ({ onError }: Props) => {
|
|||||||
onFormat={(e: any) => +e.target.value?.replace(/\D+/, "")}
|
onFormat={(e: any) => +e.target.value?.replace(/\D+/, "")}
|
||||||
onChange={(e) => onChangeData({ "mixed-port": e })}
|
onChange={(e) => onChangeData({ "mixed-port": e })}
|
||||||
onGuard={onUpdatePort}
|
onGuard={onUpdatePort}
|
||||||
waitTime={800}
|
waitTime={1000}
|
||||||
>
|
>
|
||||||
<TextField autoComplete="off" size="small" sx={{ width: 120 }} />
|
<TextField autoComplete="off" size="small" sx={{ width: 120 }} />
|
||||||
</GuardState>
|
</GuardState>
|
||||||
</SettingItem>
|
</SettingItem>
|
||||||
|
|
||||||
<SettingItem>
|
<SettingItem>
|
||||||
<ListItemText primary={t("Clash core")} />
|
<ListItemText
|
||||||
|
primary={
|
||||||
|
MULTI_CORE ? (
|
||||||
|
<Box sx={{ display: "flex", alignItems: "center" }}>
|
||||||
|
<span style={{ marginRight: 4 }}>{t("Clash Core")}</span>
|
||||||
|
<CoreSwitch />
|
||||||
|
</Box>
|
||||||
|
) : (
|
||||||
|
t("Clash Core")
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
<Typography sx={{ py: 1 }}>{clashVer}</Typography>
|
<Typography sx={{ py: 1 }}>{clashVer}</Typography>
|
||||||
</SettingItem>
|
</SettingItem>
|
||||||
</SettingList>
|
</SettingList>
|
||||||
|
|||||||
@@ -1,24 +1,49 @@
|
|||||||
import useSWR, { useSWRConfig } from "swr";
|
import useSWR, { useSWRConfig } from "swr";
|
||||||
|
import { useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { Box, ListItemText, Switch, TextField } from "@mui/material";
|
import {
|
||||||
import { getVergeConfig, patchVergeConfig } from "../../services/cmds";
|
Box,
|
||||||
|
IconButton,
|
||||||
|
ListItemText,
|
||||||
|
Switch,
|
||||||
|
TextField,
|
||||||
|
} from "@mui/material";
|
||||||
|
import { ArrowForward, PrivacyTipRounded } from "@mui/icons-material";
|
||||||
|
import {
|
||||||
|
checkService,
|
||||||
|
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";
|
||||||
import GuardState from "./guard-state";
|
import GuardState from "./guard-state";
|
||||||
|
import ServiceMode from "./service-mode";
|
||||||
import SysproxyTooltip from "./sysproxy-tooltip";
|
import SysproxyTooltip from "./sysproxy-tooltip";
|
||||||
|
import getSystem from "../../utils/get-system";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
onError?: (err: Error) => void;
|
onError?: (err: Error) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const isWIN = getSystem() === "windows";
|
||||||
|
|
||||||
const SettingSystem = ({ onError }: Props) => {
|
const SettingSystem = ({ onError }: Props) => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const { mutate } = useSWRConfig();
|
const { mutate } = useSWRConfig();
|
||||||
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
|
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
|
||||||
|
|
||||||
|
// service mode
|
||||||
|
const [serviceOpen, setServiceOpen] = useState(false);
|
||||||
|
const { data: serviceStatus } = useSWR(
|
||||||
|
isWIN ? "checkService" : null,
|
||||||
|
checkService,
|
||||||
|
{ revalidateIfStale: true, shouldRetryOnError: false }
|
||||||
|
);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
enable_tun_mode,
|
enable_tun_mode,
|
||||||
enable_auto_launch,
|
enable_auto_launch,
|
||||||
|
enable_service_mode,
|
||||||
enable_silent_start,
|
enable_silent_start,
|
||||||
enable_system_proxy,
|
enable_system_proxy,
|
||||||
system_proxy_bypass,
|
system_proxy_bypass,
|
||||||
@@ -46,6 +71,56 @@ const SettingSystem = ({ onError }: Props) => {
|
|||||||
</GuardState>
|
</GuardState>
|
||||||
</SettingItem>
|
</SettingItem>
|
||||||
|
|
||||||
|
{isWIN && (
|
||||||
|
<SettingItem>
|
||||||
|
<ListItemText
|
||||||
|
primary={
|
||||||
|
<Box sx={{ display: "flex", alignItems: "center" }}>
|
||||||
|
<span style={{ marginRight: 4 }}>{t("Service Mode")}</span>
|
||||||
|
|
||||||
|
{(serviceStatus === "active" ||
|
||||||
|
serviceStatus === "installed") && (
|
||||||
|
<PrivacyTipRounded
|
||||||
|
fontSize="small"
|
||||||
|
onClick={() => setServiceOpen(true)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{serviceStatus === "active" || serviceStatus === "installed" ? (
|
||||||
|
<GuardState
|
||||||
|
value={enable_service_mode ?? false}
|
||||||
|
valueProps="checked"
|
||||||
|
onCatch={onError}
|
||||||
|
onFormat={onSwitchFormat}
|
||||||
|
onChange={(e) => onChangeData({ enable_service_mode: e })}
|
||||||
|
onGuard={(e) => patchVergeConfig({ enable_service_mode: e })}
|
||||||
|
>
|
||||||
|
<Switch edge="end" />
|
||||||
|
</GuardState>
|
||||||
|
) : (
|
||||||
|
<IconButton
|
||||||
|
color="inherit"
|
||||||
|
size="small"
|
||||||
|
onClick={() => setServiceOpen(true)}
|
||||||
|
>
|
||||||
|
<ArrowForward />
|
||||||
|
</IconButton>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{serviceOpen && (
|
||||||
|
<ServiceMode
|
||||||
|
open={serviceOpen}
|
||||||
|
enable={!!enable_service_mode}
|
||||||
|
onError={onError}
|
||||||
|
onClose={() => setServiceOpen(false)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</SettingItem>
|
||||||
|
)}
|
||||||
|
|
||||||
<SettingItem>
|
<SettingItem>
|
||||||
<ListItemText primary={t("Auto Launch")} />
|
<ListItemText primary={t("Auto Launch")} />
|
||||||
<GuardState
|
<GuardState
|
||||||
@@ -78,7 +153,7 @@ const SettingSystem = ({ onError }: Props) => {
|
|||||||
<ListItemText
|
<ListItemText
|
||||||
primary={
|
primary={
|
||||||
<Box sx={{ display: "flex", alignItems: "center" }}>
|
<Box sx={{ display: "flex", alignItems: "center" }}>
|
||||||
{t("System Proxy")}
|
<span style={{ marginRight: 4 }}>{t("System Proxy")}</span>
|
||||||
<SysproxyTooltip />
|
<SysproxyTooltip />
|
||||||
</Box>
|
</Box>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,154 @@
|
|||||||
|
import useSWR from "swr";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { useLockFn } from "ahooks";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import {
|
||||||
|
Button,
|
||||||
|
Dialog,
|
||||||
|
DialogActions,
|
||||||
|
DialogContent,
|
||||||
|
DialogTitle,
|
||||||
|
List,
|
||||||
|
ListItem,
|
||||||
|
ListItemText,
|
||||||
|
styled,
|
||||||
|
TextField,
|
||||||
|
useTheme,
|
||||||
|
} from "@mui/material";
|
||||||
|
import { getVergeConfig, patchVergeConfig } from "../../services/cmds";
|
||||||
|
import { defaultTheme, defaultDarkTheme } from "../../pages/_theme";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
open: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
onError?: (err: Error) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const Item = styled(ListItem)(() => ({
|
||||||
|
padding: "5px 2px",
|
||||||
|
}));
|
||||||
|
|
||||||
|
const Round = styled("div")(() => ({
|
||||||
|
width: "24px",
|
||||||
|
height: "24px",
|
||||||
|
borderRadius: "18px",
|
||||||
|
display: "inline-block",
|
||||||
|
marginRight: "8px",
|
||||||
|
}));
|
||||||
|
|
||||||
|
const SettingTheme = (props: Props) => {
|
||||||
|
const { open, onClose, onError } = props;
|
||||||
|
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const { data: vergeConfig, mutate } = useSWR(
|
||||||
|
"getVergeConfig",
|
||||||
|
getVergeConfig
|
||||||
|
);
|
||||||
|
|
||||||
|
const { theme_setting } = vergeConfig ?? {};
|
||||||
|
const [theme, setTheme] = useState(theme_setting || {});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setTheme({ ...theme_setting } || {});
|
||||||
|
}, [theme_setting]);
|
||||||
|
|
||||||
|
const textProps = {
|
||||||
|
size: "small",
|
||||||
|
autoComplete: "off",
|
||||||
|
sx: { width: 135 },
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const handleChange = (field: keyof typeof theme) => (e: any) => {
|
||||||
|
setTheme((t) => ({ ...t, [field]: e.target.value }));
|
||||||
|
};
|
||||||
|
|
||||||
|
const onSave = useLockFn(async () => {
|
||||||
|
try {
|
||||||
|
await patchVergeConfig({ theme_setting: theme });
|
||||||
|
mutate();
|
||||||
|
onClose();
|
||||||
|
} catch (err: any) {
|
||||||
|
onError?.(err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// default theme
|
||||||
|
const { palette } = useTheme();
|
||||||
|
|
||||||
|
const dt = palette.mode === "light" ? defaultTheme : defaultDarkTheme;
|
||||||
|
|
||||||
|
type ThemeKey = keyof typeof theme & keyof typeof defaultTheme;
|
||||||
|
|
||||||
|
const renderItem = (label: string, key: ThemeKey) => {
|
||||||
|
return (
|
||||||
|
<Item>
|
||||||
|
<ListItemText primary={label} />
|
||||||
|
<Round sx={{ background: theme[key] || dt[key] }} />
|
||||||
|
<TextField
|
||||||
|
{...textProps}
|
||||||
|
value={theme[key] ?? ""}
|
||||||
|
placeholder={dt[key]}
|
||||||
|
onChange={handleChange(key)}
|
||||||
|
onKeyDown={(e) => e.key === "Enter" && onSave()}
|
||||||
|
/>
|
||||||
|
</Item>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onClose={onClose}>
|
||||||
|
<DialogTitle>{t("Theme Setting")}</DialogTitle>
|
||||||
|
|
||||||
|
<DialogContent
|
||||||
|
sx={{ width: 400, maxHeight: 300, overflow: "auto", pb: 0 }}
|
||||||
|
>
|
||||||
|
<List sx={{ pt: 0 }}>
|
||||||
|
{renderItem("Primary Color", "primary_color")}
|
||||||
|
|
||||||
|
{renderItem("Secondary Color", "secondary_color")}
|
||||||
|
|
||||||
|
{renderItem("Primary Text", "primary_text")}
|
||||||
|
|
||||||
|
{renderItem("Secondary Text", "secondary_text")}
|
||||||
|
|
||||||
|
{renderItem("Info Color", "info_color")}
|
||||||
|
|
||||||
|
{renderItem("Error Color", "error_color")}
|
||||||
|
|
||||||
|
{renderItem("Warning Color", "warning_color")}
|
||||||
|
|
||||||
|
{renderItem("Success Color", "success_color")}
|
||||||
|
|
||||||
|
<Item>
|
||||||
|
<ListItemText primary="Font Family" />
|
||||||
|
<TextField
|
||||||
|
{...textProps}
|
||||||
|
value={theme.font_family ?? ""}
|
||||||
|
onChange={handleChange("font_family")}
|
||||||
|
onKeyDown={(e) => e.key === "Enter" && onSave()}
|
||||||
|
/>
|
||||||
|
</Item>
|
||||||
|
|
||||||
|
<Item>
|
||||||
|
<ListItemText primary="CSS Injection" />
|
||||||
|
<TextField
|
||||||
|
{...textProps}
|
||||||
|
value={theme.css_injection ?? ""}
|
||||||
|
onChange={handleChange("css_injection")}
|
||||||
|
onKeyDown={(e) => e.key === "Enter" && onSave()}
|
||||||
|
/>
|
||||||
|
</Item>
|
||||||
|
</List>
|
||||||
|
</DialogContent>
|
||||||
|
|
||||||
|
<DialogActions>
|
||||||
|
<Button onClick={onClose}>{t("Cancel")}</Button>
|
||||||
|
<Button onClick={onSave} variant="contained">
|
||||||
|
{t("Save")}
|
||||||
|
</Button>
|
||||||
|
</DialogActions>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default SettingTheme;
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import useSWR, { useSWRConfig } from "swr";
|
import useSWR, { useSWRConfig } from "swr";
|
||||||
|
import { useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import {
|
import {
|
||||||
IconButton,
|
IconButton,
|
||||||
@@ -20,6 +21,7 @@ import { CmdType } from "../../services/types";
|
|||||||
import { version } from "../../../package.json";
|
import { version } from "../../../package.json";
|
||||||
import PaletteSwitch from "./palette-switch";
|
import PaletteSwitch from "./palette-switch";
|
||||||
import GuardState from "./guard-state";
|
import GuardState from "./guard-state";
|
||||||
|
import SettingTheme from "./setting-theme";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
onError?: (err: Error) => void;
|
onError?: (err: Error) => void;
|
||||||
@@ -32,6 +34,8 @@ const SettingVerge = ({ onError }: Props) => {
|
|||||||
|
|
||||||
const { theme_mode, theme_blur, traffic_graph, language } = vergeConfig ?? {};
|
const { theme_mode, theme_blur, traffic_graph, language } = vergeConfig ?? {};
|
||||||
|
|
||||||
|
const [themeOpen, setThemeOpen] = useState(false);
|
||||||
|
|
||||||
const onSwitchFormat = (_e: any, value: boolean) => value;
|
const onSwitchFormat = (_e: any, value: boolean) => value;
|
||||||
const onChangeData = (patch: Partial<CmdType.VergeConfig>) => {
|
const onChangeData = (patch: Partial<CmdType.VergeConfig>) => {
|
||||||
mutate("getVergeConfig", { ...vergeConfig, ...patch }, false);
|
mutate("getVergeConfig", { ...vergeConfig, ...patch }, false);
|
||||||
@@ -99,6 +103,17 @@ const SettingVerge = ({ onError }: Props) => {
|
|||||||
</GuardState>
|
</GuardState>
|
||||||
</SettingItem>
|
</SettingItem>
|
||||||
|
|
||||||
|
<SettingItem>
|
||||||
|
<ListItemText primary={t("Theme Setting")} />
|
||||||
|
<IconButton
|
||||||
|
color="inherit"
|
||||||
|
size="small"
|
||||||
|
onClick={() => setThemeOpen(true)}
|
||||||
|
>
|
||||||
|
<ArrowForward />
|
||||||
|
</IconButton>
|
||||||
|
</SettingItem>
|
||||||
|
|
||||||
<SettingItem>
|
<SettingItem>
|
||||||
<ListItemText primary={t("Open App Dir")} />
|
<ListItemText primary={t("Open App Dir")} />
|
||||||
<IconButton color="inherit" size="small" onClick={openAppDir}>
|
<IconButton color="inherit" size="small" onClick={openAppDir}>
|
||||||
@@ -117,6 +132,8 @@ const SettingVerge = ({ onError }: Props) => {
|
|||||||
<ListItemText primary={t("Version")} />
|
<ListItemText primary={t("Version")} />
|
||||||
<Typography sx={{ py: "6px" }}>v{version}</Typography>
|
<Typography sx={{ py: "6px" }}>v{version}</Typography>
|
||||||
</SettingItem>
|
</SettingItem>
|
||||||
|
|
||||||
|
<SettingTheme open={themeOpen} onClose={() => setThemeOpen(false)} />
|
||||||
</SettingList>
|
</SettingList>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -13,6 +13,7 @@
|
|||||||
"rule": "rule",
|
"rule": "rule",
|
||||||
"global": "global",
|
"global": "global",
|
||||||
"direct": "direct",
|
"direct": "direct",
|
||||||
|
"script": "script",
|
||||||
"Profiles": "Profiles",
|
"Profiles": "Profiles",
|
||||||
"Profile URL": "Profile URL",
|
"Profile URL": "Profile URL",
|
||||||
"Import": "Import",
|
"Import": "Import",
|
||||||
@@ -39,8 +40,9 @@
|
|||||||
"IPv6": "IPv6",
|
"IPv6": "IPv6",
|
||||||
"Log Level": "Log Level",
|
"Log Level": "Log Level",
|
||||||
"Mixed Port": "Mixed Port",
|
"Mixed Port": "Mixed Port",
|
||||||
"Clash core": "Clash core",
|
"Clash Core": "Clash Core",
|
||||||
"Tun Mode": "Tun Mode",
|
"Tun Mode": "Tun Mode",
|
||||||
|
"Service Mode": "Service Mode",
|
||||||
"Auto Launch": "Auto Launch",
|
"Auto Launch": "Auto Launch",
|
||||||
"Silent Start": "Silent Start",
|
"Silent Start": "Silent Start",
|
||||||
"System Proxy": "System Proxy",
|
"System Proxy": "System Proxy",
|
||||||
@@ -48,6 +50,7 @@
|
|||||||
"Proxy Bypass": "Proxy Bypass",
|
"Proxy Bypass": "Proxy Bypass",
|
||||||
"Theme Mode": "Theme Mode",
|
"Theme Mode": "Theme Mode",
|
||||||
"Theme Blur": "Theme Blur",
|
"Theme Blur": "Theme Blur",
|
||||||
|
"Theme Setting": "Theme Setting",
|
||||||
"Traffic Graph": "Traffic Graph",
|
"Traffic Graph": "Traffic Graph",
|
||||||
"Language": "Language",
|
"Language": "Language",
|
||||||
"Open App Dir": "Open App Dir",
|
"Open App Dir": "Open App Dir",
|
||||||
|
|||||||
@@ -13,6 +13,7 @@
|
|||||||
"rule": "规则",
|
"rule": "规则",
|
||||||
"global": "全局",
|
"global": "全局",
|
||||||
"direct": "直连",
|
"direct": "直连",
|
||||||
|
"script": "脚本",
|
||||||
"Profiles": "配置",
|
"Profiles": "配置",
|
||||||
"Profile URL": "配置文件链接",
|
"Profile URL": "配置文件链接",
|
||||||
"Import": "导入",
|
"Import": "导入",
|
||||||
@@ -39,8 +40,9 @@
|
|||||||
"IPv6": "IPv6",
|
"IPv6": "IPv6",
|
||||||
"Log Level": "日志等级",
|
"Log Level": "日志等级",
|
||||||
"Mixed Port": "端口设置",
|
"Mixed Port": "端口设置",
|
||||||
"Clash core": "Clash 内核",
|
"Clash Core": "Clash 内核",
|
||||||
"Tun Mode": "Tun 模式",
|
"Tun Mode": "Tun 模式",
|
||||||
|
"Service Mode": "服务模式",
|
||||||
"Auto Launch": "开机自启",
|
"Auto Launch": "开机自启",
|
||||||
"Silent Start": "静默启动",
|
"Silent Start": "静默启动",
|
||||||
"System Proxy": "系统代理",
|
"System Proxy": "系统代理",
|
||||||
@@ -48,6 +50,7 @@
|
|||||||
"Proxy Bypass": "Proxy Bypass",
|
"Proxy Bypass": "Proxy Bypass",
|
||||||
"Theme Mode": "暗夜模式",
|
"Theme Mode": "暗夜模式",
|
||||||
"Theme Blur": "背景模糊",
|
"Theme Blur": "背景模糊",
|
||||||
|
"Theme Setting": "主题设置",
|
||||||
"Traffic Graph": "流量图显",
|
"Traffic Graph": "流量图显",
|
||||||
"Language": "语言设置",
|
"Language": "语言设置",
|
||||||
"Open App Dir": "应用目录",
|
"Open App Dir": "应用目录",
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
/// <reference types="vite/client" />
|
/// <reference types="vite/client" />
|
||||||
|
/// <reference types="vite-plugin-svgr/client" />
|
||||||
import "./assets/styles/index.scss";
|
import "./assets/styles/index.scss";
|
||||||
|
|
||||||
import React from "react";
|
import React from "react";
|
||||||
|
|||||||
@@ -2,20 +2,21 @@ import dayjs from "dayjs";
|
|||||||
import i18next from "i18next";
|
import i18next from "i18next";
|
||||||
import relativeTime from "dayjs/plugin/relativeTime";
|
import relativeTime from "dayjs/plugin/relativeTime";
|
||||||
import useSWR, { SWRConfig, useSWRConfig } from "swr";
|
import useSWR, { SWRConfig, useSWRConfig } from "swr";
|
||||||
import { useEffect, useMemo } from "react";
|
import { useEffect } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { Route, Routes } from "react-router-dom";
|
import { Route, Routes } from "react-router-dom";
|
||||||
import { alpha, createTheme, List, Paper, ThemeProvider } from "@mui/material";
|
import { alpha, List, Paper, ThemeProvider } from "@mui/material";
|
||||||
import { listen } from "@tauri-apps/api/event";
|
import { listen } from "@tauri-apps/api/event";
|
||||||
import { appWindow } from "@tauri-apps/api/window";
|
import { appWindow } from "@tauri-apps/api/window";
|
||||||
import { routers } from "./_routers";
|
import { routers } from "./_routers";
|
||||||
import { getAxios } from "../services/api";
|
import { getAxios } from "../services/api";
|
||||||
import { getVergeConfig } from "../services/cmds";
|
import { getVergeConfig } from "../services/cmds";
|
||||||
import LogoSvg from "../assets/image/logo.svg";
|
import { ReactComponent as LogoSvg } from "../assets/image/logo.svg";
|
||||||
import LayoutItem from "../components/layout/layout-item";
|
import LayoutItem from "../components/layout/layout-item";
|
||||||
import LayoutControl from "../components/layout/layout-control";
|
import LayoutControl from "../components/layout/layout-control";
|
||||||
import LayoutTraffic from "../components/layout/layout-traffic";
|
import LayoutTraffic from "../components/layout/layout-traffic";
|
||||||
import UpdateButton from "../components/layout/update-button";
|
import UpdateButton from "../components/layout/update-button";
|
||||||
|
import useCustomTheme from "../components/layout/use-custom-theme";
|
||||||
import getSystem from "../utils/get-system";
|
import getSystem from "../utils/get-system";
|
||||||
import "dayjs/locale/zh-cn";
|
import "dayjs/locale/zh-cn";
|
||||||
|
|
||||||
@@ -26,14 +27,15 @@ const OS = getSystem();
|
|||||||
const Layout = () => {
|
const Layout = () => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const { mutate } = useSWRConfig();
|
const { mutate } = useSWRConfig();
|
||||||
const { data } = useSWR("getVergeConfig", getVergeConfig);
|
|
||||||
|
|
||||||
const blur = !!data?.theme_blur;
|
const { theme } = useCustomTheme();
|
||||||
const mode = data?.theme_mode ?? "light";
|
|
||||||
|
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
|
||||||
|
const { theme_blur, language } = vergeConfig || {};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
window.addEventListener("keydown", (e) => {
|
window.addEventListener("keydown", (e) => {
|
||||||
if (e.key === "Escape") appWindow.hide();
|
if (e.key === "Escape") appWindow.close();
|
||||||
});
|
});
|
||||||
|
|
||||||
listen("verge://refresh-clash-config", async () => {
|
listen("verge://refresh-clash-config", async () => {
|
||||||
@@ -48,37 +50,11 @@ const Layout = () => {
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (data?.language) {
|
if (language) {
|
||||||
dayjs.locale(data.language === "zh" ? "zh-cn" : data.language);
|
dayjs.locale(language === "zh" ? "zh-cn" : language);
|
||||||
i18next.changeLanguage(data.language);
|
i18next.changeLanguage(language);
|
||||||
}
|
}
|
||||||
}, [data?.language]);
|
}, [language]);
|
||||||
|
|
||||||
const theme = useMemo(() => {
|
|
||||||
// const background = mode === "light" ? "#f5f5f5" : "#000";
|
|
||||||
const selectColor = mode === "light" ? "#f5f5f5" : "#d5d5d5";
|
|
||||||
|
|
||||||
const rootEle = document.documentElement;
|
|
||||||
rootEle.style.background = "transparent";
|
|
||||||
rootEle.style.setProperty("--selection-color", selectColor);
|
|
||||||
|
|
||||||
return createTheme({
|
|
||||||
breakpoints: {
|
|
||||||
values: { xs: 0, sm: 650, md: 900, lg: 1200, xl: 1536 },
|
|
||||||
},
|
|
||||||
palette: {
|
|
||||||
mode,
|
|
||||||
primary: { main: "#5b5c9d" },
|
|
||||||
text: { primary: "#637381", secondary: "#909399" },
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}, [mode]);
|
|
||||||
|
|
||||||
const onDragging = (e: any) => {
|
|
||||||
if (e?.target?.dataset?.windrag) {
|
|
||||||
appWindow.startDragging();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SWRConfig value={{}}>
|
<SWRConfig value={{}}>
|
||||||
@@ -87,25 +63,27 @@ const Layout = () => {
|
|||||||
square
|
square
|
||||||
elevation={0}
|
elevation={0}
|
||||||
className={`${OS} layout`}
|
className={`${OS} layout`}
|
||||||
onPointerDown={onDragging}
|
onPointerDown={(e: any) => {
|
||||||
|
if (e.target?.dataset?.windrag) appWindow.startDragging();
|
||||||
|
}}
|
||||||
onContextMenu={(e) => {
|
onContextMenu={(e) => {
|
||||||
// only prevent it on Windows
|
// only prevent it on Windows
|
||||||
if (OS === "windows") e.preventDefault();
|
if (OS === "windows") e.preventDefault();
|
||||||
}}
|
}}
|
||||||
sx={[
|
sx={[
|
||||||
(theme) => ({
|
({ palette }) => ({
|
||||||
bgcolor: alpha(theme.palette.background.paper, blur ? 0.85 : 1),
|
bgcolor: alpha(palette.background.paper, theme_blur ? 0.8 : 1),
|
||||||
}),
|
}),
|
||||||
]}
|
]}
|
||||||
>
|
>
|
||||||
<div className="layout__left" data-windrag>
|
<div className="layout__left" data-windrag>
|
||||||
<div className="the-logo" data-windrag>
|
<div className="the-logo" data-windrag>
|
||||||
<img src={LogoSvg} alt="" data-windrag />
|
<LogoSvg />
|
||||||
|
|
||||||
<UpdateButton className="the-newbtn" />
|
<UpdateButton className="the-newbtn" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<List className="the-menu" data-windrag>
|
<List className="the-menu">
|
||||||
{routers.map((router) => (
|
{routers.map((router) => (
|
||||||
<LayoutItem key={router.label} to={router.link}>
|
<LayoutItem key={router.label} to={router.link}>
|
||||||
{t(router.label)}
|
{t(router.label)}
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
// default theme setting
|
||||||
|
export const defaultTheme = {
|
||||||
|
primary_color: "#5b5c9d",
|
||||||
|
secondary_color: "#9c27b0",
|
||||||
|
primary_text: "#637381",
|
||||||
|
secondary_text: "#909399",
|
||||||
|
info_color: "#0288d1",
|
||||||
|
error_color: "#d32f2f",
|
||||||
|
warning_color: "#ed6c02",
|
||||||
|
success_color: "#2e7d32",
|
||||||
|
font_family: `"Roboto", "Helvetica", "Arial", sans-serif`,
|
||||||
|
};
|
||||||
|
|
||||||
|
// dark mode
|
||||||
|
export const defaultDarkTheme = {
|
||||||
|
...defaultTheme,
|
||||||
|
primary_text: "#757575",
|
||||||
|
secondary_text: "#637381",
|
||||||
|
};
|
||||||
@@ -1,54 +1,65 @@
|
|||||||
import { useEffect, useState } from "react";
|
import { useEffect, useMemo, useState } from "react";
|
||||||
import { useLockFn } from "ahooks";
|
import { useLockFn } from "ahooks";
|
||||||
import { Button, Paper } from "@mui/material";
|
import { Box, Button, Paper, TextField } from "@mui/material";
|
||||||
import { Virtuoso } from "react-virtuoso";
|
import { Virtuoso } from "react-virtuoso";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { ApiType } from "../services/types";
|
import { ApiType } from "../services/types";
|
||||||
import { closeAllConnections, getInfomation } from "../services/api";
|
import { closeAllConnections, getInformation } from "../services/api";
|
||||||
import BasePage from "../components/base/base-page";
|
import BasePage from "../components/base/base-page";
|
||||||
import ConnectionItem from "../components/connection/connection-item";
|
import ConnectionItem from "../components/connection/connection-item";
|
||||||
|
|
||||||
const ConnectionsPage = () => {
|
const initConn = { uploadTotal: 0, downloadTotal: 0, connections: [] };
|
||||||
const initConn = { uploadTotal: 0, downloadTotal: 0, connections: [] };
|
|
||||||
|
|
||||||
|
const ConnectionsPage = () => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
|
||||||
|
const [filterText, setFilterText] = useState("");
|
||||||
const [connData, setConnData] = useState<ApiType.Connections>(initConn);
|
const [connData, setConnData] = useState<ApiType.Connections>(initConn);
|
||||||
|
|
||||||
|
const filterConn = useMemo(() => {
|
||||||
|
return connData.connections.filter((conn) =>
|
||||||
|
(conn.metadata.host || conn.metadata.destinationIP)?.includes(filterText)
|
||||||
|
);
|
||||||
|
}, [connData, filterText]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let ws: WebSocket | null = null;
|
let ws: WebSocket | null = null;
|
||||||
|
|
||||||
getInfomation().then((result) => {
|
getInformation().then((result) => {
|
||||||
const { server = "", secret = "" } = result;
|
const { server = "", secret = "" } = result;
|
||||||
ws = new WebSocket(`ws://${server}/connections?token=${secret}`);
|
ws = new WebSocket(`ws://${server}/connections?token=${secret}`);
|
||||||
|
|
||||||
ws.addEventListener("message", (event) => {
|
ws.addEventListener("message", (event) => {
|
||||||
const data = JSON.parse(event.data) as ApiType.Connections;
|
const data = JSON.parse(event.data) as ApiType.Connections;
|
||||||
|
|
||||||
|
// 与前一次connections的展示顺序尽量保持一致
|
||||||
setConnData((old) => {
|
setConnData((old) => {
|
||||||
const oldConn = old.connections;
|
const oldConn = old.connections;
|
||||||
const oldList = oldConn.map((each) => each.id);
|
|
||||||
const maxLen = data.connections.length;
|
const maxLen = data.connections.length;
|
||||||
|
|
||||||
const connections: typeof oldConn = [];
|
const connections: typeof oldConn = [];
|
||||||
|
|
||||||
// 与前一次连接的顺序尽量保持一致
|
const rest = data.connections.filter((each) => {
|
||||||
data.connections
|
const index = oldConn.findIndex((o) => o.id === each.id);
|
||||||
.filter((each) => {
|
|
||||||
const index = oldList.indexOf(each.id);
|
|
||||||
|
|
||||||
if (index >= 0 && index < maxLen) {
|
if (index >= 0 && index < maxLen) {
|
||||||
connections[index] = each;
|
const old = oldConn[index];
|
||||||
return false;
|
each.curUpload = each.upload - old.upload;
|
||||||
}
|
each.curDownload = each.download - old.download;
|
||||||
return true;
|
|
||||||
})
|
connections[index] = each;
|
||||||
.forEach((each) => {
|
return false;
|
||||||
for (let i = 0; i < maxLen; ++i) {
|
}
|
||||||
if (!connections[i]) {
|
return true;
|
||||||
connections[i] = each;
|
});
|
||||||
return;
|
|
||||||
}
|
for (let i = 0; i < maxLen; ++i) {
|
||||||
}
|
if (!connections[i] && rest.length > 0) {
|
||||||
});
|
connections[i] = rest.shift()!;
|
||||||
|
connections[i].curUpload = 0;
|
||||||
|
connections[i].curDownload = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return { ...data, connections };
|
return { ...data, connections };
|
||||||
});
|
});
|
||||||
@@ -76,11 +87,47 @@ const ConnectionsPage = () => {
|
|||||||
}
|
}
|
||||||
>
|
>
|
||||||
<Paper sx={{ boxShadow: 2, height: "100%" }}>
|
<Paper sx={{ boxShadow: 2, height: "100%" }}>
|
||||||
<Virtuoso
|
<Box
|
||||||
initialTopMostItemIndex={999}
|
sx={{
|
||||||
data={connData.connections}
|
pt: 1,
|
||||||
itemContent={(index, item) => <ConnectionItem value={item} />}
|
mb: 0.5,
|
||||||
/>
|
mx: "12px",
|
||||||
|
height: "36px",
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* <Select
|
||||||
|
size="small"
|
||||||
|
autoComplete="off"
|
||||||
|
value={logState}
|
||||||
|
onChange={(e) => setLogState(e.target.value)}
|
||||||
|
sx={{ width: 120, mr: 1, '[role="button"]': { py: 0.65 } }}
|
||||||
|
>
|
||||||
|
<MenuItem value="all">ALL</MenuItem>
|
||||||
|
<MenuItem value="info">INFO</MenuItem>
|
||||||
|
<MenuItem value="warn">WARN</MenuItem>
|
||||||
|
</Select> */}
|
||||||
|
|
||||||
|
<TextField
|
||||||
|
hiddenLabel
|
||||||
|
fullWidth
|
||||||
|
size="small"
|
||||||
|
autoComplete="off"
|
||||||
|
variant="outlined"
|
||||||
|
placeholder="Filter conditions"
|
||||||
|
value={filterText}
|
||||||
|
onChange={(e) => setFilterText(e.target.value)}
|
||||||
|
sx={{ input: { py: 0.65, px: 1.25 } }}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Box height="calc(100% - 50px)">
|
||||||
|
<Virtuoso
|
||||||
|
data={filterConn}
|
||||||
|
itemContent={(index, item) => <ConnectionItem value={item} />}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
</Paper>
|
</Paper>
|
||||||
</BasePage>
|
</BasePage>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
|
import { useMemo, useState } from "react";
|
||||||
import { useRecoilState } from "recoil";
|
import { useRecoilState } from "recoil";
|
||||||
import { Button, Paper } from "@mui/material";
|
import { Box, Button, MenuItem, Paper, Select, TextField } from "@mui/material";
|
||||||
import { Virtuoso } from "react-virtuoso";
|
import { Virtuoso } from "react-virtuoso";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { atomLogData } from "../services/states";
|
import { atomLogData } from "../services/states";
|
||||||
@@ -10,6 +11,18 @@ const LogPage = () => {
|
|||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const [logData, setLogData] = useRecoilState(atomLogData);
|
const [logData, setLogData] = useRecoilState(atomLogData);
|
||||||
|
|
||||||
|
const [logState, setLogState] = useState("all");
|
||||||
|
const [filterText, setFilterText] = useState("");
|
||||||
|
|
||||||
|
const filterLogs = useMemo(() => {
|
||||||
|
return logData.filter((data) => {
|
||||||
|
return (
|
||||||
|
data.payload.includes(filterText) &&
|
||||||
|
(logState === "all" ? true : data.type.includes(logState))
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}, [logData, logState, filterText]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<BasePage
|
<BasePage
|
||||||
title={t("Logs")}
|
title={t("Logs")}
|
||||||
@@ -25,13 +38,50 @@ const LogPage = () => {
|
|||||||
</Button>
|
</Button>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<Paper sx={{ boxShadow: 2, height: "100%" }}>
|
<Paper sx={{ boxSizing: "border-box", boxShadow: 2, height: "100%" }}>
|
||||||
<Virtuoso
|
<Box
|
||||||
initialTopMostItemIndex={999}
|
sx={{
|
||||||
data={logData}
|
pt: 1,
|
||||||
itemContent={(index, item) => <LogItem value={item} />}
|
mb: 0.5,
|
||||||
followOutput={"smooth"}
|
mx: "12px",
|
||||||
/>
|
height: "36px",
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Select
|
||||||
|
size="small"
|
||||||
|
autoComplete="off"
|
||||||
|
value={logState}
|
||||||
|
onChange={(e) => setLogState(e.target.value)}
|
||||||
|
sx={{ width: 120, mr: 1, '[role="button"]': { py: 0.65 } }}
|
||||||
|
>
|
||||||
|
<MenuItem value="all">ALL</MenuItem>
|
||||||
|
<MenuItem value="info">INFO</MenuItem>
|
||||||
|
<MenuItem value="warn">WARN</MenuItem>
|
||||||
|
</Select>
|
||||||
|
|
||||||
|
<TextField
|
||||||
|
hiddenLabel
|
||||||
|
fullWidth
|
||||||
|
size="small"
|
||||||
|
autoComplete="off"
|
||||||
|
variant="outlined"
|
||||||
|
placeholder="Filter conditions"
|
||||||
|
value={filterText}
|
||||||
|
onChange={(e) => setFilterText(e.target.value)}
|
||||||
|
sx={{ input: { py: 0.65, px: 1.25 } }}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Box height="calc(100% - 50px)">
|
||||||
|
<Virtuoso
|
||||||
|
initialTopMostItemIndex={999}
|
||||||
|
data={filterLogs}
|
||||||
|
itemContent={(index, item) => <LogItem value={item} />}
|
||||||
|
followOutput={"smooth"}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
</Paper>
|
</Paper>
|
||||||
</BasePage>
|
</BasePage>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -6,18 +6,15 @@ import { useTranslation } from "react-i18next";
|
|||||||
import {
|
import {
|
||||||
getProfiles,
|
getProfiles,
|
||||||
patchProfile,
|
patchProfile,
|
||||||
deleteProfile,
|
|
||||||
selectProfile,
|
selectProfile,
|
||||||
importProfile,
|
importProfile,
|
||||||
enhanceProfiles,
|
|
||||||
changeProfileChain,
|
|
||||||
} from "../services/cmds";
|
} from "../services/cmds";
|
||||||
import { getProxies, updateProxy } from "../services/api";
|
import { getProxies, updateProxy } from "../services/api";
|
||||||
import Notice from "../components/base/base-notice";
|
import Notice from "../components/base/base-notice";
|
||||||
import BasePage from "../components/base/base-page";
|
import BasePage from "../components/base/base-page";
|
||||||
import ProfileNew from "../components/profile/profile-new";
|
import ProfileNew from "../components/profile/profile-new";
|
||||||
import ProfileItem from "../components/profile/profile-item";
|
import ProfileItem from "../components/profile/profile-item";
|
||||||
import ProfileMore from "../components/profile/profile-more";
|
import EnhancedMode from "../components/profile/enhanced";
|
||||||
|
|
||||||
const ProfilePage = () => {
|
const ProfilePage = () => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -125,59 +122,12 @@ const ProfilePage = () => {
|
|||||||
try {
|
try {
|
||||||
await selectProfile(uid);
|
await selectProfile(uid);
|
||||||
mutate("getProfiles", { ...profiles, current: uid }, true);
|
mutate("getProfiles", { ...profiles, current: uid }, true);
|
||||||
|
if (force) Notice.success("Refresh clash config", 1000);
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
Notice.error(err?.message || err.toString());
|
Notice.error(err?.message || err.toString());
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
/** 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={t("Profiles")}>
|
<BasePage title={t("Profiles")}>
|
||||||
<Box sx={{ display: "flex", mb: 2.5 }}>
|
<Box sx={{ display: "flex", mb: 2.5 }}>
|
||||||
@@ -216,22 +166,9 @@ const ProfilePage = () => {
|
|||||||
))}
|
))}
|
||||||
</Grid>
|
</Grid>
|
||||||
|
|
||||||
<Grid container spacing={2} sx={{ mt: 3 }}>
|
{enhanceItems.length > 0 && (
|
||||||
{enhanceItems.map((item) => (
|
<EnhancedMode items={enhanceItems} chain={profiles.chain || []} />
|
||||||
<Grid item xs={12} sm={6} key={item.file}>
|
)}
|
||||||
<ProfileMore
|
|
||||||
selected={!!profiles.chain?.includes(item.uid)}
|
|
||||||
itemData={item}
|
|
||||||
onEnable={() => onEnhanceEnable(item.uid)}
|
|
||||||
onDisable={() => onEnhanceDisable(item.uid)}
|
|
||||||
onDelete={() => onEnhanceDelete(item.uid)}
|
|
||||||
onMoveTop={() => onMoveTop(item.uid)}
|
|
||||||
onMoveEnd={() => onMoveEnd(item.uid)}
|
|
||||||
onEnhance={onEnhance}
|
|
||||||
/>
|
|
||||||
</Grid>
|
|
||||||
))}
|
|
||||||
</Grid>
|
|
||||||
|
|
||||||
<ProfileNew open={dialogOpen} onClose={() => setDialogOpen(false)} />
|
<ProfileNew open={dialogOpen} onClose={() => setDialogOpen(false)} />
|
||||||
</BasePage>
|
</BasePage>
|
||||||
|
|||||||
@@ -16,8 +16,8 @@ const ProxyPage = () => {
|
|||||||
const { data: proxiesData } = useSWR("getProxies", getProxies);
|
const { data: proxiesData } = useSWR("getProxies", getProxies);
|
||||||
const { data: clashConfig } = useSWR("getClashConfig", getClashConfig);
|
const { data: clashConfig } = useSWR("getClashConfig", getClashConfig);
|
||||||
|
|
||||||
const modeList = ["rule", "global", "direct"];
|
const modeList = ["rule", "global", "direct", "script"];
|
||||||
const curMode = clashConfig?.mode.toLowerCase() ?? "direct";
|
const curMode = clashConfig?.mode.toLowerCase();
|
||||||
const { groups = [], proxies = [] } = proxiesData ?? {};
|
const { groups = [], proxies = [] } = proxiesData ?? {};
|
||||||
|
|
||||||
// make sure that fetch the proxies successfully
|
// make sure that fetch the proxies successfully
|
||||||
@@ -38,7 +38,8 @@ const ProxyPage = () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// difference style
|
// difference style
|
||||||
const showGroup = curMode === "rule" && !!groups.length;
|
const showGroup =
|
||||||
|
(curMode === "rule" || curMode === "script") && !!groups.length;
|
||||||
const pageStyle = showGroup ? {} : { height: "100%" };
|
const pageStyle = showGroup ? {} : { height: "100%" };
|
||||||
const paperStyle: any = showGroup
|
const paperStyle: any = showGroup
|
||||||
? { mb: 0.5 }
|
? { mb: 0.5 }
|
||||||
@@ -64,7 +65,7 @@ const ProxyPage = () => {
|
|||||||
}
|
}
|
||||||
>
|
>
|
||||||
<Paper sx={{ borderRadius: 1, boxShadow: 2, ...paperStyle }}>
|
<Paper sx={{ borderRadius: 1, boxShadow: 2, ...paperStyle }}>
|
||||||
{curMode === "rule" && !!groups.length && (
|
{(curMode === "rule" || curMode === "script") && !!groups.length && (
|
||||||
<List>
|
<List>
|
||||||
{groups.map((group) => (
|
{groups.map((group) => (
|
||||||
<ProxyGroup key={group.name} group={group} />
|
<ProxyGroup key={group.name} group={group} />
|
||||||
|
|||||||
@@ -32,8 +32,8 @@ export async function getAxios(force: boolean = false) {
|
|||||||
return axiosIns;
|
return axiosIns;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// get infomation
|
/// get information
|
||||||
export async function getInfomation() {
|
export async function getInformation() {
|
||||||
if (server) return { server, secret };
|
if (server) return { server, secret };
|
||||||
const info = await getClashInfo();
|
const info = await getClashInfo();
|
||||||
return info!;
|
return info!;
|
||||||
@@ -142,6 +142,14 @@ export async function getProviders() {
|
|||||||
return response.providers as any;
|
return response.providers as any;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// todo: proxy providers health check
|
||||||
|
export async function getProviderHealthCheck(name: string) {
|
||||||
|
const instance = await getAxios();
|
||||||
|
return instance.get(
|
||||||
|
`/providers/proxies/${encodeURIComponent(name)}/healthcheck`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Close specific connection
|
// Close specific connection
|
||||||
export async function deleteConnection(id: string) {
|
export async function deleteConnection(id: string) {
|
||||||
const instance = await getAxios();
|
const instance = await getAxios();
|
||||||
|
|||||||
@@ -6,10 +6,6 @@ export async function getProfiles() {
|
|||||||
return invoke<CmdType.ProfilesConfig>("get_profiles");
|
return invoke<CmdType.ProfilesConfig>("get_profiles");
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function syncProfiles() {
|
|
||||||
return invoke<void>("sync_profiles");
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function enhanceProfiles() {
|
export async function enhanceProfiles() {
|
||||||
return invoke<void>("enhance_profiles");
|
return invoke<void>("enhance_profiles");
|
||||||
}
|
}
|
||||||
@@ -66,6 +62,10 @@ export async function changeProfileChain(chain?: string[]) {
|
|||||||
return invoke<void>("change_profile_chain", { chain });
|
return invoke<void>("change_profile_chain", { chain });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function changeProfileValid(valid?: string[]) {
|
||||||
|
return invoke<void>("change_profile_valid", { valid });
|
||||||
|
}
|
||||||
|
|
||||||
export async function getClashInfo() {
|
export async function getClashInfo() {
|
||||||
return invoke<CmdType.ClashInfo | null>("get_clash_info");
|
return invoke<CmdType.ClashInfo | null>("get_clash_info");
|
||||||
}
|
}
|
||||||
@@ -86,12 +86,16 @@ export async function getSystemProxy() {
|
|||||||
return invoke<any>("get_sys_proxy");
|
return invoke<any>("get_sys_proxy");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function changeClashCore(clashCore: string) {
|
||||||
|
return invoke<any>("change_clash_core", { clashCore });
|
||||||
|
}
|
||||||
|
|
||||||
export async function restartSidecar() {
|
export async function restartSidecar() {
|
||||||
return invoke<void>("restart_sidecar");
|
return invoke<void>("restart_sidecar");
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function killSidecars() {
|
export async function killSidecar() {
|
||||||
return invoke<any>("kill_sidecars");
|
return invoke<any>("kill_sidecar");
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function openAppDir() {
|
export async function openAppDir() {
|
||||||
@@ -105,3 +109,32 @@ export async function openLogsDir() {
|
|||||||
Notice.error(err?.message || err.toString(), 1500)
|
Notice.error(err?.message || err.toString(), 1500)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// service mode
|
||||||
|
|
||||||
|
export async function startService() {
|
||||||
|
return invoke<void>("start_service");
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function stopService() {
|
||||||
|
return invoke<void>("stop_service");
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function checkService() {
|
||||||
|
try {
|
||||||
|
const result = await invoke<any>("check_service");
|
||||||
|
if (result?.code === 0) return "active";
|
||||||
|
if (result?.code === 400) return "installed";
|
||||||
|
return "unknown";
|
||||||
|
} catch (err: any) {
|
||||||
|
return "uninstall";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function installService() {
|
||||||
|
return invoke<void>("install_service");
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function uninstallService() {
|
||||||
|
return invoke<void>("uninstall_service");
|
||||||
|
}
|
||||||
|
|||||||
@@ -4,6 +4,15 @@ const hashKey = (name: string, group: string) => `${group ?? ""}::${name}`;
|
|||||||
|
|
||||||
class DelayManager {
|
class DelayManager {
|
||||||
private cache = new Map<string, [number, number]>();
|
private cache = new Map<string, [number, number]>();
|
||||||
|
private urlMap = new Map<string, string>();
|
||||||
|
|
||||||
|
setUrl(group: string, url: string) {
|
||||||
|
this.urlMap.set(group, url);
|
||||||
|
}
|
||||||
|
|
||||||
|
getUrl(group: string) {
|
||||||
|
return this.urlMap.get(group);
|
||||||
|
}
|
||||||
|
|
||||||
setDelay(name: string, group: string, delay: number) {
|
setDelay(name: string, group: string, delay: number) {
|
||||||
this.cache.set(hashKey(name, group), [Date.now(), delay]);
|
this.cache.set(hashKey(name, group), [Date.now(), delay]);
|
||||||
@@ -23,7 +32,8 @@ class DelayManager {
|
|||||||
let delay = -1;
|
let delay = -1;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const result = await getProxyDelay(name);
|
const url = this.getUrl(group);
|
||||||
|
const result = await getProxyDelay(name, url);
|
||||||
delay = result.delay;
|
delay = result.delay;
|
||||||
} catch {
|
} catch {
|
||||||
delay = 1e6; // error
|
delay = 1e6; // error
|
||||||
@@ -38,32 +48,36 @@ class DelayManager {
|
|||||||
names: readonly string[];
|
names: readonly string[];
|
||||||
groupName: string;
|
groupName: string;
|
||||||
skipNum: number;
|
skipNum: number;
|
||||||
maxTimeout: number;
|
|
||||||
},
|
},
|
||||||
callback: Function
|
callback: Function
|
||||||
) {
|
) {
|
||||||
let names = [...options.names];
|
const { groupName, skipNum } = options;
|
||||||
const { groupName, skipNum, maxTimeout } = options;
|
|
||||||
|
|
||||||
while (names.length) {
|
const names = [...options.names];
|
||||||
const list = names.slice(0, skipNum);
|
const total = names.length;
|
||||||
names = names.slice(skipNum);
|
|
||||||
|
|
||||||
let called = false;
|
let count = 0;
|
||||||
setTimeout(() => {
|
let current = 0;
|
||||||
if (!called) {
|
|
||||||
called = true;
|
|
||||||
callback();
|
|
||||||
}
|
|
||||||
}, maxTimeout);
|
|
||||||
|
|
||||||
await Promise.all(list.map((n) => this.checkDelay(n, groupName)));
|
return new Promise((resolve) => {
|
||||||
|
const help = async (): Promise<void> => {
|
||||||
|
if (current >= skipNum) return;
|
||||||
|
|
||||||
if (!called) {
|
const task = names.shift();
|
||||||
called = true;
|
if (!task) return;
|
||||||
callback();
|
|
||||||
}
|
current += 1;
|
||||||
}
|
await this.checkDelay(task, groupName);
|
||||||
|
current -= 1;
|
||||||
|
|
||||||
|
if (count++ % skipNum === 0 || count === total) callback();
|
||||||
|
if (count === total) resolve(null);
|
||||||
|
|
||||||
|
return help();
|
||||||
|
};
|
||||||
|
|
||||||
|
for (let i = 0; i < skipNum; ++i) help();
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { emit, listen } from "@tauri-apps/api/event";
|
import { emit, listen, Event } from "@tauri-apps/api/event";
|
||||||
|
import { appWindow } from "@tauri-apps/api/window";
|
||||||
import { CmdType } from "./types";
|
import { CmdType } from "./types";
|
||||||
import ignoreCase from "../utils/ignore-case";
|
import ignoreCase from "../utils/ignore-case";
|
||||||
|
|
||||||
@@ -124,32 +125,42 @@ class Enhance {
|
|||||||
return this.resultMap.get(uid);
|
return this.resultMap.get(uid);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async enhanceHandler(event: Event<unknown>) {
|
||||||
|
const payload = event.payload as CmdType.EnhancedPayload;
|
||||||
|
|
||||||
|
const result = await this.runner(payload).catch((err: any) => ({
|
||||||
|
data: null,
|
||||||
|
status: "error",
|
||||||
|
error: err.message,
|
||||||
|
}));
|
||||||
|
|
||||||
|
emit(payload.callback, JSON.stringify(result)).catch(console.error);
|
||||||
|
}
|
||||||
|
|
||||||
// setup the handler
|
// setup the handler
|
||||||
setup() {
|
setup() {
|
||||||
if (this.isSetup) return;
|
if (this.isSetup) return;
|
||||||
this.isSetup = true;
|
this.isSetup = true;
|
||||||
|
|
||||||
listen("script-handler", async (event) => {
|
listen("script-handler", async (event) => {
|
||||||
const payload = event.payload as CmdType.EnhancedPayload;
|
await this.enhanceHandler(event);
|
||||||
|
});
|
||||||
|
|
||||||
const result = await this.runner(payload).catch((err: any) => ({
|
listen("script-handler-close", async (event) => {
|
||||||
data: null,
|
await this.enhanceHandler(event);
|
||||||
status: "error",
|
appWindow.close();
|
||||||
error: err.message,
|
|
||||||
}));
|
|
||||||
|
|
||||||
emit(payload.callback, JSON.stringify(result)).catch(console.error);
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// enhanced mode runner
|
// enhanced mode runner
|
||||||
private async runner(payload: CmdType.EnhancedPayload) {
|
private async runner(payload: CmdType.EnhancedPayload) {
|
||||||
const chain = payload.chain || [];
|
const chain = payload.chain || [];
|
||||||
|
const valid = payload.valid || [];
|
||||||
|
|
||||||
if (!Array.isArray(chain)) throw new Error("unhandle error");
|
if (!Array.isArray(chain)) throw new Error("unhandle error");
|
||||||
|
|
||||||
let pdata = payload.current || {};
|
let pdata = payload.current || {};
|
||||||
let useList = [] as string[];
|
let useList = valid;
|
||||||
|
|
||||||
for (const each of chain) {
|
for (const each of chain) {
|
||||||
const { uid, type = "" } = each.item;
|
const { uid, type = "" } = each.item;
|
||||||
|
|||||||
@@ -65,6 +65,8 @@ export namespace ApiType {
|
|||||||
chains: string[];
|
chains: string[];
|
||||||
rule: string;
|
rule: string;
|
||||||
rulePayload: string;
|
rulePayload: string;
|
||||||
|
curUpload?: number; // calculate
|
||||||
|
curDownload?: number; // calculate
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Connections {
|
export interface Connections {
|
||||||
@@ -111,25 +113,41 @@ export namespace CmdType {
|
|||||||
export interface ProfileOption {
|
export interface ProfileOption {
|
||||||
user_agent?: string;
|
user_agent?: string;
|
||||||
with_proxy?: boolean;
|
with_proxy?: boolean;
|
||||||
|
update_interval?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ProfilesConfig {
|
export interface ProfilesConfig {
|
||||||
current?: string;
|
current?: string;
|
||||||
chain?: string[];
|
chain?: string[];
|
||||||
|
valid?: string[];
|
||||||
items?: ProfileItem[];
|
items?: ProfileItem[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface VergeConfig {
|
export interface VergeConfig {
|
||||||
language?: string;
|
language?: string;
|
||||||
|
clash_core?: string;
|
||||||
theme_mode?: "light" | "dark";
|
theme_mode?: "light" | "dark";
|
||||||
theme_blur?: boolean;
|
theme_blur?: boolean;
|
||||||
traffic_graph?: boolean;
|
traffic_graph?: boolean;
|
||||||
enable_tun_mode?: boolean;
|
enable_tun_mode?: boolean;
|
||||||
enable_auto_launch?: boolean;
|
enable_auto_launch?: boolean;
|
||||||
|
enable_service_mode?: boolean;
|
||||||
enable_silent_start?: boolean;
|
enable_silent_start?: boolean;
|
||||||
enable_system_proxy?: boolean;
|
enable_system_proxy?: boolean;
|
||||||
enable_proxy_guard?: boolean;
|
enable_proxy_guard?: boolean;
|
||||||
system_proxy_bypass?: string;
|
system_proxy_bypass?: string;
|
||||||
|
theme_setting?: {
|
||||||
|
primary_color?: string;
|
||||||
|
secondary_color?: string;
|
||||||
|
primary_text?: string;
|
||||||
|
secondary_text?: string;
|
||||||
|
info_color?: string;
|
||||||
|
error_color?: string;
|
||||||
|
warning_color?: string;
|
||||||
|
success_color?: string;
|
||||||
|
font_family?: string;
|
||||||
|
css_injection?: string;
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
type ClashConfigValue = any;
|
type ClashConfigValue = any;
|
||||||
@@ -179,6 +197,7 @@ export namespace CmdType {
|
|||||||
|
|
||||||
export interface EnhancedPayload {
|
export interface EnhancedPayload {
|
||||||
chain: ChainItem[];
|
chain: ChainItem[];
|
||||||
|
valid: string[];
|
||||||
current: ProfileData;
|
current: ProfileData;
|
||||||
callback: string;
|
callback: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
import { defineConfig } from "vite";
|
import { defineConfig } from "vite";
|
||||||
|
import svgr from "vite-plugin-svgr";
|
||||||
import react from "@vitejs/plugin-react";
|
import react from "@vitejs/plugin-react";
|
||||||
import monaco from "vite-plugin-monaco-editor";
|
import monaco from "vite-plugin-monaco-editor";
|
||||||
|
|
||||||
// https://vitejs.dev/config/
|
// https://vitejs.dev/config/
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
root: "src",
|
root: "src",
|
||||||
plugins: [react(), monaco()],
|
plugins: [svgr(), react(), monaco()],
|
||||||
build: {
|
build: {
|
||||||
outDir: "../dist",
|
outDir: "../dist",
|
||||||
emptyOutDir: true,
|
emptyOutDir: true,
|
||||||
|
|||||||