Compare commits
535 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
3bdc98bd12 | ||
|
68d2a6e951 | ||
|
acf47ac947 | ||
|
fda24e5f5a | ||
|
05eca8e4d8 | ||
|
b915f3b1a9 | ||
|
ab58968f4d | ||
|
820d1e7570 | ||
|
a120c8cf98 | ||
|
5a35ea116f | ||
|
e72ad1f030 | ||
|
a17362437a | ||
|
8643dc43b1 | ||
|
e1c869a358 | ||
|
2f5b8d9abe | ||
|
db324f54eb | ||
|
3242efb1a2 | ||
|
30f9f1a021 | ||
|
3f58d05aa7 | ||
|
c611a51575 | ||
|
73458dcd28 | ||
|
23ebeb1cc0 | ||
|
a7ba9f1886 | ||
|
d5192e2244 | ||
|
7eb595170f | ||
|
bd576ca808 | ||
|
2f8146b11f | ||
|
7f321c89cb | ||
|
fa65f606b8 | ||
|
7a3285adaf | ||
|
8bf78fef10 | ||
|
78f97ce4df | ||
|
66ccbf70f8 | ||
|
cb48600b40 | ||
|
33ce235713 | ||
|
f1a68ece01 | ||
|
dd563360af | ||
|
7f6dac4271 | ||
|
178fd8e828 | ||
|
1641e02a7d | ||
|
cfd04e9bb4 | ||
|
38effaf740 | ||
|
a68eb4a73e | ||
|
c02990ef98 | ||
|
5aa7d5ffe9 | ||
|
4942b0fca5 | ||
|
aed1bdff5a | ||
|
929c840006 | ||
|
57aef1d3c2 | ||
|
c1734a094c | ||
|
99c46685ac | ||
|
066b08040a | ||
|
35de2334fb | ||
|
5564c966a5 | ||
|
0891b5e7b7 | ||
|
f3341f201f | ||
|
bf0dafabe2 | ||
|
60f6587169 | ||
|
a9bf32919e | ||
|
7633f9f88b | ||
|
9b56233938 | ||
|
65074264b8 | ||
|
4f6fceb87f | ||
|
659fdd1d37 | ||
|
8bce2ce040 | ||
|
55cc83a5d4 | ||
|
6a51e93ded | ||
|
fcf570e96e | ||
|
cbc184e953 | ||
|
98f9063352 | ||
|
c278f1af00 | ||
|
fbb17a0ba5 | ||
|
8637a9823e | ||
|
d717fe7e8c | ||
|
5e8dfe7267 | ||
|
aaa4fbcdbd | ||
|
150f0cf486 | ||
|
711b220a05 | ||
|
b615c485f7 | ||
|
2f3b6b29ae | ||
|
7aecd83c4a | ||
|
3b460ab91f | ||
|
661c0eb970 | ||
|
f4a1f1fdc8 | ||
|
b5432c3728 | ||
|
6d0625c409 | ||
|
2f1ea08b8a | ||
|
a092da1943 | ||
|
43ef3cc562 | ||
|
047774475c | ||
|
91b8504df5 | ||
|
a4fb2dfcf8 | ||
|
ba16ec02e5 | ||
|
55b7af2623 | ||
|
b428eff10e | ||
|
35aee15b6d | ||
|
6f53c1bfde | ||
|
db0230ed75 | ||
|
7fa3c1e12a | ||
|
3b5993652f | ||
|
be4ad8947f | ||
|
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 | ||
|
5c3696123a | ||
|
4140fc86ee | ||
|
2ad771e7fd | ||
|
5a38468144 | ||
|
0a9c81772f | ||
|
c9649ac501 | ||
|
6ea567742b | ||
|
f31349eaa0 | ||
|
9d44668d5f | ||
|
a12f58c1c7 | ||
|
b5283eaaed | ||
|
4b6189af5f | ||
|
5d0ffbe453 | ||
|
502706931e | ||
|
57c411288f | ||
|
b09b7b11a1 | ||
|
1a7b3c7294 | ||
|
4678fc7dde | ||
|
9f492fad49 | ||
|
bd0a959e18 | ||
|
dd605e2610 | ||
|
9910f6b817 | ||
|
991897aff4 | ||
|
3cde019208 | ||
|
2f6efbed63 | ||
|
5cff4e299b | ||
|
bce33639da | ||
|
366c465cad | ||
|
acc6e05bdc | ||
|
4ce15577cd | ||
|
98fa4d5e65 | ||
|
7fe94076c7 | ||
|
b8b0c8fa63 | ||
|
e585e87bec | ||
|
6a4924bb16 | ||
|
ab0d516d91 | ||
|
b756ae39d0 | ||
|
c15c38ea8f | ||
|
743963318f | ||
|
ed3fc50858 | ||
|
5b886fe6be | ||
|
7074bbc405 | ||
|
ef314c1707 | ||
|
a3e7626dd9 | ||
|
5cb5d74eed | ||
|
6eee10d46d | ||
|
2d95f2b0d6 | ||
|
ec41bb9c70 | ||
|
2d1780b1cf | ||
|
d9ce99887c | ||
|
9b9cc90414 | ||
|
c1eb539a5c | ||
|
e1793f57ef | ||
|
dbd09a8743 | ||
|
0d189ca617 | ||
|
dc9bcc40ee | ||
|
4991f7ff39 | ||
|
a393b8b122 | ||
|
c73b354386 | ||
|
392ecee3ff | ||
|
bae721c49e | ||
|
4e806e21a6 | ||
|
ec0fdf83b2 | ||
|
cb94d8414f | ||
|
8890051c17 | ||
|
cf00c9476f | ||
|
b2a24c7abd | ||
|
732a1f4694 | ||
|
4c5aa7084e | ||
|
fe1fea671c | ||
|
04c754c0ac | ||
|
754c22c84e | ||
|
629331870b | ||
|
78774315cb | ||
|
36b9c07928 | ||
|
40a818630d | ||
|
568511a4cf | ||
|
109fb39e09 | ||
|
68450d2042 | ||
|
8a052bbed6 | ||
|
3afbb56640 | ||
|
c0ad84a491 | ||
|
c72f17605c | ||
|
42fbee0cdb | ||
|
e9b7ec735f | ||
|
743788135f | ||
|
8ea3e6fa26 | ||
|
f23c83e681 | ||
|
b615bda17e | ||
|
f7c7cd1d3c | ||
|
c7e7be4379 | ||
|
d63d49f246 | ||
|
dad94edb20 | ||
|
7108d5f3ab | ||
|
ef47a74920 | ||
|
a43dab8057 | ||
|
f44039b628 | ||
|
08fa5205b0 | ||
|
b91daebd92 | ||
|
9cd6c5c624 | ||
|
650e017b72 | ||
|
18f9d6dec5 | ||
|
4df6571ad9 | ||
|
0f5923a10a | ||
|
bcdae1169e | ||
|
f260d5df49 | ||
|
808b861dd1 | ||
|
17f1c487a8 | ||
|
8dc2c1a38f | ||
|
220a494692 | ||
|
db6bc10196 | ||
|
1880363aeb | ||
|
19c7b59883 | ||
|
749df89229 | ||
|
444f2172fa | ||
|
77a77c0ea7 | ||
|
dbf380a0d1 | ||
|
ade34f5217 | ||
|
e89607799a | ||
|
d05d8d6a9e | ||
|
b6aa50d3dc | ||
|
9df361935f | ||
|
98b8a122b6 | ||
|
c7232522ee | ||
|
5280f1d745 | ||
|
b52a081e7b | ||
|
f981a44861 | ||
|
d7c5ce0750 | ||
|
9ccc66ca1e | ||
|
8606af3616 | ||
|
f6e821ba6b | ||
|
e8dbcf819b | ||
|
bbe2ef4e8e | ||
|
dd15455031 | ||
|
12ac7bb338 | ||
|
46ef348f0d | ||
|
1a55cca8af | ||
|
81ee989f1f | ||
|
c9c06f8a3d | ||
|
72127979c3 | ||
|
1ad3ddef94 | ||
|
97ec5eabf7 | ||
|
e12e3a3f2d | ||
|
4ff625f23b | ||
|
e38dcd85ac | ||
|
0245baf1b6 | ||
|
10b55c043c | ||
|
457655b416 | ||
|
7e4506c860 | ||
|
794d376348 | ||
|
c60578f5b5 | ||
|
3a9a392a77 | ||
|
a13d4698be | ||
|
c046a1993e | ||
|
f709117cc4 | ||
|
30dd298fca | ||
|
0ff8bb8090 | ||
|
74bbd3c3a2 | ||
|
2e82eaf59a | ||
|
7f1df1f1bd | ||
|
3c79238a44 | ||
|
0aa2565df3 | ||
|
22b11db16e | ||
|
d0e678b5e9 | ||
|
e7bba968b3 | ||
|
4934a24293 | ||
|
ccb68bcda9 | ||
|
66bf4ba3ad | ||
|
78a0cfd052 | ||
|
8548373742 | ||
|
2dfd725ee0 | ||
|
5b779b4f14 | ||
|
fc48aa7155 | ||
|
6193a842f4 | ||
|
eb86b471fe | ||
|
2b52584547 | ||
|
6e3cc57f48 | ||
|
f2c04621a5 | ||
|
3ed6938d4a | ||
|
99fec25ed5 | ||
|
73758ad1fd | ||
|
c53fe0ed1f | ||
|
6082c2bcac | ||
|
069abed784 | ||
|
7d8fa4d78a | ||
|
76081f8d89 | ||
|
5ef4285558 | ||
|
aa7df4282e | ||
|
0ef1d5d0de | ||
|
cceb4bb81f | ||
|
f0f45e007d | ||
|
6a8ffe1642 | ||
|
3a73868c10 | ||
|
ab1b5897a6 | ||
|
f94734a5c8 | ||
|
61b86c9584 | ||
|
1ac1d6e903 | ||
|
b6c58f74c0 | ||
|
c88e99d87c | ||
|
8d7ab9d05e | ||
|
47155a4a29 | ||
|
d0b87fd7c3 | ||
|
d49fd37656 | ||
|
0bd29d71be | ||
|
4b5b62c8ae | ||
|
65fb2ca2d5 | ||
|
0d5bfc0997 | ||
|
4f02c373c2 | ||
|
209a5b1207 | ||
|
95349eacab | ||
|
82ba604b99 | ||
|
46a8dec655 | ||
|
b5af234524 | ||
|
b5c41750f7 | ||
|
6083824eec | ||
|
40977785c3 | ||
|
5eddf4f1aa | ||
|
99a8e25411 | ||
|
08587d8f2f | ||
|
3480d50f61 | ||
|
43af55252d | ||
|
9c43b31fc0 | ||
|
9ec7184aa1 | ||
|
4e2cb30db7 | ||
|
9ca83d3291 | ||
|
6b2172d873 | ||
|
1a5d9f7dad | ||
|
a8425862f0 | ||
|
a3a3db6abb | ||
|
d6c3bc57c0 | ||
|
59c09f90f9 | ||
|
d982b83e14 | ||
|
cc0e930d34 | ||
|
3c3d77fbea | ||
|
da7453fdbf | ||
|
5fcd25506e | ||
|
4979a472de | ||
|
4e8d4f4591 | ||
|
0f5d2b15e0 | ||
|
7fc9631434 | ||
|
df5953dd7b | ||
|
8f5b2b4a0e | ||
|
43c63ffa70 | ||
|
6779bc7459 | ||
|
664be2d0ba | ||
|
6113898b69 | ||
|
79aad6b5c2 | ||
|
6da7757d36 | ||
|
dbb3cb8cc8 | ||
|
579f36a1dd | ||
|
72c2b306cf | ||
|
c2673cd396 | ||
|
8eb152816a | ||
|
a0bc8a21a5 | ||
|
08e4d72758 | ||
|
66340a27fa | ||
|
83fe9835b6 | ||
|
4c1a50a3ca | ||
|
fe44a7b3bc | ||
|
e86d192db7 | ||
|
ea8f1c52f9 | ||
|
a4c1573c45 | ||
|
182bf49ad0 | ||
|
13e1ddbccd | ||
|
327b9a1757 | ||
|
18c48db7f7 | ||
|
b6543bd87f | ||
|
9ad8f71d7c | ||
|
e369311fc2 | ||
|
72ff261fe3 | ||
|
774c6f7e05 | ||
|
771af6ae08 | ||
|
b3cd207444 | ||
|
03f9fa4bc2 | ||
|
e32bfd9aab | ||
|
7e47f8f893 | ||
|
cb816e9653 | ||
|
6b3e7cbc08 | ||
|
db4993ae9b | ||
|
4dc3cf6c6b | ||
|
2b84bbf3a8 | ||
|
26ef4c9961 | ||
|
4f56c38599 | ||
|
240f4dcfb1 | ||
|
ac6abd81c9 | ||
|
14bda4f3a5 | ||
|
61b9670b45 | ||
|
01e8db317e | ||
|
92fc09493e | ||
|
d927209db7 | ||
|
e94007b21f | ||
|
18750f275a | ||
|
d686a853f4 |
84
.github/workflows/alpha.yml
vendored
Normal file
@ -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 }}
|
119
.github/workflows/ci.yml
vendored
Normal file
@ -0,0 +1,119 @@
|
||||
name: Release CI
|
||||
|
||||
on: [push]
|
||||
|
||||
env:
|
||||
CARGO_INCREMENTAL: 0
|
||||
RUST_BACKTRACE: short
|
||||
|
||||
jobs:
|
||||
release:
|
||||
strategy:
|
||||
matrix:
|
||||
os: [windows-latest, ubuntu-18.04, macos-latest]
|
||||
runs-on: ${{ matrix.os }}
|
||||
if: |
|
||||
startsWith(github.repository, 'zzzgydi') &&
|
||||
startsWith(github.ref, 'refs/tags/v')
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Install Rust
|
||||
uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: stable
|
||||
profile: minimal
|
||||
override: true
|
||||
|
||||
- name: Rust Cache
|
||||
uses: Swatinem/rust-cache@ce325b60658c1b38465c06cc965b79baf32c1e72
|
||||
with:
|
||||
working-directory: src-tauri
|
||||
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: 14
|
||||
|
||||
- name: Install Dependencies (ubuntu only)
|
||||
if: startsWith(matrix.os, 'ubuntu-')
|
||||
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
|
||||
# enable cache even though failed
|
||||
# continue-on-error: true
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
|
||||
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
|
||||
with:
|
||||
tagName: v__VERSION__
|
||||
releaseName: "Clash Verge v__VERSION__"
|
||||
releaseBody: "More new features are now supported."
|
||||
releaseDraft: false
|
||||
prerelease: true
|
||||
|
||||
- name: Portable Bundle
|
||||
if: matrix.os == 'windows-latest'
|
||||
# rebuild with env settings
|
||||
run: |
|
||||
yarn build
|
||||
yarn run portable
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
|
||||
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
|
||||
VITE_WIN_PORTABLE: 1
|
||||
|
||||
release-update:
|
||||
needs: release
|
||||
runs-on: macos-latest
|
||||
if: |
|
||||
startsWith(github.repository, 'zzzgydi') &&
|
||||
startsWith(github.ref, 'refs/tags/v')
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Get yarn cache dir path
|
||||
id: yarn-cache-dir-path
|
||||
run: echo "::set-output name=dir::$(yarn cache dir)"
|
||||
|
||||
- name: Yarn Cache
|
||||
uses: actions/cache@v2
|
||||
id: yarn-cache
|
||||
with:
|
||||
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
|
||||
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-yarn-
|
||||
|
||||
- name: Yarn install
|
||||
run: yarn install
|
||||
|
||||
- name: Release updater file
|
||||
run: yarn run updater
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
55
.github/workflows/release.yml
vendored
@ -1,55 +0,0 @@
|
||||
name: Release Project
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- v*
|
||||
|
||||
jobs:
|
||||
build-tauri:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
platform: [windows-latest]
|
||||
runs-on: ${{ matrix.platform }}
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: setup node
|
||||
uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: 14
|
||||
- name: install Rust stable
|
||||
uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: stable
|
||||
- name: Get yarn cache directory path
|
||||
id: yarn-cache-dir-path
|
||||
run: echo "::set-output name=dir::$(yarn cache dir)"
|
||||
- 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-
|
||||
- uses: actions/cache@v2
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/bin/
|
||||
~/.cargo/registry/index/
|
||||
~/.cargo/registry/cache/
|
||||
~/.cargo/git/db/
|
||||
src-tauri/target/
|
||||
src-tauri/WixTools/
|
||||
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
|
||||
- name: install app dependencies and build it
|
||||
run: yarn && yarn run predev
|
||||
- uses: tauri-apps/tauri-action@v0
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
tagName: v__VERSION__
|
||||
releaseName: "Clash Verge v__VERSION__"
|
||||
releaseBody: "This is a release."
|
||||
releaseDraft: true
|
||||
prerelease: false
|
82
.github/workflows/test.yml
vendored
Normal file
@ -0,0 +1,82 @@
|
||||
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
|
||||
- ubuntu-18.04
|
||||
- ubuntu-20.04
|
||||
- ubuntu-22.04
|
||||
- macos-10.15
|
||||
- macos-11
|
||||
- macos-12
|
||||
- windows-2019
|
||||
- windows-2022
|
||||
|
||||
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: startsWith(github.event.inputs.os, 'ubuntu-')
|
||||
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 }}
|
32
.github/workflows/updater.yml
vendored
Normal file
@ -0,0 +1,32 @@
|
||||
name: Updater CI
|
||||
|
||||
on: workflow_dispatch
|
||||
|
||||
jobs:
|
||||
release-update:
|
||||
runs-on: macos-latest
|
||||
if: startsWith(github.repository, 'zzzgydi')
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Get yarn cache dir path
|
||||
id: yarn-cache-dir-path
|
||||
run: echo "::set-output name=dir::$(yarn cache dir)"
|
||||
|
||||
- name: Yarn Cache
|
||||
uses: actions/cache@v2
|
||||
id: yarn-cache
|
||||
with:
|
||||
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
|
||||
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-yarn-
|
||||
|
||||
- name: Yarn install
|
||||
run: yarn install
|
||||
|
||||
- name: Release updater file
|
||||
run: yarn run updater
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
4
.gitignore
vendored
@ -3,5 +3,5 @@ node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
package-lock.json
|
||||
yarn.lock
|
||||
update.json
|
||||
scripts/_env.sh
|
||||
|
61
README.md
@ -11,22 +11,32 @@ A <a href="https://github.com/Dreamacro/clash">Clash</a> GUI based on <a href="h
|
||||
|
||||
## Features
|
||||
|
||||
Now it's no different from the others, even fewer. (WIP)
|
||||
- Full `clash` config supported, Partial `clash premium` config supported.
|
||||
- Profiles management and enhancement (by yaml and Javascript). [Doc](https://github.com/zzzgydi/clash-verge/wiki/%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97)
|
||||
- Simple UI and supports custom theme color.
|
||||
- Built-in support [Clash.Meta](https://github.com/MetaCubeX/Clash.Meta) core.
|
||||
- System proxy setting and guard.
|
||||
|
||||
## Install
|
||||
|
||||
Download from [release](https://github.com/zzzgydi/clash-verge/releases). Supports Windows x64, Linux x86_64 and macOS 11+
|
||||
|
||||
Or you can build it yourself. Supports Windows, Linux and macOS 10.15+
|
||||
|
||||
Notes: If you could not start the app on Windows, please check that you have [Webview2](https://developer.microsoft.com/en-us/microsoft-edge/webview2/#download-section) installed.
|
||||
|
||||
## Development
|
||||
|
||||
You should install Rust and Nodejs. Then install tauri cli and packages.
|
||||
You should install Rust and Nodejs, see [here](https://tauri.studio/docs/getting-started/prerequisites) for more details. Then install Nodejs packages.
|
||||
|
||||
```shell
|
||||
cargo install tauri-cli --git https://github.com/tauri-apps/tauri
|
||||
|
||||
yarn install
|
||||
```
|
||||
|
||||
Then download the clash binary... Or you can download it from [clash premium release](https://github.com/Dreamacro/clash/releases/tag/premium) and rename it according to [tauri config](https://tauri.studio/en/docs/api/config#tauri.bundle.externalBin).
|
||||
Then download the clash binary... Or you can download it from [clash premium release](https://github.com/Dreamacro/clash/releases/tag/premium) and rename it according to [tauri config](https://tauri.studio/docs/api/config/#tauri.bundle.externalBin).
|
||||
|
||||
```shell
|
||||
yarn run predev
|
||||
yarn run check
|
||||
```
|
||||
|
||||
Then run
|
||||
@ -35,6 +45,12 @@ Then run
|
||||
yarn dev
|
||||
```
|
||||
|
||||
Or you can build it
|
||||
|
||||
```shell
|
||||
yarn build
|
||||
```
|
||||
|
||||
## Todos
|
||||
|
||||
> This keng is a little big...
|
||||
@ -42,8 +58,23 @@ yarn dev
|
||||
## Screenshots
|
||||
|
||||
<div align="center">
|
||||
<img src="./docs/demo1.png" alt="demo1" width="42%" />
|
||||
<img src="./docs/demo2.png" alt="demo2" width="42%" />
|
||||
<img src="./docs/demo1.png" alt="demo1" width="32%" />
|
||||
<img src="./docs/demo2.png" alt="demo2" width="32%" />
|
||||
<img src="./docs/demo3.png" alt="demo3" width="32%" />
|
||||
<img src="./docs/demo4.png" alt="demo4" width="32%" />
|
||||
<img src="./docs/demo5.png" alt="demo5" width="32%" />
|
||||
<img src="./docs/demo6.png" alt="demo6" width="32%" />
|
||||
</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
|
||||
@ -52,8 +83,18 @@ This is a learning project for Rust practice.
|
||||
|
||||
## Contributions
|
||||
|
||||
PR welcome!
|
||||
Issue and PR welcome!
|
||||
|
||||
## Acknowledgement
|
||||
|
||||
Clash Verge was based on or inspired by these projects and so on:
|
||||
|
||||
- [tauri-apps/tauri](https://github.com/tauri-apps/tauri): Build smaller, faster, and more secure desktop applications with a web frontend.
|
||||
- [Dreamacro/clash](https://github.com/Dreamacro/clash): A rule-based tunnel in Go.
|
||||
- [MetaCubeX/Clash.Meta](https://github.com/MetaCubeX/Clash.Meta): A rule-based tunnel in Go.
|
||||
- [Fndroid/clash_for_windows_pkg](https://github.com/Fndroid/clash_for_windows_pkg): A Windows/macOS GUI based on Clash.
|
||||
- [vitejs/vite](https://github.com/vitejs/vite): Next generation frontend tooling. It's fast!
|
||||
|
||||
## License
|
||||
|
||||
GPL-3.0 License
|
||||
GPL-3.0 License. See [License here](./LICENSE) for details.
|
||||
|
204
UPDATELOG.md
Normal file
@ -0,0 +1,204 @@
|
||||
## v1.0.6
|
||||
|
||||
### Features
|
||||
|
||||
- update clash and clash.meta
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- only script profile display console
|
||||
- automatic configuration update on demand at launch
|
||||
|
||||
---
|
||||
|
||||
## v1.0.5
|
||||
|
||||
### Features
|
||||
|
||||
- reimplement profile enhanced mode with quick-js
|
||||
- optimize the runtime config generation process
|
||||
- support web ui management
|
||||
- support clash field management
|
||||
- support viewing the runtime config
|
||||
- adjust some pages style
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- fix silent start
|
||||
- fix incorrectly reset system proxy on exit
|
||||
|
||||
---
|
||||
|
||||
## v1.0.4
|
||||
|
||||
### Features
|
||||
|
||||
- update clash core and clash meta version
|
||||
- support switch clash mode on system tray
|
||||
- theme mode support follows system
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- config load error on first use
|
||||
|
||||
---
|
||||
|
||||
## v1.0.3
|
||||
|
||||
### Features
|
||||
|
||||
- save some states such as URL test, filter, etc
|
||||
- update clash core and clash-meta core
|
||||
- new icon for macOS
|
||||
|
||||
---
|
||||
|
||||
## 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
|
||||
|
||||
### Features
|
||||
|
||||
- silent start
|
||||
- profile editor
|
||||
- profile enhance mode supports more fields
|
||||
- optimize profile enhance mode strategy
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- fix csp restriction on macOS
|
||||
- window controllers on Linux
|
||||
|
||||
---
|
||||
|
||||
## v0.0.25
|
||||
|
||||
### Features
|
||||
|
||||
- update clash core version
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- app updater error
|
||||
- display window controllers on Linux
|
||||
|
||||
### Notes
|
||||
|
||||
If you can't update the app properly, please consider downloading the latest version from github release.
|
||||
|
||||
---
|
||||
|
||||
## v0.0.24
|
||||
|
||||
### Features
|
||||
|
||||
- Connections page
|
||||
- add wintun.dll (Windows)
|
||||
- supports create local profile with selected file (Windows)
|
||||
- system tray enable set system proxy
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- open dir error
|
||||
- auto launch path (Windows)
|
||||
- fix some clash config error
|
||||
- reduce the impact of the enhanced mode
|
||||
|
||||
---
|
||||
|
||||
## v0.0.23
|
||||
|
||||
### Features
|
||||
|
||||
- i18n supports
|
||||
- Remote profile User Agent supports
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- clash config file case ignore
|
||||
- clash `external-controller` only port
|
BIN
docs/color1.png
Normal file
After Width: | Height: | Size: 29 KiB |
BIN
docs/color2.png
Normal file
After Width: | Height: | Size: 30 KiB |
BIN
docs/color3.png
Normal file
After Width: | Height: | Size: 29 KiB |
BIN
docs/color4.png
Normal file
After Width: | Height: | Size: 29 KiB |
BIN
docs/color5.png
Normal file
After Width: | Height: | Size: 32 KiB |
BIN
docs/color6.png
Normal file
After Width: | Height: | Size: 31 KiB |
BIN
docs/demo1.png
Before Width: | Height: | Size: 52 KiB After Width: | Height: | Size: 21 KiB |
BIN
docs/demo2.png
Before Width: | Height: | Size: 73 KiB After Width: | Height: | Size: 30 KiB |
BIN
docs/demo3.png
Normal file
After Width: | Height: | Size: 28 KiB |
BIN
docs/demo4.png
Normal file
After Width: | Height: | Size: 24 KiB |
BIN
docs/demo5.png
Normal file
After Width: | Height: | Size: 27 KiB |
BIN
docs/demo6.png
Normal file
After Width: | Height: | Size: 28 KiB |
66
package.json
@ -1,44 +1,64 @@
|
||||
{
|
||||
"name": "clash-verge",
|
||||
"version": "0.0.1",
|
||||
"version": "1.0.6",
|
||||
"license": "GPL-3.0",
|
||||
"scripts": {
|
||||
"dev": "cargo tauri dev",
|
||||
"build": "cargo tauri build",
|
||||
"dev": "tauri dev",
|
||||
"dev:diff": "tauri dev -f verge-dev",
|
||||
"build": "tauri build",
|
||||
"tauri": "tauri",
|
||||
"web:dev": "vite",
|
||||
"web:build": "tsc && vite build",
|
||||
"web:serve": "vite preview",
|
||||
"predev": "node scripts/pre-dev.mjs",
|
||||
"aarch": "node scripts/aarch.mjs",
|
||||
"check": "node scripts/check.mjs",
|
||||
"updater": "node scripts/updater.mjs",
|
||||
"publish": "node scripts/publish.mjs",
|
||||
"portable": "node scripts/portable.mjs",
|
||||
"prepare": "husky install"
|
||||
},
|
||||
"dependencies": {
|
||||
"@emotion/react": "^11.7.0",
|
||||
"@emotion/styled": "^11.6.0",
|
||||
"@mui/icons-material": "^5.2.1",
|
||||
"@mui/material": "^5.2.3",
|
||||
"@tauri-apps/api": "^1.0.0-beta.8",
|
||||
"axios": "^0.24.0",
|
||||
"dayjs": "^1.10.7",
|
||||
"react": "^17.0.0",
|
||||
"react-dom": "^17.0.0",
|
||||
"react-router-dom": "^6.0.2",
|
||||
"react-virtuoso": "^2.3.1",
|
||||
"recoil": "^0.5.2",
|
||||
"swr": "^1.1.2-beta.0"
|
||||
"@emotion/react": "^11.10.4",
|
||||
"@emotion/styled": "^11.10.4",
|
||||
"@mui/icons-material": "^5.10.3",
|
||||
"@mui/material": "^5.10.3",
|
||||
"@tauri-apps/api": "^1.0.2",
|
||||
"ahooks": "^3.7.0",
|
||||
"axios": "^0.27.2",
|
||||
"dayjs": "^1.11.5",
|
||||
"i18next": "^21.9.1",
|
||||
"monaco-editor": "^0.34.0",
|
||||
"react": "^17.0.2",
|
||||
"react-dom": "^17.0.2",
|
||||
"react-i18next": "^11.17.4",
|
||||
"react-router-dom": "^6.3.0",
|
||||
"react-virtuoso": "^2.17.2",
|
||||
"recoil": "^0.7.5",
|
||||
"snarkdown": "^2.0.0",
|
||||
"swr": "^1.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tauri-apps/cli": "^1.0.0-beta.10",
|
||||
"@actions/github": "^5.0.3",
|
||||
"@tauri-apps/cli": "^1.0.5",
|
||||
"@types/fs-extra": "^9.0.13",
|
||||
"@types/js-cookie": "^3.0.2",
|
||||
"@types/lodash": "^4.14.180",
|
||||
"@types/react": "^17.0.0",
|
||||
"@types/react-dom": "^17.0.0",
|
||||
"@vitejs/plugin-react": "^1.1.1",
|
||||
"@vitejs/plugin-react": "^2.0.1",
|
||||
"adm-zip": "^0.5.9",
|
||||
"cross-env": "^7.0.3",
|
||||
"fs-extra": "^10.0.0",
|
||||
"https-proxy-agent": "^5.0.1",
|
||||
"husky": "^7.0.0",
|
||||
"node-fetch": "^3.1.0",
|
||||
"node-fetch": "^3.2.6",
|
||||
"prettier": "^2.7.1",
|
||||
"pretty-quick": "^3.1.3",
|
||||
"sass": "^1.44.0",
|
||||
"typescript": "^4.5.2",
|
||||
"vite": "^2.7.1"
|
||||
"sass": "^1.54.0",
|
||||
"typescript": "^4.7.4",
|
||||
"vite": "^3.0.9",
|
||||
"vite-plugin-monaco-editor": "^1.1.0",
|
||||
"vite-plugin-svgr": "^2.2.1"
|
||||
},
|
||||
"prettier": {
|
||||
"tabWidth": 2,
|
||||
|
104
scripts/aarch.mjs
Normal file
@ -0,0 +1,104 @@
|
||||
/**
|
||||
* Build and upload assets for macOS(aarch)
|
||||
*/
|
||||
import fs from "fs-extra";
|
||||
import path from "path";
|
||||
import { exit } from "process";
|
||||
import { createRequire } from "module";
|
||||
import { getOctokit, context } from "@actions/github";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
|
||||
async function resolve() {
|
||||
if (!process.env.GITHUB_TOKEN) {
|
||||
throw new Error("GITHUB_TOKEN is required");
|
||||
}
|
||||
if (!process.env.GITHUB_REPOSITORY) {
|
||||
throw new Error("GITHUB_REPOSITORY is required");
|
||||
}
|
||||
if (!process.env.TAURI_PRIVATE_KEY) {
|
||||
throw new Error("TAURI_PRIVATE_KEY is required");
|
||||
}
|
||||
if (!process.env.TAURI_KEY_PASSWORD) {
|
||||
throw new Error("TAURI_KEY_PASSWORD is required");
|
||||
}
|
||||
|
||||
const { version } = require("../package.json");
|
||||
|
||||
const cwd = process.cwd();
|
||||
const bundlePath = path.join(cwd, "src-tauri/target/release/bundle");
|
||||
const join = (p) => path.join(bundlePath, p);
|
||||
|
||||
const appPathList = [
|
||||
join("macos/Clash Verge.aarch64.app.tar.gz"),
|
||||
join("macos/Clash Verge.aarch64.app.tar.gz.sig"),
|
||||
];
|
||||
|
||||
for (const appPath of appPathList) {
|
||||
if (fs.pathExistsSync(appPath)) {
|
||||
fs.removeSync(appPath);
|
||||
}
|
||||
}
|
||||
|
||||
fs.copyFileSync(join("macos/Clash Verge.app.tar.gz"), appPathList[0]);
|
||||
fs.copyFileSync(join("macos/Clash Verge.app.tar.gz.sig"), appPathList[1]);
|
||||
|
||||
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}`,
|
||||
});
|
||||
|
||||
if (!release.id) throw new Error("failed to find the release");
|
||||
|
||||
await uploadAssets(release.id, [
|
||||
join(`dmg/Clash Verge_${version}_aarch64.dmg`),
|
||||
...appPathList,
|
||||
]);
|
||||
}
|
||||
|
||||
// From tauri-apps/tauri-action
|
||||
// https://github.com/tauri-apps/tauri-action/blob/dev/packages/action/src/upload-release-assets.ts
|
||||
async function uploadAssets(releaseId, assets) {
|
||||
const github = getOctokit(process.env.GITHUB_TOKEN);
|
||||
|
||||
// Determine content-length for header to upload asset
|
||||
const contentLength = (filePath) => fs.statSync(filePath).size;
|
||||
|
||||
for (const assetPath of assets) {
|
||||
const headers = {
|
||||
"content-type": "application/zip",
|
||||
"content-length": contentLength(assetPath),
|
||||
};
|
||||
|
||||
const ext = path.extname(assetPath);
|
||||
const filename = path.basename(assetPath).replace(ext, "");
|
||||
const assetName = path.dirname(assetPath).includes(`target${path.sep}debug`)
|
||||
? `${filename}-debug${ext}`
|
||||
: `${filename}${ext}`;
|
||||
|
||||
console.log(`[INFO]: Uploading ${assetName}...`);
|
||||
|
||||
try {
|
||||
await github.rest.repos.uploadReleaseAsset({
|
||||
headers,
|
||||
name: assetName,
|
||||
data: fs.readFileSync(assetPath),
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
release_id: releaseId,
|
||||
});
|
||||
} catch (error) {
|
||||
console.log(error.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (process.platform === "darwin" && process.arch === "arm64") {
|
||||
resolve();
|
||||
} else {
|
||||
console.error("invalid");
|
||||
exit(1);
|
||||
}
|
305
scripts/check.mjs
Normal file
@ -0,0 +1,305 @@
|
||||
import fs from "fs-extra";
|
||||
import zlib from "zlib";
|
||||
import path from "path";
|
||||
import AdmZip from "adm-zip";
|
||||
import fetch from "node-fetch";
|
||||
import proxyAgent from "https-proxy-agent";
|
||||
import { execSync } from "child_process";
|
||||
|
||||
const cwd = process.cwd();
|
||||
const TEMP_DIR = path.join(cwd, "node_modules/.verge");
|
||||
|
||||
const FORCE = process.argv.includes("--force");
|
||||
const NO_META = process.argv.includes("--no-meta") || false;
|
||||
|
||||
/**
|
||||
* get the correct clash release infomation
|
||||
*/
|
||||
function resolveClash() {
|
||||
const { platform, arch } = process;
|
||||
|
||||
const CLASH_URL_PREFIX =
|
||||
"https://github.com/Dreamacro/clash/releases/download/premium/";
|
||||
const CLASH_LATEST_DATE = "2022.08.26";
|
||||
|
||||
// todo
|
||||
const map = {
|
||||
"win32-x64": "clash-windows-amd64",
|
||||
"darwin-x64": "clash-darwin-amd64",
|
||||
"darwin-arm64": "clash-darwin-arm64",
|
||||
"linux-x64": "clash-linux-amd64",
|
||||
};
|
||||
|
||||
const name = map[`${platform}-${arch}`];
|
||||
|
||||
if (!name) {
|
||||
throw new Error(`unsupport platform "${platform}-${arch}"`);
|
||||
}
|
||||
|
||||
const isWin = platform === "win32";
|
||||
const zip = isWin ? "zip" : "gz";
|
||||
const url = `${CLASH_URL_PREFIX}${name}-${CLASH_LATEST_DATE}.${zip}`;
|
||||
const exefile = `${name}${isWin ? ".exe" : ""}`;
|
||||
const zipfile = `${name}.${zip}`;
|
||||
|
||||
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.13.1";
|
||||
|
||||
const map = {
|
||||
"win32-x64": "Clash.Meta-windows-amd64",
|
||||
"darwin-x64": "Clash.Meta-darwin-amd64",
|
||||
"darwin-arm64": "Clash.Meta-darwin-arm64",
|
||||
"linux-x64": "Clash.Meta-linux-amd64",
|
||||
};
|
||||
|
||||
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
|
||||
* clash and Clash Meta
|
||||
*/
|
||||
async function resolveSidecar() {
|
||||
const sidecarDir = path.join(cwd, "src-tauri", "sidecar");
|
||||
|
||||
const host = execSync("rustc -vV")
|
||||
.toString()
|
||||
.match(/(?<=host: ).+(?=\s*)/g)[0];
|
||||
|
||||
const ext = process.platform === "win32" ? ".exe" : "";
|
||||
|
||||
await clash();
|
||||
if (!NO_META) await clashMeta();
|
||||
|
||||
async function clash() {
|
||||
const sidecarFile = `clash-${host}${ext}`;
|
||||
const sidecarPath = path.join(sidecarDir, sidecarFile);
|
||||
|
||||
await fs.mkdirp(sidecarDir);
|
||||
if (!FORCE && (await fs.pathExists(sidecarPath))) return;
|
||||
|
||||
// download sidecar
|
||||
const binInfo = resolveClash();
|
||||
const tempDir = path.join(TEMP_DIR, "clash");
|
||||
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);
|
||||
}
|
||||
|
||||
async function clashMeta() {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* only Windows
|
||||
* get the wintun.dll (not required)
|
||||
*/
|
||||
async function resolveWintun() {
|
||||
const { platform } = process;
|
||||
|
||||
if (platform !== "win32") return;
|
||||
|
||||
const url = "https://www.wintun.net/builds/wintun-0.14.1.zip";
|
||||
|
||||
const tempDir = path.join(TEMP_DIR, "wintun");
|
||||
const tempZip = path.join(tempDir, "wintun.zip");
|
||||
|
||||
const wintunPath = path.join(tempDir, "wintun/bin/amd64/wintun.dll");
|
||||
const targetPath = path.join(cwd, "src-tauri/resources", "wintun.dll");
|
||||
|
||||
if (!FORCE && (await fs.pathExists(targetPath))) return;
|
||||
|
||||
await fs.mkdirp(tempDir);
|
||||
|
||||
if (!(await fs.pathExists(tempZip))) {
|
||||
await downloadFile(url, tempZip);
|
||||
}
|
||||
|
||||
// unzip
|
||||
const zip = new AdmZip(tempZip);
|
||||
zip.extractAllTo(tempDir, true);
|
||||
|
||||
if (!(await fs.pathExists(wintunPath))) {
|
||||
throw new Error(`path not found "${wintunPath}"`);
|
||||
}
|
||||
|
||||
await fs.rename(wintunPath, targetPath);
|
||||
await fs.remove(tempDir);
|
||||
|
||||
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)
|
||||
*/
|
||||
async function resolveMmdb() {
|
||||
const url =
|
||||
"https://github.com/Dreamacro/maxmind-geoip/releases/download/20220512/Country.mmdb";
|
||||
|
||||
const resDir = path.join(cwd, "src-tauri", "resources");
|
||||
const resPath = path.join(resDir, "Country.mmdb");
|
||||
|
||||
if (!FORCE && (await fs.pathExists(resPath))) return;
|
||||
|
||||
await fs.mkdirp(resDir);
|
||||
await downloadFile(url, resPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* download file and save to `path`
|
||||
*/
|
||||
async function downloadFile(url, path) {
|
||||
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, {
|
||||
...options,
|
||||
method: "GET",
|
||||
headers: { "Content-Type": "application/octet-stream" },
|
||||
});
|
||||
const buffer = await response.arrayBuffer();
|
||||
await fs.writeFile(path, new Uint8Array(buffer));
|
||||
|
||||
console.log(`[INFO]: download finished "${url}"`);
|
||||
}
|
||||
|
||||
/// main
|
||||
resolveSidecar().catch(console.error);
|
||||
resolveWintun().catch(console.error);
|
||||
resolveMmdb().catch(console.error);
|
||||
resolveService().catch(console.error);
|
109
scripts/portable.mjs
Normal file
@ -0,0 +1,109 @@
|
||||
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.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_${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);
|
@ -1,104 +0,0 @@
|
||||
import fs from "fs-extra";
|
||||
import path from "path";
|
||||
import AdmZip from "adm-zip";
|
||||
import fetch from "node-fetch";
|
||||
import { execSync } from "child_process";
|
||||
|
||||
const cwd = process.cwd();
|
||||
|
||||
const CLASH_URL_PREFIX =
|
||||
"https://github.com/Dreamacro/clash/releases/download/premium/";
|
||||
const CLASH_LATEST_DATE = "2021.12.07";
|
||||
|
||||
/**
|
||||
* get the correct clash release infomation
|
||||
*/
|
||||
function resolveClash() {
|
||||
const { platform, arch } = process;
|
||||
|
||||
let name = "";
|
||||
|
||||
// todo
|
||||
if (platform === "win32" && arch === "x64") {
|
||||
name = `clash-windows-386`;
|
||||
}
|
||||
|
||||
if (!name) {
|
||||
throw new Error("todo");
|
||||
}
|
||||
|
||||
const isWin = platform === "win32";
|
||||
const zip = isWin ? "zip" : "gz";
|
||||
const url = `${CLASH_URL_PREFIX}${name}-${CLASH_LATEST_DATE}.${zip}`;
|
||||
const exefile = `${name}${isWin ? ".exe" : ""}`;
|
||||
const zipfile = `${name}.${zip}`;
|
||||
|
||||
return { url, zip, exefile, zipfile };
|
||||
}
|
||||
|
||||
/**
|
||||
* get the sidecar bin
|
||||
*/
|
||||
async function resolveSidecar() {
|
||||
const sidecarDir = path.join(cwd, "src-tauri", "sidecar");
|
||||
|
||||
const host = execSync("rustc -vV | grep host").toString().slice(6).trim();
|
||||
const ext = process.platform === "win32" ? ".exe" : "";
|
||||
const sidecarFile = `clash-${host}${ext}`;
|
||||
const sidecarPath = path.join(sidecarDir, sidecarFile);
|
||||
|
||||
if (!(await fs.pathExists(sidecarDir))) await fs.mkdir(sidecarDir);
|
||||
if (await fs.pathExists(sidecarPath)) return;
|
||||
|
||||
// download sidecar
|
||||
const binInfo = resolveClash();
|
||||
const tempDir = path.join(cwd, "pre-dev-temp");
|
||||
const tempZip = path.join(tempDir, binInfo.zipfile);
|
||||
const tempExe = path.join(tempDir, binInfo.exefile);
|
||||
|
||||
if (!(await fs.pathExists(tempDir))) await fs.mkdir(tempDir);
|
||||
if (!(await fs.pathExists(tempZip))) await downloadFile(binInfo.url, tempZip);
|
||||
|
||||
// Todo: support gz
|
||||
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);
|
||||
|
||||
// delete temp dir
|
||||
await fs.remove(tempDir);
|
||||
}
|
||||
|
||||
/**
|
||||
* get the Country.mmdb (not required)
|
||||
*/
|
||||
async function resolveMmdb() {
|
||||
const url =
|
||||
"https://github.com/Dreamacro/maxmind-geoip/releases/latest/download/Country.mmdb";
|
||||
|
||||
const resPath = path.join(cwd, "src-tauri", "resources", "Country.mmdb");
|
||||
if (await fs.pathExists(resPath)) return;
|
||||
await downloadFile(url, resPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* download file and save to `path`
|
||||
*/
|
||||
async function downloadFile(url, path) {
|
||||
console.log(`[INFO]: downloading from "${url}"`);
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: "GET",
|
||||
headers: { "Content-Type": "application/octet-stream" },
|
||||
});
|
||||
const buffer = await response.arrayBuffer();
|
||||
await fs.writeFile(path, new Uint8Array(buffer));
|
||||
}
|
||||
|
||||
/// main
|
||||
resolveSidecar();
|
||||
resolveMmdb();
|
53
scripts/publish.mjs
Normal file
@ -0,0 +1,53 @@
|
||||
import fs from "fs-extra";
|
||||
import { createRequire } from "module";
|
||||
import { execSync } from "child_process";
|
||||
import { resolveUpdateLog } from "./updatelog.mjs";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
|
||||
// publish
|
||||
async function resolvePublish() {
|
||||
const flag = process.argv[2] ?? "patch";
|
||||
const packageJson = require("../package.json");
|
||||
const tauriJson = require("../src-tauri/tauri.conf.json");
|
||||
|
||||
let [a, b, c] = packageJson.version.split(".").map(Number);
|
||||
|
||||
if (flag === "major") {
|
||||
a += 1;
|
||||
b = 0;
|
||||
c = 0;
|
||||
} else if (flag === "minor") {
|
||||
b += 1;
|
||||
c = 0;
|
||||
} else if (flag === "patch") {
|
||||
c += 1;
|
||||
} else throw new Error(`invalid flag "${flag}"`);
|
||||
|
||||
const nextVersion = `${a}.${b}.${c}`;
|
||||
packageJson.version = nextVersion;
|
||||
tauriJson.package.version = nextVersion;
|
||||
|
||||
// 发布更新前先写更新日志
|
||||
const nextTag = `v${nextVersion}`;
|
||||
await resolveUpdateLog(nextTag);
|
||||
|
||||
await fs.writeFile(
|
||||
"./package.json",
|
||||
JSON.stringify(packageJson, undefined, 2)
|
||||
);
|
||||
await fs.writeFile(
|
||||
"./src-tauri/tauri.conf.json",
|
||||
JSON.stringify(tauriJson, undefined, 2)
|
||||
);
|
||||
|
||||
execSync("git add ./package.json");
|
||||
execSync("git add ./src-tauri/tauri.conf.json");
|
||||
execSync(`git commit -m "v${nextVersion}"`);
|
||||
execSync(`git tag -a v${nextVersion} -m "v${nextVersion}"`);
|
||||
execSync(`git push`);
|
||||
execSync(`git push origin v${nextVersion}`);
|
||||
console.log(`Publish Successfully...`);
|
||||
}
|
||||
|
||||
resolvePublish();
|
44
scripts/updatelog.mjs
Normal file
@ -0,0 +1,44 @@
|
||||
import fs from "fs-extra";
|
||||
import path from "path";
|
||||
|
||||
const UPDATE_LOG = "UPDATELOG.md";
|
||||
|
||||
// parse the UPDATELOG.md
|
||||
export async function resolveUpdateLog(tag) {
|
||||
const cwd = process.cwd();
|
||||
|
||||
const reTitle = /^## v[\d\.]+/;
|
||||
const reEnd = /^---/;
|
||||
|
||||
const file = path.join(cwd, UPDATE_LOG);
|
||||
|
||||
if (!(await fs.pathExists(file))) {
|
||||
throw new Error("could not found UPDATELOG.md");
|
||||
}
|
||||
|
||||
const data = await fs.readFile(file).then((d) => d.toString("utf8"));
|
||||
|
||||
const map = {};
|
||||
let p = "";
|
||||
|
||||
data.split("\n").forEach((line) => {
|
||||
if (reTitle.test(line)) {
|
||||
p = line.slice(3).trim();
|
||||
if (!map[p]) {
|
||||
map[p] = [];
|
||||
} else {
|
||||
throw new Error(`Tag ${p} dup`);
|
||||
}
|
||||
} else if (reEnd.test(line)) {
|
||||
p = "";
|
||||
} else if (p) {
|
||||
map[p].push(line);
|
||||
}
|
||||
});
|
||||
|
||||
if (!map[tag]) {
|
||||
throw new Error(`could not found "${tag}" in UPDATELOG.md`);
|
||||
}
|
||||
|
||||
return map[tag].join("\n").trim();
|
||||
}
|
177
scripts/updater.mjs
Normal file
@ -0,0 +1,177 @@
|
||||
import fetch from "node-fetch";
|
||||
import { getOctokit, context } from "@actions/github";
|
||||
import { resolveUpdateLog } from "./updatelog.mjs";
|
||||
|
||||
const UPDATE_TAG_NAME = "updater";
|
||||
const UPDATE_JSON_FILE = "update.json";
|
||||
const UPDATE_JSON_PROXY = "update-proxy.json";
|
||||
|
||||
/// generate update.json
|
||||
/// upload to update tag's release asset
|
||||
async function resolveUpdater() {
|
||||
if (process.env.GITHUB_TOKEN === undefined) {
|
||||
throw new Error("GITHUB_TOKEN is required");
|
||||
}
|
||||
|
||||
const options = { owner: context.repo.owner, repo: context.repo.repo };
|
||||
const github = getOctokit(process.env.GITHUB_TOKEN);
|
||||
|
||||
const { data: tags } = await github.rest.repos.listTags({
|
||||
...options,
|
||||
per_page: 10,
|
||||
page: 1,
|
||||
});
|
||||
|
||||
// get the latest publish tag
|
||||
const tag = tags.find((t) => t.name.startsWith("v"));
|
||||
|
||||
console.log(tag);
|
||||
console.log();
|
||||
|
||||
const { data: latestRelease } = await github.rest.repos.getReleaseByTag({
|
||||
...options,
|
||||
tag: tag.name,
|
||||
});
|
||||
|
||||
const updateData = {
|
||||
name: tag.name,
|
||||
notes: await resolveUpdateLog(tag.name), // use updatelog.md
|
||||
pub_date: new Date().toISOString(),
|
||||
platforms: {
|
||||
win64: { signature: "", url: "" }, // compatible with older formats
|
||||
linux: { signature: "", url: "" }, // compatible with older formats
|
||||
darwin: { signature: "", url: "" }, // compatible with older formats
|
||||
"darwin-aarch64": { signature: "", url: "" },
|
||||
"darwin-intel": { signature: "", url: "" },
|
||||
"linux-x86_64": { signature: "", url: "" },
|
||||
"windows-x86_64": { signature: "", url: "" },
|
||||
"windows-i686": { signature: "", url: "" }, // no supported
|
||||
},
|
||||
};
|
||||
|
||||
const promises = latestRelease.assets.map(async (asset) => {
|
||||
const { name, browser_download_url } = asset;
|
||||
|
||||
// win64 url
|
||||
if (name.endsWith(".msi.zip") && name.includes("en-US")) {
|
||||
updateData.platforms.win64.url = browser_download_url;
|
||||
updateData.platforms["windows-x86_64"].url = browser_download_url;
|
||||
}
|
||||
// win64 signature
|
||||
if (name.endsWith(".msi.zip.sig") && name.includes("en-US")) {
|
||||
const sig = await getSignature(browser_download_url);
|
||||
updateData.platforms.win64.signature = sig;
|
||||
updateData.platforms["windows-x86_64"].signature = sig;
|
||||
}
|
||||
|
||||
// darwin url (intel)
|
||||
if (name.endsWith(".app.tar.gz") && !name.includes("aarch")) {
|
||||
updateData.platforms.darwin.url = browser_download_url;
|
||||
updateData.platforms["darwin-intel"].url = browser_download_url;
|
||||
}
|
||||
// darwin signature (intel)
|
||||
if (name.endsWith(".app.tar.gz.sig") && !name.includes("aarch")) {
|
||||
const sig = await getSignature(browser_download_url);
|
||||
updateData.platforms.darwin.signature = sig;
|
||||
updateData.platforms["darwin-intel"].signature = sig;
|
||||
}
|
||||
|
||||
// darwin url (aarch)
|
||||
if (name.endsWith("aarch64.app.tar.gz")) {
|
||||
updateData.platforms["darwin-aarch64"].url = browser_download_url;
|
||||
}
|
||||
// darwin signature (aarch)
|
||||
if (name.endsWith("aarch64.app.tar.gz.sig")) {
|
||||
const sig = await getSignature(browser_download_url);
|
||||
updateData.platforms["darwin-aarch64"].signature = sig;
|
||||
}
|
||||
|
||||
// linux url
|
||||
if (name.endsWith(".AppImage.tar.gz")) {
|
||||
updateData.platforms.linux.url = browser_download_url;
|
||||
updateData.platforms["linux-x86_64"].url = browser_download_url;
|
||||
}
|
||||
// linux signature
|
||||
if (name.endsWith(".AppImage.tar.gz.sig")) {
|
||||
const sig = await getSignature(browser_download_url);
|
||||
updateData.platforms.linux.signature = sig;
|
||||
updateData.platforms["linux-x86_64"].signature = sig;
|
||||
}
|
||||
});
|
||||
|
||||
await Promise.allSettled(promises);
|
||||
console.log(updateData);
|
||||
|
||||
// maybe should test the signature as well
|
||||
// delete the null field
|
||||
Object.entries(updateData.platforms).forEach(([key, value]) => {
|
||||
if (!value.url) {
|
||||
console.log(`[Error]: failed to parse release for "${key}"`);
|
||||
delete updateData.platforms[key];
|
||||
}
|
||||
});
|
||||
|
||||
// 生成一个代理github的更新文件
|
||||
// 使用 https://hub.fastgit.xyz/ 做github资源的加速
|
||||
const updateDataNew = JSON.parse(JSON.stringify(updateData));
|
||||
|
||||
Object.entries(updateDataNew.platforms).forEach(([key, value]) => {
|
||||
if (value.url) {
|
||||
updateDataNew.platforms[key].url = value.url.replace(
|
||||
"https://github.com/",
|
||||
"https://hub.fastgit.xyz/"
|
||||
);
|
||||
} else {
|
||||
console.log(`[Error]: updateDataNew.platforms.${key} is null`);
|
||||
}
|
||||
});
|
||||
|
||||
// update the update.json
|
||||
const { data: updateRelease } = await github.rest.repos.getReleaseByTag({
|
||||
...options,
|
||||
tag: UPDATE_TAG_NAME,
|
||||
});
|
||||
|
||||
// delete the old assets
|
||||
for (let asset of updateRelease.assets) {
|
||||
if (asset.name === UPDATE_JSON_FILE) {
|
||||
await github.rest.repos.deleteReleaseAsset({
|
||||
...options,
|
||||
asset_id: asset.id,
|
||||
});
|
||||
}
|
||||
|
||||
if (asset.name === UPDATE_JSON_PROXY) {
|
||||
await github.rest.repos
|
||||
.deleteReleaseAsset({ ...options, asset_id: asset.id })
|
||||
.catch(console.error); // do not break the pipeline
|
||||
}
|
||||
}
|
||||
|
||||
// upload new assets
|
||||
await github.rest.repos.uploadReleaseAsset({
|
||||
...options,
|
||||
release_id: updateRelease.id,
|
||||
name: UPDATE_JSON_FILE,
|
||||
data: JSON.stringify(updateData, null, 2),
|
||||
});
|
||||
|
||||
await github.rest.repos.uploadReleaseAsset({
|
||||
...options,
|
||||
release_id: updateRelease.id,
|
||||
name: UPDATE_JSON_PROXY,
|
||||
data: JSON.stringify(updateDataNew, null, 2),
|
||||
});
|
||||
}
|
||||
|
||||
// get the signature file content
|
||||
async function getSignature(url) {
|
||||
const response = await fetch(url, {
|
||||
method: "GET",
|
||||
headers: { "Content-Type": "application/octet-stream" },
|
||||
});
|
||||
|
||||
return response.text();
|
||||
}
|
||||
|
||||
resolveUpdater().catch(console.error);
|
2
src-tauri/.gitignore
vendored
@ -2,5 +2,5 @@
|
||||
# will have compiled files and executables
|
||||
/target/
|
||||
WixTools
|
||||
resources/Country.mmdb
|
||||
resources
|
||||
sidecar
|
||||
|
3111
src-tauri/Cargo.lock
generated
@ -1,34 +1,56 @@
|
||||
[package]
|
||||
name = "app"
|
||||
name = "clash-verge"
|
||||
version = "0.1.0"
|
||||
description = "clash verge"
|
||||
authors = ["zzzgydi"]
|
||||
license = "GPL-3.0"
|
||||
repository = ""
|
||||
default-run = "app"
|
||||
repository = "https://github.com/zzzgydi/clash-verge.git"
|
||||
default-run = "clash-verge"
|
||||
edition = "2021"
|
||||
build = "build.rs"
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "1.0.0-beta.4" }
|
||||
tauri-build = { version = "1.0.0", features = [] }
|
||||
|
||||
[dependencies]
|
||||
warp = "0.3"
|
||||
which = "4.2.2"
|
||||
anyhow = "1.0"
|
||||
dirs = "4.0.0"
|
||||
open = "2.1.1"
|
||||
log = "0.4.14"
|
||||
dunce = "1.0.2"
|
||||
log4rs = "1.0.0"
|
||||
nanoid = "0.4.0"
|
||||
chrono = "0.4.19"
|
||||
serde_json = "1.0"
|
||||
serde_yaml = "0.8"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
tauri = { version = "1.0.0-beta.8", features = ["api-all", "system-tray"] }
|
||||
reqwest = { version = "0.11", features = ["json"] }
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
log = "0.4.14"
|
||||
log4rs = "1.0.0"
|
||||
warp = "0.3"
|
||||
auto-launch = "0.3"
|
||||
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", features = ["process-all", "shell-all", "system-tray", "updater", "window-all"] }
|
||||
rquickjs = { version = "0.1.6" }
|
||||
window-shadows = { version = "0.1" }
|
||||
window-vibrancy = { version = "0.1" }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
runas = "0.2.1"
|
||||
deelevate = "0.2.0"
|
||||
winreg = { version = "0.10", features = ["transactions"] }
|
||||
windows-sys = { version = "0.36", features = ["Win32_System_LibraryLoader", "Win32_System_SystemInformation"] }
|
||||
|
||||
[features]
|
||||
default = [ "custom-protocol" ]
|
||||
custom-protocol = [ "tauri/custom-protocol" ]
|
||||
default = ["custom-protocol"]
|
||||
custom-protocol = ["tauri/custom-protocol"]
|
||||
verge-dev = []
|
||||
debug-yml = []
|
||||
|
||||
[profile.release]
|
||||
panic = "abort"
|
||||
codegen-units = 1
|
||||
lto = true
|
||||
opt-level = "s"
|
||||
|
Before Width: | Height: | Size: 33 KiB |
BIN
src-tauri/icons/icon-new.icns
Normal file
BIN
src-tauri/icons/icon-shrink.png
Normal file
After Width: | Height: | Size: 21 KiB |
Before Width: | Height: | Size: 4.2 KiB After Width: | Height: | Size: 33 KiB |
BIN
src-tauri/icons/tray-icon.ico
Normal file
After Width: | Height: | Size: 4.2 KiB |
BIN
src-tauri/icons/tray-icon.png
Normal file
After Width: | Height: | Size: 12 KiB |
@ -1,7 +0,0 @@
|
||||
# Default Config For Clash Core
|
||||
|
||||
mixed-port: 7890
|
||||
log-level: info
|
||||
allow-lan: false
|
||||
external-controller: 127.0.0.1:9090
|
||||
secret: ""
|
@ -1,3 +0,0 @@
|
||||
# Profiles Config for Clash Verge
|
||||
|
||||
current: 0
|
@ -1,6 +0,0 @@
|
||||
# Defaulf Config For Clash Verge
|
||||
|
||||
theme_mode: light
|
||||
enable_self_startup: false
|
||||
enable_system_proxy: false
|
||||
system_proxy_bypass: localhost;127.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;192.168.*;<local>
|
342
src-tauri/src/cmds.rs
Normal file
@ -0,0 +1,342 @@
|
||||
use crate::{
|
||||
core::{ClashInfo, Core, PrfItem, PrfOption, Profiles, Verge},
|
||||
utils::{dirs, help, sysopt::SysProxyConfig},
|
||||
};
|
||||
use crate::{log_if_err, ret_err, wrap_err};
|
||||
use anyhow::Result;
|
||||
use serde_yaml::Mapping;
|
||||
use std::collections::HashMap;
|
||||
use tauri::{api, State};
|
||||
|
||||
type CmdResult<T = ()> = Result<T, String>;
|
||||
|
||||
/// get all profiles from `profiles.yaml`
|
||||
#[tauri::command]
|
||||
pub fn get_profiles(core: State<'_, Core>) -> CmdResult<Profiles> {
|
||||
let profiles = core.profiles.lock();
|
||||
Ok(profiles.clone())
|
||||
}
|
||||
|
||||
/// manually exec enhanced profile
|
||||
#[tauri::command]
|
||||
pub fn enhance_profiles(core: State<'_, Core>) -> CmdResult {
|
||||
wrap_err!(core.activate())
|
||||
}
|
||||
|
||||
/// import the profile from url
|
||||
/// and save to `profiles.yaml`
|
||||
#[tauri::command]
|
||||
pub async fn import_profile(
|
||||
url: String,
|
||||
option: Option<PrfOption>,
|
||||
core: State<'_, Core>,
|
||||
) -> CmdResult {
|
||||
let item = wrap_err!(PrfItem::from_url(&url, None, None, option).await)?;
|
||||
|
||||
let mut profiles = core.profiles.lock();
|
||||
wrap_err!(profiles.append_item(item))
|
||||
}
|
||||
|
||||
/// new a profile
|
||||
/// append a temp profile item file to the `profiles` dir
|
||||
/// view the temp profile file by using vscode or other editor
|
||||
#[tauri::command]
|
||||
pub async fn create_profile(
|
||||
item: PrfItem, // partial
|
||||
file_data: Option<String>,
|
||||
core: State<'_, Core>,
|
||||
) -> CmdResult {
|
||||
let item = wrap_err!(PrfItem::from(item, file_data).await)?;
|
||||
|
||||
let mut profiles = core.profiles.lock();
|
||||
wrap_err!(profiles.append_item(item))
|
||||
}
|
||||
|
||||
/// Update the profile
|
||||
#[tauri::command]
|
||||
pub async fn update_profile(
|
||||
index: String,
|
||||
option: Option<PrfOption>,
|
||||
core: State<'_, Core>,
|
||||
) -> CmdResult {
|
||||
wrap_err!(core.update_profile_item(index, option).await)
|
||||
}
|
||||
|
||||
/// change the current profile
|
||||
#[tauri::command]
|
||||
pub fn select_profile(index: String, core: State<'_, Core>) -> CmdResult {
|
||||
let mut profiles = core.profiles.lock();
|
||||
wrap_err!(profiles.put_current(index))?;
|
||||
drop(profiles);
|
||||
wrap_err!(core.activate())
|
||||
}
|
||||
|
||||
/// change the profile chain
|
||||
#[tauri::command]
|
||||
pub fn change_profile_chain(chain: Option<Vec<String>>, core: State<'_, Core>) -> CmdResult {
|
||||
let mut profiles = core.profiles.lock();
|
||||
wrap_err!(profiles.put_chain(chain))?;
|
||||
drop(profiles);
|
||||
wrap_err!(core.activate())
|
||||
}
|
||||
|
||||
/// change the profile valid fields
|
||||
#[tauri::command]
|
||||
pub fn change_profile_valid(valid: Option<Vec<String>>, core: State<Core>) -> CmdResult {
|
||||
let mut profiles = core.profiles.lock();
|
||||
wrap_err!(profiles.put_valid(valid))?;
|
||||
drop(profiles);
|
||||
wrap_err!(core.activate())
|
||||
}
|
||||
|
||||
/// delete profile item
|
||||
#[tauri::command]
|
||||
pub fn delete_profile(index: String, core: State<'_, Core>) -> CmdResult {
|
||||
let mut profiles = core.profiles.lock();
|
||||
if wrap_err!(profiles.delete_item(index))? {
|
||||
drop(profiles);
|
||||
log_if_err!(core.activate());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// patch the profile config
|
||||
#[tauri::command]
|
||||
pub fn patch_profile(index: String, profile: PrfItem, core: State<'_, Core>) -> CmdResult {
|
||||
let mut profiles = core.profiles.lock();
|
||||
wrap_err!(profiles.patch_item(index, profile))?;
|
||||
drop(profiles);
|
||||
|
||||
// update cron task
|
||||
let mut timer = core.timer.lock();
|
||||
wrap_err!(timer.refresh())
|
||||
}
|
||||
|
||||
/// run vscode command to edit the profile
|
||||
#[tauri::command]
|
||||
pub fn view_profile(index: String, core: State<'_, Core>) -> CmdResult {
|
||||
let profiles = core.profiles.lock();
|
||||
let item = wrap_err!(profiles.get_item(&index))?;
|
||||
|
||||
let file = item.file.clone();
|
||||
if file.is_none() {
|
||||
ret_err!("the file is null");
|
||||
}
|
||||
|
||||
let path = dirs::app_profiles_dir().join(file.unwrap());
|
||||
if !path.exists() {
|
||||
ret_err!("the file not found");
|
||||
}
|
||||
|
||||
wrap_err!(help::open_file(path))
|
||||
}
|
||||
|
||||
/// read the profile item file data
|
||||
#[tauri::command]
|
||||
pub fn read_profile_file(index: String, core: State<'_, Core>) -> CmdResult<String> {
|
||||
let profiles = core.profiles.lock();
|
||||
let item = wrap_err!(profiles.get_item(&index))?;
|
||||
let data = wrap_err!(item.read_file())?;
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
/// save the profile item file data
|
||||
#[tauri::command]
|
||||
pub fn save_profile_file(
|
||||
index: String,
|
||||
file_data: Option<String>,
|
||||
core: State<'_, Core>,
|
||||
) -> CmdResult {
|
||||
if file_data.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let profiles = core.profiles.lock();
|
||||
let item = wrap_err!(profiles.get_item(&index))?;
|
||||
wrap_err!(item.save_file(file_data.unwrap()))
|
||||
}
|
||||
|
||||
/// get the clash core info from the state
|
||||
/// the caller can also get the infomation by clash's api
|
||||
#[tauri::command]
|
||||
pub fn get_clash_info(core: State<'_, Core>) -> CmdResult<ClashInfo> {
|
||||
let clash = core.clash.lock();
|
||||
Ok(clash.info.clone())
|
||||
}
|
||||
|
||||
/// get the runtime clash config mapping
|
||||
#[tauri::command]
|
||||
pub fn get_runtime_config(core: State<'_, Core>) -> CmdResult<Option<Mapping>> {
|
||||
let rt = core.runtime.lock();
|
||||
Ok(rt.config.clone())
|
||||
}
|
||||
|
||||
/// get the runtime clash config yaml string
|
||||
#[tauri::command]
|
||||
pub fn get_runtime_yaml(core: State<'_, Core>) -> CmdResult<Option<String>> {
|
||||
let rt = core.runtime.lock();
|
||||
Ok(rt.config_yaml.clone())
|
||||
}
|
||||
|
||||
/// get the runtime config exists keys
|
||||
#[tauri::command]
|
||||
pub fn get_runtime_exists(core: State<'_, Core>) -> CmdResult<Vec<String>> {
|
||||
let rt = core.runtime.lock();
|
||||
Ok(rt.exists_keys.clone())
|
||||
}
|
||||
|
||||
/// get the runtime enhanced chain log
|
||||
#[tauri::command]
|
||||
pub fn get_runtime_logs(
|
||||
core: State<'_, Core>,
|
||||
) -> CmdResult<HashMap<String, Vec<(String, String)>>> {
|
||||
let rt = core.runtime.lock();
|
||||
Ok(rt.chain_logs.clone())
|
||||
}
|
||||
|
||||
/// update the clash core config
|
||||
/// after putting the change to the clash core
|
||||
/// then we should save the latest config
|
||||
#[tauri::command]
|
||||
pub fn patch_clash_config(
|
||||
payload: Mapping,
|
||||
app_handle: tauri::AppHandle,
|
||||
core: State<'_, Core>,
|
||||
) -> CmdResult {
|
||||
wrap_err!(core.patch_clash(payload, &app_handle))
|
||||
}
|
||||
|
||||
/// get the verge config
|
||||
#[tauri::command]
|
||||
pub fn get_verge_config(core: State<'_, Core>) -> CmdResult<Verge> {
|
||||
let verge = core.verge.lock();
|
||||
Ok(verge.clone())
|
||||
}
|
||||
|
||||
/// 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
|
||||
#[tauri::command]
|
||||
pub fn get_sys_proxy() -> Result<SysProxyConfig, String> {
|
||||
wrap_err!(SysProxyConfig::get_sys())
|
||||
}
|
||||
|
||||
/// get the current proxy config
|
||||
/// which may not the same as system proxy
|
||||
#[tauri::command]
|
||||
pub fn get_cur_proxy(core: State<'_, Core>) -> CmdResult<Option<SysProxyConfig>> {
|
||||
let sysopt = core.sysopt.lock();
|
||||
wrap_err!(sysopt.get_sysproxy())
|
||||
}
|
||||
|
||||
/// open app config dir
|
||||
#[tauri::command]
|
||||
pub fn open_app_dir() -> Result<(), String> {
|
||||
let app_dir = dirs::app_home_dir();
|
||||
wrap_err!(open::that(app_dir))
|
||||
}
|
||||
|
||||
/// open logs dir
|
||||
#[tauri::command]
|
||||
pub fn open_logs_dir() -> Result<(), String> {
|
||||
let log_dir = dirs::app_logs_dir();
|
||||
wrap_err!(open::that(log_dir))
|
||||
}
|
||||
|
||||
/// open url
|
||||
#[tauri::command]
|
||||
pub fn open_web_url(url: String) -> Result<(), String> {
|
||||
wrap_err!(open::that(url))
|
||||
}
|
||||
|
||||
/// 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,2 +0,0 @@
|
||||
pub mod profile;
|
||||
pub mod some;
|
@ -1,190 +0,0 @@
|
||||
use crate::{
|
||||
config::{ProfileItem, ProfilesConfig},
|
||||
events::state::{ClashInfoState, ProfileLock},
|
||||
utils::{
|
||||
app_home_dir,
|
||||
clash::put_clash_profile,
|
||||
config::{read_profiles, save_profiles},
|
||||
fetch::fetch_profile,
|
||||
},
|
||||
};
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use tauri::State;
|
||||
|
||||
/// Import the profile from url
|
||||
/// and save to `profiles.yaml`
|
||||
#[tauri::command]
|
||||
pub async fn import_profile(url: String, lock: State<'_, ProfileLock>) -> Result<(), String> {
|
||||
let result = match fetch_profile(&url).await {
|
||||
Some(r) => r,
|
||||
None => {
|
||||
log::error!("failed to fetch profile from `{}`", url);
|
||||
return Err(format!("failed to fetch profile from `{}`", url));
|
||||
}
|
||||
};
|
||||
|
||||
// get lock
|
||||
if lock.0.lock().is_err() {
|
||||
return Err(format!("can not get file lock"));
|
||||
}
|
||||
|
||||
// save the profile file
|
||||
let path = app_home_dir().join("profiles").join(&result.file);
|
||||
let file_data = result.data.as_bytes();
|
||||
File::create(path).unwrap().write(file_data).unwrap();
|
||||
|
||||
// update `profiles.yaml`
|
||||
let mut profiles = read_profiles();
|
||||
let mut items = profiles.items.unwrap_or(vec![]);
|
||||
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs();
|
||||
|
||||
items.push(ProfileItem {
|
||||
name: Some(result.name),
|
||||
file: Some(result.file),
|
||||
mode: Some(format!("rule")),
|
||||
url: Some(url),
|
||||
selected: Some(vec![]),
|
||||
extra: Some(result.extra),
|
||||
updated: Some(now as usize),
|
||||
});
|
||||
profiles.items = Some(items);
|
||||
save_profiles(&profiles)
|
||||
}
|
||||
|
||||
/// Update the profile
|
||||
/// and save to `profiles.yaml`
|
||||
/// http request firstly
|
||||
/// then acquire the lock of `profiles.yaml`
|
||||
#[tauri::command]
|
||||
pub async fn update_profile(index: usize, lock: State<'_, ProfileLock>) -> Result<(), String> {
|
||||
// get lock
|
||||
if lock.0.lock().is_err() {
|
||||
return Err(format!("can not get file lock"));
|
||||
}
|
||||
|
||||
// update `profiles.yaml`
|
||||
let mut profiles = read_profiles();
|
||||
let mut items = profiles.items.unwrap_or(vec![]);
|
||||
|
||||
if index >= items.len() {
|
||||
return Err(format!("the index out of bound"));
|
||||
}
|
||||
|
||||
let url = match &items[index].url {
|
||||
Some(u) => u,
|
||||
None => return Err(format!("invalid url")),
|
||||
};
|
||||
|
||||
let result = match fetch_profile(&url).await {
|
||||
Some(r) => r,
|
||||
None => {
|
||||
log::error!("failed to fetch profile from `{}`", url);
|
||||
return Err(format!("failed to fetch profile from `{}`", url));
|
||||
}
|
||||
};
|
||||
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs() as usize;
|
||||
|
||||
// update file
|
||||
let file_path = &items[index].file.as_ref().unwrap();
|
||||
let file_path = app_home_dir().join("profiles").join(file_path);
|
||||
let file_data = result.data.as_bytes();
|
||||
File::create(file_path).unwrap().write(file_data).unwrap();
|
||||
|
||||
items[index].name = Some(result.name);
|
||||
items[index].extra = Some(result.extra);
|
||||
items[index].updated = Some(now);
|
||||
profiles.items = Some(items);
|
||||
save_profiles(&profiles)
|
||||
}
|
||||
|
||||
/// get all profiles from `profiles.yaml`
|
||||
/// do not acquire the lock of ProfileLock
|
||||
#[tauri::command]
|
||||
pub fn get_profiles() -> Result<ProfilesConfig, String> {
|
||||
Ok(read_profiles())
|
||||
}
|
||||
|
||||
/// patch the profile config
|
||||
#[tauri::command]
|
||||
pub fn set_profiles(
|
||||
index: usize,
|
||||
profile: ProfileItem,
|
||||
lock: State<'_, ProfileLock>,
|
||||
) -> Result<(), String> {
|
||||
// get lock
|
||||
if lock.0.lock().is_err() {
|
||||
return Err(format!("can not get file lock"));
|
||||
}
|
||||
|
||||
let mut profiles = read_profiles();
|
||||
let mut items = profiles.items.unwrap_or(vec![]);
|
||||
|
||||
if index >= items.len() {
|
||||
return Err(format!("the index out of bound"));
|
||||
}
|
||||
|
||||
if profile.name.is_some() {
|
||||
items[index].name = profile.name;
|
||||
}
|
||||
if profile.file.is_some() {
|
||||
items[index].file = profile.file;
|
||||
}
|
||||
if profile.mode.is_some() {
|
||||
items[index].mode = profile.mode;
|
||||
}
|
||||
if profile.url.is_some() {
|
||||
items[index].url = profile.url;
|
||||
}
|
||||
if profile.selected.is_some() {
|
||||
items[index].selected = profile.selected;
|
||||
}
|
||||
if profile.extra.is_some() {
|
||||
items[index].extra = profile.extra;
|
||||
}
|
||||
|
||||
profiles.items = Some(items);
|
||||
save_profiles(&profiles)
|
||||
}
|
||||
|
||||
/// change the current profile
|
||||
#[tauri::command]
|
||||
pub async fn put_profiles(
|
||||
current: usize,
|
||||
lock: State<'_, ProfileLock>,
|
||||
clash_info: State<'_, ClashInfoState>,
|
||||
) -> Result<(), String> {
|
||||
if lock.0.lock().is_err() {
|
||||
return Err(format!("can not get file lock"));
|
||||
}
|
||||
|
||||
let clash_info = match clash_info.0.lock() {
|
||||
Ok(arc) => arc.clone(),
|
||||
_ => return Err(format!("can not get clash info")),
|
||||
};
|
||||
|
||||
let mut profiles = read_profiles();
|
||||
let items_len = match &profiles.items {
|
||||
Some(list) => list.len(),
|
||||
None => 0,
|
||||
};
|
||||
|
||||
if current >= items_len {
|
||||
return Err(format!("the index out of bound"));
|
||||
}
|
||||
|
||||
profiles.current = Some(current);
|
||||
match save_profiles(&profiles) {
|
||||
Ok(_) => put_clash_profile(&clash_info).await,
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
@ -1,154 +0,0 @@
|
||||
use crate::{
|
||||
config::VergeConfig,
|
||||
events::{
|
||||
emit::ClashInfoPayload,
|
||||
state::{ClashInfoState, VergeConfLock},
|
||||
},
|
||||
utils::{
|
||||
clash::run_clash_bin,
|
||||
config::{read_clash, save_clash, save_verge},
|
||||
sysopt::{get_proxy_config, set_proxy_config, SysProxyConfig, DEFAULT_BYPASS},
|
||||
},
|
||||
};
|
||||
use serde_yaml::Mapping;
|
||||
use tauri::{api::process::kill_children, AppHandle, State};
|
||||
|
||||
/// restart the sidecar
|
||||
#[tauri::command]
|
||||
pub fn restart_sidecar(app_handle: AppHandle, clash_info: State<'_, ClashInfoState>) {
|
||||
kill_children();
|
||||
let payload = run_clash_bin(&app_handle);
|
||||
|
||||
if let Ok(mut arc) = clash_info.0.lock() {
|
||||
*arc = payload;
|
||||
}
|
||||
}
|
||||
|
||||
/// get the clash core info from the state
|
||||
/// the caller can also get the infomation by clash's api
|
||||
#[tauri::command]
|
||||
pub fn get_clash_info(clash_info: State<'_, ClashInfoState>) -> Result<ClashInfoPayload, String> {
|
||||
match clash_info.0.lock() {
|
||||
Ok(arc) => Ok(arc.clone()),
|
||||
Err(_) => Err(format!("can not get clash info")),
|
||||
}
|
||||
}
|
||||
|
||||
/// update the clash core config
|
||||
/// after putting the change to the clash core
|
||||
/// then we should save the latest config
|
||||
#[tauri::command]
|
||||
pub fn patch_clash_config(payload: Mapping) -> Result<(), String> {
|
||||
let mut config = read_clash();
|
||||
for (key, value) in payload.iter() {
|
||||
if config.contains_key(key) {
|
||||
config[key] = value.clone();
|
||||
} else {
|
||||
config.insert(key.clone(), value.clone());
|
||||
}
|
||||
}
|
||||
save_clash(&config)
|
||||
}
|
||||
|
||||
/// set the system proxy
|
||||
/// Tips: only support windows now
|
||||
#[tauri::command]
|
||||
pub fn set_sys_proxy(
|
||||
enable: bool,
|
||||
clash_info: State<'_, ClashInfoState>,
|
||||
verge_lock: State<'_, VergeConfLock>,
|
||||
) -> Result<(), String> {
|
||||
let clash_info = match clash_info.0.lock() {
|
||||
Ok(arc) => arc.clone(),
|
||||
_ => return Err(format!("can not get clash info")),
|
||||
};
|
||||
|
||||
let verge_info = match verge_lock.0.lock() {
|
||||
Ok(arc) => arc.clone(),
|
||||
_ => return Err(format!("can not get verge info")),
|
||||
};
|
||||
|
||||
let port = match clash_info.controller {
|
||||
Some(ctrl) => ctrl.port,
|
||||
None => None,
|
||||
};
|
||||
|
||||
if port.is_none() {
|
||||
return Err(format!("can not get clash core's port"));
|
||||
}
|
||||
|
||||
let config = if enable {
|
||||
let server = format!("127.0.0.1:{}", port.unwrap());
|
||||
let bypass = verge_info
|
||||
.system_proxy_bypass
|
||||
.unwrap_or(String::from(DEFAULT_BYPASS));
|
||||
SysProxyConfig {
|
||||
enable,
|
||||
server,
|
||||
bypass,
|
||||
}
|
||||
} else {
|
||||
SysProxyConfig {
|
||||
enable,
|
||||
server: String::from(""),
|
||||
bypass: String::from(""),
|
||||
}
|
||||
};
|
||||
|
||||
match set_proxy_config(&config) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(_) => Err(format!("can not set proxy")),
|
||||
}
|
||||
}
|
||||
|
||||
/// get the system proxy
|
||||
/// Tips: only support windows now
|
||||
#[tauri::command]
|
||||
pub fn get_sys_proxy() -> Result<SysProxyConfig, String> {
|
||||
match get_proxy_config() {
|
||||
Ok(value) => Ok(value),
|
||||
Err(err) => Err(err.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// get the verge config
|
||||
#[tauri::command]
|
||||
pub fn get_verge_config(verge_lock: State<'_, VergeConfLock>) -> Result<VergeConfig, String> {
|
||||
match verge_lock.0.lock() {
|
||||
Ok(arc) => Ok(arc.clone()),
|
||||
Err(_) => Err(format!("can not get the lock")),
|
||||
}
|
||||
}
|
||||
|
||||
/// patch the verge config
|
||||
/// this command only save the config and not responsible for other things
|
||||
#[tauri::command]
|
||||
pub async fn patch_verge_config(
|
||||
payload: VergeConfig,
|
||||
verge_lock: State<'_, VergeConfLock>,
|
||||
) -> Result<(), String> {
|
||||
let mut verge = match verge_lock.0.lock() {
|
||||
Ok(v) => v,
|
||||
Err(_) => return Err(format!("can not get the lock")),
|
||||
};
|
||||
|
||||
if payload.theme_mode.is_some() {
|
||||
verge.theme_mode = payload.theme_mode;
|
||||
}
|
||||
|
||||
// todo
|
||||
if payload.enable_self_startup.is_some() {
|
||||
verge.enable_self_startup = payload.enable_self_startup;
|
||||
}
|
||||
|
||||
// todo
|
||||
if payload.enable_system_proxy.is_some() {
|
||||
verge.enable_system_proxy = payload.enable_system_proxy;
|
||||
}
|
||||
|
||||
if payload.system_proxy_bypass.is_some() {
|
||||
verge.system_proxy_bypass = payload.system_proxy_bypass;
|
||||
}
|
||||
|
||||
save_verge(&verge)
|
||||
}
|
@ -1,30 +0,0 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// ### `config.yaml` schema
|
||||
/// here should contain all configuration options.
|
||||
/// See: https://github.com/Dreamacro/clash/wiki/configuration for details
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct ClashConfig {
|
||||
pub port: Option<u32>,
|
||||
|
||||
/// alias to `mixed-port`
|
||||
pub mixed_port: Option<u32>,
|
||||
|
||||
/// alias to `allow-lan`
|
||||
pub allow_lan: Option<bool>,
|
||||
|
||||
/// alias to `external-controller`
|
||||
pub external_ctrl: Option<String>,
|
||||
|
||||
pub secret: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct ClashController {
|
||||
/// clash core port
|
||||
pub port: Option<String>,
|
||||
|
||||
/// same as `external-controller`
|
||||
pub server: Option<String>,
|
||||
pub secret: Option<String>,
|
||||
}
|
118
src-tauri/src/config/field.rs
Normal file
@ -0,0 +1,118 @@
|
||||
use serde_yaml::{Mapping, Value};
|
||||
|
||||
pub const HANDLE_FIELDS: [&str; 9] = [
|
||||
"port",
|
||||
"socks-port",
|
||||
"mixed-port",
|
||||
"mode",
|
||||
"ipv6",
|
||||
"log-level",
|
||||
"allow-lan",
|
||||
"external-controller",
|
||||
"secret",
|
||||
];
|
||||
|
||||
pub const DEFAULT_FIELDS: [&str; 5] = [
|
||||
"proxies",
|
||||
"proxy-groups",
|
||||
"rules",
|
||||
"proxy-providers",
|
||||
"rule-providers",
|
||||
];
|
||||
|
||||
pub const OTHERS_FIELDS: [&str; 20] = [
|
||||
"tun",
|
||||
"dns",
|
||||
"ebpf",
|
||||
"hosts",
|
||||
"script",
|
||||
"profile",
|
||||
"payload",
|
||||
"auto-redir",
|
||||
"experimental",
|
||||
"interface-name",
|
||||
"routing-mark",
|
||||
"redir-port",
|
||||
"tproxy-port",
|
||||
"iptables",
|
||||
"external-ui",
|
||||
"bind-address",
|
||||
"authentication",
|
||||
"sniffer", // meta
|
||||
"geodata-mode", // meta
|
||||
"tcp-concurrent", // meta
|
||||
];
|
||||
|
||||
pub fn use_clash_fields() -> Vec<String> {
|
||||
DEFAULT_FIELDS
|
||||
.into_iter()
|
||||
.chain(HANDLE_FIELDS)
|
||||
.chain(OTHERS_FIELDS)
|
||||
.map(|s| s.to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn use_valid_fields(mut valid: Vec<String>) -> Vec<String> {
|
||||
let others = Vec::from(OTHERS_FIELDS);
|
||||
|
||||
valid.iter_mut().for_each(|s| s.make_ascii_lowercase());
|
||||
valid
|
||||
.into_iter()
|
||||
.filter(|s| others.contains(&s.as_str()))
|
||||
.chain(DEFAULT_FIELDS.iter().map(|s| s.to_string()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn use_filter(config: Mapping, filter: &Vec<String>) -> Mapping {
|
||||
let mut ret = Mapping::new();
|
||||
|
||||
for (key, value) in config.into_iter() {
|
||||
if let Some(key) = key.as_str() {
|
||||
if filter.contains(&key.to_string()) {
|
||||
ret.insert(Value::from(key), value);
|
||||
}
|
||||
}
|
||||
}
|
||||
ret
|
||||
}
|
||||
|
||||
pub fn use_lowercase(config: Mapping) -> Mapping {
|
||||
let mut ret = Mapping::new();
|
||||
|
||||
for (key, value) in config.into_iter() {
|
||||
if let Some(key_str) = key.as_str() {
|
||||
let mut key_str = String::from(key_str);
|
||||
key_str.make_ascii_lowercase();
|
||||
ret.insert(Value::from(key_str), value);
|
||||
}
|
||||
}
|
||||
ret
|
||||
}
|
||||
|
||||
pub fn use_sort(config: Mapping) -> Mapping {
|
||||
let mut ret = Mapping::new();
|
||||
|
||||
HANDLE_FIELDS
|
||||
.into_iter()
|
||||
.chain(OTHERS_FIELDS)
|
||||
.chain(DEFAULT_FIELDS)
|
||||
.for_each(|key| {
|
||||
let key = Value::from(key);
|
||||
config.get(&key).map(|value| {
|
||||
ret.insert(key, value.clone());
|
||||
});
|
||||
});
|
||||
ret
|
||||
}
|
||||
|
||||
pub fn use_keys(config: &Mapping) -> Vec<String> {
|
||||
config
|
||||
.iter()
|
||||
.filter_map(|(key, _)| key.as_str())
|
||||
.map(|s| {
|
||||
let mut s = s.to_string();
|
||||
s.make_ascii_lowercase();
|
||||
return s;
|
||||
})
|
||||
.collect()
|
||||
}
|
93
src-tauri/src/config/merge.rs
Normal file
@ -0,0 +1,93 @@
|
||||
use super::{use_filter, use_lowercase};
|
||||
use serde_yaml::{self, Mapping, Sequence, Value};
|
||||
|
||||
#[allow(unused)]
|
||||
const MERGE_FIELDS: [&str; 6] = [
|
||||
"prepend-rules",
|
||||
"append-rules",
|
||||
"prepend-proxies",
|
||||
"append-proxies",
|
||||
"prepend-proxy-groups",
|
||||
"append-proxy-groups",
|
||||
];
|
||||
|
||||
pub fn use_merge(merge: Mapping, mut config: Mapping) -> Mapping {
|
||||
// 直接覆盖原字段
|
||||
use_lowercase(merge.clone())
|
||||
.into_iter()
|
||||
.for_each(|(key, value)| {
|
||||
config.insert(key, value);
|
||||
});
|
||||
|
||||
let merge_list = MERGE_FIELDS.iter().map(|s| s.to_string());
|
||||
let merge = use_filter(merge, &merge_list.collect());
|
||||
|
||||
["rules", "proxies", "proxy-groups"]
|
||||
.iter()
|
||||
.for_each(|key_str| {
|
||||
let key_val = Value::from(key_str.to_string());
|
||||
|
||||
let mut list = Sequence::default();
|
||||
list = config.get(&key_val).map_or(list.clone(), |val| {
|
||||
val.as_sequence().map_or(list, |v| v.clone())
|
||||
});
|
||||
|
||||
let pre_key = Value::from(format!("prepend-{key_str}"));
|
||||
let post_key = Value::from(format!("append-{key_str}"));
|
||||
|
||||
if let Some(pre_val) = merge.get(&pre_key) {
|
||||
if pre_val.is_sequence() {
|
||||
let mut pre_val = pre_val.as_sequence().unwrap().clone();
|
||||
pre_val.extend(list);
|
||||
list = pre_val;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(post_val) = merge.get(&post_key) {
|
||||
if post_val.is_sequence() {
|
||||
list.extend(post_val.as_sequence().unwrap().clone());
|
||||
}
|
||||
}
|
||||
|
||||
config.insert(key_val, Value::from(list));
|
||||
});
|
||||
config
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_merge() -> anyhow::Result<()> {
|
||||
let merge = r"
|
||||
prepend-rules:
|
||||
- prepend
|
||||
- 1123123
|
||||
append-rules:
|
||||
- append
|
||||
prepend-proxies:
|
||||
- 9999
|
||||
append-proxies:
|
||||
- 1111
|
||||
rules:
|
||||
- replace
|
||||
proxy-groups:
|
||||
- 123781923810
|
||||
tun:
|
||||
enable: true
|
||||
dns:
|
||||
enable: true
|
||||
";
|
||||
|
||||
let config = r"
|
||||
rules:
|
||||
- aaaaa
|
||||
script1: test
|
||||
";
|
||||
|
||||
let merge = serde_yaml::from_str::<Mapping>(merge)?;
|
||||
let config = serde_yaml::from_str::<Mapping>(config)?;
|
||||
|
||||
let result = serde_yaml::to_string(&use_merge(merge, config))?;
|
||||
|
||||
println!("{result}");
|
||||
|
||||
Ok(())
|
||||
}
|
@ -1,7 +1,69 @@
|
||||
mod clash;
|
||||
mod profiles;
|
||||
mod verge;
|
||||
mod field;
|
||||
mod merge;
|
||||
mod script;
|
||||
mod tun;
|
||||
|
||||
pub use self::clash::*;
|
||||
pub use self::profiles::*;
|
||||
pub use self::verge::*;
|
||||
pub(self) use self::field::*;
|
||||
use self::merge::*;
|
||||
use self::script::*;
|
||||
use self::tun::*;
|
||||
use crate::core::ChainItem;
|
||||
use crate::core::ChainType;
|
||||
use serde_yaml::Mapping;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
|
||||
type ResultLog = Vec<(String, String)>;
|
||||
|
||||
pub fn enhance_config(
|
||||
clash_config: Mapping,
|
||||
profile_config: Mapping,
|
||||
chain: Vec<ChainItem>,
|
||||
valid: Vec<String>,
|
||||
tun_mode: bool,
|
||||
) -> (Mapping, Vec<String>, HashMap<String, ResultLog>) {
|
||||
let mut config = profile_config;
|
||||
let mut result_map = HashMap::new();
|
||||
let mut exists_keys = use_keys(&config);
|
||||
|
||||
let valid = use_valid_fields(valid);
|
||||
|
||||
chain.into_iter().for_each(|item| match item.data {
|
||||
ChainType::Merge(merge) => {
|
||||
exists_keys.extend(use_keys(&merge));
|
||||
config = use_merge(merge, config.to_owned());
|
||||
config = use_filter(config.to_owned(), &valid);
|
||||
}
|
||||
ChainType::Script(script) => {
|
||||
let mut logs = vec![];
|
||||
|
||||
match use_script(script, config.to_owned()) {
|
||||
Ok((res_config, res_logs)) => {
|
||||
exists_keys.extend(use_keys(&res_config));
|
||||
config = use_filter(res_config, &valid);
|
||||
logs.extend(res_logs);
|
||||
}
|
||||
Err(err) => logs.push(("exception".into(), err.to_string())),
|
||||
}
|
||||
|
||||
result_map.insert(item.uid, logs);
|
||||
}
|
||||
});
|
||||
|
||||
config = use_filter(config, &valid);
|
||||
|
||||
for (key, value) in clash_config.into_iter() {
|
||||
config.insert(key, value);
|
||||
}
|
||||
|
||||
let clash_fields = use_clash_fields();
|
||||
config = use_filter(config, &clash_fields);
|
||||
config = use_tun(config, tun_mode);
|
||||
config = use_sort(config);
|
||||
|
||||
let mut exists_set = HashSet::new();
|
||||
exists_set.extend(exists_keys.into_iter().filter(|s| clash_fields.contains(s)));
|
||||
exists_keys = exists_set.into_iter().collect();
|
||||
|
||||
(config, exists_keys, result_map)
|
||||
}
|
||||
|
@ -1,52 +0,0 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Define the `profiles.yaml` schema
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct ProfilesConfig {
|
||||
/// current profile's name
|
||||
pub current: Option<usize>,
|
||||
|
||||
/// profile list
|
||||
pub items: Option<Vec<ProfileItem>>,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct ProfileItem {
|
||||
/// profile name
|
||||
pub name: Option<String>,
|
||||
/// profile file
|
||||
pub file: Option<String>,
|
||||
/// current mode
|
||||
pub mode: Option<String>,
|
||||
/// source url
|
||||
pub url: Option<String>,
|
||||
/// selected infomation
|
||||
pub selected: Option<Vec<ProfileSelected>>,
|
||||
/// user info
|
||||
pub extra: Option<ProfileExtra>,
|
||||
/// updated time
|
||||
pub updated: Option<usize>,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct ProfileSelected {
|
||||
pub name: Option<String>,
|
||||
pub now: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Copy, Deserialize, Serialize)]
|
||||
pub struct ProfileExtra {
|
||||
pub upload: usize,
|
||||
pub download: usize,
|
||||
pub total: usize,
|
||||
pub expire: usize,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
/// the result from url
|
||||
pub struct ProfileResponse {
|
||||
pub name: String,
|
||||
pub file: String,
|
||||
pub data: String,
|
||||
pub extra: ProfileExtra,
|
||||
}
|
94
src-tauri/src/config/script.rs
Normal file
@ -0,0 +1,94 @@
|
||||
use super::use_lowercase;
|
||||
use anyhow::Result;
|
||||
use serde_yaml::Mapping;
|
||||
|
||||
pub fn use_script(script: String, config: Mapping) -> Result<(Mapping, Vec<(String, String)>)> {
|
||||
use rquickjs::{Context, Func, Runtime};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
let runtime = Runtime::new().unwrap();
|
||||
let context = Context::full(&runtime).unwrap();
|
||||
let outputs = Arc::new(Mutex::new(vec![]));
|
||||
|
||||
let copy_outputs = outputs.clone();
|
||||
let result = context.with(|ctx| -> Result<Mapping> {
|
||||
ctx.globals().set(
|
||||
"__verge_log__",
|
||||
Func::from(move |level: String, data: String| {
|
||||
let mut out = copy_outputs.lock().unwrap();
|
||||
out.push((level, data));
|
||||
}),
|
||||
)?;
|
||||
|
||||
ctx.eval(
|
||||
r#"var console = Object.freeze({
|
||||
log(data){__verge_log__("log",JSON.stringify(data))},
|
||||
info(data){__verge_log__("info",JSON.stringify(data))},
|
||||
error(data){__verge_log__("error",JSON.stringify(data))},
|
||||
debug(data){__verge_log__("debug",JSON.stringify(data))},
|
||||
});"#,
|
||||
)?;
|
||||
|
||||
let config = use_lowercase(config.clone());
|
||||
let config_str = serde_json::to_string(&config)?;
|
||||
|
||||
let code = format!(
|
||||
r#"try{{
|
||||
{script};
|
||||
JSON.stringify(main({config_str})||'')
|
||||
}} catch(err) {{
|
||||
`__error_flag__ ${{err.toString()}}`
|
||||
}}"#
|
||||
);
|
||||
let result: String = ctx.eval(code.as_str())?;
|
||||
if result.starts_with("__error_flag__") {
|
||||
anyhow::bail!(result[15..].to_owned());
|
||||
}
|
||||
if result == "\"\"" {
|
||||
anyhow::bail!("main function should return object");
|
||||
}
|
||||
return Ok(serde_json::from_str::<Mapping>(result.as_str())?);
|
||||
});
|
||||
|
||||
let mut out = outputs.lock().unwrap();
|
||||
match result {
|
||||
Ok(config) => Ok((use_lowercase(config), out.to_vec())),
|
||||
Err(err) => {
|
||||
out.push(("exception".into(), err.to_string()));
|
||||
Ok((config, out.to_vec()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_script() {
|
||||
let script = r#"
|
||||
function main(config) {
|
||||
if (Array.isArray(config.rules)) {
|
||||
config.rules = [...config.rules, "add"];
|
||||
}
|
||||
console.log(config);
|
||||
config.proxies = ["111"];
|
||||
return config;
|
||||
}
|
||||
"#;
|
||||
|
||||
let config = r#"
|
||||
rules:
|
||||
- 111
|
||||
- 222
|
||||
tun:
|
||||
enable: false
|
||||
dns:
|
||||
enable: false
|
||||
"#;
|
||||
|
||||
let config = serde_yaml::from_str(config).unwrap();
|
||||
let (config, results) = use_script(script.into(), config).unwrap();
|
||||
|
||||
let config_str = serde_yaml::to_string(&config).unwrap();
|
||||
|
||||
println!("{config_str}");
|
||||
|
||||
dbg!(results);
|
||||
}
|
81
src-tauri/src/config/tun.rs
Normal file
@ -0,0 +1,81 @@
|
||||
use serde_yaml::{Mapping, Value};
|
||||
|
||||
macro_rules! revise {
|
||||
($map: expr, $key: expr, $val: expr) => {
|
||||
let ret_key = Value::String($key.into());
|
||||
$map.insert(ret_key, Value::from($val));
|
||||
};
|
||||
}
|
||||
|
||||
// if key not exists then append value
|
||||
macro_rules! append {
|
||||
($map: expr, $key: expr, $val: expr) => {
|
||||
let ret_key = Value::String($key.into());
|
||||
if !$map.contains_key(&ret_key) {
|
||||
$map.insert(ret_key, Value::from($val));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub fn use_tun(mut config: Mapping, enable: bool) -> Mapping {
|
||||
let tun_key = Value::from("tun");
|
||||
let tun_val = config.get(&tun_key);
|
||||
|
||||
if !enable && tun_val.is_none() {
|
||||
return config;
|
||||
}
|
||||
|
||||
let mut tun_val = tun_val.map_or(Mapping::new(), |val| {
|
||||
val.as_mapping().cloned().unwrap_or(Mapping::new())
|
||||
});
|
||||
|
||||
revise!(tun_val, "enable", enable);
|
||||
if enable {
|
||||
append!(tun_val, "stack", "gvisor");
|
||||
append!(tun_val, "dns-hijack", vec!["198.18.0.2:53"]);
|
||||
append!(tun_val, "auto-route", true);
|
||||
append!(tun_val, "auto-detect-interface", true);
|
||||
}
|
||||
|
||||
revise!(config, "tun", tun_val);
|
||||
|
||||
if enable {
|
||||
use_dns_for_tun(config)
|
||||
} else {
|
||||
config
|
||||
}
|
||||
}
|
||||
|
||||
fn use_dns_for_tun(mut config: Mapping) -> Mapping {
|
||||
let dns_key = Value::from("dns");
|
||||
let dns_val = config.get(&dns_key);
|
||||
|
||||
let mut dns_val = dns_val.map_or(Mapping::new(), |val| {
|
||||
val.as_mapping().cloned().unwrap_or(Mapping::new())
|
||||
});
|
||||
|
||||
// 开启tun将同时开启dns
|
||||
revise!(dns_val, "enable", true);
|
||||
|
||||
// 借鉴cfw的默认配置
|
||||
append!(dns_val, "enhanced-mode", "fake-ip");
|
||||
append!(
|
||||
dns_val,
|
||||
"nameserver",
|
||||
vec!["114.114.114.114", "223.5.5.5", "8.8.8.8"]
|
||||
);
|
||||
append!(dns_val, "fallback", vec![] as Vec<&str>);
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
append!(
|
||||
dns_val,
|
||||
"fake-ip-filter",
|
||||
vec![
|
||||
"dns.msftncsi.com",
|
||||
"www.msftncsi.com",
|
||||
"www.msftconnecttest.com"
|
||||
]
|
||||
);
|
||||
revise!(config, "dns", dns_val);
|
||||
config
|
||||
}
|
@ -1,17 +0,0 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// ### `verge.yaml` schema
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct VergeConfig {
|
||||
/// `light` or `dark`
|
||||
pub theme_mode: Option<String>,
|
||||
|
||||
/// can the app auto startup
|
||||
pub enable_self_startup: Option<bool>,
|
||||
|
||||
/// set system proxy
|
||||
pub enable_system_proxy: Option<bool>,
|
||||
|
||||
/// set system proxy bypass
|
||||
pub system_proxy_bypass: Option<String>,
|
||||
}
|
166
src-tauri/src/core/clash.rs
Normal file
@ -0,0 +1,166 @@
|
||||
use crate::utils::{config, dirs};
|
||||
use anyhow::Result;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_yaml::{Mapping, Value};
|
||||
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct ClashInfo {
|
||||
/// clash sidecar status
|
||||
pub status: String,
|
||||
|
||||
/// clash core port
|
||||
pub port: Option<String>,
|
||||
|
||||
/// same as `external-controller`
|
||||
pub server: Option<String>,
|
||||
|
||||
/// clash secret
|
||||
pub secret: Option<String>,
|
||||
}
|
||||
|
||||
impl ClashInfo {
|
||||
/// parse the clash's config.yaml
|
||||
/// get some information
|
||||
pub fn from(config: &Mapping) -> ClashInfo {
|
||||
let key_port_1 = Value::from("mixed-port");
|
||||
let key_port_2 = Value::from("port");
|
||||
let key_server = Value::from("external-controller");
|
||||
let key_secret = Value::from("secret");
|
||||
|
||||
let mut status: u32 = 0;
|
||||
|
||||
let port = match config.get(&key_port_1) {
|
||||
Some(value) => match value {
|
||||
Value::String(val_str) => Some(val_str.clone()),
|
||||
Value::Number(val_num) => Some(val_num.to_string()),
|
||||
_ => {
|
||||
status |= 0b1;
|
||||
None
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
status |= 0b10;
|
||||
None
|
||||
}
|
||||
};
|
||||
let port = match port {
|
||||
Some(_) => port,
|
||||
None => match config.get(&key_port_2) {
|
||||
Some(value) => match value {
|
||||
Value::String(val_str) => Some(val_str.clone()),
|
||||
Value::Number(val_num) => Some(val_num.to_string()),
|
||||
_ => {
|
||||
status |= 0b100;
|
||||
None
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
status |= 0b1000;
|
||||
None
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
// `external-controller` could be
|
||||
// "127.0.0.1:9090" or ":9090"
|
||||
let server = match config.get(&key_server) {
|
||||
Some(value) => match value.as_str() {
|
||||
Some(val_str) => {
|
||||
if val_str.starts_with(":") {
|
||||
Some(format!("127.0.0.1{val_str}"))
|
||||
} else if val_str.starts_with("0.0.0.0:") {
|
||||
Some(format!("127.0.0.1:{}", &val_str[8..]))
|
||||
} else if val_str.starts_with("[::]:") {
|
||||
Some(format!("127.0.0.1:{}", &val_str[5..]))
|
||||
} else {
|
||||
Some(val_str.into())
|
||||
}
|
||||
}
|
||||
None => {
|
||||
status |= 0b10000;
|
||||
None
|
||||
}
|
||||
},
|
||||
None => {
|
||||
status |= 0b100000;
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
let secret = match config.get(&key_secret) {
|
||||
Some(value) => match value {
|
||||
Value::String(val_str) => Some(val_str.clone()),
|
||||
Value::Bool(val_bool) => Some(val_bool.to_string()),
|
||||
Value::Number(val_num) => Some(val_num.to_string()),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
|
||||
ClashInfo {
|
||||
status: format!("{status}"),
|
||||
port,
|
||||
server,
|
||||
secret,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Clash {
|
||||
/// maintain the clash config
|
||||
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 }
|
||||
}
|
||||
|
||||
/// get clash config
|
||||
pub fn read_config() -> Mapping {
|
||||
config::read_yaml::<Mapping>(dirs::clash_path())
|
||||
}
|
||||
|
||||
/// save the clash config
|
||||
pub fn save_config(&self) -> Result<()> {
|
||||
config::save_yaml(
|
||||
dirs::clash_path(),
|
||||
&self.config,
|
||||
Some("# Default Config For Clash Core\n\n"),
|
||||
)
|
||||
}
|
||||
|
||||
/// patch update the clash config
|
||||
/// if the port is changed then return true
|
||||
pub fn patch_config(&mut self, patch: Mapping) -> Result<()> {
|
||||
let port_key = Value::from("mixed-port");
|
||||
let server_key = Value::from("external-controller");
|
||||
let secret_key = Value::from("secret");
|
||||
|
||||
let change_info = patch.contains_key(&port_key)
|
||||
|| patch.contains_key(&server_key)
|
||||
|| patch.contains_key(&secret_key);
|
||||
|
||||
for (key, value) in patch.into_iter() {
|
||||
self.config.insert(key, value);
|
||||
}
|
||||
|
||||
if change_info {
|
||||
self.info = ClashInfo::from(&self.config);
|
||||
}
|
||||
|
||||
self.save_config()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Clash {
|
||||
fn default() -> Self {
|
||||
Clash::new()
|
||||
}
|
||||
}
|
387
src-tauri/src/core/mod.rs
Normal file
@ -0,0 +1,387 @@
|
||||
use self::notice::Notice;
|
||||
use self::sysopt::Sysopt;
|
||||
use self::timer::Timer;
|
||||
use crate::config::enhance_config;
|
||||
use crate::log_if_err;
|
||||
use anyhow::{bail, Result};
|
||||
use parking_lot::Mutex;
|
||||
use serde_yaml::Mapping;
|
||||
use serde_yaml::Value;
|
||||
use std::sync::Arc;
|
||||
use tauri::{AppHandle, Manager, Window};
|
||||
|
||||
mod clash;
|
||||
mod notice;
|
||||
mod prfitem;
|
||||
mod profiles;
|
||||
mod service;
|
||||
mod sysopt;
|
||||
mod timer;
|
||||
mod verge;
|
||||
|
||||
pub use self::clash::*;
|
||||
pub use self::prfitem::*;
|
||||
pub use self::profiles::*;
|
||||
pub use self::service::*;
|
||||
pub use self::verge::*;
|
||||
|
||||
#[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 runtime: Arc<Mutex<RuntimeResult>>,
|
||||
pub window: Arc<Mutex<Option<Window>>>,
|
||||
}
|
||||
|
||||
impl Core {
|
||||
pub fn new() -> Core {
|
||||
Core {
|
||||
clash: Arc::new(Mutex::new(Clash::new())),
|
||||
verge: Arc::new(Mutex::new(Verge::new())),
|
||||
profiles: Arc::new(Mutex::new(Profiles::new())),
|
||||
service: Arc::new(Mutex::new(Service::new())),
|
||||
sysopt: Arc::new(Mutex::new(Sysopt::new())),
|
||||
timer: Arc::new(Mutex::new(Timer::new())),
|
||||
runtime: Arc::new(Mutex::new(RuntimeResult::default())),
|
||||
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();
|
||||
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));
|
||||
log_if_err!(self.update_systray_clash(&app_handle));
|
||||
|
||||
// timer initialize
|
||||
let mut timer = self.timer.lock();
|
||||
timer.set_core(self.clone());
|
||||
log_if_err!(timer.restore());
|
||||
}
|
||||
|
||||
/// 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()
|
||||
}
|
||||
|
||||
/// 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()
|
||||
}
|
||||
|
||||
/// Patch Clash
|
||||
/// handle the clash config changed
|
||||
pub fn patch_clash(&self, patch: Mapping, app_handle: &AppHandle) -> Result<()> {
|
||||
let has_port = patch.contains_key(&Value::from("mixed-port"));
|
||||
let has_mode = patch.contains_key(&Value::from("mode"));
|
||||
|
||||
let port = {
|
||||
let mut clash = self.clash.lock();
|
||||
clash.patch_config(patch)?;
|
||||
clash.info.port.clone()
|
||||
};
|
||||
|
||||
// todo: port check
|
||||
if has_port && port.is_some() {
|
||||
let mut service = self.service.lock();
|
||||
service.restart()?;
|
||||
drop(service);
|
||||
|
||||
self.activate()?;
|
||||
|
||||
let mut sysopt = self.sysopt.lock();
|
||||
let verge = self.verge.lock();
|
||||
sysopt.init_sysproxy(port, &verge);
|
||||
}
|
||||
|
||||
if has_mode {
|
||||
self.update_systray_clash(app_handle)?;
|
||||
}
|
||||
|
||||
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)?;
|
||||
self.activate()?;
|
||||
}
|
||||
}
|
||||
|
||||
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 = crate::utils::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()?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// update system tray state (clash config)
|
||||
pub fn update_systray_clash(&self, app_handle: &AppHandle) -> Result<()> {
|
||||
let clash = self.clash.lock();
|
||||
let mode = clash
|
||||
.config
|
||||
.get(&Value::from("mode"))
|
||||
.map(|val| val.as_str().unwrap_or("rule"))
|
||||
.unwrap_or("rule");
|
||||
|
||||
let tray = app_handle.tray_handle();
|
||||
|
||||
tray.get_item("rule_mode").set_selected(mode == "rule")?;
|
||||
tray
|
||||
.get_item("global_mode")
|
||||
.set_selected(mode == "global")?;
|
||||
tray
|
||||
.get_item("direct_mode")
|
||||
.set_selected(mode == "direct")?;
|
||||
tray
|
||||
.get_item("script_mode")
|
||||
.set_selected(mode == "script")?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// update the system tray state (verge config)
|
||||
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(())
|
||||
}
|
||||
|
||||
// update rule/global/direct/script mode
|
||||
pub fn update_mode(&self, app_handle: &AppHandle, mode: &str) -> Result<()> {
|
||||
// save config to file
|
||||
let mut clash = self.clash.lock();
|
||||
clash.config.insert(Value::from("mode"), Value::from(mode));
|
||||
clash.save_config()?;
|
||||
|
||||
let info = clash.info.clone();
|
||||
drop(clash);
|
||||
|
||||
let notice = {
|
||||
let window = self.window.lock();
|
||||
Notice::from(window.clone())
|
||||
};
|
||||
|
||||
let mut mapping = Mapping::new();
|
||||
mapping.insert(Value::from("mode"), Value::from(mode));
|
||||
|
||||
let service = self.service.lock();
|
||||
service.patch_config(info, mapping, notice)?;
|
||||
|
||||
// update tray
|
||||
self.update_systray_clash(app_handle)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// activate the profile
|
||||
/// auto activate enhanced profile
|
||||
pub fn activate(&self) -> Result<()> {
|
||||
let profile_activate = {
|
||||
let profiles = self.profiles.lock();
|
||||
profiles.gen_activate()?
|
||||
};
|
||||
|
||||
let (clash_config, clash_info) = {
|
||||
let clash = self.clash.lock();
|
||||
(clash.config.clone(), clash.info.clone())
|
||||
};
|
||||
|
||||
let tun_mode = {
|
||||
let verge = self.verge.lock();
|
||||
verge.enable_tun_mode.unwrap_or(false)
|
||||
};
|
||||
|
||||
let (config, exists_keys, logs) = enhance_config(
|
||||
clash_config,
|
||||
profile_activate.current,
|
||||
profile_activate.chain,
|
||||
profile_activate.valid,
|
||||
tun_mode,
|
||||
);
|
||||
|
||||
let mut runtime = self.runtime.lock();
|
||||
runtime.config = Some(config.clone());
|
||||
runtime.config_yaml = Some(serde_yaml::to_string(&config).unwrap_or("".into()));
|
||||
runtime.exists_keys = exists_keys;
|
||||
runtime.chain_logs = logs;
|
||||
|
||||
let notice = {
|
||||
let window = self.window.lock();
|
||||
Notice::from(window.clone())
|
||||
};
|
||||
|
||||
let service = self.service.lock();
|
||||
service.set_config(clash_info, config, notice)
|
||||
}
|
||||
|
||||
/// Static function
|
||||
/// update profile item
|
||||
pub async fn update_profile_item(&self, uid: String, option: Option<PrfOption>) -> Result<()> {
|
||||
let (url, opt) = {
|
||||
let profiles = self.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 self.activate();
|
||||
}
|
||||
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 = self.profiles.lock();
|
||||
profiles.update_item(uid.clone(), item)?;
|
||||
|
||||
// reactivate the profile
|
||||
if Some(uid) == profiles.get_current() {
|
||||
drop(profiles);
|
||||
self.activate()?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
37
src-tauri/src/core/notice.rs
Normal file
@ -0,0 +1,37 @@
|
||||
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 }
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
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"));
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
pub fn refresh_profiles(&self) {
|
||||
if let Some(window) = self.win.as_ref() {
|
||||
log_if_err!(window.emit("verge://refresh-profiles-config", "yes"));
|
||||
}
|
||||
}
|
||||
}
|
372
src-tauri/src/core/prfitem.rs
Normal file
@ -0,0 +1,372 @@
|
||||
use crate::utils::{config, 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")
|
||||
}
|
||||
|
||||
/// get the data for enhanced mode
|
||||
pub fn to_enhance(&self) -> Option<ChainItem> {
|
||||
let itype = self.itype.as_ref()?.as_str();
|
||||
let file = self.file.clone()?;
|
||||
let uid = self.uid.clone().unwrap_or("".into());
|
||||
let path = dirs::app_profiles_dir().join(file);
|
||||
|
||||
if !path.exists() {
|
||||
return None;
|
||||
}
|
||||
|
||||
match itype {
|
||||
"script" => Some(ChainItem {
|
||||
uid,
|
||||
data: ChainType::Script(fs::read_to_string(path).unwrap_or("".into())),
|
||||
}),
|
||||
"merge" => Some(ChainItem {
|
||||
uid,
|
||||
data: ChainType::Merge(config::read_yaml::<Mapping>(path)),
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ChainItem {
|
||||
pub uid: String,
|
||||
pub data: ChainType,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum ChainType {
|
||||
Merge(Mapping),
|
||||
Script(String),
|
||||
}
|
328
src-tauri/src/core/profiles.rs
Normal file
@ -0,0 +1,328 @@
|
||||
use super::prfitem::PrfItem;
|
||||
use super::ChainItem;
|
||||
use crate::utils::{config, dirs, help};
|
||||
use anyhow::{bail, Context, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_yaml::Mapping;
|
||||
use std::collections::HashMap;
|
||||
use std::{fs, io::Write};
|
||||
|
||||
///
|
||||
/// ## Profiles Config
|
||||
///
|
||||
/// Define the `profiles.yaml` schema
|
||||
///
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct Profiles {
|
||||
/// same as PrfConfig.current
|
||||
current: Option<String>,
|
||||
|
||||
/// same as PrfConfig.chain
|
||||
chain: Option<Vec<String>>,
|
||||
|
||||
/// record valid fields for clash
|
||||
valid: Option<Vec<String>>,
|
||||
|
||||
/// profile list
|
||||
items: Option<Vec<PrfItem>>,
|
||||
}
|
||||
|
||||
macro_rules! patch {
|
||||
($lv: expr, $rv: expr, $key: tt) => {
|
||||
if ($rv.$key).is_some() {
|
||||
$lv.$key = $rv.$key;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
impl Profiles {
|
||||
pub fn new() -> Self {
|
||||
Profiles::read_file()
|
||||
}
|
||||
|
||||
/// read the config from the file
|
||||
pub fn read_file() -> Self {
|
||||
let mut profiles = config::read_yaml::<Self>(dirs::profiles_path());
|
||||
|
||||
if profiles.items.is_none() {
|
||||
profiles.items = Some(vec![]);
|
||||
}
|
||||
|
||||
// compatiable with the old old old version
|
||||
profiles.items.as_mut().map(|items| {
|
||||
for mut item in items.iter_mut() {
|
||||
if item.uid.is_none() {
|
||||
item.uid = Some(help::get_uid("d"));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
profiles
|
||||
}
|
||||
|
||||
/// save the config to the file
|
||||
pub fn save_file(&self) -> Result<()> {
|
||||
config::save_yaml(
|
||||
dirs::profiles_path(),
|
||||
self,
|
||||
Some("# Profiles Config for Clash Verge\n\n"),
|
||||
)
|
||||
}
|
||||
|
||||
/// get the current uid
|
||||
pub fn get_current(&self) -> Option<String> {
|
||||
self.current.clone()
|
||||
}
|
||||
|
||||
/// only change the main to the target id
|
||||
pub fn put_current(&mut self, uid: String) -> Result<()> {
|
||||
if self.items.is_none() {
|
||||
self.items = Some(vec![]);
|
||||
}
|
||||
|
||||
let items = self.items.as_ref().unwrap();
|
||||
let some_uid = Some(uid.clone());
|
||||
|
||||
if items.iter().find(|&each| each.uid == some_uid).is_some() {
|
||||
self.current = some_uid;
|
||||
return self.save_file();
|
||||
}
|
||||
|
||||
bail!("invalid uid \"{uid}\"");
|
||||
}
|
||||
|
||||
/// just change the `chain`
|
||||
pub fn put_chain(&mut self, chain: Option<Vec<String>>) -> Result<()> {
|
||||
self.chain = chain;
|
||||
self.save_file()
|
||||
}
|
||||
|
||||
/// just change the `field`
|
||||
pub fn put_valid(&mut self, valid: Option<Vec<String>>) -> Result<()> {
|
||||
self.valid = valid;
|
||||
self.save_file()
|
||||
}
|
||||
|
||||
/// get items ref
|
||||
pub fn get_items(&self) -> Option<&Vec<PrfItem>> {
|
||||
self.items.as_ref()
|
||||
}
|
||||
|
||||
/// find the item by the uid
|
||||
pub fn get_item(&self, uid: &String) -> Result<&PrfItem> {
|
||||
if self.items.is_some() {
|
||||
let items = self.items.as_ref().unwrap();
|
||||
let some_uid = Some(uid.clone());
|
||||
|
||||
for each in items.iter() {
|
||||
if each.uid == some_uid {
|
||||
return Ok(each);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bail!("failed to get the profile item \"uid:{uid}\"");
|
||||
}
|
||||
|
||||
/// append new item
|
||||
/// if the file_data is some
|
||||
/// then should save the data to file
|
||||
pub fn append_item(&mut self, mut item: PrfItem) -> Result<()> {
|
||||
if item.uid.is_none() {
|
||||
bail!("the uid should not be null");
|
||||
}
|
||||
|
||||
// save the file data
|
||||
// move the field value after save
|
||||
if let Some(file_data) = item.file_data.take() {
|
||||
if item.file.is_none() {
|
||||
bail!("the file should not be null");
|
||||
}
|
||||
|
||||
let file = item.file.clone().unwrap();
|
||||
let path = dirs::app_profiles_dir().join(&file);
|
||||
|
||||
fs::File::create(path)
|
||||
.context(format!("failed to create file \"{}\"", file))?
|
||||
.write(file_data.as_bytes())
|
||||
.context(format!("failed to write to file \"{}\"", file))?;
|
||||
}
|
||||
|
||||
if self.items.is_none() {
|
||||
self.items = Some(vec![]);
|
||||
}
|
||||
|
||||
self.items.as_mut().map(|items| items.push(item));
|
||||
self.save_file()
|
||||
}
|
||||
|
||||
/// update the item value
|
||||
pub fn patch_item(&mut self, uid: String, item: PrfItem) -> Result<()> {
|
||||
let mut items = self.items.take().unwrap_or(vec![]);
|
||||
|
||||
for mut each in items.iter_mut() {
|
||||
if each.uid == Some(uid.clone()) {
|
||||
patch!(each, item, itype);
|
||||
patch!(each, item, name);
|
||||
patch!(each, item, desc);
|
||||
patch!(each, item, file);
|
||||
patch!(each, item, url);
|
||||
patch!(each, item, selected);
|
||||
patch!(each, item, extra);
|
||||
patch!(each, item, updated);
|
||||
patch!(each, item, option);
|
||||
|
||||
self.items = Some(items);
|
||||
return self.save_file();
|
||||
}
|
||||
}
|
||||
|
||||
self.items = Some(items);
|
||||
bail!("failed to find the profile item \"uid:{uid}\"")
|
||||
}
|
||||
|
||||
/// be used to update the remote item
|
||||
/// only patch `updated` `extra` `file_data`
|
||||
pub fn update_item(&mut self, uid: String, mut item: PrfItem) -> Result<()> {
|
||||
if self.items.is_none() {
|
||||
self.items = Some(vec![]);
|
||||
}
|
||||
|
||||
// find the item
|
||||
let _ = self.get_item(&uid)?;
|
||||
|
||||
if let Some(items) = self.items.as_mut() {
|
||||
let some_uid = Some(uid.clone());
|
||||
|
||||
for mut each in items.iter_mut() {
|
||||
if each.uid == some_uid {
|
||||
each.extra = item.extra;
|
||||
each.updated = item.updated;
|
||||
|
||||
// save the file data
|
||||
// move the field value after save
|
||||
if let Some(file_data) = item.file_data.take() {
|
||||
let file = each.file.take();
|
||||
let file = file.unwrap_or(item.file.take().unwrap_or(format!("{}.yaml", &uid)));
|
||||
|
||||
// the file must exists
|
||||
each.file = Some(file.clone());
|
||||
|
||||
let path = dirs::app_profiles_dir().join(&file);
|
||||
|
||||
fs::File::create(path)
|
||||
.context(format!("failed to create file \"{}\"", file))?
|
||||
.write(file_data.as_bytes())
|
||||
.context(format!("failed to write to file \"{}\"", file))?;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.save_file()
|
||||
}
|
||||
|
||||
/// delete item
|
||||
/// if delete the current then return true
|
||||
pub fn delete_item(&mut self, uid: String) -> Result<bool> {
|
||||
let current = self.current.as_ref().unwrap_or(&uid);
|
||||
let current = current.clone();
|
||||
|
||||
let mut items = self.items.take().unwrap_or(vec![]);
|
||||
let mut index = None;
|
||||
|
||||
// get the index
|
||||
for i in 0..items.len() {
|
||||
if items[i].uid == Some(uid.clone()) {
|
||||
index = Some(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(index) = index {
|
||||
items.remove(index).file.map(|file| {
|
||||
let path = dirs::app_profiles_dir().join(file);
|
||||
if path.exists() {
|
||||
let _ = fs::remove_file(path);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// delete the original uid
|
||||
if current == uid {
|
||||
self.current = match items.len() > 0 {
|
||||
true => items[0].uid.clone(),
|
||||
false => None,
|
||||
};
|
||||
}
|
||||
|
||||
self.items = Some(items);
|
||||
self.save_file()?;
|
||||
Ok(current == uid)
|
||||
}
|
||||
|
||||
/// generate the current Mapping data
|
||||
fn gen_current(&self) -> Result<Mapping> {
|
||||
let config = Mapping::new();
|
||||
|
||||
if self.current.is_none() || self.items.is_none() {
|
||||
return Ok(config);
|
||||
}
|
||||
|
||||
let current = self.current.clone().unwrap();
|
||||
for item in self.items.as_ref().unwrap().iter() {
|
||||
if item.uid == Some(current.clone()) {
|
||||
let file_path = match item.file.clone() {
|
||||
Some(file) => dirs::app_profiles_dir().join(file),
|
||||
None => bail!("failed to get the file field"),
|
||||
};
|
||||
|
||||
if !file_path.exists() {
|
||||
bail!("failed to read the file \"{}\"", file_path.display());
|
||||
}
|
||||
|
||||
return Ok(config::read_yaml::<Mapping>(file_path.clone()));
|
||||
}
|
||||
}
|
||||
bail!("failed to find current profile \"uid:{current}\"");
|
||||
}
|
||||
|
||||
/// generate the data for activate clash config
|
||||
pub fn gen_activate(&self) -> Result<PrfActivate> {
|
||||
let current = self.gen_current()?;
|
||||
let chain = match self.chain.as_ref() {
|
||||
Some(chain) => chain
|
||||
.iter()
|
||||
.filter_map(|uid| self.get_item(uid).ok())
|
||||
.filter_map(|item| item.to_enhance())
|
||||
.collect::<Vec<ChainItem>>(),
|
||||
None => vec![],
|
||||
};
|
||||
let valid = self.valid.clone().unwrap_or(vec![]);
|
||||
|
||||
Ok(PrfActivate {
|
||||
current,
|
||||
chain,
|
||||
valid,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
pub struct PrfActivate {
|
||||
pub current: Mapping,
|
||||
pub chain: Vec<ChainItem>,
|
||||
pub valid: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct RuntimeResult {
|
||||
pub config: Option<Mapping>,
|
||||
pub config_yaml: Option<String>,
|
||||
// 记录在配置中(包括merge和script生成的)出现过的keys
|
||||
// 这些keys不一定都生效
|
||||
pub exists_keys: Vec<String>,
|
||||
pub chain_logs: HashMap<String, Vec<(String, String)>>,
|
||||
}
|
442
src-tauri/src/core/service.rs
Normal file
@ -0,0 +1,442 @@
|
||||
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_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 {
|
||||
log_if_err!(Self::start_clash_by_service().await);
|
||||
}
|
||||
}
|
||||
Err(err) => log::error!(target: "app", "{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 {
|
||||
log_if_err!(Self::stop_clash_by_service().await);
|
||||
});
|
||||
|
||||
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) => {
|
||||
let stdout = if line.len() > 33 { &line[33..] } else { &line };
|
||||
log::info!(target: "app" ,"[clash]: {}", stdout);
|
||||
}
|
||||
CommandEvent::Stderr(err) => log::error!(target: "app" ,"[clash error]: {}", 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"))?;
|
||||
|
||||
let (server, headers) = Self::clash_client_info(info)?;
|
||||
|
||||
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!(target: "app", "failed to activate clash with status \"{}\"", resp.status());
|
||||
}
|
||||
|
||||
notice.refresh_clash();
|
||||
|
||||
// do not retry
|
||||
break;
|
||||
}
|
||||
Err(err) => log::error!(target: "app", "failed to activate for `{err}`"),
|
||||
}
|
||||
}
|
||||
Err(err) => log::error!(target: "app", "failed to activate for `{err}`"),
|
||||
}
|
||||
sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// patch clash config
|
||||
pub fn patch_config(&self, info: ClashInfo, config: Mapping, notice: Notice) -> Result<()> {
|
||||
if !self.service_mode && self.sidecar.is_none() {
|
||||
bail!("did not start sidecar");
|
||||
}
|
||||
|
||||
let (server, headers) = Self::clash_client_info(info)?;
|
||||
|
||||
tauri::async_runtime::spawn(async move {
|
||||
if let Ok(client) = reqwest::ClientBuilder::new().no_proxy().build() {
|
||||
let builder = client.patch(&server).headers(headers.clone()).json(&config);
|
||||
|
||||
match builder.send().await {
|
||||
Ok(_) => notice.refresh_clash(),
|
||||
Err(err) => log::error!(target: "app", "{err}"),
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// get clash client url and headers from clash info
|
||||
fn clash_client_info(info: ClashInfo) -> Result<(String, HeaderMap)> {
|
||||
if info.server.is_none() {
|
||||
let status = &info.status;
|
||||
if info.port.is_none() {
|
||||
bail!("failed to parse config.yaml file with status {status}");
|
||||
} else {
|
||||
bail!("failed to parse the server with status {status}");
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
Ok((server, headers))
|
||||
}
|
||||
}
|
||||
|
||||
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 serde::{Deserialize, Serialize};
|
||||
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(())
|
||||
}
|
||||
}
|
||||
}
|
215
src-tauri/src/core/sysopt.rs
Normal file
@ -0,0 +1,215 @@
|
||||
use super::{Clash, Verge};
|
||||
use crate::{log_if_err, utils::sysopt::SysProxyConfig};
|
||||
use anyhow::{bail, Result};
|
||||
use auto_launch::{AutoLaunch, AutoLaunchBuilder};
|
||||
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!(target: "app", "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() {
|
||||
// 如果原代理设置是开启的,且域名端口设置和当前的一致,就不恢复原设置
|
||||
// https://github.com/zzzgydi/clash-verge/issues/157
|
||||
if let Some(cur) = self.cur_sysproxy.as_ref() {
|
||||
if sysproxy.enable && cur.server == sysproxy.server {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
match sysproxy.set_sys() {
|
||||
Ok(_) => self.cur_sysproxy = None,
|
||||
Err(_) => log::error!(target: "app", "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!(target: "app", "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 => {
|
||||
let status = &clash.info.status;
|
||||
log::error!(target: "app", "failed to parse clash port with status {status}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut state = guard_state.lock().await;
|
||||
*state = false;
|
||||
});
|
||||
}
|
||||
}
|
181
src-tauri/src/core/timer.rs
Normal file
@ -0,0 +1,181 @@
|
||||
use super::Core;
|
||||
use crate::log_if_err;
|
||||
use crate::utils::help::get_now;
|
||||
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(())
|
||||
}
|
||||
|
||||
/// restore timer
|
||||
pub fn restore(&mut self) -> Result<()> {
|
||||
self.refresh()?;
|
||||
|
||||
let cur_timestamp = get_now(); // seconds
|
||||
let profiles = self.core.as_ref().unwrap().profiles.lock();
|
||||
|
||||
profiles
|
||||
.get_items()
|
||||
.unwrap_or(&vec![])
|
||||
.iter()
|
||||
.filter(|item| item.uid.is_some() && item.updated.is_some() && item.option.is_some())
|
||||
.filter(|item| {
|
||||
// mins to seconds
|
||||
let interval = item.option.as_ref().unwrap().update_interval.unwrap_or(0) as usize * 60;
|
||||
let updated = item.updated.unwrap();
|
||||
return interval > 0 && cur_timestamp - updated >= interval;
|
||||
})
|
||||
.for_each(|item| {
|
||||
let uid = item.uid.as_ref().unwrap();
|
||||
if let Some((task_id, _)) = self.timer_map.get(uid) {
|
||||
log_if_err!(self.delay_timer.advance_task(*task_id));
|
||||
}
|
||||
});
|
||||
|
||||
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!(target: "app", "running timer task `{uid}`");
|
||||
log_if_err!(core.update_profile_item(uid, None).await);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum DiffFlag {
|
||||
Del(TaskID),
|
||||
Add(TaskID, u64),
|
||||
Mod(TaskID, u64),
|
||||
}
|
118
src-tauri/src/core/verge.rs
Normal file
@ -0,0 +1,118 @@
|
||||
use crate::utils::{config, dirs};
|
||||
use anyhow::Result;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// ### `verge.yaml` schema
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct Verge {
|
||||
// i18n
|
||||
pub language: Option<String>,
|
||||
|
||||
/// `light` or `dark`
|
||||
pub theme_mode: Option<String>,
|
||||
|
||||
/// enable blur mode
|
||||
/// maybe be able to set the alpha
|
||||
pub theme_blur: Option<bool>,
|
||||
|
||||
/// enable traffic graph default is true
|
||||
pub traffic_graph: Option<bool>,
|
||||
|
||||
/// clash tun mode
|
||||
pub enable_tun_mode: Option<bool>,
|
||||
|
||||
/// windows service mode
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub enable_service_mode: Option<bool>,
|
||||
|
||||
/// can the app auto startup
|
||||
pub enable_auto_launch: Option<bool>,
|
||||
|
||||
/// not show the window on launch
|
||||
pub enable_silent_start: Option<bool>,
|
||||
|
||||
/// set system proxy
|
||||
pub enable_system_proxy: Option<bool>,
|
||||
|
||||
/// enable proxy guard
|
||||
pub enable_proxy_guard: Option<bool>,
|
||||
|
||||
/// set system proxy bypass
|
||||
pub system_proxy_bypass: Option<String>,
|
||||
|
||||
/// proxy guard duration
|
||||
pub proxy_guard_duration: Option<u64>,
|
||||
|
||||
/// theme setting
|
||||
pub theme_setting: Option<VergeTheme>,
|
||||
|
||||
/// web ui list
|
||||
pub web_ui_list: Option<Vec<String>>,
|
||||
|
||||
/// clash core path
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub clash_core: Option<String>,
|
||||
}
|
||||
|
||||
#[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 {
|
||||
config::read_yaml::<Verge>(dirs::verge_path())
|
||||
}
|
||||
|
||||
/// Save Verge App Config
|
||||
pub fn save_file(&self) -> Result<()> {
|
||||
config::save_yaml(
|
||||
dirs::verge_path(),
|
||||
self,
|
||||
Some("# The Config for Clash Verge App\n\n"),
|
||||
)
|
||||
}
|
||||
|
||||
/// patch verge config
|
||||
/// only save to file
|
||||
pub fn patch_config(&mut self, patch: Verge) -> Result<()> {
|
||||
macro_rules! patch {
|
||||
($key: tt) => {
|
||||
if patch.$key.is_some() {
|
||||
self.$key = patch.$key;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
patch!(language);
|
||||
patch!(theme_mode);
|
||||
patch!(theme_blur);
|
||||
patch!(traffic_graph);
|
||||
|
||||
patch!(enable_tun_mode);
|
||||
patch!(enable_service_mode);
|
||||
patch!(enable_auto_launch);
|
||||
patch!(enable_silent_start);
|
||||
patch!(enable_system_proxy);
|
||||
patch!(enable_proxy_guard);
|
||||
patch!(system_proxy_bypass);
|
||||
patch!(proxy_guard_duration);
|
||||
|
||||
patch!(theme_setting);
|
||||
patch!(web_ui_list);
|
||||
patch!(clash_core);
|
||||
|
||||
self.save_file()
|
||||
}
|
||||
}
|
@ -1,26 +0,0 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tauri::{AppHandle, Manager};
|
||||
|
||||
use crate::config::ClashController;
|
||||
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct ClashInfoPayload {
|
||||
/// value between `success` and `error`
|
||||
pub status: String,
|
||||
|
||||
/// the clash core's external controller infomation
|
||||
pub controller: Option<ClashController>,
|
||||
|
||||
/// some message
|
||||
pub message: Option<String>,
|
||||
}
|
||||
|
||||
/// emit `clash_runtime` to the main windows
|
||||
pub fn clash_start(app_handle: &AppHandle, payload: &ClashInfoPayload) {
|
||||
match app_handle.get_window("main") {
|
||||
Some(main_win) => {
|
||||
main_win.emit("clash_start", payload).unwrap();
|
||||
}
|
||||
_ => {}
|
||||
};
|
||||
}
|
@ -1,2 +0,0 @@
|
||||
pub mod emit;
|
||||
pub mod state;
|
@ -1,16 +0,0 @@
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use super::emit::ClashInfoPayload;
|
||||
use crate::{config::VergeConfig, utils::sysopt::SysProxyConfig};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct ClashInfoState(pub Arc<Mutex<ClashInfoPayload>>);
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct ProfileLock(pub Mutex<bool>);
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct VergeConfLock(pub Arc<Mutex<VergeConfig>>);
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct SomthingState(pub Arc<Mutex<Option<SysProxyConfig>>>);
|
@ -3,15 +3,13 @@
|
||||
windows_subsystem = "windows"
|
||||
)]
|
||||
|
||||
extern crate tauri;
|
||||
|
||||
mod cmds;
|
||||
mod config;
|
||||
mod events;
|
||||
mod core;
|
||||
mod utils;
|
||||
|
||||
use crate::{
|
||||
events::state,
|
||||
core::Verge,
|
||||
utils::{resolve, server},
|
||||
};
|
||||
use tauri::{
|
||||
@ -24,65 +22,165 @@ fn main() -> std::io::Result<()> {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let menu = SystemTrayMenu::new()
|
||||
.add_item(CustomMenuItem::new("open_window", "显示应用"))
|
||||
.add_native_item(SystemTrayMenuItem::Separator)
|
||||
.add_item(CustomMenuItem::new("quit", "退出").accelerator("CmdOrControl+Q"));
|
||||
#[cfg(target_os = "windows")]
|
||||
unsafe {
|
||||
use crate::utils::dirs;
|
||||
|
||||
tauri::Builder::default()
|
||||
.manage(state::VergeConfLock::default())
|
||||
.manage(state::ClashInfoState::default())
|
||||
.manage(state::SomthingState::default())
|
||||
.manage(state::ProfileLock::default())
|
||||
dirs::init_portable_flag();
|
||||
}
|
||||
|
||||
let tray_menu = SystemTrayMenu::new()
|
||||
.add_item(CustomMenuItem::new("open_window", "Show"))
|
||||
.add_native_item(SystemTrayMenuItem::Separator)
|
||||
.add_item(CustomMenuItem::new("rule_mode", "Rule Mode"))
|
||||
.add_item(CustomMenuItem::new("global_mode", "Global Mode"))
|
||||
.add_item(CustomMenuItem::new("direct_mode", "Direct Mode"))
|
||||
.add_item(CustomMenuItem::new("script_mode", "Script Mode"))
|
||||
.add_native_item(SystemTrayMenuItem::Separator)
|
||||
.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_app", "Restart App"))
|
||||
.add_native_item(SystemTrayMenuItem::Separator)
|
||||
.add_item(CustomMenuItem::new("quit", "Quit").accelerator("CmdOrControl+Q"));
|
||||
|
||||
#[allow(unused_mut)]
|
||||
let mut builder = tauri::Builder::default()
|
||||
.setup(|app| Ok(resolve::resolve_setup(app)))
|
||||
.system_tray(SystemTray::new().with_menu(menu))
|
||||
.system_tray(SystemTray::new().with_menu(tray_menu))
|
||||
.on_system_tray_event(move |app_handle, event| match event {
|
||||
SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() {
|
||||
"open_window" => {
|
||||
let window = app_handle.get_window("main").unwrap();
|
||||
window.show().unwrap();
|
||||
window.set_focus().unwrap();
|
||||
resolve::create_window(app_handle);
|
||||
}
|
||||
mode @ ("rule_mode" | "global_mode" | "direct_mode" | "script_mode") => {
|
||||
let mode = &mode[0..mode.len() - 5];
|
||||
let core = app_handle.state::<core::Core>();
|
||||
crate::log_if_err!(core.update_mode(app_handle, mode));
|
||||
}
|
||||
"system_proxy" => {
|
||||
let core = app_handle.state::<core::Core>();
|
||||
|
||||
let new_value = {
|
||||
let verge = core.verge.lock();
|
||||
!verge.enable_system_proxy.clone().unwrap_or(false)
|
||||
};
|
||||
|
||||
let patch = Verge {
|
||||
enable_system_proxy: Some(new_value),
|
||||
..Verge::default()
|
||||
};
|
||||
|
||||
crate::log_if_err!(core.patch_verge(patch, app_handle));
|
||||
}
|
||||
"tun_mode" => {
|
||||
let core = app_handle.state::<core::Core>();
|
||||
|
||||
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" => {
|
||||
let core = app_handle.state::<core::Core>();
|
||||
crate::log_if_err!(core.restart_clash());
|
||||
}
|
||||
"restart_app" => {
|
||||
api::process::restart(&app_handle.env());
|
||||
}
|
||||
"quit" => {
|
||||
api::process::kill_children();
|
||||
resolve::resolve_reset(app_handle);
|
||||
app_handle.exit(0);
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
#[cfg(target_os = "windows")]
|
||||
SystemTrayEvent::LeftClick { .. } => {
|
||||
let window = app_handle.get_window("main").unwrap();
|
||||
window.show().unwrap();
|
||||
window.set_focus().unwrap();
|
||||
resolve::create_window(app_handle);
|
||||
}
|
||||
_ => {}
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
cmds::some::restart_sidecar,
|
||||
cmds::some::set_sys_proxy,
|
||||
cmds::some::get_sys_proxy,
|
||||
cmds::some::get_clash_info,
|
||||
cmds::some::patch_clash_config,
|
||||
cmds::some::get_verge_config,
|
||||
cmds::some::patch_verge_config,
|
||||
cmds::profile::import_profile,
|
||||
cmds::profile::update_profile,
|
||||
cmds::profile::get_profiles,
|
||||
cmds::profile::set_profiles,
|
||||
cmds::profile::put_profiles,
|
||||
])
|
||||
.build(tauri::generate_context!())
|
||||
// common
|
||||
cmds::get_sys_proxy,
|
||||
cmds::get_cur_proxy,
|
||||
cmds::open_app_dir,
|
||||
cmds::open_logs_dir,
|
||||
cmds::open_web_url,
|
||||
cmds::kill_sidecar,
|
||||
cmds::restart_sidecar,
|
||||
// clash
|
||||
cmds::get_clash_info,
|
||||
cmds::patch_clash_config,
|
||||
cmds::change_clash_core,
|
||||
cmds::get_runtime_config,
|
||||
cmds::get_runtime_yaml,
|
||||
cmds::get_runtime_exists,
|
||||
cmds::get_runtime_logs,
|
||||
// verge
|
||||
cmds::get_verge_config,
|
||||
cmds::patch_verge_config,
|
||||
// profile
|
||||
cmds::view_profile,
|
||||
cmds::patch_profile,
|
||||
cmds::create_profile,
|
||||
cmds::import_profile,
|
||||
cmds::update_profile,
|
||||
cmds::delete_profile,
|
||||
cmds::select_profile,
|
||||
cmds::get_profiles,
|
||||
cmds::enhance_profiles,
|
||||
cmds::change_profile_chain,
|
||||
cmds::change_profile_valid,
|
||||
cmds::read_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")]
|
||||
{
|
||||
use tauri::{Menu, MenuItem, Submenu};
|
||||
|
||||
let submenu_file = Submenu::new(
|
||||
"File",
|
||||
Menu::new()
|
||||
.add_native_item(MenuItem::Undo)
|
||||
.add_native_item(MenuItem::Redo)
|
||||
.add_native_item(MenuItem::Copy)
|
||||
.add_native_item(MenuItem::Paste)
|
||||
.add_native_item(MenuItem::Cut)
|
||||
.add_native_item(MenuItem::SelectAll),
|
||||
);
|
||||
builder = builder.menu(Menu::new().add_submenu(submenu_file));
|
||||
}
|
||||
|
||||
let mut context = tauri::generate_context!();
|
||||
let verge = Verge::new();
|
||||
for win in context.config_mut().tauri.windows.iter_mut() {
|
||||
if verge.enable_silent_start.unwrap_or(false) {
|
||||
win.visible = false;
|
||||
}
|
||||
}
|
||||
builder
|
||||
.build(context)
|
||||
.expect("error while running tauri application")
|
||||
.run(|app_handle, e| match e {
|
||||
tauri::Event::CloseRequested { label, api, .. } => {
|
||||
let app_handle = app_handle.clone();
|
||||
api.prevent_close();
|
||||
app_handle.get_window(&label).unwrap().hide().unwrap();
|
||||
}
|
||||
tauri::Event::ExitRequested { api, .. } => {
|
||||
tauri::RunEvent::ExitRequested { api, .. } => {
|
||||
api.prevent_exit();
|
||||
}
|
||||
tauri::Event::Exit => {
|
||||
tauri::RunEvent::Exit => {
|
||||
resolve::resolve_reset(app_handle);
|
||||
api::process::kill_children();
|
||||
}
|
||||
|
@ -1,150 +0,0 @@
|
||||
extern crate log;
|
||||
|
||||
use crate::{
|
||||
events::emit::{clash_start, ClashInfoPayload},
|
||||
utils::{
|
||||
app_home_dir,
|
||||
config::{read_clash_controller, read_profiles, read_yaml, save_yaml},
|
||||
},
|
||||
};
|
||||
use reqwest::header::HeaderMap;
|
||||
use serde_yaml::{Mapping, Value};
|
||||
use std::{collections::HashMap, env::temp_dir};
|
||||
use tauri::{
|
||||
api::process::{Command, CommandEvent},
|
||||
AppHandle,
|
||||
};
|
||||
|
||||
/// Run the clash bin
|
||||
pub fn run_clash_bin(app_handle: &AppHandle) -> ClashInfoPayload {
|
||||
let app_dir = app_home_dir();
|
||||
let app_dir = app_dir.as_os_str().to_str().unwrap();
|
||||
|
||||
let mut payload = ClashInfoPayload {
|
||||
status: "success".to_string(),
|
||||
controller: None,
|
||||
message: None,
|
||||
};
|
||||
|
||||
let result = match Command::new_sidecar("clash") {
|
||||
Ok(cmd) => match cmd.args(["-d", app_dir]).spawn() {
|
||||
Ok(res) => Ok(res),
|
||||
Err(err) => Err(err.to_string()),
|
||||
},
|
||||
Err(err) => Err(err.to_string()),
|
||||
};
|
||||
|
||||
match result {
|
||||
Ok((mut rx, _)) => {
|
||||
log::info!("Successfully execute clash sidecar");
|
||||
payload.controller = Some(read_clash_controller());
|
||||
|
||||
tauri::async_runtime::spawn(async move {
|
||||
while let Some(event) = rx.recv().await {
|
||||
match event {
|
||||
CommandEvent::Stdout(line) => log::info!("{}", line),
|
||||
CommandEvent::Stderr(err) => log::error!("{}", err),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
Err(err) => {
|
||||
log::error!("Failed to execute clash sidecar for \"{}\"", err);
|
||||
payload.status = "error".to_string();
|
||||
payload.message = Some(err.to_string());
|
||||
}
|
||||
};
|
||||
|
||||
clash_start(app_handle, &payload);
|
||||
payload
|
||||
}
|
||||
|
||||
/// Update the clash profile firstly
|
||||
pub async fn put_clash_profile(payload: &ClashInfoPayload) -> Result<(), String> {
|
||||
let profile = {
|
||||
let profiles = read_profiles();
|
||||
let current = profiles.current.unwrap_or(0) as usize;
|
||||
match profiles.items {
|
||||
Some(items) => {
|
||||
if items.len() == 0 {
|
||||
return Err("can not read profiles".to_string());
|
||||
}
|
||||
let idx = if current < items.len() { current } else { 0 };
|
||||
items[idx].clone()
|
||||
}
|
||||
None => {
|
||||
return Err("can not read profiles".to_string());
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// temp profile's path
|
||||
let temp_path = temp_dir().join("clash-verge-runtime.yaml");
|
||||
|
||||
// generate temp profile
|
||||
{
|
||||
let file_name = match profile.file {
|
||||
Some(file_name) => file_name.clone(),
|
||||
None => {
|
||||
return Err(format!("profile item should have `file` field"));
|
||||
}
|
||||
};
|
||||
|
||||
let file_path = app_home_dir().join("profiles").join(file_name);
|
||||
if !file_path.exists() {
|
||||
return Err(format!("profile `{:?}` not exists", file_path));
|
||||
}
|
||||
|
||||
// Only the following fields are allowed:
|
||||
// proxies/proxy-providers/proxy-groups/rule-providers/rules
|
||||
let config = read_yaml::<Mapping>(file_path.clone());
|
||||
let mut new_config = Mapping::new();
|
||||
vec![
|
||||
"proxies",
|
||||
"proxy-providers",
|
||||
"proxy-groups",
|
||||
"rule-providers",
|
||||
"rules",
|
||||
]
|
||||
.iter()
|
||||
.map(|item| Value::String(item.to_string()))
|
||||
.for_each(|key| {
|
||||
if config.contains_key(&key) {
|
||||
let value = config[&key].clone();
|
||||
new_config.insert(key, value);
|
||||
}
|
||||
});
|
||||
|
||||
match save_yaml(
|
||||
temp_path.clone(),
|
||||
&new_config,
|
||||
Some("# Clash Verge Temp File"),
|
||||
) {
|
||||
Err(err) => return Err(err),
|
||||
_ => {}
|
||||
};
|
||||
}
|
||||
|
||||
let ctrl = payload.controller.clone().unwrap();
|
||||
let server = format!("http://{}/configs", ctrl.server.unwrap());
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("Content-Type", "application/json".parse().unwrap());
|
||||
|
||||
if let Some(secret) = ctrl.secret {
|
||||
headers.insert(
|
||||
"Authorization",
|
||||
format!("Bearer {}", secret).parse().unwrap(),
|
||||
);
|
||||
}
|
||||
|
||||
let mut data = HashMap::new();
|
||||
data.insert("path", temp_path.as_os_str().to_str().unwrap());
|
||||
|
||||
let client = reqwest::Client::new();
|
||||
match client.put(server).headers(headers).json(&data).send().await {
|
||||
Ok(_) => Ok(()),
|
||||
Err(err) => Err(format!("request failed `{}`", err.to_string())),
|
||||
}
|
||||
}
|
@ -1,132 +1,35 @@
|
||||
use crate::{
|
||||
config::{ClashController, ProfilesConfig, VergeConfig},
|
||||
utils::app_home_dir,
|
||||
};
|
||||
use anyhow::{Context, Result};
|
||||
use serde::{de::DeserializeOwned, Serialize};
|
||||
use serde_yaml::{Mapping, Value};
|
||||
use std::{fs, path::PathBuf};
|
||||
|
||||
/// read data from yaml as struct T
|
||||
pub fn read_yaml<T: DeserializeOwned + Default>(path: PathBuf) -> T {
|
||||
let yaml_str = fs::read_to_string(path).unwrap_or("".into());
|
||||
serde_yaml::from_str::<T>(&yaml_str).unwrap_or(T::default())
|
||||
}
|
||||
if !path.exists() {
|
||||
log::error!(target: "app", "file not found \"{}\"", path.display());
|
||||
return T::default();
|
||||
}
|
||||
|
||||
/// - save the data to the file
|
||||
/// - can set `prefix` string to add some comments
|
||||
pub fn save_yaml<T: Serialize>(
|
||||
path: PathBuf,
|
||||
data: &T,
|
||||
prefix: Option<&str>,
|
||||
) -> Result<(), String> {
|
||||
if let Ok(data_str) = serde_yaml::to_string(data) {
|
||||
let yaml_str = if prefix.is_some() {
|
||||
prefix.unwrap().to_string() + &data_str
|
||||
} else {
|
||||
data_str
|
||||
};
|
||||
let yaml_str = fs::read_to_string(&path).unwrap_or("".into());
|
||||
|
||||
if fs::write(path.clone(), yaml_str.as_bytes()).is_err() {
|
||||
Err(format!("can not save file `{:?}`", path))
|
||||
} else {
|
||||
Ok(())
|
||||
match serde_yaml::from_str::<T>(&yaml_str) {
|
||||
Ok(val) => val,
|
||||
Err(_) => {
|
||||
log::error!(target: "app", "failed to read yaml file \"{}\"", path.display());
|
||||
T::default()
|
||||
}
|
||||
} else {
|
||||
Err(String::from("can not convert the data to yaml"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Get Clash Core Config `config.yaml`
|
||||
pub fn read_clash() -> Mapping {
|
||||
read_yaml::<Mapping>(app_home_dir().join("config.yaml"))
|
||||
}
|
||||
/// save the data to the file
|
||||
/// can set `prefix` string to add some comments
|
||||
pub fn save_yaml<T: Serialize>(path: PathBuf, data: &T, prefix: Option<&str>) -> Result<()> {
|
||||
let data_str = serde_yaml::to_string(data)?;
|
||||
|
||||
/// Save the clash core Config `config.yaml`
|
||||
pub fn save_clash(config: &Mapping) -> Result<(), String> {
|
||||
save_yaml(
|
||||
app_home_dir().join("config.yaml"),
|
||||
config,
|
||||
Some("# Default Config For Clash Core\n\n"),
|
||||
)
|
||||
}
|
||||
|
||||
/// Get infomation of the clash's `external-controller` and `secret`
|
||||
pub fn read_clash_controller() -> ClashController {
|
||||
let config = read_clash();
|
||||
|
||||
let key_port_1 = Value::String("port".to_string());
|
||||
let key_port_2 = Value::String("mixed-port".to_string());
|
||||
let key_server = Value::String("external-controller".to_string());
|
||||
let key_secret = Value::String("secret".to_string());
|
||||
|
||||
let port = match config.get(&key_port_1) {
|
||||
Some(value) => match value {
|
||||
Value::String(val_str) => Some(val_str.clone()),
|
||||
Value::Number(val_num) => Some(val_num.to_string()),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
let port = match port {
|
||||
Some(_) => port,
|
||||
None => match config.get(&key_port_2) {
|
||||
Some(value) => match value {
|
||||
Value::String(val_str) => Some(val_str.clone()),
|
||||
Value::Number(val_num) => Some(val_num.to_string()),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
},
|
||||
let yaml_str = match prefix {
|
||||
Some(prefix) => format!("{prefix}{data_str}"),
|
||||
None => data_str,
|
||||
};
|
||||
|
||||
let server = match config.get(&key_server) {
|
||||
Some(value) => match value {
|
||||
Value::String(val_str) => Some(val_str.clone()),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
let secret = match config.get(&key_secret) {
|
||||
Some(value) => match value {
|
||||
Value::String(val_str) => Some(val_str.clone()),
|
||||
Value::Bool(val_bool) => Some(val_bool.to_string()),
|
||||
Value::Number(val_num) => Some(val_num.to_string()),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
|
||||
ClashController {
|
||||
port,
|
||||
server,
|
||||
secret,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get Profiles Config
|
||||
pub fn read_profiles() -> ProfilesConfig {
|
||||
read_yaml::<ProfilesConfig>(app_home_dir().join("profiles.yaml"))
|
||||
}
|
||||
|
||||
/// Save Verge App Config
|
||||
pub fn save_profiles(profiles: &ProfilesConfig) -> Result<(), String> {
|
||||
save_yaml(
|
||||
app_home_dir().join("profiles.yaml"),
|
||||
profiles,
|
||||
Some("# Profiles Config for Clash Verge\n\n"),
|
||||
)
|
||||
}
|
||||
|
||||
/// Get the `verge.yaml`
|
||||
pub fn read_verge() -> VergeConfig {
|
||||
read_yaml::<VergeConfig>(app_home_dir().join("verge.yaml"))
|
||||
}
|
||||
|
||||
/// Save Verge App Config
|
||||
pub fn save_verge(verge: &VergeConfig) -> Result<(), String> {
|
||||
save_yaml(
|
||||
app_home_dir().join("verge.yaml"),
|
||||
verge,
|
||||
Some("# The Config for Clash Verge App\n\n"),
|
||||
)
|
||||
let path_str = path.as_os_str().to_string_lossy().to_string();
|
||||
fs::write(path, yaml_str.as_bytes()).context(format!("failed to save file \"{path_str}\""))
|
||||
}
|
||||
|
@ -1,18 +1,130 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::env::temp_dir;
|
||||
use std::path::PathBuf;
|
||||
use tauri::{
|
||||
api::path::{home_dir, resource_dir},
|
||||
PackageInfo,
|
||||
Env, PackageInfo,
|
||||
};
|
||||
|
||||
#[cfg(not(feature = "verge-dev"))]
|
||||
static APP_DIR: &str = "clash-verge";
|
||||
#[cfg(feature = "verge-dev")]
|
||||
static APP_DIR: &str = "clash-verge-dev";
|
||||
|
||||
static CLASH_CONFIG: &str = "config.yaml";
|
||||
static VERGE_CONFIG: &str = "verge.yaml";
|
||||
static PROFILE_YAML: &str = "profiles.yaml";
|
||||
static PROFILE_TEMP: &str = "clash-verge-runtime.yaml";
|
||||
|
||||
#[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
|
||||
pub fn app_home_dir() -> PathBuf {
|
||||
home_dir()
|
||||
.unwrap()
|
||||
.join(Path::new(".config"))
|
||||
.join(Path::new("clash-verge"))
|
||||
#[cfg(target_os = "windows")]
|
||||
unsafe {
|
||||
use tauri::utils::platform::current_exe;
|
||||
|
||||
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
|
||||
pub fn app_resources_dir(package_info: &PackageInfo) -> PathBuf {
|
||||
resource_dir(package_info).unwrap().join("resources")
|
||||
let res_dir = resource_dir(package_info, &Env::default())
|
||||
.unwrap()
|
||||
.join("resources");
|
||||
|
||||
#[cfg(windows)]
|
||||
unsafe {
|
||||
RESOURCE_DIR = Some(res_dir.clone());
|
||||
}
|
||||
|
||||
res_dir
|
||||
}
|
||||
|
||||
/// profiles dir
|
||||
pub fn app_profiles_dir() -> PathBuf {
|
||||
app_home_dir().join("profiles")
|
||||
}
|
||||
|
||||
/// logs dir
|
||||
pub fn app_logs_dir() -> PathBuf {
|
||||
app_home_dir().join("logs")
|
||||
}
|
||||
|
||||
pub fn clash_path() -> PathBuf {
|
||||
app_home_dir().join(CLASH_CONFIG)
|
||||
}
|
||||
|
||||
pub fn verge_path() -> PathBuf {
|
||||
app_home_dir().join(VERGE_CONFIG)
|
||||
}
|
||||
|
||||
pub fn profiles_path() -> PathBuf {
|
||||
app_home_dir().join(PROFILE_YAML)
|
||||
}
|
||||
|
||||
pub fn profiles_temp_path() -> PathBuf {
|
||||
#[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,96 +0,0 @@
|
||||
use crate::config::{ProfileExtra, ProfileResponse};
|
||||
use std::{
|
||||
str::FromStr,
|
||||
time::{SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
/// parse the string
|
||||
fn parse_string<T: FromStr>(target: &str, key: &str) -> Option<T> {
|
||||
match target.find(key) {
|
||||
Some(idx) => {
|
||||
let idx = idx + key.len();
|
||||
let value = &target[idx..];
|
||||
match match value.split(';').nth(0) {
|
||||
Some(value) => value.trim().parse(),
|
||||
None => value.trim().parse(),
|
||||
} {
|
||||
Ok(r) => Some(r),
|
||||
Err(_) => None,
|
||||
}
|
||||
}
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// fetch and parse the profile
|
||||
pub async fn fetch_profile(url: &str) -> Option<ProfileResponse> {
|
||||
let resp = match reqwest::get(url).await {
|
||||
Ok(res) => res,
|
||||
Err(_) => return None,
|
||||
};
|
||||
let header = resp.headers();
|
||||
|
||||
// parse the Subscription Userinfo
|
||||
let extra = {
|
||||
let sub_info = match header.get("Subscription-Userinfo") {
|
||||
Some(value) => value.to_str().unwrap_or(""),
|
||||
None => "",
|
||||
};
|
||||
|
||||
ProfileExtra {
|
||||
upload: parse_string(sub_info, "upload=").unwrap_or(0),
|
||||
download: parse_string(sub_info, "download=").unwrap_or(0),
|
||||
total: parse_string(sub_info, "total=").unwrap_or(0),
|
||||
expire: parse_string(sub_info, "expire=").unwrap_or(0),
|
||||
}
|
||||
};
|
||||
|
||||
// parse the `name` and `file`
|
||||
let (name, file) = {
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs();
|
||||
let file = format!("{}.yaml", now);
|
||||
let name = header.get("Content-Disposition").unwrap().to_str().unwrap();
|
||||
let name = parse_string::<String>(name, "filename=");
|
||||
|
||||
match name {
|
||||
Some(f) => (f, file),
|
||||
None => (file.clone(), file),
|
||||
}
|
||||
};
|
||||
|
||||
// get the data
|
||||
let data = match resp.text_with_charset("utf-8").await {
|
||||
Ok(d) => d,
|
||||
Err(_) => return None,
|
||||
};
|
||||
|
||||
Some(ProfileResponse {
|
||||
file,
|
||||
name,
|
||||
data,
|
||||
extra,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_value() {
|
||||
let test_1 = "upload=111; download=2222; total=3333; expire=444";
|
||||
let test_2 = "attachment; filename=Clash.yaml";
|
||||
|
||||
assert_eq!(parse_string::<usize>(test_1, "upload=").unwrap(), 111);
|
||||
assert_eq!(parse_string::<usize>(test_1, "download=").unwrap(), 2222);
|
||||
assert_eq!(parse_string::<usize>(test_1, "total=").unwrap(), 3333);
|
||||
assert_eq!(parse_string::<usize>(test_1, "expire=").unwrap(), 444);
|
||||
assert_eq!(
|
||||
parse_string::<String>(test_2, "filename=").unwrap(),
|
||||
format!("Clash.yaml")
|
||||
);
|
||||
|
||||
assert_eq!(parse_string::<usize>(test_1, "aaa="), None);
|
||||
assert_eq!(parse_string::<usize>(test_1, "upload1="), None);
|
||||
assert_eq!(parse_string::<usize>(test_1, "expire1="), None);
|
||||
assert_eq!(parse_string::<usize>(test_2, "attachment="), None);
|
||||
}
|
129
src-tauri/src/utils/help.rs
Normal file
@ -0,0 +1,129 @@
|
||||
use anyhow::{bail, Result};
|
||||
use nanoid::nanoid;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use std::str::FromStr;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
pub fn get_now() -> usize {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs() as _
|
||||
}
|
||||
|
||||
const ALPHABET: [char; 62] = [
|
||||
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
|
||||
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B',
|
||||
'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
|
||||
'V', 'W', 'X', 'Y', 'Z',
|
||||
];
|
||||
|
||||
/// generate the uid
|
||||
pub fn get_uid(prefix: &str) -> String {
|
||||
let id = nanoid!(11, &ALPHABET);
|
||||
format!("{prefix}{id}")
|
||||
}
|
||||
|
||||
/// parse the string
|
||||
/// xxx=123123; => 123123
|
||||
pub fn parse_str<T: FromStr>(target: &str, key: &str) -> Option<T> {
|
||||
match target.find(key) {
|
||||
Some(idx) => {
|
||||
let idx = idx + key.len();
|
||||
let value = &target[idx..];
|
||||
match match value.split(';').nth(0) {
|
||||
Some(value) => value.trim().parse(),
|
||||
None => value.trim().parse(),
|
||||
} {
|
||||
Ok(r) => Some(r),
|
||||
Err(_) => None,
|
||||
}
|
||||
}
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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_rules! log_if_err {
|
||||
($result: expr) => {
|
||||
if let Err(err) = $result {
|
||||
log::error!(target: "app", "{err}");
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// wrap the anyhow error
|
||||
/// transform the error to String
|
||||
#[macro_export]
|
||||
macro_rules! wrap_err {
|
||||
($stat: expr) => {
|
||||
match $stat {
|
||||
Ok(a) => Ok(a),
|
||||
Err(err) => {
|
||||
log::error!(target: "app", "{}", err.to_string());
|
||||
Err(format!("{}", err.to_string()))
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// return the string literal error
|
||||
#[macro_export]
|
||||
macro_rules! ret_err {
|
||||
($str: expr) => {
|
||||
return Err($str.into())
|
||||
};
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_value() {
|
||||
let test_1 = "upload=111; download=2222; total=3333; expire=444";
|
||||
let test_2 = "attachment; filename=Clash.yaml";
|
||||
|
||||
assert_eq!(parse_str::<usize>(test_1, "upload=").unwrap(), 111);
|
||||
assert_eq!(parse_str::<usize>(test_1, "download=").unwrap(), 2222);
|
||||
assert_eq!(parse_str::<usize>(test_1, "total=").unwrap(), 3333);
|
||||
assert_eq!(parse_str::<usize>(test_1, "expire=").unwrap(), 444);
|
||||
assert_eq!(
|
||||
parse_str::<String>(test_2, "filename=").unwrap(),
|
||||
format!("Clash.yaml")
|
||||
);
|
||||
|
||||
assert_eq!(parse_str::<usize>(test_1, "aaa="), None);
|
||||
assert_eq!(parse_str::<usize>(test_1, "upload1="), None);
|
||||
assert_eq!(parse_str::<usize>(test_1, "expire1="), None);
|
||||
assert_eq!(parse_str::<usize>(test_2, "attachment="), None);
|
||||
}
|
@ -1,20 +1,18 @@
|
||||
extern crate serde_yaml;
|
||||
|
||||
use crate::utils::{dirs, tmpl};
|
||||
use anyhow::Result;
|
||||
use chrono::Local;
|
||||
use log::LevelFilter;
|
||||
use log4rs::append::console::ConsoleAppender;
|
||||
use log4rs::append::file::FileAppender;
|
||||
use log4rs::config::{Appender, Config, Root};
|
||||
use log4rs::config::{Appender, Config, Logger, Root};
|
||||
use log4rs::encode::pattern::PatternEncoder;
|
||||
use std::fs::{self, File};
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use tauri::PackageInfo;
|
||||
|
||||
use crate::utils::{app_home_dir, app_resources_dir};
|
||||
|
||||
/// initialize this instance's log file
|
||||
fn init_log(log_dir: &PathBuf) {
|
||||
fn init_log(log_dir: &PathBuf) -> Result<()> {
|
||||
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);
|
||||
@ -25,82 +23,80 @@ fn init_log(log_dir: &PathBuf) {
|
||||
.build();
|
||||
let tofile = FileAppender::builder()
|
||||
.encoder(Box::new(PatternEncoder::new(time_format)))
|
||||
.build(log_file)
|
||||
.unwrap();
|
||||
.build(log_file)?;
|
||||
|
||||
let config = Config::builder()
|
||||
.appender(Appender::builder().build("stdout", Box::new(stdout)))
|
||||
.appender(Appender::builder().build("file", Box::new(tofile)))
|
||||
.build(
|
||||
Root::builder()
|
||||
.appenders(["stdout", "file"])
|
||||
.build(LevelFilter::Debug),
|
||||
.logger(
|
||||
Logger::builder()
|
||||
.appenders(["file", "stdout"])
|
||||
.additive(false)
|
||||
.build("app", LevelFilter::Info),
|
||||
)
|
||||
.unwrap();
|
||||
.build(Root::builder().appender("stdout").build(LevelFilter::Info))?;
|
||||
|
||||
log4rs::init_config(config).unwrap();
|
||||
log4rs::init_config(config)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Initialize all the files from resources
|
||||
fn init_config_file(app_dir: &PathBuf, res_dir: &PathBuf) {
|
||||
fn init_config(app_dir: &PathBuf) -> Result<()> {
|
||||
// target path
|
||||
let clash_path = app_dir.join("config.yaml");
|
||||
let verge_path = app_dir.join("verge.yaml");
|
||||
let profile_path = app_dir.join("profiles.yaml");
|
||||
let mmdb_path = app_dir.join("Country.mmdb");
|
||||
|
||||
// template path
|
||||
let clash_tmpl = res_dir.join("config_tmp.yaml");
|
||||
let verge_tmpl = res_dir.join("verge_tmp.yaml");
|
||||
let profiles_tmpl = res_dir.join("profiles_tmp.yaml");
|
||||
let mmdb_tmpl = res_dir.join("Country.mmdb");
|
||||
|
||||
if !clash_path.exists() {
|
||||
if clash_tmpl.exists() {
|
||||
fs::copy(clash_tmpl, clash_path).unwrap();
|
||||
} else {
|
||||
// make sure that the config.yaml not null
|
||||
let content = b"\
|
||||
mixed-port: 7890\n\
|
||||
log-level: info\n\
|
||||
allow-lan: false\n\
|
||||
external-controller: 127.0.0.1:9090\n\
|
||||
secret: \"\"\n";
|
||||
File::create(clash_path).unwrap().write(content).unwrap();
|
||||
}
|
||||
fs::File::create(clash_path)?.write(tmpl::CLASH_CONFIG)?;
|
||||
}
|
||||
|
||||
// only copy it
|
||||
if !verge_path.exists() && verge_tmpl.exists() {
|
||||
fs::copy(verge_tmpl, verge_path).unwrap();
|
||||
if !verge_path.exists() {
|
||||
fs::File::create(verge_path)?.write(tmpl::VERGE_CONFIG)?;
|
||||
}
|
||||
if !profile_path.exists() && profiles_tmpl.exists() {
|
||||
fs::copy(profiles_tmpl, profile_path).unwrap();
|
||||
}
|
||||
if !mmdb_path.exists() && mmdb_tmpl.exists() {
|
||||
fs::copy(mmdb_tmpl, mmdb_path).unwrap();
|
||||
if !profile_path.exists() {
|
||||
fs::File::create(profile_path)?.write(tmpl::PROFILES_CONFIG)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// initialize app
|
||||
pub fn init_app(package_info: &PackageInfo) {
|
||||
// create app dir
|
||||
let app_dir = app_home_dir();
|
||||
let log_dir = app_dir.join("logs");
|
||||
let profiles_dir = app_dir.join("profiles");
|
||||
let app_dir = dirs::app_home_dir();
|
||||
let log_dir = dirs::app_logs_dir();
|
||||
let profiles_dir = dirs::app_profiles_dir();
|
||||
|
||||
let res_dir = app_resources_dir(package_info);
|
||||
let res_dir = dirs::app_resources_dir(package_info);
|
||||
|
||||
if !app_dir.exists() {
|
||||
fs::create_dir(&app_dir).unwrap();
|
||||
let _ = fs::create_dir_all(&app_dir);
|
||||
}
|
||||
if !log_dir.exists() {
|
||||
fs::create_dir(&log_dir).unwrap();
|
||||
let _ = fs::create_dir_all(&log_dir);
|
||||
}
|
||||
if !profiles_dir.exists() {
|
||||
fs::create_dir(&profiles_dir).unwrap();
|
||||
let _ = fs::create_dir_all(&profiles_dir);
|
||||
}
|
||||
|
||||
init_log(&log_dir);
|
||||
init_config_file(&app_dir, &res_dir);
|
||||
crate::log_if_err!(init_log(&log_dir));
|
||||
|
||||
crate::log_if_err!(init_config(&app_dir));
|
||||
|
||||
// copy the resource file
|
||||
let mmdb_path = app_dir.join("Country.mmdb");
|
||||
let mmdb_tmpl = res_dir.join("Country.mmdb");
|
||||
if !mmdb_path.exists() && mmdb_tmpl.exists() {
|
||||
let _ = fs::copy(mmdb_tmpl, mmdb_path);
|
||||
}
|
||||
|
||||
// copy the wintun.dll
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let wintun_path = app_dir.join("wintun.dll");
|
||||
let wintun_tmpl = res_dir.join("wintun.dll");
|
||||
if !wintun_path.exists() && wintun_tmpl.exists() {
|
||||
let _ = fs::copy(wintun_tmpl, wintun_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,10 +1,9 @@
|
||||
mod dirs;
|
||||
pub use self::dirs::*;
|
||||
|
||||
pub mod clash;
|
||||
pub mod config;
|
||||
pub mod fetch;
|
||||
pub mod dirs;
|
||||
pub mod help;
|
||||
pub mod init;
|
||||
pub mod resolve;
|
||||
pub mod server;
|
||||
pub mod sysopt;
|
||||
pub mod tmpl;
|
||||
mod winhelp;
|
||||
|
@ -1,5 +1,4 @@
|
||||
use super::{clash, config, init, server, sysopt};
|
||||
use crate::events::state;
|
||||
use crate::{core::Core, utils::init, utils::server};
|
||||
use tauri::{App, AppHandle, Manager};
|
||||
|
||||
/// handle something when start app
|
||||
@ -10,71 +9,123 @@ pub fn resolve_setup(app: &App) {
|
||||
// init app config
|
||||
init::init_app(app.package_info());
|
||||
|
||||
// run clash sidecar
|
||||
let info = clash::run_clash_bin(&app.handle());
|
||||
// init core
|
||||
// should be initialized after init_app fix #122
|
||||
let core = Core::new();
|
||||
|
||||
// update the profile
|
||||
let info_ = info.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
if let Err(err) = clash::put_clash_profile(&info_).await {
|
||||
log::error!("failed to put config for `{}`", err);
|
||||
};
|
||||
});
|
||||
core.set_win(app.get_window("main"));
|
||||
core.init(app.app_handle());
|
||||
|
||||
// resolve the verge config - enable system proxy
|
||||
let mut original: Option<sysopt::SysProxyConfig> = None;
|
||||
let verge = config::read_verge();
|
||||
let enable = verge.enable_system_proxy.unwrap_or(false);
|
||||
// fix #122
|
||||
app.manage(core);
|
||||
|
||||
if enable && info.controller.is_some() {
|
||||
if let Ok(original_conf) = sysopt::get_proxy_config() {
|
||||
original = Some(original_conf)
|
||||
};
|
||||
let ctl = info.controller.clone().unwrap();
|
||||
if ctl.port.is_some() {
|
||||
let server = format!("127.0.0.1:{}", ctl.port.unwrap());
|
||||
let bypass = verge
|
||||
.system_proxy_bypass
|
||||
.clone()
|
||||
.unwrap_or(String::from(sysopt::DEFAULT_BYPASS));
|
||||
let config = sysopt::SysProxyConfig {
|
||||
enable,
|
||||
server,
|
||||
bypass,
|
||||
};
|
||||
if let Err(err) = sysopt::set_proxy_config(&config) {
|
||||
log::error!("can not set system proxy for `{}`", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
// update state
|
||||
let verge_state = app.state::<state::VergeConfLock>();
|
||||
let mut verge_arc = verge_state.0.lock().unwrap();
|
||||
*verge_arc = verge;
|
||||
|
||||
let clash_state = app.state::<state::ClashInfoState>();
|
||||
let mut clash_arc = clash_state.0.lock().unwrap();
|
||||
*clash_arc = info;
|
||||
|
||||
let some_state = app.state::<state::SomthingState>();
|
||||
let mut some_arc = some_state.0.lock().unwrap();
|
||||
*some_arc = original;
|
||||
resolve_window(app);
|
||||
}
|
||||
|
||||
/// reset system proxy
|
||||
pub fn resolve_reset(app_handle: &AppHandle) {
|
||||
let state = app_handle.try_state::<state::SomthingState>();
|
||||
if state.is_none() {
|
||||
let core = app_handle.state::<Core>();
|
||||
let mut sysopt = core.sysopt.lock();
|
||||
sysopt.reset_sysproxy();
|
||||
drop(sysopt);
|
||||
|
||||
let mut service = core.service.lock();
|
||||
crate::log_if_err!(service.stop());
|
||||
}
|
||||
|
||||
/// customize the window theme
|
||||
fn resolve_window(app: &App) {
|
||||
let window = app.get_window("main").unwrap();
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
use crate::utils::winhelp;
|
||||
use window_shadows::set_shadow;
|
||||
use window_vibrancy::apply_blur;
|
||||
|
||||
let _ = window.set_decorations(false);
|
||||
let _ = set_shadow(&window, true);
|
||||
|
||||
// todo
|
||||
// win11 disable this feature temporarily due to lag
|
||||
if !winhelp::is_win11() {
|
||||
let _ = apply_blur(&window, None);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
use tauri::LogicalSize;
|
||||
use tauri::Size::Logical;
|
||||
|
||||
let _ = window.set_decorations(true);
|
||||
let _ = window.set_size(Logical(LogicalSize {
|
||||
width: 800.0,
|
||||
height: 620.0,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
/// 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;
|
||||
}
|
||||
match state.unwrap().0.lock() {
|
||||
Ok(arc) => {
|
||||
if arc.is_some() {
|
||||
if let Err(err) = sysopt::set_proxy_config(arc.as_ref().unwrap()) {
|
||||
log::error!("failed to reset proxy for `{}`", err);
|
||||
}
|
||||
|
||||
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 std::time::Duration;
|
||||
use tokio::time::sleep;
|
||||
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 {
|
||||
sleep(Duration::from_secs(1)).await;
|
||||
|
||||
if let Some(window) = app_handle.get_window("main") {
|
||||
let _ = window.show();
|
||||
let _ = set_shadow(&window, true);
|
||||
|
||||
if !winhelp::is_win11() {
|
||||
let _ = apply_blur(&window, None);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
Err(err) => log::error!(target: "app", "{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());
|
||||
}
|
||||
|
@ -4,7 +4,10 @@ use port_scanner::local_port_available;
|
||||
use tauri::{AppHandle, Manager};
|
||||
use warp::Filter;
|
||||
|
||||
#[cfg(not(feature = "verge-dev"))]
|
||||
const SERVER_PORT: u16 = 33333;
|
||||
#[cfg(feature = "verge-dev")]
|
||||
const SERVER_PORT: u16 = 11233;
|
||||
|
||||
/// check whether there is already exists
|
||||
pub fn check_singleton() -> Result<(), ()> {
|
||||
@ -24,13 +27,13 @@ pub fn check_singleton() -> Result<(), ()> {
|
||||
pub fn embed_server(app: &AppHandle) {
|
||||
let window = app.get_window("main").unwrap();
|
||||
|
||||
let commands = warp::path!("commands" / "visible").map(move || {
|
||||
window.show().unwrap();
|
||||
window.set_focus().unwrap();
|
||||
return format!("ok");
|
||||
});
|
||||
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let commands = warp::path!("commands" / "visible").map(move || {
|
||||
window.show().unwrap();
|
||||
window.set_focus().unwrap();
|
||||
return format!("ok");
|
||||
});
|
||||
|
||||
warp::serve(commands)
|
||||
.bind(([127, 0, 0, 1], SERVER_PORT))
|
||||
.await;
|
||||
|
329
src-tauri/src/utils/sysopt.rs
Normal file → Executable file
@ -1,5 +1,15 @@
|
||||
use anyhow::Result;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::io;
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
static DEFAULT_BYPASS: &str = "localhost;127.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;192.168.*;<local>";
|
||||
#[cfg(target_os = "linux")]
|
||||
static DEFAULT_BYPASS: &str = "localhost,127.0.0.1/8,::1";
|
||||
#[cfg(target_os = "macos")]
|
||||
static DEFAULT_BYPASS: &str =
|
||||
"192.168.0.0/16\n10.0.0.0/8\n172.16.0.0/12\n127.0.0.1\nlocalhost\n*.local\ntimestamp.apple.com\n";
|
||||
#[cfg(target_os = "macos")]
|
||||
static MACOS_SERVICE: &str = "Wi-Fi";
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||
pub struct SysProxyConfig {
|
||||
@ -18,16 +28,23 @@ impl Default for SysProxyConfig {
|
||||
}
|
||||
}
|
||||
|
||||
pub static DEFAULT_BYPASS: &str = "localhost;127.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;192.168.*;<local>";
|
||||
impl SysProxyConfig {
|
||||
pub fn new(enable: bool, port: String, bypass: Option<String>) -> Self {
|
||||
SysProxyConfig {
|
||||
enable,
|
||||
server: format!("127.0.0.1:{}", port),
|
||||
bypass: bypass.unwrap_or(DEFAULT_BYPASS.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
mod win {
|
||||
use super::*;
|
||||
use winreg::enums::*;
|
||||
use winreg::RegKey;
|
||||
|
||||
impl SysProxyConfig {
|
||||
/// Get the windows system proxy config
|
||||
pub fn get_proxy_config() -> io::Result<SysProxyConfig> {
|
||||
pub fn get_sys() -> Result<Self> {
|
||||
use winreg::enums::*;
|
||||
use winreg::RegKey;
|
||||
|
||||
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
|
||||
let cur_var = hkcu.open_subkey_with_flags(
|
||||
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",
|
||||
@ -42,42 +59,308 @@ mod win {
|
||||
}
|
||||
|
||||
/// Set the windows system proxy config
|
||||
pub fn set_proxy_config(config: &SysProxyConfig) -> io::Result<()> {
|
||||
pub fn set_sys(&self) -> Result<()> {
|
||||
use winreg::enums::*;
|
||||
use winreg::RegKey;
|
||||
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
|
||||
let cur_var = hkcu.open_subkey_with_flags(
|
||||
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",
|
||||
KEY_SET_VALUE,
|
||||
)?;
|
||||
|
||||
let enable: u32 = if config.enable { 1u32 } else { 0u32 };
|
||||
let enable: u32 = if self.enable { 1u32 } else { 0u32 };
|
||||
|
||||
cur_var.set_value("ProxyEnable", &enable)?;
|
||||
cur_var.set_value("ProxyServer", &config.server)?;
|
||||
cur_var.set_value("ProxyOverride", &config.bypass)?;
|
||||
cur_var.set_value("ProxyServer", &self.server)?;
|
||||
cur_var.set_value("ProxyOverride", &self.bypass)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos {
|
||||
use super::*;
|
||||
impl SysProxyConfig {
|
||||
/// Get the macos system proxy config
|
||||
pub fn get_sys() -> Result<Self> {
|
||||
use std::process::Command;
|
||||
|
||||
let http = macproxy::get_proxy(&["-getwebproxy", MACOS_SERVICE])?;
|
||||
let https = macproxy::get_proxy(&["-getsecurewebproxy", MACOS_SERVICE])?;
|
||||
let sock = macproxy::get_proxy(&["-getsocksfirewallproxy", MACOS_SERVICE])?;
|
||||
|
||||
let mut enable = false;
|
||||
let mut server = "".into();
|
||||
|
||||
if sock.0 == "Yes" {
|
||||
enable = true;
|
||||
server = sock.1;
|
||||
}
|
||||
if https.0 == "Yes" {
|
||||
enable = true;
|
||||
server = https.1;
|
||||
}
|
||||
if http.0 == "Yes" || !enable {
|
||||
enable = http.0 == "Yes";
|
||||
server = http.1;
|
||||
}
|
||||
|
||||
let bypass_output = Command::new("networksetup")
|
||||
.args(["-getproxybypassdomains", MACOS_SERVICE])
|
||||
.output()?;
|
||||
|
||||
// change the format to xxx,xxx
|
||||
let bypass = std::str::from_utf8(&bypass_output.stdout)
|
||||
.unwrap_or(DEFAULT_BYPASS)
|
||||
.to_string()
|
||||
.split('\n')
|
||||
.collect::<Vec<_>>()
|
||||
.join(",");
|
||||
|
||||
pub fn get_proxy_config() -> io::Result<SysProxyConfig> {
|
||||
Ok(SysProxyConfig {
|
||||
enable: false,
|
||||
server: "server".into(),
|
||||
bypass: "bypass".into(),
|
||||
enable,
|
||||
server,
|
||||
bypass,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn set_proxy_config(config: &SysProxyConfig) -> io::Result<()> {
|
||||
/// Set the macos system proxy config
|
||||
pub fn set_sys(&self) -> Result<()> {
|
||||
use std::process::Command;
|
||||
|
||||
let enable = self.enable;
|
||||
let server = self.server.as_str();
|
||||
let bypass = self.bypass.clone();
|
||||
macproxy::set_proxy("-setwebproxy", MACOS_SERVICE, enable, server)?;
|
||||
macproxy::set_proxy("-setsecurewebproxy", MACOS_SERVICE, enable, server)?;
|
||||
macproxy::set_proxy("-setsocksfirewallproxy", MACOS_SERVICE, enable, server)?;
|
||||
|
||||
let domains = bypass.split(",").collect::<Vec<_>>();
|
||||
Command::new("networksetup")
|
||||
.args([["-setproxybypassdomains", MACOS_SERVICE].to_vec(), domains].concat())
|
||||
.status()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
pub use win::*;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub use macos::*;
|
||||
mod macproxy {
|
||||
use super::*;
|
||||
use anyhow::bail;
|
||||
use std::process::Command;
|
||||
|
||||
/// use networksetup
|
||||
/// get the target proxy config
|
||||
pub(super) fn get_proxy(args: &[&str; 2]) -> Result<(String, String)> {
|
||||
let output = Command::new("networksetup").args(args).output()?;
|
||||
|
||||
let stdout = std::str::from_utf8(&output.stdout)?;
|
||||
let enable = parse(stdout, "Enabled:");
|
||||
let server = parse(stdout, "Server:");
|
||||
let port = parse(stdout, "Port:");
|
||||
let server = format!("{server}:{port}");
|
||||
Ok((enable.into(), server))
|
||||
}
|
||||
|
||||
/// use networksetup
|
||||
/// set the target proxy config
|
||||
pub(super) fn set_proxy(
|
||||
target: &str, // like: -setwebproxy
|
||||
device: &str,
|
||||
enable: bool,
|
||||
server: &str,
|
||||
) -> Result<()> {
|
||||
let mut split = server.split(":");
|
||||
let host = split.next();
|
||||
let port = split.next();
|
||||
|
||||
// can not parse the field
|
||||
if host.is_none() || port.is_none() {
|
||||
bail!("failed to parse the server into host:port");
|
||||
}
|
||||
|
||||
let args = vec![target, device, host.unwrap(), port.unwrap()];
|
||||
Command::new("networksetup").args(&args).status()?;
|
||||
|
||||
let target_state = String::from(target) + "state";
|
||||
let enable = if enable { "on" } else { "off" };
|
||||
let args = vec![target_state.as_str(), device, enable];
|
||||
Command::new("networksetup").args(&args).status()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// parse the networksetup output
|
||||
fn parse<'a>(target: &'a str, key: &'a str) -> &'a str {
|
||||
match target.find(key) {
|
||||
Some(idx) => {
|
||||
let idx = idx + key.len();
|
||||
let value = &target[idx..];
|
||||
let value = match value.find("\n") {
|
||||
Some(end) => &value[..end],
|
||||
None => value,
|
||||
};
|
||||
value.trim()
|
||||
}
|
||||
None => "",
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get() {
|
||||
use std::process::Command;
|
||||
|
||||
let output = Command::new("networksetup")
|
||||
.args(["-getwebproxy", "Wi-Fi"])
|
||||
.output();
|
||||
|
||||
let output = output.unwrap();
|
||||
let stdout = std::str::from_utf8(&output.stdout).unwrap();
|
||||
let enable = parse(stdout, "Enabled:");
|
||||
let server = parse(stdout, "Server:");
|
||||
let port = parse(stdout, "Port:");
|
||||
|
||||
println!("enable: {}, server: {}, port: {}", enable, server, port);
|
||||
|
||||
dbg!(SysProxyConfig::get_sys().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_set() {
|
||||
let sysproxy = SysProxyConfig::new(true, "7890".into(), None);
|
||||
dbg!(sysproxy.set_sys().unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
///
|
||||
/// Linux Desktop System Proxy Supports
|
||||
/// by using `gsettings`
|
||||
#[cfg(target_os = "linux")]
|
||||
impl SysProxyConfig {
|
||||
/// Get the system proxy config [http/https/socks]
|
||||
pub fn get_sys() -> Result<Self> {
|
||||
use std::process::Command;
|
||||
|
||||
let schema = "org.gnome.system.proxy";
|
||||
|
||||
// get enable
|
||||
let mode = Command::new("gsettings")
|
||||
.args(["get", schema, "mode"])
|
||||
.output()?;
|
||||
let mode = std::str::from_utf8(&mode.stdout)?;
|
||||
let enable = mode == "manual";
|
||||
|
||||
// get bypass
|
||||
// Todo: parse the ignore-hosts
|
||||
// ['aaa', 'bbb'] -> aaa,bbb
|
||||
let ignore = Command::new("gsettings")
|
||||
.args(["get", schema, "ignore-hosts"])
|
||||
.output()?;
|
||||
let ignore = std::str::from_utf8(&ignore.stdout)?;
|
||||
let bypass = ignore.to_string();
|
||||
|
||||
let http = Self::get_proxy("http")?;
|
||||
let https = Self::get_proxy("https")?;
|
||||
let socks = Self::get_proxy("socks")?;
|
||||
|
||||
let mut server = "".into();
|
||||
|
||||
if socks.len() > 0 {
|
||||
server = socks;
|
||||
}
|
||||
if https.len() > 0 {
|
||||
server = https;
|
||||
}
|
||||
if http.len() > 0 {
|
||||
server = http;
|
||||
}
|
||||
|
||||
Ok(SysProxyConfig {
|
||||
enable,
|
||||
server,
|
||||
bypass,
|
||||
})
|
||||
}
|
||||
|
||||
/// Get the system proxy config [http/https/socks]
|
||||
pub fn set_sys(&self) -> Result<()> {
|
||||
use anyhow::bail;
|
||||
use std::process::Command;
|
||||
|
||||
let enable = self.enable;
|
||||
let server = self.server.as_str();
|
||||
let bypass = self.bypass.clone();
|
||||
let schema = "org.gnome.system.proxy";
|
||||
|
||||
if enable {
|
||||
let mut split = server.split(":");
|
||||
let host = split.next();
|
||||
let port = split.next();
|
||||
|
||||
if port.is_none() {
|
||||
bail!("failed to parse the port");
|
||||
}
|
||||
|
||||
let host = format!("'{}'", host.unwrap_or("127.0.0.1"));
|
||||
let host = host.as_str();
|
||||
let port = port.unwrap();
|
||||
|
||||
let http = format!("{schema}.http");
|
||||
Command::new("gsettings")
|
||||
.args(["set", http.as_str(), "host", host])
|
||||
.status()?;
|
||||
Command::new("gsettings")
|
||||
.args(["set", http.as_str(), "port", port])
|
||||
.status()?;
|
||||
|
||||
let https = format!("{schema}.https");
|
||||
Command::new("gsettings")
|
||||
.args(["set", https.as_str(), "host", host])
|
||||
.status()?;
|
||||
Command::new("gsettings")
|
||||
.args(["set", https.as_str(), "port", port])
|
||||
.status()?;
|
||||
|
||||
let socks = format!("{schema}.socks");
|
||||
Command::new("gsettings")
|
||||
.args(["set", socks.as_str(), "host", host])
|
||||
.status()?;
|
||||
Command::new("gsettings")
|
||||
.args(["set", socks.as_str(), "port", port])
|
||||
.status()?;
|
||||
|
||||
// set bypass
|
||||
// Todo: parse the ignore-hosts
|
||||
// aaa,bbb,cccc -> ['aaa', 'bbb', 'ccc']
|
||||
Command::new("gsettings")
|
||||
.args(["set", schema, "ignore-hosts", bypass.as_str()]) // todo
|
||||
.status()?;
|
||||
}
|
||||
|
||||
let mode = if enable { "'manual'" } else { "'none'" };
|
||||
Command::new("gsettings")
|
||||
.args(["set", schema, "mode", mode])
|
||||
.status()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// help function
|
||||
fn get_proxy(typ: &str) -> Result<String> {
|
||||
use std::process::Command;
|
||||
|
||||
let schema = format!("org.gnome.system.proxy.{typ}");
|
||||
let schema = schema.as_str();
|
||||
|
||||
let host = Command::new("gsettings")
|
||||
.args(["get", schema, "host"])
|
||||
.output()?;
|
||||
let host = std::str::from_utf8(&host.stdout)?;
|
||||
|
||||
let port = Command::new("gsettings")
|
||||
.args(["get", schema, "port"])
|
||||
.output()?;
|
||||
let port = std::str::from_utf8(&port.stdout)?;
|
||||
|
||||
Ok(format!("{host}:{port}"))
|
||||
}
|
||||
}
|
||||
|
70
src-tauri/src/utils/tmpl.rs
Normal file
@ -0,0 +1,70 @@
|
||||
///! Some config file template
|
||||
|
||||
/// template for clash core `config.yaml`
|
||||
pub const CLASH_CONFIG: &[u8] = br#"# Default Config For Clash Core
|
||||
|
||||
mixed-port: 7890
|
||||
log-level: info
|
||||
allow-lan: false
|
||||
external-controller: 127.0.0.1:9090
|
||||
mode: rule
|
||||
secret: ""
|
||||
"#;
|
||||
|
||||
/// template for `profiles.yaml`
|
||||
pub const PROFILES_CONFIG: &[u8] = b"# Profiles Config for Clash Verge
|
||||
|
||||
current: ~
|
||||
items: ~
|
||||
";
|
||||
|
||||
/// template for `verge.yaml`
|
||||
pub const VERGE_CONFIG: &[u8] = b"# Defaulf Config For Clash Verge
|
||||
|
||||
language: en
|
||||
theme_mode: light
|
||||
theme_blur: false
|
||||
traffic_graph: true
|
||||
enable_self_startup: false
|
||||
enable_system_proxy: false
|
||||
enable_proxy_guard: false
|
||||
proxy_guard_duration: 10
|
||||
system_proxy_bypass: localhost;127.*;10.*;192.168.*;<local>
|
||||
";
|
||||
|
||||
/// template for new a profile item
|
||||
pub const ITEM_LOCAL: &str = "# Profile Template for clash verge
|
||||
|
||||
proxies:
|
||||
|
||||
proxy-groups:
|
||||
|
||||
rules:
|
||||
";
|
||||
|
||||
/// enhanced profile
|
||||
pub const ITEM_MERGE: &str = "# Merge Template for clash verge
|
||||
# The `Merge` format used to enhance profile
|
||||
|
||||
prepend-rules:
|
||||
|
||||
prepend-proxies:
|
||||
|
||||
prepend-proxy-groups:
|
||||
|
||||
append-rules:
|
||||
|
||||
append-proxies:
|
||||
|
||||
append-proxy-groups:
|
||||
";
|
||||
|
||||
/// enhanced profile
|
||||
pub const ITEM_SCRIPT: &str = "// Should define the `main` function
|
||||
// The argument to this function is the clash config
|
||||
// or the result of the previous handler
|
||||
// so you should return the config after processing
|
||||
function main(params) {
|
||||
return params;
|
||||
}
|
||||
";
|
69
src-tauri/src/utils/winhelp.rs
Normal file
@ -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,17 +1,17 @@
|
||||
{
|
||||
"package": {
|
||||
"productName": "clash-verge",
|
||||
"version": "0.0.1"
|
||||
"productName": "Clash Verge",
|
||||
"version": "1.0.6"
|
||||
},
|
||||
"build": {
|
||||
"distDir": "../dist",
|
||||
"devPath": "http://localhost:3000/proxy",
|
||||
"devPath": "http://localhost:3000/",
|
||||
"beforeDevCommand": "yarn run web:dev",
|
||||
"beforeBuildCommand": "yarn run web:build"
|
||||
},
|
||||
"tauri": {
|
||||
"systemTray": {
|
||||
"iconPath": "icons/icon.png",
|
||||
"iconPath": "icons/tray-icon.ico",
|
||||
"iconAsTemplate": true
|
||||
},
|
||||
"bundle": {
|
||||
@ -22,23 +22,21 @@
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
"icons/128x128@2x.png",
|
||||
"icons/icon.icns",
|
||||
"icons/icon-new.icns",
|
||||
"icons/icon.ico"
|
||||
],
|
||||
"resources": ["resources"],
|
||||
"externalBin": ["sidecar/clash"],
|
||||
"copyright": "© 2021 zzzgydi All Rights Reserved",
|
||||
"externalBin": ["sidecar/clash", "sidecar/clash-meta"],
|
||||
"copyright": "© 2022 zzzgydi All Rights Reserved",
|
||||
"category": "DeveloperTool",
|
||||
"shortDescription": "A Clash GUI based on tauri.",
|
||||
"longDescription": "A Clash GUI based on tauri.",
|
||||
"deb": {
|
||||
"depends": [],
|
||||
"useBootstrapper": false
|
||||
"depends": []
|
||||
},
|
||||
"macOS": {
|
||||
"frameworks": [],
|
||||
"minimumSystemVersion": "",
|
||||
"useBootstrapper": false,
|
||||
"exceptionDomain": "",
|
||||
"signingIdentity": null,
|
||||
"entitlements": null
|
||||
@ -46,30 +44,47 @@
|
||||
"windows": {
|
||||
"certificateThumbprint": null,
|
||||
"digestAlgorithm": "sha256",
|
||||
"timestampUrl": ""
|
||||
"timestampUrl": "",
|
||||
"wix": {
|
||||
"language": ["zh-CN", "en-US"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"updater": {
|
||||
"active": false
|
||||
"active": true,
|
||||
"endpoints": [
|
||||
"https://github.com/zzzgydi/clash-verge/releases/download/updater/update.json",
|
||||
"https://hub.fastgit.xyz/zzzgydi/clash-verge/releases/download/updater/update-proxy.json"
|
||||
],
|
||||
"dialog": false,
|
||||
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDExNUFBNTBBN0FDNEFBRTUKUldUbHFzUjZDcVZhRVRJM25NS3NkSFlFVElxUkNZMzZ6bHUwRVJjb2F3alJXVzRaeDdSaTA2YWYK"
|
||||
},
|
||||
"allowlist": {
|
||||
"all": true
|
||||
"shell": {
|
||||
"all": true
|
||||
},
|
||||
"window": {
|
||||
"all": true
|
||||
},
|
||||
"process": {
|
||||
"all": true
|
||||
}
|
||||
},
|
||||
"windows": [
|
||||
{
|
||||
"title": "Clash Verge",
|
||||
"width": 800,
|
||||
"height": 600,
|
||||
"height": 636,
|
||||
"resizable": true,
|
||||
"fullscreen": false,
|
||||
"decorations": true,
|
||||
"transparent": false,
|
||||
"decorations": false,
|
||||
"transparent": true,
|
||||
"minWidth": 600,
|
||||
"minHeight": 520
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": "default-src blob: data: filesystem: ws: wss: http: https: tauri: 'unsafe-eval' 'unsafe-inline' 'self' img-src: 'self'"
|
||||
"csp": "script-src 'unsafe-eval' 'self'; default-src blob: data: filesystem: ws: wss: http: https: tauri: 'unsafe-eval' 'unsafe-inline' 'self'; img-src data: 'self';"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
BIN
src/assets/image/logo-box.png
Normal file
After Width: | Height: | Size: 57 KiB |
@ -4,12 +4,14 @@ body {
|
||||
"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
|
||||
sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
:root {
|
||||
--primary-main: #5b5c9d;
|
||||
--text-primary: #637381;
|
||||
--selection-color: #f5f5f5;
|
||||
--scroller-color: #90939980;
|
||||
}
|
||||
|
||||
::selection {
|
||||
@ -24,7 +26,8 @@ body {
|
||||
}
|
||||
*::-webkit-scrollbar-thumb {
|
||||
border-radius: 6px;
|
||||
background-color: rgba(#909399, 0.5);
|
||||
background-color: var(--scroller-color);
|
||||
}
|
||||
|
||||
@import "./layout.scss";
|
||||
@import "./page.scss";
|
||||
|
@ -1,45 +1,94 @@
|
||||
.layout {
|
||||
width: 100%;
|
||||
height: 100vh;
|
||||
display: flex;
|
||||
overflow: hidden;
|
||||
|
||||
&__sidebar {
|
||||
position: relative;
|
||||
&__left {
|
||||
flex: 1 0 25%;
|
||||
height: 100vh;
|
||||
display: flex;
|
||||
height: 100%;
|
||||
max-width: 225px;
|
||||
min-width: 125px;
|
||||
overflow: hidden auto;
|
||||
padding: 16px 0 8px;
|
||||
flex-direction: column;
|
||||
box-sizing: border-box;
|
||||
user-select: none;
|
||||
overflow: hidden;
|
||||
|
||||
.the-logo {
|
||||
position: relative;
|
||||
flex: 0 1 168px;
|
||||
width: 100%;
|
||||
max-width: 168px;
|
||||
max-height: 168px;
|
||||
margin: 0 auto;
|
||||
padding: 0 16px;
|
||||
text-align: center;
|
||||
box-sizing: border-box;
|
||||
|
||||
img,
|
||||
svg {
|
||||
width: 96%;
|
||||
height: 96%;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.the-newbtn {
|
||||
position: absolute;
|
||||
right: 20px;
|
||||
bottom: 12px;
|
||||
transform: scale(0.8);
|
||||
}
|
||||
}
|
||||
|
||||
.the-menu {
|
||||
flex: 1 1 80%;
|
||||
overflow-y: auto;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.the-traffic {
|
||||
flex: 0 0 60px;
|
||||
|
||||
> div {
|
||||
margin: 0 auto;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&__content {
|
||||
&__right {
|
||||
position: relative;
|
||||
flex: 1 1 75%;
|
||||
height: 100vh;
|
||||
overflow: overlay;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
height: 100%;
|
||||
|
||||
&__logo {
|
||||
width: 100%;
|
||||
height: auto;
|
||||
max-width: 180px;
|
||||
max-height: 180px;
|
||||
margin: 0 auto;
|
||||
padding: 8px 8px 0;
|
||||
user-select: none;
|
||||
text-align: center;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.the-bar {
|
||||
position: absolute;
|
||||
top: 2px;
|
||||
right: 8px;
|
||||
height: 36px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
box-sizing: border-box;
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
&__traffic {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 8px;
|
||||
|
||||
> div {
|
||||
margin: 0 auto;
|
||||
.the-content {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 2px;
|
||||
bottom: 10px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.linux,
|
||||
.windows,
|
||||
.unknown {
|
||||
&.layout {
|
||||
.layout__right .the-content {
|
||||
top: 30px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
35
src/assets/styles/page.scss
Normal file
@ -0,0 +1,35 @@
|
||||
.base-page {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
> header {
|
||||
flex: 0 0 58px;
|
||||
width: 90%;
|
||||
max-width: 850px;
|
||||
margin: 0 auto;
|
||||
padding-right: 4px;
|
||||
box-sizing: border-box;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
> section {
|
||||
position: relative;
|
||||
flex: 1 1 100%;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow: auto;
|
||||
padding: 8px 0;
|
||||
box-sizing: border-box;
|
||||
scrollbar-gutter: stable;
|
||||
|
||||
.base-content {
|
||||
width: 90%;
|
||||
max-width: 850px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
}
|
||||
}
|
31
src/components/base/base-empty.tsx
Normal file
@ -0,0 +1,31 @@
|
||||
import { alpha, Box, Typography } from "@mui/material";
|
||||
import { BlurOnRounded } from "@mui/icons-material";
|
||||
|
||||
interface Props {
|
||||
text?: React.ReactNode;
|
||||
extra?: React.ReactNode;
|
||||
}
|
||||
|
||||
const BaseEmpty = (props: Props) => {
|
||||
const { text = "Empty", extra } = props;
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={({ palette }) => ({
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
color: alpha(palette.text.secondary, 0.75),
|
||||
})}
|
||||
>
|
||||
<BlurOnRounded sx={{ fontSize: "4em" }} />
|
||||
<Typography sx={{ fontSize: "1.25em" }}>{text}</Typography>
|
||||
{extra}
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export default BaseEmpty;
|
95
src/components/base/base-notice.tsx
Normal file
@ -0,0 +1,95 @@
|
||||
import ReactDOM from "react-dom";
|
||||
import { ReactNode, useState } from "react";
|
||||
import { Box, IconButton, Slide, Snackbar, Typography } from "@mui/material";
|
||||
import { Close, CheckCircleRounded, ErrorRounded } from "@mui/icons-material";
|
||||
|
||||
interface InnerProps {
|
||||
type: string;
|
||||
duration?: number;
|
||||
message: ReactNode;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
const NoticeInner = (props: InnerProps) => {
|
||||
const { type, message, duration = 1500, onClose } = props;
|
||||
const [visible, setVisible] = useState(true);
|
||||
|
||||
const onBtnClose = () => {
|
||||
setVisible(false);
|
||||
onClose();
|
||||
};
|
||||
const onAutoClose = (_e: any, reason: string) => {
|
||||
if (reason !== "clickaway") onBtnClose();
|
||||
};
|
||||
|
||||
const msgElement =
|
||||
type === "info" ? (
|
||||
message
|
||||
) : (
|
||||
<Box sx={{ width: 328, display: "flex", alignItems: "center" }}>
|
||||
{type === "error" && <ErrorRounded color="error" />}
|
||||
{type === "success" && <CheckCircleRounded color="success" />}
|
||||
|
||||
<Typography
|
||||
component="span"
|
||||
sx={{ ml: 1, wordWrap: "break-word", width: "calc(100% - 35px)" }}
|
||||
>
|
||||
{message}
|
||||
</Typography>
|
||||
</Box>
|
||||
);
|
||||
|
||||
return (
|
||||
<Snackbar
|
||||
open={visible}
|
||||
anchorOrigin={{ vertical: "top", horizontal: "right" }}
|
||||
autoHideDuration={duration}
|
||||
onClose={onAutoClose}
|
||||
message={msgElement}
|
||||
sx={{ maxWidth: 360 }}
|
||||
TransitionComponent={(p) => <Slide {...p} direction="left" />}
|
||||
transitionDuration={200}
|
||||
action={
|
||||
<IconButton size="small" color="inherit" onClick={onBtnClose}>
|
||||
<Close fontSize="inherit" />
|
||||
</IconButton>
|
||||
}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
interface NoticeInstance {
|
||||
(props: Omit<InnerProps, "onClose">): void;
|
||||
|
||||
info(message: ReactNode, duration?: number): void;
|
||||
error(message: ReactNode, duration?: number): void;
|
||||
success(message: ReactNode, duration?: number): void;
|
||||
}
|
||||
|
||||
let parent: HTMLDivElement = null!;
|
||||
|
||||
// @ts-ignore
|
||||
const Notice: NoticeInstance = (props) => {
|
||||
if (!parent) {
|
||||
parent = document.createElement("div");
|
||||
document.body.appendChild(parent);
|
||||
}
|
||||
|
||||
const container = document.createElement("div");
|
||||
parent.appendChild(container);
|
||||
|
||||
const onUnmount = () => {
|
||||
const result = ReactDOM.unmountComponentAtNode(container);
|
||||
if (result && parent) setTimeout(() => parent.removeChild(container), 500);
|
||||
};
|
||||
|
||||
ReactDOM.render(<NoticeInner {...props} onClose={onUnmount} />, container);
|
||||
};
|
||||
|
||||
(["info", "error", "success"] as const).forEach((type) => {
|
||||
Notice[type] = (message, duration) => {
|
||||
setTimeout(() => Notice({ type, message, duration }), 0);
|
||||
};
|
||||
});
|
||||
|
||||
export default Notice;
|
32
src/components/base/base-page.tsx
Normal file
@ -0,0 +1,32 @@
|
||||
import { Typography } from "@mui/material";
|
||||
import React from "react";
|
||||
|
||||
interface Props {
|
||||
title?: React.ReactNode; // the page title
|
||||
header?: React.ReactNode; // something behind title
|
||||
contentStyle?: React.CSSProperties;
|
||||
}
|
||||
|
||||
const BasePage: React.FC<Props> = (props) => {
|
||||
const { title, header, contentStyle, children } = props;
|
||||
|
||||
return (
|
||||
<div className="base-page" data-windrag>
|
||||
<header data-windrag style={{ userSelect: "none" }}>
|
||||
<Typography variant="h4" component="h1" data-windrag>
|
||||
{title}
|
||||
</Typography>
|
||||
|
||||
{header}
|
||||
</header>
|
||||
|
||||
<section>
|
||||
<div className="base-content" style={contentStyle} data-windrag>
|
||||
{children}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default BasePage;
|
@ -1,13 +0,0 @@
|
||||
import { ApiType } from "../services/types";
|
||||
|
||||
interface Props {
|
||||
value: ApiType.ConnectionsItem;
|
||||
}
|
||||
|
||||
const ConnectionItem = (props: Props) => {
|
||||
const { value } = props;
|
||||
|
||||
return <div>{value.metadata.host || value.metadata.destinationIP}</div>;
|
||||
};
|
||||
|
||||
export default ConnectionItem;
|
66
src/components/connection/connection-item.tsx
Normal file
@ -0,0 +1,66 @@
|
||||
import dayjs from "dayjs";
|
||||
import { useLockFn } from "ahooks";
|
||||
import { styled, ListItem, IconButton, ListItemText } from "@mui/material";
|
||||
import { CloseRounded } from "@mui/icons-material";
|
||||
import { deleteConnection } from "@/services/api";
|
||||
import parseTraffic from "@/utils/parse-traffic";
|
||||
|
||||
const Tag = styled("span")(({ theme }) => ({
|
||||
display: "inline-block",
|
||||
fontSize: "12px",
|
||||
padding: "0 4px",
|
||||
lineHeight: 1.375,
|
||||
border: "1px solid #ccc",
|
||||
borderRadius: 4,
|
||||
marginRight: "0.1em",
|
||||
transform: "scale(0.92)",
|
||||
}));
|
||||
|
||||
interface Props {
|
||||
value: ApiType.ConnectionsItem;
|
||||
}
|
||||
|
||||
const ConnectionItem = (props: Props) => {
|
||||
const { value } = props;
|
||||
|
||||
const { id, metadata, chains, start, curUpload, curDownload } = value;
|
||||
|
||||
const onDelete = useLockFn(async () => deleteConnection(id));
|
||||
const showTraffic = curUpload! > 1024 || curDownload! > 1024;
|
||||
|
||||
return (
|
||||
<ListItem
|
||||
dense
|
||||
secondaryAction={
|
||||
<IconButton edge="end" color="inherit" onClick={onDelete}>
|
||||
<CloseRounded />
|
||||
</IconButton>
|
||||
}
|
||||
>
|
||||
<ListItemText
|
||||
primary={metadata.host || metadata.destinationIP}
|
||||
secondary={
|
||||
<>
|
||||
<Tag sx={{ textTransform: "uppercase", color: "success" }}>
|
||||
{metadata.network}
|
||||
</Tag>
|
||||
|
||||
<Tag>{metadata.type}</Tag>
|
||||
|
||||
{chains.length > 0 && <Tag>{chains[value.chains.length - 1]}</Tag>}
|
||||
|
||||
<Tag>{dayjs(start).fromNow()}</Tag>
|
||||
|
||||
{showTraffic && (
|
||||
<Tag>
|
||||
{parseTraffic(curUpload!)} / {parseTraffic(curDownload!)}
|
||||
</Tag>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
/>
|
||||
</ListItem>
|
||||
);
|
||||
};
|
||||
|
||||
export default ConnectionItem;
|
@ -1,58 +0,0 @@
|
||||
import { cloneElement, isValidElement, ReactNode, useRef } from "react";
|
||||
import noop from "../utils/noop";
|
||||
|
||||
interface Props<Value> {
|
||||
value?: Value;
|
||||
valueProps?: string;
|
||||
onChangeProps?: string;
|
||||
onChange?: (value: Value) => void;
|
||||
onFormat?: (...args: any[]) => Value;
|
||||
onGuard?: (value: Value) => Promise<void>;
|
||||
onCatch?: (error: Error) => void;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
function GuardState<T>(props: Props<T>) {
|
||||
const {
|
||||
value,
|
||||
children,
|
||||
valueProps = "value",
|
||||
onChangeProps = "onChange",
|
||||
onGuard = noop,
|
||||
onCatch = noop,
|
||||
onChange = noop,
|
||||
onFormat = (v: T) => v,
|
||||
} = props;
|
||||
|
||||
const lockRef = useRef(false);
|
||||
|
||||
if (isValidElement(children)) {
|
||||
const childProps = { ...children.props };
|
||||
|
||||
childProps[valueProps] = value;
|
||||
childProps[onChangeProps] = async (...args: any[]) => {
|
||||
// 多次操作无效
|
||||
if (lockRef.current) return;
|
||||
|
||||
lockRef.current = true;
|
||||
const oldValue = value;
|
||||
|
||||
try {
|
||||
const newValue = (onFormat as any)(...args);
|
||||
// 先在ui上响应操作
|
||||
onChange(newValue);
|
||||
await onGuard(newValue);
|
||||
} catch (err: any) {
|
||||
// 状态回退
|
||||
onChange(oldValue!);
|
||||
onCatch(err);
|
||||
}
|
||||
lockRef.current = false;
|
||||
};
|
||||
return cloneElement(children, childProps);
|
||||
}
|
||||
|
||||
return children as any;
|
||||
}
|
||||
|
||||
export default GuardState;
|
41
src/components/layout/layout-control.tsx
Normal file
@ -0,0 +1,41 @@
|
||||
import { Button } from "@mui/material";
|
||||
import { appWindow } from "@tauri-apps/api/window";
|
||||
import {
|
||||
CloseRounded,
|
||||
CropSquareRounded,
|
||||
HorizontalRuleRounded,
|
||||
} from "@mui/icons-material";
|
||||
|
||||
const LayoutControl = () => {
|
||||
const minWidth = 40;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
size="small"
|
||||
sx={{ minWidth, svg: { transform: "scale(0.9)" } }}
|
||||
onClick={() => appWindow.minimize()}
|
||||
>
|
||||
<HorizontalRuleRounded fontSize="small" />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
size="small"
|
||||
sx={{ minWidth, svg: { transform: "scale(0.9)" } }}
|
||||
onClick={() => appWindow.toggleMaximize()}
|
||||
>
|
||||
<CropSquareRounded fontSize="small" />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
size="small"
|
||||
sx={{ minWidth, svg: { transform: "scale(1.05)" } }}
|
||||
onClick={() => appWindow.close()}
|
||||
>
|
||||
<CloseRounded fontSize="small" />
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default LayoutControl;
|
107
src/components/layout/layout-traffic.tsx
Normal file
@ -0,0 +1,107 @@
|
||||
import useSWR from "swr";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useRecoilValue } from "recoil";
|
||||
import { Box, Typography } from "@mui/material";
|
||||
import { ArrowDownward, ArrowUpward } from "@mui/icons-material";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { getInformation } from "@/services/api";
|
||||
import { getVergeConfig } from "@/services/cmds";
|
||||
import { atomClashPort } from "@/services/states";
|
||||
import TrafficGraph from "./traffic-graph";
|
||||
import useLogSetup from "./use-log-setup";
|
||||
import parseTraffic from "@/utils/parse-traffic";
|
||||
|
||||
// setup the traffic
|
||||
const LayoutTraffic = () => {
|
||||
const portValue = useRecoilValue(atomClashPort);
|
||||
const [traffic, setTraffic] = useState({ up: 0, down: 0 });
|
||||
const [refresh, setRefresh] = useState({});
|
||||
|
||||
const trafficRef = useRef<any>();
|
||||
|
||||
// whether hide traffic graph
|
||||
const { data } = useSWR("getVergeConfig", getVergeConfig);
|
||||
const trafficGraph = data?.traffic_graph ?? true;
|
||||
|
||||
// setup log ws during layout
|
||||
useLogSetup();
|
||||
|
||||
useEffect(() => {
|
||||
// should reconnect the traffic ws
|
||||
const unlisten = listen("verge://refresh-clash-config", () =>
|
||||
setRefresh({})
|
||||
);
|
||||
|
||||
return () => {
|
||||
unlisten.then((fn) => fn());
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
let ws: WebSocket | null = null;
|
||||
|
||||
getInformation().then((result) => {
|
||||
const { server = "", secret = "" } = result;
|
||||
ws = new WebSocket(`ws://${server}/traffic?token=${secret}`);
|
||||
|
||||
ws.addEventListener("message", (event) => {
|
||||
const data = JSON.parse(event.data) as ApiType.TrafficItem;
|
||||
trafficRef.current?.appendData(data);
|
||||
setTraffic(data);
|
||||
});
|
||||
});
|
||||
|
||||
return () => ws?.close();
|
||||
}, [portValue, refresh]);
|
||||
|
||||
const [up, upUnit] = parseTraffic(traffic.up);
|
||||
const [down, downUnit] = parseTraffic(traffic.down);
|
||||
|
||||
const valStyle: any = {
|
||||
component: "span",
|
||||
color: "primary",
|
||||
textAlign: "center",
|
||||
sx: { flex: "1 1 54px" },
|
||||
};
|
||||
const unitStyle: any = {
|
||||
component: "span",
|
||||
color: "grey.500",
|
||||
fontSize: "12px",
|
||||
textAlign: "right",
|
||||
sx: { flex: "0 1 28px", userSelect: "none" },
|
||||
};
|
||||
|
||||
return (
|
||||
<Box
|
||||
width="110px"
|
||||
position="relative"
|
||||
onClick={trafficRef.current?.toggleStyle}
|
||||
>
|
||||
{trafficGraph && (
|
||||
<div style={{ width: "100%", height: 60, marginBottom: 6 }}>
|
||||
<TrafficGraph instance={trafficRef} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Box mb={1.5} display="flex" alignItems="center" whiteSpace="nowrap">
|
||||
<ArrowUpward
|
||||
fontSize="small"
|
||||
color={+up > 0 ? "primary" : "disabled"}
|
||||
/>
|
||||
<Typography {...valStyle}>{up}</Typography>
|
||||
<Typography {...unitStyle}>{upUnit}/s</Typography>
|
||||
</Box>
|
||||
|
||||
<Box display="flex" alignItems="center" whiteSpace="nowrap">
|
||||
<ArrowDownward
|
||||
fontSize="small"
|
||||
color={+down > 0 ? "primary" : "disabled"}
|
||||
/>
|
||||
<Typography {...valStyle}>{down}</Typography>
|
||||
<Typography {...unitStyle}>{downUnit}/s</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export default LayoutTraffic;
|
201
src/components/layout/traffic-graph.tsx
Normal file
@ -0,0 +1,201 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useTheme } from "@mui/material";
|
||||
|
||||
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);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
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);
|
||||
};
|
||||
}, [palette]);
|
||||
|
||||
return <canvas ref={canvasRef} style={{ width: "100%", height: "100%" }} />;
|
||||
};
|
||||
|
||||
export default TrafficGraph;
|
42
src/components/layout/update-button.tsx
Normal file
@ -0,0 +1,42 @@
|
||||
import useSWR from "swr";
|
||||
import { useState } from "react";
|
||||
import { Button } from "@mui/material";
|
||||
import { checkUpdate } from "@tauri-apps/api/updater";
|
||||
import UpdateDialog from "./update-dialog";
|
||||
|
||||
interface Props {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const UpdateButton = (props: Props) => {
|
||||
const { className } = props;
|
||||
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const { data: updateInfo } = useSWR("checkUpdate", checkUpdate, {
|
||||
errorRetryCount: 2,
|
||||
revalidateIfStale: false,
|
||||
focusThrottleInterval: 36e5, // 1 hour
|
||||
});
|
||||
|
||||
if (!updateInfo?.shouldUpdate) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
color="error"
|
||||
variant="contained"
|
||||
size="small"
|
||||
className={className}
|
||||
onClick={() => setDialogOpen(true)}
|
||||
>
|
||||
New
|
||||
</Button>
|
||||
|
||||
{dialogOpen && (
|
||||
<UpdateDialog open={dialogOpen} onClose={() => setDialogOpen(false)} />
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default UpdateButton;
|
90
src/components/layout/update-dialog.tsx
Normal file
@ -0,0 +1,90 @@
|
||||
import useSWR from "swr";
|
||||
import snarkdown from "snarkdown";
|
||||
import { useMemo } from "react";
|
||||
import { useRecoilState } from "recoil";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
Box,
|
||||
Button,
|
||||
Dialog,
|
||||
DialogActions,
|
||||
DialogContent,
|
||||
DialogTitle,
|
||||
styled,
|
||||
} from "@mui/material";
|
||||
import { relaunch } from "@tauri-apps/api/process";
|
||||
import { checkUpdate, installUpdate } from "@tauri-apps/api/updater";
|
||||
import { killSidecar, restartSidecar } from "@/services/cmds";
|
||||
import { atomUpdateState } from "@/services/states";
|
||||
import Notice from "../base/base-notice";
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
const UpdateLog = styled(Box)(() => ({
|
||||
"h1,h2,h3,ul,ol,p": { margin: "0.5em 0", color: "inherit" },
|
||||
}));
|
||||
|
||||
const UpdateDialog = (props: Props) => {
|
||||
const { open, onClose } = props;
|
||||
const { t } = useTranslation();
|
||||
const { data: updateInfo } = useSWR("checkUpdate", checkUpdate, {
|
||||
errorRetryCount: 2,
|
||||
revalidateIfStale: false,
|
||||
focusThrottleInterval: 36e5, // 1 hour
|
||||
});
|
||||
|
||||
const [updateState, setUpdateState] = useRecoilState(atomUpdateState);
|
||||
|
||||
const onUpdate = async () => {
|
||||
if (updateState) return;
|
||||
setUpdateState(true);
|
||||
|
||||
try {
|
||||
await killSidecar();
|
||||
await installUpdate();
|
||||
await relaunch();
|
||||
} catch (err: any) {
|
||||
await restartSidecar();
|
||||
Notice.error(err?.message || err.toString());
|
||||
} finally {
|
||||
setUpdateState(false);
|
||||
}
|
||||
};
|
||||
|
||||
// markdown parser
|
||||
const parseContent = useMemo(() => {
|
||||
if (!updateInfo?.manifest?.body) {
|
||||
return "New Version is available";
|
||||
}
|
||||
return snarkdown(updateInfo?.manifest?.body);
|
||||
}, [updateInfo]);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onClose={onClose}>
|
||||
<DialogTitle>New Version v{updateInfo?.manifest?.version}</DialogTitle>
|
||||
|
||||
<DialogContent sx={{ minWidth: 360, maxWidth: 400, maxHeight: "50vh" }}>
|
||||
<UpdateLog dangerouslySetInnerHTML={{ __html: parseContent }} />
|
||||
</DialogContent>
|
||||
|
||||
<DialogActions>
|
||||
<Button variant="outlined" onClick={onClose}>
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
autoFocus
|
||||
variant="contained"
|
||||
disabled={updateState}
|
||||
onClick={onUpdate}
|
||||
>
|
||||
{t("Update")}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default UpdateDialog;
|
104
src/components/layout/use-custom-theme.ts
Normal file
@ -0,0 +1,104 @@
|
||||
import useSWR from "swr";
|
||||
import { useEffect, useMemo } from "react";
|
||||
import { useRecoilState } from "recoil";
|
||||
import { createTheme } from "@mui/material";
|
||||
import { appWindow } from "@tauri-apps/api/window";
|
||||
import { getVergeConfig } from "@/services/cmds";
|
||||
import { atomThemeMode } from "@/services/states";
|
||||
import { defaultTheme, defaultDarkTheme } from "@/pages/_theme";
|
||||
|
||||
/**
|
||||
* custome theme
|
||||
*/
|
||||
export default function useCustomTheme() {
|
||||
const { data } = useSWR("getVergeConfig", getVergeConfig);
|
||||
const { theme_mode, theme_setting } = data ?? {};
|
||||
const [mode, setMode] = useRecoilState(atomThemeMode);
|
||||
|
||||
useEffect(() => {
|
||||
const themeMode = ["light", "dark", "system"].includes(theme_mode!)
|
||||
? theme_mode!
|
||||
: "light";
|
||||
|
||||
if (themeMode !== "system") {
|
||||
setMode(themeMode);
|
||||
return;
|
||||
}
|
||||
|
||||
appWindow.theme().then((m) => m && setMode(m));
|
||||
const unlisten = appWindow.onThemeChanged((e) => setMode(e.payload));
|
||||
|
||||
return () => {
|
||||
unlisten.then((fn) => fn());
|
||||
};
|
||||
}, [theme_mode]);
|
||||
|
||||
const theme = useMemo(() => {
|
||||
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;
|
||||
}, [mode, theme_setting]);
|
||||
|
||||
return { theme };
|
||||
}
|
42
src/components/layout/use-log-setup.ts
Normal file
@ -0,0 +1,42 @@
|
||||
import dayjs from "dayjs";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useSetRecoilState } from "recoil";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { getInformation } from "@/services/api";
|
||||
import { atomLogData } from "@/services/states";
|
||||
|
||||
const MAX_LOG_NUM = 1000;
|
||||
|
||||
// setup the log websocket
|
||||
export default function useLogSetup() {
|
||||
const [refresh, setRefresh] = useState({});
|
||||
const setLogData = useSetRecoilState(atomLogData);
|
||||
|
||||
useEffect(() => {
|
||||
let ws: WebSocket = null!;
|
||||
|
||||
const handler = (event: MessageEvent<any>) => {
|
||||
const data = JSON.parse(event.data) as ApiType.LogItem;
|
||||
const time = dayjs().format("MM-DD HH:mm:ss");
|
||||
setLogData((l) => {
|
||||
if (l.length >= MAX_LOG_NUM) l.shift();
|
||||
return [...l, { ...data, time }];
|
||||
});
|
||||
};
|
||||
|
||||
getInformation().then((info) => {
|
||||
const { server = "", secret = "" } = info;
|
||||
ws = new WebSocket(`ws://${server}/logs?token=${secret}`);
|
||||
ws.addEventListener("message", handler);
|
||||
});
|
||||
|
||||
const unlisten = listen("verge://refresh-clash-config", () =>
|
||||
setRefresh({})
|
||||
);
|
||||
|
||||
return () => {
|
||||
ws?.close();
|
||||
unlisten?.then((fn) => fn());
|
||||
};
|
||||
}, [refresh]);
|
||||
}
|
@ -1,11 +1,12 @@
|
||||
import { styled, Box } from "@mui/material";
|
||||
import { ApiType } from "../services/types";
|
||||
|
||||
const Item = styled(Box)(({ theme }) => ({
|
||||
padding: "8px 0",
|
||||
margin: "0 12px",
|
||||
lineHeight: 1.35,
|
||||
borderBottom: `1px solid ${theme.palette.divider}`,
|
||||
fontSize: "0.875rem",
|
||||
userSelect: "text",
|
||||
"& .time": {},
|
||||
"& .type": {
|
||||
display: "inline-block",
|
@ -1,51 +0,0 @@
|
||||
import { styled, Switch } from "@mui/material";
|
||||
|
||||
// From: https://mui.com/components/switches/
|
||||
const PaletteSwitch = styled(Switch)(({ theme }) => ({
|
||||
width: 62,
|
||||
height: 34,
|
||||
padding: 7,
|
||||
"& .MuiSwitch-switchBase": {
|
||||
margin: 1,
|
||||
padding: 0,
|
||||
transform: "translateX(6px)",
|
||||
"&.Mui-checked": {
|
||||
color: "#fff",
|
||||
transform: "translateX(22px)",
|
||||
"& .MuiSwitch-thumb:before": {
|
||||
backgroundImage: `url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" height="20" width="20" viewBox="0 0 20 20"><path fill="${encodeURIComponent(
|
||||
"#fff"
|
||||
)}" d="M4.2 2.5l-.7 1.8-1.8.7 1.8.7.7 1.8.6-1.8L6.7 5l-1.9-.7-.6-1.8zm15 8.3a6.7 6.7 0 11-6.6-6.6 5.8 5.8 0 006.6 6.6z"/></svg>')`,
|
||||
},
|
||||
"& + .MuiSwitch-track": {
|
||||
opacity: 1,
|
||||
backgroundColor: theme.palette.mode === "dark" ? "#8796A5" : "#aab4be",
|
||||
},
|
||||
},
|
||||
},
|
||||
"& .MuiSwitch-thumb": {
|
||||
backgroundColor: theme.palette.mode === "dark" ? "#003892" : "#001e3c",
|
||||
width: 32,
|
||||
height: 32,
|
||||
"&:before": {
|
||||
content: "''",
|
||||
position: "absolute",
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
left: 0,
|
||||
top: 0,
|
||||
backgroundRepeat: "no-repeat",
|
||||
backgroundPosition: "center",
|
||||
backgroundImage: `url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" height="20" width="20" viewBox="0 0 20 20"><path fill="${encodeURIComponent(
|
||||
"#fff"
|
||||
)}" d="M9.305 1.667V3.75h1.389V1.667h-1.39zm-4.707 1.95l-.982.982L5.09 6.072l.982-.982-1.473-1.473zm10.802 0L13.927 5.09l.982.982 1.473-1.473-.982-.982zM10 5.139a4.872 4.872 0 00-4.862 4.86A4.872 4.872 0 0010 14.862 4.872 4.872 0 0014.86 10 4.872 4.872 0 0010 5.139zm0 1.389A3.462 3.462 0 0113.471 10a3.462 3.462 0 01-3.473 3.472A3.462 3.462 0 016.527 10 3.462 3.462 0 0110 6.528zM1.665 9.305v1.39h2.083v-1.39H1.666zm14.583 0v1.39h2.084v-1.39h-2.084zM5.09 13.928L3.616 15.4l.982.982 1.473-1.473-.982-.982zm9.82 0l-.982.982 1.473 1.473.982-.982-1.473-1.473zM9.305 16.25v2.083h1.389V16.25h-1.39z"/></svg>')`,
|
||||
},
|
||||
},
|
||||
"& .MuiSwitch-track": {
|
||||
opacity: 1,
|
||||
backgroundColor: theme.palette.mode === "dark" ? "#8796A5" : "#aab4be",
|
||||
borderRadius: 20 / 2,
|
||||
},
|
||||
}));
|
||||
|
||||
export default PaletteSwitch;
|
@ -1,177 +0,0 @@
|
||||
import React, { useState } from "react";
|
||||
import dayjs from "dayjs";
|
||||
import {
|
||||
alpha,
|
||||
Box,
|
||||
styled,
|
||||
Typography,
|
||||
LinearProgress,
|
||||
IconButton,
|
||||
keyframes,
|
||||
} from "@mui/material";
|
||||
import { useSWRConfig } from "swr";
|
||||
import { RefreshRounded } from "@mui/icons-material";
|
||||
import { CmdType } from "../services/types";
|
||||
import parseTraffic from "../utils/parse-traffic";
|
||||
import relativeTime from "dayjs/plugin/relativeTime";
|
||||
import { updateProfile } from "../services/cmds";
|
||||
|
||||
dayjs.extend(relativeTime);
|
||||
|
||||
const Wrapper = styled(Box)(({ theme }) => ({
|
||||
width: "100%",
|
||||
display: "block",
|
||||
cursor: "pointer",
|
||||
textAlign: "left",
|
||||
borderRadius: theme.shape.borderRadius,
|
||||
boxShadow: theme.shadows[2],
|
||||
padding: "8px 16px",
|
||||
boxSizing: "border-box",
|
||||
}));
|
||||
|
||||
const round = keyframes`
|
||||
from { transform: rotate(0deg); }
|
||||
to { transform: rotate(360deg); }
|
||||
`;
|
||||
|
||||
interface Props {
|
||||
index: number;
|
||||
selected: boolean;
|
||||
itemData: CmdType.ProfileItem;
|
||||
onClick: () => void;
|
||||
}
|
||||
|
||||
const ProfileItemComp: React.FC<Props> = (props) => {
|
||||
const { index, selected, itemData, onClick } = props;
|
||||
|
||||
const { mutate } = useSWRConfig();
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const { name = "Profile", extra, updated = 0 } = itemData;
|
||||
const { upload = 0, download = 0, total = 0 } = extra ?? {};
|
||||
const from = parseUrl(itemData.url);
|
||||
const expire = parseExpire(extra?.expire);
|
||||
const progress = Math.round(((download + upload) * 100) / (total + 0.1));
|
||||
const fromnow = updated > 0 ? dayjs(updated * 1000).fromNow() : "";
|
||||
|
||||
const onUpdate = async () => {
|
||||
if (loading) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
await updateProfile(index);
|
||||
mutate("getProfiles");
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Wrapper
|
||||
sx={({ palette }) => {
|
||||
const { mode, primary, text, grey } = palette;
|
||||
const isDark = mode === "dark";
|
||||
|
||||
if (selected) {
|
||||
const bgcolor = isDark
|
||||
? alpha(primary.main, 0.35)
|
||||
: alpha(primary.main, 0.15);
|
||||
|
||||
return {
|
||||
bgcolor,
|
||||
color: isDark ? alpha(text.secondary, 0.6) : text.secondary,
|
||||
"& h2": {
|
||||
color: isDark ? primary.light : primary.main,
|
||||
},
|
||||
};
|
||||
}
|
||||
const bgcolor = isDark
|
||||
? alpha(grey[700], 0.35)
|
||||
: palette.background.paper;
|
||||
return {
|
||||
bgcolor,
|
||||
color: isDark ? alpha(text.secondary, 0.6) : text.secondary,
|
||||
"& h2": {
|
||||
color: isDark ? text.primary : text.primary,
|
||||
},
|
||||
};
|
||||
}}
|
||||
onClick={onClick}
|
||||
>
|
||||
<Box display="flex" justifyContent="space-between">
|
||||
<Typography
|
||||
width="calc(100% - 40px)"
|
||||
variant="h6"
|
||||
component="h2"
|
||||
noWrap
|
||||
title={name}
|
||||
>
|
||||
{name}
|
||||
</Typography>
|
||||
|
||||
<IconButton
|
||||
sx={{
|
||||
width: 30,
|
||||
height: 30,
|
||||
animation: loading ? `1s linear infinite ${round}` : "none",
|
||||
}}
|
||||
color="inherit"
|
||||
disabled={loading}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onUpdate();
|
||||
}}
|
||||
>
|
||||
<RefreshRounded />
|
||||
</IconButton>
|
||||
</Box>
|
||||
|
||||
<Box display="flex" justifyContent="space-between" alignItems="center">
|
||||
<Typography noWrap title={`From: ${from}`}>
|
||||
{from}
|
||||
</Typography>
|
||||
|
||||
<Typography
|
||||
noWrap
|
||||
flex="1 0 auto"
|
||||
fontSize={14}
|
||||
textAlign="right"
|
||||
title="updated time"
|
||||
>
|
||||
{fromnow}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
my: 0.5,
|
||||
fontSize: 14,
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
}}
|
||||
>
|
||||
<span title="used / total">
|
||||
{parseTraffic(upload + download)} / {parseTraffic(total)}
|
||||
</span>
|
||||
<span title="expire time">{expire}</span>
|
||||
</Box>
|
||||
|
||||
<LinearProgress variant="determinate" value={progress} color="inherit" />
|
||||
</Wrapper>
|
||||
);
|
||||
};
|
||||
|
||||
function parseUrl(url?: string) {
|
||||
if (!url) return "";
|
||||
const regex = /https?:\/\/(.+?)\//;
|
||||
const result = url.match(regex);
|
||||
return result ? result[1] : "local file";
|
||||
}
|
||||
|
||||
function parseExpire(expire?: number) {
|
||||
if (!expire) return "-";
|
||||
return dayjs(expire * 1000).format("YYYY-MM-DD");
|
||||
}
|
||||
|
||||
export default ProfileItemComp;
|