Compare commits

...

341 Commits

Author SHA1 Message Date
GyDi
f4f1a0fbc6 v0.0.29 2022-04-13 01:30:08 +08:00
GyDi
74e10dc012
chore: update log 2022-04-13 01:29:48 +08:00
GyDi
359812b7ed
chore: update dep 2022-04-13 01:21:49 +08:00
GyDi
c2449e53c4
chore: rename green to portable 2022-04-13 01:17:40 +08:00
GyDi
1a91249da2
feat: system tray add tun mode 2022-04-13 01:09:51 +08:00
GyDi
b9162f9576
fix: adjust log 2022-04-13 00:49:30 +08:00
GyDi
f726e8a7b3
feat: supports change config dir 2022-04-12 23:09:32 +08:00
GyDi
2f284cfdc9
chore: update clash version 2022-04-12 23:04:19 +08:00
GyDi
b74696adba
feat: add default user agent 2022-04-12 01:05:51 +08:00
GyDi
c8ccba0192
chore: rm console 2022-04-11 02:26:09 +08:00
GyDi
41b0e05f62
feat: connections page supports filter 2022-04-11 02:25:34 +08:00
GyDi
847d5f1b3b
feat: log page supports filter 2022-04-11 01:46:33 +08:00
GyDi
0445f9dfc2
fix: check button hover style 2022-04-10 03:33:17 +08:00
GyDi
3001c780bd
feat: optimize delay checker concurrency strategy 2022-04-10 02:58:48 +08:00
GyDi
68ad5e2320
feat: support sort proxy node and custom test url 2022-04-10 02:09:36 +08:00
GyDi
b5e229b19c
chore: update deps 2022-04-10 01:31:05 +08:00
GyDi
453d798fcf
refactor: proxy head 2022-04-08 01:35:18 +08:00
GyDi
451afdb660 v0.0.28 2022-04-07 01:28:30 +08:00
GyDi
d298bda92c
chore: update log 2022-04-07 01:27:48 +08:00
GyDi
fd99ba6255
feat: handle remote clash config fields 2022-04-07 01:20:44 +08:00
GyDi
6ade0b2b1a
fix: icon button color inherit 2022-04-06 22:52:00 +08:00
GyDi
9902003da9
fix: remove the lonely zero 2022-04-06 22:48:10 +08:00
GyDi
0ff2fcac11
chore: readme 2022-04-06 01:52:20 +08:00
GyDi
e80be8e7b6 v0.0.27 2022-04-06 01:21:33 +08:00
GyDi
fe0ad0f5cb
chore: update log 2022-04-06 01:19:13 +08:00
GyDi
cb8e162f4e
refactor: update profile menu 2022-04-06 01:13:06 +08:00
GyDi
ae8c30fe57
chore: add updater script 2022-04-05 23:24:52 +08:00
GyDi
ab82db9e22
chore: updater json supports arch field 2022-04-05 23:19:54 +08:00
GyDi
cb9d3098de
chore: add ci 2022-04-05 20:21:53 +08:00
GyDi
c927419c99
refactor: enhanced mode ui component 2022-04-03 01:41:48 +08:00
GyDi
c009026961
feat: add text color 2022-04-02 17:18:38 +08:00
GyDi
51cf442fa5
fix: i18n add value 2022-04-02 13:49:48 +08:00
GyDi
954e3553ee
fix: proxy page first render 2022-04-02 01:23:31 +08:00
GyDi
cde17385b4
feat: control final tun config 2022-04-01 23:55:44 +08:00
GyDi
5b9e078061
chore: add debug feature 2022-04-01 23:43:35 +08:00
GyDi
0290d9ddfc
feat: support css injection 2022-04-01 02:08:42 +08:00
GyDi
eab671d102
fix: console warning 2022-04-01 01:16:23 +08:00
GyDi
f9a96ff914
feat: support theme setting 2022-03-31 23:38:00 +08:00
GyDi
3ec2b46d28
feat: add text color 2022-03-31 23:34:36 +08:00
GyDi
aec30b89e0
feat: add theme setting 2022-03-31 23:11:50 +08:00
GyDi
309c33e190
refactor: ui theme 2022-03-30 12:36:39 +08:00
GyDi
9c0276f97b
chore: add api 2022-03-30 01:30:22 +08:00
GyDi
0a3402ff43
fix: icon button title 2022-03-30 01:29:25 +08:00
GyDi
bd82308024
chore: update tauri 2022-03-29 23:05:32 +08:00
GyDi
db3b634e62
fix: macOS transition flickers close #47 2022-03-29 01:39:54 +08:00
GyDi
40bcb22977
chore: update deps 2022-03-29 01:33:14 +08:00
GyDi
4bd94092f1
fix: csp image data 2022-03-28 23:17:11 +08:00
GyDi
cac1ce6895
chore: readme 2022-03-28 01:33:58 +08:00
GyDi
5c3696123a v0.0.26 2022-03-28 01:30:54 +08:00
GyDi
4140fc86ee
chore: update log 2022-03-28 01:18:18 +08:00
GyDi
2ad771e7fd
fix: close dialog after save 2022-03-28 01:09:34 +08:00
GyDi
5a38468144
refactor: optimize enhance mode strategy 2022-03-28 01:07:14 +08:00
GyDi
0a9c81772f
fix: change to deep copy 2022-03-28 00:56:48 +08:00
GyDi
c9649ac501
feat: enhanced mode supports more fields 2022-03-27 20:36:13 +08:00
GyDi
6ea567742b
chore: profile release 2022-03-27 01:38:40 +08:00
GyDi
f31349eaa0
feat: supports edit profile file 2022-03-27 00:58:17 +08:00
GyDi
9d44668d5f
feat: supports silent start 2022-03-26 18:56:16 +08:00
GyDi
a12f58c1c7
feat: use crate open 2022-03-23 23:00:14 +08:00
GyDi
b5283eaaed
fix: window style close #45 2022-03-23 21:43:13 +08:00
GyDi
4b6189af5f
feat: enhance connections display order 2022-03-23 14:02:08 +08:00
GyDi
5d0ffbe453
chore: adjust style 2022-03-23 13:58:57 +08:00
GyDi
502706931e
fix: manage global proxy correctly 2022-03-23 12:49:34 +08:00
GyDi
57c411288f
fix: tauri csp 2022-03-23 01:47:35 +08:00
GyDi
b09b7b11a1
feat: save global selected 2022-03-22 12:38:59 +08:00
GyDi
1a7b3c7294 v0.0.25 2022-03-22 01:51:06 +08:00
GyDi
4678fc7dde
chore: update log 2022-03-22 01:50:24 +08:00
GyDi
9f492fad49
chore: update clash core 2022-03-22 01:50:15 +08:00
GyDi
bd0a959e18
fix: windows style 2022-03-22 01:36:06 +08:00
GyDi
dd605e2610
fix: update state 2022-03-22 01:27:22 +08:00
inRm3D
9910f6b817
chore: readme (#43) 2022-03-21 21:55:45 +08:00
GyDi
991897aff4
chore: tauri feature 2022-03-21 11:40:52 +08:00
GyDi
3cde019208
fix: profile item loading state 2022-03-21 11:40:27 +08:00
GyDi
2f6efbed63
chore: tauri allowList 2022-03-20 13:16:50 +08:00
GyDi
5cff4e299b
chore: update clash version 2022-03-20 12:37:55 +08:00
GyDi
bce33639da v0.0.24 2022-03-20 01:50:39 +08:00
GyDi
366c465cad
chore: update log 2022-03-20 01:50:15 +08:00
GyDi
acc6e05bdc
feat: system tray supports system proxy setting 2022-03-20 01:36:43 +08:00
GyDi
4ce15577cd
feat: prevent context menu on Windows close #22 2022-03-19 19:28:53 +08:00
GyDi
98fa4d5e65
feat: create local profile with selected file 2022-03-19 19:21:55 +08:00
GyDi
7fe94076c7
feat: reduce the impact of the enhanced mode 2022-03-19 16:02:47 +08:00
GyDi
b8b0c8fa63
fix: adjust windows style 2022-03-19 15:35:59 +08:00
GyDi
e585e87bec
feat: parse update log 2022-03-19 15:31:58 +08:00
GyDi
6a4924bb16
chore: update log supports 2022-03-19 14:04:58 +08:00
GyDi
ab0d516d91
chore: updater proxy 2022-03-19 11:14:12 +08:00
GyDi
b756ae39d0
chore: ci support linux 2022-03-19 10:50:44 +08:00
GyDi
c15c38ea8f
chore: readme 2022-03-18 19:02:53 +08:00
GyDi
743963318f
feat: fill i18n 2022-03-18 14:59:23 +08:00
GyDi
ed3fc50858
feat: dayjs i18n 2022-03-18 14:45:24 +08:00
GyDi
5b886fe6be
feat: connections page simply support 2022-03-18 14:43:22 +08:00
GyDi
7074bbc405
feat: add wintun.dll by default 2022-03-18 11:49:00 +08:00
GyDi
ef314c1707
fix: change mixed port error 2022-03-18 11:39:02 +08:00
GyDi
a3e7626dd9
chore: add dev feature 2022-03-18 10:59:35 +08:00
GyDi
5cb5d74eed
chore: rename temp dir 2022-03-18 10:20:24 +08:00
GyDi
6eee10d46d
chore: resolve wintun.dll 2022-03-17 19:29:30 +08:00
GyDi
2d95f2b0d6
fix: auto launch path 2022-03-16 18:44:25 +08:00
GyDi
ec41bb9c70
fix: tun mode config 2022-03-15 14:23:57 +08:00
GyDi
2d1780b1cf
fix: adjsut open cmd error 2022-03-15 12:51:39 +08:00
GyDi
d9ce99887c
chore: fix ci env 2022-03-15 00:00:20 +08:00
GyDi
9b9cc90414 v0.0.23 2022-03-14 01:34:26 +08:00
GyDi
c1eb539a5c
feat: event emit when clash config update 2022-03-13 01:37:41 +08:00
GyDi
e1793f57ef
chore: fix ci 2022-03-13 00:59:42 +08:00
GyDi
dbd09a8743
chore: update tauri action 2022-03-13 00:58:49 +08:00
GyDi
0d189ca617
chore: green version bundle 2022-03-13 00:52:31 +08:00
GyDi
dc9bcc40ee
chore: rm then 2022-03-12 23:58:20 +08:00
GyDi
4991f7ff39
feat: i18n supports 2022-03-12 23:07:45 +08:00
GyDi
a393b8b122
fix: parse external-controller 2022-03-12 21:35:20 +08:00
GyDi
c73b354386
fix: config file case close #18 2022-03-12 21:03:17 +08:00
GyDi
392ecee3ff
chore: merge 2022-03-12 18:45:07 +08:00
ttyS3
bae721c49e
chore: show open app and log dir failed message 2022-03-12 18:04:56 +08:00
GyDi
4e806e21a6
chore: adjust error log 2022-03-12 15:57:16 +08:00
GyDi
ec0fdf83b2
feat: change open command on linux
refactor(logging): refine open dir failed log message, add Linux support
2022-03-12 15:40:23 +08:00
ttyS3
cb94d8414f
feat: add Linux open dir support
refactor(logging): refine open dir failed log message
2022-03-12 03:18:25 +08:00
GyDi
8890051c17
fix: patch item option 2022-03-11 19:56:56 +08:00
GyDi
cf00c9476f
fix: user agent not works 2022-03-11 19:50:51 +08:00
GyDi
b2a24c7abd v0.0.22 2022-03-10 02:27:00 +08:00
GyDi
732a1f4694
chore: rm dead code 2022-03-10 02:25:35 +08:00
GyDi
4c5aa7084e
fix: external-controller 2022-03-10 02:19:06 +08:00
GyDi
fe1fea671c
feat: support more options for remote profile 2022-03-10 02:03:55 +08:00
GyDi
04c754c0ac
chore: reduce icon size on macOS 2022-03-10 01:04:53 +08:00
GyDi
754c22c84e
chore: adjust icon 2022-03-10 00:04:59 +08:00
GyDi
629331870b
chore: add linux link 2022-03-09 20:14:15 +08:00
GyDi
78774315cb
feat: linux system proxy 2022-03-09 19:48:32 +08:00
GyDi
36b9c07928
chore: update deps 2022-03-09 02:36:40 +08:00
GyDi
40a818630d
fix: change proxy bypass on mac 2022-03-09 02:36:03 +08:00
GyDi
568511a4cf
fix: kill sidecars after install still in test 2022-03-09 02:09:51 +08:00
GyDi
109fb39e09
fix: log some error 2022-03-09 02:00:56 +08:00
GyDi
68450d2042
chore: rename productName 2022-03-09 01:53:34 +08:00
GyDi
8a052bbed6
chore: update tauri version 2022-03-09 01:50:37 +08:00
GyDi
3afbb56640
fix: apply_blur parameter 2022-03-08 10:44:41 +08:00
GyDi
c0ad84a491
fix: limit enhanced profile range 2022-03-08 01:45:46 +08:00
GyDi
c72f17605c
chore: update deps 2022-03-08 01:18:20 +08:00
GyDi
42fbee0cdb
chore: add default bypass 2022-03-08 00:39:09 +08:00
GyDi
e9b7ec735f
fix: profile updated field 2022-03-07 01:41:42 +08:00
GyDi
743788135f
fix: profile field check 2022-03-07 01:30:32 +08:00
GyDi
8ea3e6fa26
fix: create dir panic 2022-03-07 01:06:21 +08:00
GyDi
f23c83e681 v0.0.21 2022-03-06 18:36:02 +08:00
GyDi
b615bda17e
chore: default release body 2022-03-06 18:34:38 +08:00
GyDi
f7c7cd1d3c chore: update deps 2022-03-06 18:04:44 +08:00
GyDi
c7e7be4379
fix: only error when selected 2022-03-06 17:06:45 +08:00
GyDi
d63d49f246
feat: enhance profile status 2022-03-06 17:02:29 +08:00
GyDi
dad94edb20
feat: menu item refresh enhanced mode 2022-03-06 15:46:16 +08:00
GyDi
7108d5f3ab
fix: enhanced profile consistency 2022-03-06 15:40:16 +08:00
GyDi
ef47a74920
feat: profile enhanced mode 2022-03-06 14:59:25 +08:00
GyDi
a43dab8057
feat: profile enhanced ui 2022-03-05 22:54:39 +08:00
GyDi
f44039b628
feat: profile item adjust 2022-03-05 19:04:20 +08:00
GyDi
08fa5205b0
fix: simply compatible with proxy providers 2022-03-05 16:18:44 +08:00
GyDi
b91daebd92
fix: component warning 2022-03-05 15:48:39 +08:00
GyDi
9cd6c5c624
chore: update copyright 2022-03-05 01:51:29 +08:00
GyDi
650e017b72
fix: when updater failed 2022-03-04 02:10:27 +08:00
GyDi
18f9d6dec5 fix: log file 2022-03-04 02:08:26 +08:00
GyDi
4df6571ad9
chore: update deps 2022-03-03 20:37:06 +08:00
GyDi
0f5923a10a
chore: enhance wip 2022-03-03 01:58:05 +08:00
GyDi
bcdae1169e
fix: result 2022-03-03 01:56:47 +08:00
GyDi
f260d5df49
feat: enhanced profile (wip) 2022-03-03 01:52:02 +08:00
GyDi
808b861dd1 v0.0.20 2022-03-02 01:59:53 +08:00
GyDi
17f1c487a8
feat: edit profile item 2022-03-02 01:58:16 +08:00
GyDi
8dc2c1a38f
fix: cover profile extra 2022-03-02 01:45:00 +08:00
GyDi
220a494692
chore: adjust log field 2022-03-02 01:13:31 +08:00
GyDi
db6bc10196
chore: rm file 2022-03-02 00:58:07 +08:00
GyDi
1880363aeb
feat: use nanoid 2022-03-02 00:56:05 +08:00
GyDi
19c7b59883
feat: compatible profile config 2022-03-01 11:05:33 +08:00
GyDi
749df89229
refactor: profile config 2022-03-01 08:58:47 +08:00
GyDi
444f2172fa v0.0.19 2022-02-28 01:59:53 +08:00
GyDi
77a77c0ea7
wip: refactor profile 2022-02-28 01:59:13 +08:00
GyDi
dbf380a0d1
refactor: use anyhow to handle error 2022-02-28 01:34:25 +08:00
GyDi
ade34f5217
fix: display menu only on macos 2022-02-27 01:47:56 +08:00
GyDi
e89607799a
fix: proxy global showType 2022-02-27 01:33:22 +08:00
GyDi
d05d8d6a9e
feat: native menu supports 2022-02-27 01:29:57 +08:00
GyDi
b6aa50d3dc
chore: update deps 2022-02-27 01:16:43 +08:00
GyDi
9df361935f
feat: filter proxy and display type 2022-02-27 00:58:14 +08:00
GyDi
98b8a122b6
feat: use lock fn 2022-02-26 17:39:36 +08:00
GyDi
c7232522ee
feat: refactor proxy page 2022-02-26 17:39:08 +08:00
GyDi
5280f1d745
feat: proxy group auto scroll to current 2022-02-26 01:21:39 +08:00
GyDi
b52a081e7b v0.0.18 2022-02-25 02:13:41 +08:00
GyDi
f981a44861
chore: ci 2022-02-25 02:12:55 +08:00
GyDi
d7c5ce0750
feat: clash tun mode supports 2022-02-25 02:09:39 +08:00
GyDi
9ccc66ca1e
feat: use enhanced guard-state 2022-02-25 01:22:33 +08:00
GyDi
8606af3616
feat: guard state supports debounce guard 2022-02-25 01:21:13 +08:00
GyDi
f6e821ba6b
feat: adjust clash version display 2022-02-24 23:04:18 +08:00
GyDi
e8dbcf819b
feat: hide command window 2022-02-24 22:46:12 +08:00
GyDi
bbe2ef4e8e
fix: use full clash config 2022-02-23 23:23:07 +08:00
GyDi
dd15455031
feat: enhance log data 2022-02-23 02:00:45 +08:00
GyDi
12ac7bb338
chore: update readme 2022-02-22 21:54:33 +08:00
GyDi
46ef348f0d v0.0.17 2022-02-22 02:08:31 +08:00
GyDi
1a55cca8af
fix: reconnect websocket when restart clash 2022-02-22 02:05:22 +08:00
GyDi
81ee989f1f
chore: enhance publish ci 2022-02-22 01:56:06 +08:00
GyDi
c9c06f8a3d
fix: wrong exe path 2022-02-21 22:33:37 +08:00
GyDi
72127979c3
chore: use tauri cli 2022-02-21 22:31:00 +08:00
GyDi
1ad3ddef94 v0.0.16 2022-02-21 01:33:11 +08:00
GyDi
97ec5eabf7
feat: change window style 2022-02-20 23:46:13 +08:00
GyDi
e12e3a3f2d
feat: fill verge template 2022-02-20 20:12:55 +08:00
GyDi
4ff625f23b
feat: enable customize guard duration 2022-02-20 20:11:39 +08:00
GyDi
e38dcd85ac
feat: system proxy guard 2022-02-20 18:53:21 +08:00
GyDi
0245baf1b6
feat: enable show or hide traffic graph 2022-02-19 18:14:40 +08:00
GyDi
10b55c043c
fix: patch verge config 2022-02-19 17:32:23 +08:00
GyDi
457655b416
feat: traffic line graph 2022-02-19 17:02:24 +08:00
GyDi
7e4506c860
chore: update deps 2022-02-19 00:34:09 +08:00
GyDi
794d376348
feat: adjust profile item ui 2022-02-19 00:23:47 +08:00
GyDi
c60578f5b5
feat: adjust fetch profile url 2022-02-19 00:09:36 +08:00
GyDi
3a9a392a77
feat: inline config file template 2022-02-18 23:57:13 +08:00
GyDi
a13d4698be
chore: update check script 2022-02-18 23:49:39 +08:00
GyDi
c046a1993e
fix: fetch profile panic 2022-02-17 13:44:26 +08:00
GyDi
f709117cc4
feat: kill sidecars when update app 2022-02-17 02:10:25 +08:00
GyDi
30dd298fca
feat: delete file 2022-02-17 01:58:12 +08:00
GyDi
0ff8bb8090
feat: lock some async functions 2022-02-17 01:42:25 +08:00
GyDi
74bbd3c3a2
chore: tauri updater env 2022-02-16 11:02:00 +08:00
GyDi
2e82eaf59a
chore: add pubkey 2022-02-16 10:59:31 +08:00
GyDi
7f1df1f1bd v0.0.15 2022-02-16 03:22:25 +08:00
GyDi
3c79238a44
feat: support open dir 2022-02-16 03:21:34 +08:00
GyDi
0aa2565df3
fix: spawn command 2022-02-16 02:43:52 +08:00
GyDi
22b11db16e
feat: change allow list 2022-02-16 02:42:56 +08:00
GyDi
d0e678b5e9
feat: support check delay 2022-02-16 02:22:01 +08:00
GyDi
e7bba968b3 fix: import error 2022-02-15 01:36:19 +08:00
GyDi
4934a24293
feat: scroll to proxy item 2022-02-15 01:34:10 +08:00
GyDi
ccb68bcda9
chore: update deps 2022-02-15 00:33:58 +08:00
GyDi
66bf4ba3ad
fix: not open file when new profile 2022-02-15 00:21:34 +08:00
GyDi
78a0cfd052
feat: edit system proxy bypass 2022-02-14 01:26:24 +08:00
GyDi
8548373742
feat: disable user select 2022-02-13 19:52:35 +08:00
GyDi
2dfd725ee0
fix: reset value correctly 2022-02-13 19:40:31 +08:00
GyDi
5b779b4f14
feat: new profile able to edit name and desc 2022-02-13 19:33:24 +08:00
GyDi
fc48aa7155 chore: adjust files 2022-02-13 19:27:24 +08:00
GyDi
6193a842f4
feat: update tauri version 2022-02-13 18:45:03 +08:00
GyDi
eb86b471fe
fix: something 2022-02-12 21:12:39 +08:00
GyDi
2b52584547
fix: menu without fragment 2022-02-10 01:42:52 +08:00
GyDi
6e3cc57f48
feat: display clash core version 2022-02-10 01:35:55 +08:00
GyDi
f2c04621a5
feat: adjust profile item menu 2022-02-10 01:14:57 +08:00
GyDi
3ed6938d4a v0.0.14 2022-02-09 02:11:01 +08:00
GyDi
99fec25ed5
feat: profile item ui 2022-02-09 02:08:27 +08:00
GyDi
73758ad1fd
fix: proxy list error 2022-02-09 02:02:29 +08:00
GyDi
c53fe0ed1f
feat: support new profile 2022-02-07 17:26:05 +08:00
GyDi
6082c2bcac
feat: support open command for viewing 2022-02-07 16:45:20 +08:00
GyDi
069abed784
chore: add item template yaml 2022-02-02 20:56:06 +08:00
GyDi
7d8fa4d78a
fix: something 2022-01-31 23:34:58 +08:00
GyDi
76081f8d89
fix: macos auto launch fail 2022-01-31 23:32:41 +08:00
GyDi
5ef4285558
chore: update deps and app name 2022-01-31 23:27:11 +08:00
GyDi
aa7df4282e
chore: cargo update 2022-01-28 22:02:17 +08:00
GyDi
0ef1d5d0de
chore: update clash version 2022-01-28 22:00:15 +08:00
GyDi
cceb4bb81f v0.0.13 2022-01-25 02:11:00 +08:00
GyDi
f0f45e007d
feat: global proxies use virtual list 2022-01-25 02:08:10 +08:00
GyDi
6a8ffe1642
feat: enable change proxy mode 2022-01-25 01:51:44 +08:00
GyDi
3a73868c10
feat: update styles 2022-01-25 01:48:26 +08:00
GyDi
ab1b5897a6
feat: manage clash mode 2022-01-24 23:13:13 +08:00
GyDi
f94734a5c8 chore: update readme 2022-01-22 23:57:39 +08:00
GyDi
61b86c9584 v0.0.12 2022-01-21 03:09:21 +08:00
GyDi
1ac1d6e903
chore: update ci 2022-01-21 03:08:40 +08:00
GyDi
b6c58f74c0
fix: type error 2022-01-21 03:08:20 +08:00
GyDi
c88e99d87c v0.0.12 2022-01-21 02:59:33 +08:00
GyDi
8d7ab9d05e
refactor: rename profiles & command state 2022-01-21 02:57:15 +08:00
GyDi
47155a4a29
feat: change system porxy when changed port 2022-01-21 02:50:13 +08:00
GyDi
d0b87fd7c3
feat: enable change mixed port 2022-01-21 02:32:23 +08:00
GyDi
d49fd37656
feat: manage clash config 2022-01-21 02:31:44 +08:00
GyDi
0bd29d71be
chore: add ahooks 2022-01-21 02:29:45 +08:00
GyDi
4b5b62c8ae
fix: restart clash should update something 2022-01-21 00:29:33 +08:00
GyDi
65fb2ca2d5
feat: enable update clash info 2022-01-20 23:41:08 +08:00
GyDi
0d5bfc0997
feat: rename edit as view 2022-01-19 23:58:34 +08:00
GyDi
4f02c373c2
chore: adjust ci 2022-01-19 23:55:05 +08:00
GyDi
209a5b1207
fix: script error... 2022-01-19 00:49:23 +08:00
GyDi
95349eacab
fix: tag error 2022-01-19 00:46:43 +08:00
GyDi
82ba604b99
fix: script error 2022-01-19 00:42:37 +08:00
GyDi
46a8dec655
feat: test auto gen update.json ci 2022-01-19 00:37:59 +08:00
GyDi
b5af234524 v0.0.11 2022-01-17 02:53:07 +08:00
GyDi
b5c41750f7
fix: remove cargo test 2022-01-17 02:50:19 +08:00
GyDi
6083824eec v0.0.11 2022-01-17 02:44:08 +08:00
GyDi
40977785c3
feat: adjust setting typography 2022-01-17 02:42:52 +08:00
GyDi
5eddf4f1aa
feat: enable force select profile 2022-01-17 02:28:23 +08:00
GyDi
99a8e25411
feat: support edit profile item 2022-01-17 02:16:17 +08:00
GyDi
08587d8f2f
fix: reduce proxy item height 2022-01-17 02:15:54 +08:00
GyDi
3480d50f61
feat: adjust control ui 2022-01-17 02:15:06 +08:00
GyDi
43af55252d
feat: update profile supports noproxy 2022-01-16 22:57:42 +08:00
GyDi
9c43b31fc0
refactor: something 2022-01-16 18:30:25 +08:00
GyDi
9ec7184aa1
fix: put profile request with no proxy 2022-01-16 18:20:01 +08:00
GyDi
4e2cb30db7
refactor: notice caller 2022-01-16 17:56:43 +08:00
GyDi
9ca83d3291
chore: change ci 2022-01-16 16:03:53 +08:00
GyDi
6b2172d873
fix: ci strategy 2022-01-16 14:30:49 +08:00
GyDi
1a5d9f7dad
chore: enhance ci 2022-01-16 14:27:41 +08:00
GyDi
a8425862f0
feat: rename page 2022-01-16 03:25:50 +08:00
GyDi
a3a3db6abb
refactor: setting page 2022-01-16 03:22:37 +08:00
GyDi
d6c3bc57c0
feat: refactor and adjust ui 2022-01-16 03:11:07 +08:00
GyDi
59c09f90f9
feat: rm some commands 2022-01-16 03:09:36 +08:00
GyDi
d982b83e14
feat: change type 2022-01-15 21:58:13 +08:00
GyDi
cc0e930d34
feat: supports auto launch on macos and windows 2022-01-15 21:55:05 +08:00
GyDi
3c3d77fbea
chore: add auto-launch 2022-01-15 21:00:19 +08:00
GyDi
da7453fdbf v0.0.10 2022-01-13 02:53:29 +08:00
GyDi
5fcd25506e feat: adjust proxy page 2022-01-13 02:51:30 +08:00
GyDi
4979a472de feat: press esc hide the window 2022-01-13 02:11:50 +08:00
GyDi
4e8d4f4591 fix: version update error 2022-01-12 22:19:44 +08:00
GyDi
0f5d2b15e0 v0.0.9 2022-01-12 02:55:07 +08:00
GyDi
7fc9631434 feat: show system proxy info 2022-01-12 02:54:50 +08:00
GyDi
df5953dd7b feat: support blur window 2022-01-12 02:27:29 +08:00
GyDi
8f5b2b4a0e chore: add macos startup todo 2022-01-11 23:14:43 +08:00
GyDi
43c63ffa70 chore: cargo update 2022-01-11 23:13:02 +08:00
GyDi
6779bc7459 v0.0.8 2022-01-11 02:27:04 +08:00
GyDi
664be2d0ba chore: update ci 2022-01-11 02:26:50 +08:00
GyDi
6113898b69 feat: windows support startup 2022-01-11 02:24:43 +08:00
GyDi
79aad6b5c2 feat: window self startup 2022-01-11 02:21:51 +08:00
GyDi
6da7757d36 fix: text 2022-01-10 22:57:21 +08:00
GyDi
dbb3cb8cc8 chore: ignore update json 2022-01-10 22:08:57 +08:00
GyDi
579f36a1dd fix: update profile after restart clash 2022-01-10 22:08:18 +08:00
GyDi
72c2b306cf fix: get proxies multiple times 2022-01-10 21:25:41 +08:00
GyDi
c2673cd396 docs: fix img width 2022-01-10 02:52:12 +08:00
GyDi
8eb152816a docs: update 2022-01-10 02:49:42 +08:00
GyDi
a0bc8a21a5 v0.0.7 2022-01-10 02:17:35 +08:00
GyDi
08e4d72758 feat: use tauri updater 2022-01-10 02:15:38 +08:00
GyDi
66340a27fa feat: support update checker 2022-01-10 02:05:35 +08:00
GyDi
83fe9835b6 v0.0.6 2022-01-09 21:36:43 +08:00
GyDi
4c1a50a3ca chore: ci add macos 2022-01-09 21:34:14 +08:00
GyDi
fe44a7b3bc feat: support macos proxy config 2022-01-09 21:19:35 +08:00
GyDi
e86d192db7 feat: custom window decorations 2022-01-08 22:23:48 +08:00
GyDi
ea8f1c52f9 feat: profiles add menu and delete button 2022-01-08 16:52:18 +08:00
GyDi
a4c1573c45 fix: delete profile item command 2022-01-08 14:21:12 +08:00
GyDi
182bf49ad0 chore: temp 2022-01-08 02:54:37 +08:00
GyDi
13e1ddbccd v0.0.5 2022-01-08 02:12:56 +08:00
GyDi
327b9a1757 chore: enhance ci 2022-01-08 02:12:12 +08:00
GyDi
18c48db7f7 chore: rename script 2022-01-08 01:56:28 +08:00
GyDi
b6543bd87f chore: update publish script 2022-01-08 01:51:24 +08:00
GyDi
9ad8f71d7c refactor: rename 2022-01-08 01:27:25 +08:00
GyDi
e369311fc2 refactor: impl structs methods 2022-01-07 23:29:20 +08:00
GyDi
72ff261fe3 chore: update clash version 2022-01-06 23:40:57 +08:00
GyDi
774c6f7e05 fix: initialize profiles state 2022-01-05 23:30:18 +08:00
GyDi
771af6ae08 chore: fixed tauri rev 2022-01-05 23:27:26 +08:00
GyDi
b3cd207444 feat: delay put profiles and retry 2022-01-05 02:01:32 +08:00
GyDi
03f9fa4bc2 refactor: impl as struct methods 2022-01-05 02:00:59 +08:00
GyDi
e32bfd9aab feat: Window Send and Sync 2022-01-04 21:29:04 +08:00
GyDi
7e47f8f893 chore: update tauri 2022-01-04 21:25:00 +08:00
GyDi
cb816e9653 feat: support restart sidecar tray event 2021-12-31 18:24:50 +08:00
GyDi
6b3e7cbc08 feat: prevent click same 2021-12-31 18:21:35 +08:00
GyDi
db4993ae9b fix: item header bgcolor 2021-12-31 18:19:53 +08:00
GyDi
4dc3cf6c6b feat: scroller stable 2021-12-31 18:19:17 +08:00
GyDi
2b84bbf3a8 feat: compatible with macos(wip) 2021-12-29 18:49:38 +08:00
GyDi
26ef4c9961 chore: change tauri to git repo 2021-12-29 18:47:29 +08:00
GyDi
4f56c38599 fix: null type error 2021-12-29 01:01:22 +08:00
GyDi
240f4dcfb1 chore: dev support macos 2021-12-29 01:01:09 +08:00
GyDi
ac6abd81c9 v0.0.4 2021-12-28 01:48:25 +08:00
GyDi
14bda4f3a5 feat: record selected proxy 2021-12-28 01:47:43 +08:00
GyDi
61b9670b45 feat: display version 2021-12-28 01:35:58 +08:00
GyDi
01e8db317e chore: save lock file 2021-12-28 00:14:15 +08:00
GyDi
92fc09493e chore: post version script 2021-12-27 23:07:56 +08:00
GyDi
d927209db7 v0.0.3 2021-12-27 23:06:46 +08:00
GyDi
e94007b21f v0.0.3 2021-12-27 23:06:45 +08:00
GyDi
18750f275a
chore: update version 2021-12-27 10:21:49 +08:00
GyDi
d686a853f4
chore: update version 2021-12-27 10:21:10 +08:00
133 changed files with 11841 additions and 3494 deletions

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

@ -0,0 +1,112 @@
name: Release CI
on: [push]
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') &&
startsWith(github.ref, 'refs/tags/v')
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
profile: minimal
override: true
- name: Rust Cache
uses: Swatinem/rust-cache@ce325b60658c1b38465c06cc965b79baf32c1e72
- name: Install Node
uses: actions/setup-node@v1
with:
node-version: 14
- name: Install Dependencies (ubuntu only)
if: matrix.os == 'ubuntu-latest'
run: |
sudo apt-get update
sudo apt-get install -y libgtk-3-dev webkit2gtk-4.0 libappindicator3-dev librsvg2-dev patchelf
- name: Get yarn cache dir path
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: Green zip bundle
if: matrix.os == 'windows-latest'
run: |
yarn run portable
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
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 }}

View File

@ -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

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

@ -0,0 +1,32 @@
name: Updater CI
on: workflow_dispatch
jobs:
release-update:
runs-on: macos-latest
if: startsWith(github.repository, 'zzzgydi')
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Get yarn cache dir path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- name: Yarn Cache
uses: actions/cache@v2
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: Yarn install
run: yarn install
- name: Release updater file
run: yarn run updater
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

3
.gitignore vendored
View File

@ -3,5 +3,4 @@ node_modules
dist
dist-ssr
*.local
package-lock.json
yarn.lock
update.json

View File

@ -11,22 +11,31 @@ 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/issues/12)
- Simple UI and supports custom theme color.
- System proxy setting and guard.
## Install
Download from [release](https://github.com/zzzgydi/clash-verge/releases). Supports Windows x64, Linux x86_64 and macOS 11+
Or you can build it yourself. Supports Windows, Linux and macOS 10.15+
Notes: If you could not start the app on Windows, please check that you have [Webview2](https://developer.microsoft.com/en-us/microsoft-edge/webview2/#download-section) installed.
## Development
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 +44,12 @@ Then run
yarn dev
```
Or you can build it
```shell
yarn build
```
## Todos
> This keng is a little big...
@ -42,8 +57,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 +82,17 @@ 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.
- [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.

101
UPDATELOG.md Normal file
View File

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

BIN
docs/color1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

BIN
docs/color2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

BIN
docs/color3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

BIN
docs/color4.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

BIN
docs/color5.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

BIN
docs/color6.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 52 KiB

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 73 KiB

After

Width:  |  Height:  |  Size: 30 KiB

BIN
docs/demo3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

BIN
docs/demo4.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

BIN
docs/demo5.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

BIN
docs/demo6.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

View File

@ -1,44 +1,59 @@
{
"name": "clash-verge",
"version": "0.0.1",
"version": "0.0.29",
"license": "GPL-3.0",
"scripts": {
"dev": "cargo tauri dev",
"build": "cargo tauri build",
"dev": "tauri dev",
"build": "tauri build",
"tauri": "tauri",
"web:dev": "vite",
"web:build": "tsc && vite build",
"web:serve": "vite preview",
"predev": "node scripts/pre-dev.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.8.2",
"@emotion/styled": "^11.8.1",
"@mui/icons-material": "^5.6.1",
"@mui/material": "^5.6.1",
"@tauri-apps/api": "^1.0.0-rc.3",
"ahooks": "^3.2.0",
"axios": "^0.26.0",
"dayjs": "^1.11.0",
"i18next": "^21.6.14",
"monaco-editor": "^0.33.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-i18next": "^11.15.6",
"react-router-dom": "^6.2.2",
"react-virtuoso": "~2.7.2",
"recoil": "^0.6.1",
"snarkdown": "^2.0.0",
"swr": "^1.2.2"
},
"devDependencies": {
"@tauri-apps/cli": "^1.0.0-beta.10",
"@actions/github": "^5.0.0",
"@tauri-apps/cli": "^1.0.0-rc.8",
"@types/fs-extra": "^9.0.13",
"@types/js-cookie": "^3.0.1",
"@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": "^1.2.0",
"adm-zip": "^0.5.9",
"fs-extra": "^10.0.0",
"husky": "^7.0.0",
"node-fetch": "^3.1.0",
"node-fetch": "^3.2.0",
"pretty-quick": "^3.1.3",
"sass": "^1.44.0",
"typescript": "^4.5.2",
"vite": "^2.7.1"
"sass": "^1.49.7",
"typescript": "^4.5.5",
"vite": "^2.8.6",
"vite-plugin-monaco-editor": "^1.0.10",
"vite-plugin-svgr": "^1.1.0"
},
"prettier": {
"tabWidth": 2,

169
scripts/check.mjs Normal file
View File

@ -0,0 +1,169 @@
import fs from "fs-extra";
import zlib from "zlib";
import path from "path";
import AdmZip from "adm-zip";
import fetch from "node-fetch";
import { execSync } from "child_process";
const cwd = process.cwd();
const FORCE = process.argv.includes("--force");
/**
* 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.04.11";
// 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 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);
await fs.mkdirp(sidecarDir);
if (!FORCE && (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);
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(cwd, "pre-dev-temp-1");
const tempZip = path.join(tempDir, "wintun.zip");
const wintunPath = path.join(tempDir, "wintun/bin/amd64/wintun.dll");
const targetPath = path.join(cwd, "src-tauri/resources", "wintun.dll");
if (!FORCE && (await fs.pathExists(targetPath))) return;
await fs.mkdirp(tempDir);
if (!(await fs.pathExists(tempZip))) {
await downloadFile(url, tempZip);
}
// unzip
const zip = new AdmZip(tempZip);
zip.extractAllTo(tempDir, true);
if (!(await fs.pathExists(wintunPath))) {
throw new Error(`path not found "${wintunPath}"`);
}
// move wintun.dll to resources
await fs.rename(wintunPath, targetPath);
// delete temp dir
await fs.remove(tempDir);
console.log(`[INFO]: resolve wintun.dll finished`);
}
/**
* get the Country.mmdb (not required)
*/
async function resolveMmdb() {
const url =
"https://github.com/Dreamacro/maxmind-geoip/releases/latest/download/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 response = await fetch(url, {
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);

56
scripts/portable.mjs Normal file
View File

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

View File

@ -1,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
View 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
View File

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

177
scripts/updater.mjs Normal file
View File

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

View File

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

2291
src-tauri/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,29 +1,38 @@
[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-rc.5", features = [] }
[dependencies]
anyhow = "1.0"
dirs = "4.0.0"
open = "2.1.1"
dunce = "1.0.2"
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"] }
tauri = { version = "1.0.0-rc.6", features = ["process-all", "shell-all", "system-tray", "updater", "window-all"] }
window-shadows = { git = "https://github.com/tauri-apps/window-shadows" }
window-vibrancy = { git = "https://github.com/tauri-apps/window-vibrancy" }
reqwest = { version = "0.11", features = ["json"] }
tokio = { version = "1", features = ["full"] }
log = "0.4.14"
log4rs = "1.0.0"
warp = "0.3"
which = "4.2.2"
auto-launch = "0.2"
port_scanner = "0.1.5"
[target.'cfg(windows)'.dependencies]
@ -32,3 +41,11 @@ winreg = { version = "0.10", features = ["transactions"] }
[features]
default = [ "custom-protocol" ]
custom-protocol = [ "tauri/custom-protocol" ]
verge-dev = []
debug-yml = []
[profile.release]
panic = "abort"
codegen-units = 1
lto = true
opt-level = "s"

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

View File

@ -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: ""

View File

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

View File

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

383
src-tauri/src/cmds.rs Normal file
View File

@ -0,0 +1,383 @@
use crate::{
core::{ClashInfo, PrfItem, PrfOption, Profiles, VergeConfig},
states::{ClashState, ProfilesState, VergeState},
utils::{dirs, sysopt::SysProxyConfig},
};
use crate::{ret_err, wrap_err};
use anyhow::Result;
use serde_yaml::Mapping;
use std::process::Command;
use tauri::{api, Manager, State};
/// get all profiles from `profiles.yaml`
#[tauri::command]
pub fn get_profiles<'a>(profiles_state: State<'_, ProfilesState>) -> Result<Profiles, String> {
let profiles = profiles_state.0.lock().unwrap();
Ok(profiles.clone())
}
/// synchronize data irregularly
#[tauri::command]
pub fn sync_profiles(profiles_state: State<'_, ProfilesState>) -> Result<(), String> {
let mut profiles = profiles_state.0.lock().unwrap();
wrap_err!(profiles.sync_file())
}
/// import the profile from url
/// and save to `profiles.yaml`
#[tauri::command]
pub async fn import_profile(
url: String,
option: Option<PrfOption>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let item = wrap_err!(PrfItem::from_url(&url, None, None, option).await)?;
let mut profiles = profiles_state.0.lock().unwrap();
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>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let item = wrap_err!(PrfItem::from(item, file_data).await)?;
let mut profiles = profiles_state.0.lock().unwrap();
wrap_err!(profiles.append_item(item))
}
/// Update the profile
#[tauri::command]
pub async fn update_profile(
index: String,
option: Option<PrfOption>,
clash_state: State<'_, ClashState>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let (url, opt) = {
// must release the lock here
let profiles = profiles_state.0.lock().unwrap();
let item = wrap_err!(profiles.get_item(&index))?;
// check the profile type
if let Some(typ) = item.itype.as_ref() {
if *typ != "remote" {
ret_err!(format!("could not update the `{typ}` profile"));
}
}
if item.url.is_none() {
ret_err!("failed to get the item url");
}
(item.url.clone().unwrap(), item.option.clone())
};
let fetch_opt = PrfOption::merge(opt, option);
let item = wrap_err!(PrfItem::from_url(&url, None, None, fetch_opt).await)?;
let mut profiles = profiles_state.0.lock().unwrap();
wrap_err!(profiles.update_item(index.clone(), item))?;
// reactivate the profile
if Some(index) == profiles.get_current() {
let clash = clash_state.0.lock().unwrap();
wrap_err!(clash.activate_enhanced(&profiles, false, false))?;
}
Ok(())
}
/// change the current profile
#[tauri::command]
pub fn select_profile(
index: String,
clash_state: State<'_, ClashState>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let mut profiles = profiles_state.0.lock().unwrap();
wrap_err!(profiles.put_current(index))?;
let clash = clash_state.0.lock().unwrap();
wrap_err!(clash.activate_enhanced(&profiles, false, false))
}
/// change the profile chain
#[tauri::command]
pub fn change_profile_chain(
chain: Option<Vec<String>>,
app_handle: tauri::AppHandle,
clash_state: State<'_, ClashState>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let mut clash = clash_state.0.lock().unwrap();
let mut profiles = profiles_state.0.lock().unwrap();
profiles.put_chain(chain);
clash.set_window(app_handle.get_window("main"));
wrap_err!(clash.activate_enhanced(&profiles, false, false))
}
/// change the profile valid fields
#[tauri::command]
pub fn change_profile_valid(
valid: Option<Vec<String>>,
app_handle: tauri::AppHandle,
clash_state: State<'_, ClashState>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let mut clash = clash_state.0.lock().unwrap();
let mut profiles = profiles_state.0.lock().unwrap();
profiles.put_valid(valid);
clash.set_window(app_handle.get_window("main"));
wrap_err!(clash.activate_enhanced(&profiles, false, false))
}
/// manually exec enhanced profile
#[tauri::command]
pub fn enhance_profiles(
app_handle: tauri::AppHandle,
clash_state: State<'_, ClashState>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let mut clash = clash_state.0.lock().unwrap();
let profiles = profiles_state.0.lock().unwrap();
clash.set_window(app_handle.get_window("main"));
wrap_err!(clash.activate_enhanced(&profiles, false, false))
}
/// delete profile item
#[tauri::command]
pub fn delete_profile(
index: String,
clash_state: State<'_, ClashState>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let mut profiles = profiles_state.0.lock().unwrap();
if wrap_err!(profiles.delete_item(index))? {
let clash = clash_state.0.lock().unwrap();
wrap_err!(clash.activate_enhanced(&profiles, false, false))?;
}
Ok(())
}
/// patch the profile config
#[tauri::command]
pub fn patch_profile(
index: String,
profile: PrfItem,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let mut profiles = profiles_state.0.lock().unwrap();
wrap_err!(profiles.patch_item(index, profile))
}
/// run vscode command to edit the profile
#[tauri::command]
pub fn view_profile(index: String, profiles_state: State<'_, ProfilesState>) -> Result<(), String> {
let profiles = profiles_state.0.lock().unwrap();
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");
}
// 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()
{
log::error!("failed to open file by VScode for {err}");
return Err("failed to open file by VScode".into());
}
}
#[cfg(not(target_os = "windows"))]
if let Err(err) = Command::new(code).arg(path).spawn() {
log::error!("failed to open file by VScode for {err}");
return Err("failed to open file by VScode".into());
}
return Ok(());
}
wrap_err!(open::that(path))
}
/// read the profile item file data
#[tauri::command]
pub fn read_profile_file(
index: String,
profiles_state: State<'_, ProfilesState>,
) -> Result<String, String> {
let profiles = profiles_state.0.lock().unwrap();
let item = wrap_err!(profiles.get_item(&index))?;
let data = wrap_err!(item.read_file())?;
Ok(data)
}
/// save the profile item file data
#[tauri::command]
pub fn save_profile_file(
index: String,
file_data: Option<String>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
if file_data.is_none() {
return Ok(());
}
let profiles = profiles_state.0.lock().unwrap();
let item = wrap_err!(profiles.get_item(&index))?;
wrap_err!(item.save_file(file_data.unwrap()))
}
/// restart the sidecar
#[tauri::command]
pub fn restart_sidecar(
clash_state: State<'_, ClashState>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let mut clash = clash_state.0.lock().unwrap();
let mut profiles = profiles_state.0.lock().unwrap();
wrap_err!(clash.restart_sidecar(&mut profiles))
}
/// get the clash core info from the state
/// the caller can also get the infomation by clash's api
#[tauri::command]
pub fn get_clash_info(clash_state: State<'_, ClashState>) -> Result<ClashInfo, String> {
let clash = clash_state.0.lock().unwrap();
Ok(clash.info.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,
clash_state: State<'_, ClashState>,
verge_state: State<'_, VergeState>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let mut clash = clash_state.0.lock().unwrap();
let mut verge = verge_state.0.lock().unwrap();
let mut profiles = profiles_state.0.lock().unwrap();
wrap_err!(clash.patch_config(payload, &mut verge, &mut profiles))
}
/// 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(verge_state: State<'_, VergeState>) -> Result<Option<SysProxyConfig>, String> {
let verge = verge_state.0.lock().unwrap();
Ok(verge.cur_sysproxy.clone())
}
/// get the verge config
#[tauri::command]
pub fn get_verge_config(verge_state: State<'_, VergeState>) -> Result<VergeConfig, String> {
let verge = verge_state.0.lock().unwrap();
let mut config = verge.config.clone();
if config.system_proxy_bypass.is_none() && verge.cur_sysproxy.is_some() {
config.system_proxy_bypass = Some(verge.cur_sysproxy.clone().unwrap().bypass)
}
Ok(config)
}
/// patch the verge config
/// this command only save the config and not responsible for other things
#[tauri::command]
pub fn patch_verge_config(
payload: VergeConfig,
app_handle: tauri::AppHandle,
clash_state: State<'_, ClashState>,
verge_state: State<'_, VergeState>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let tun_mode = payload.enable_tun_mode.clone();
let system_proxy = payload.enable_system_proxy.clone();
let mut verge = verge_state.0.lock().unwrap();
wrap_err!(verge.patch_config(payload))?;
// change tun mode
if tun_mode.is_some() {
#[cfg(target_os = "windows")]
if *tun_mode.as_ref().unwrap() {
let wintun_dll = dirs::app_home_dir().join("wintun.dll");
if !wintun_dll.exists() {
log::error!("failed to enable TUN for missing `wintun.dll`");
return Err("failed to enable TUN for missing `wintun.dll`".into());
}
}
let clash = clash_state.0.lock().unwrap();
let profiles = profiles_state.0.lock().unwrap();
wrap_err!(clash.activate_enhanced(&profiles, false, false))?;
}
// change system tray
if system_proxy.is_some() || tun_mode.is_some() {
verge.update_systray(&app_handle).unwrap();
}
Ok(())
}
/// kill all sidecars when update app
#[tauri::command]
pub fn kill_sidecars() {
api::process::kill_children();
}
/// open app config dir
#[tauri::command]
pub fn open_app_dir() -> Result<(), String> {
let app_dir = dirs::app_home_dir();
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))
}

View File

@ -1,2 +0,0 @@
pub mod profile;
pub mod some;

View File

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

View File

@ -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)
}

View File

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

View File

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

View File

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

518
src-tauri/src/core/clash.rs Normal file
View File

@ -0,0 +1,518 @@
use super::{PrfEnhancedResult, Profiles, Verge, VergeConfig};
use crate::log_if_err;
use crate::utils::{config, dirs, help};
use anyhow::{bail, Result};
use reqwest::header::HeaderMap;
use serde::{Deserialize, Serialize};
use serde_yaml::{Mapping, Value};
use std::{collections::HashMap, time::Duration};
use tauri::api::process::{Command, CommandChild, CommandEvent};
use tauri::Window;
use tokio::time::sleep;
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
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>,
}
pub struct Clash {
/// maintain the clash config
pub config: Mapping,
/// some info
pub info: ClashInfo,
/// clash sidecar
pub sidecar: Option<CommandChild>,
/// save the main window
pub window: Option<Window>,
}
impl Clash {
pub fn new() -> Clash {
let config = Clash::read_config();
let info = Clash::get_info(&config);
Clash {
config,
info,
sidecar: None,
window: None,
}
}
/// get clash config
fn read_config() -> Mapping {
config::read_yaml::<Mapping>(dirs::clash_path())
}
/// save the clash config
fn save_config(&self) -> Result<()> {
config::save_yaml(
dirs::clash_path(),
&self.config,
Some("# Default Config For Clash Core\n\n"),
)
}
/// parse the clash's config.yaml
/// get some information
fn get_info(clash_config: &Mapping) -> ClashInfo {
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 clash_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 clash_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 server = match clash_config.get(&key_server) {
Some(value) => match value {
Value::String(val_str) => {
// `external-controller` could be
// "127.0.0.1:9090" or ":9090"
// Todo: maybe it could support single port
let server = val_str.clone();
let server = match server.starts_with(":") {
true => format!("127.0.0.1{server}"),
false => server,
};
Some(server)
}
_ => None,
},
_ => None,
};
let secret = match clash_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: "init".into(),
port,
server,
secret,
}
}
/// save the main window
pub fn set_window(&mut self, win: Option<Window>) {
self.window = win;
}
/// run clash sidecar
pub fn run_sidecar(&mut self) -> Result<()> {
let app_dir = dirs::app_home_dir();
let app_dir = app_dir.as_os_str().to_str().unwrap();
match Command::new_sidecar("clash") {
Ok(cmd) => match cmd.args(["-d", app_dir]).spawn() {
Ok((mut rx, cmd_child)) => {
self.sidecar = Some(cmd_child);
// clash log
tauri::async_runtime::spawn(async move {
while let Some(event) = rx.recv().await {
match event {
CommandEvent::Stdout(line) => log::info!("[clash]: {}", line),
CommandEvent::Stderr(err) => log::error!("[clash]: {}", err),
_ => {}
}
}
});
Ok(())
}
Err(err) => bail!(err.to_string()),
},
Err(err) => bail!(err.to_string()),
}
}
/// drop clash sidecar
pub fn drop_sidecar(&mut self) -> Result<()> {
if let Some(sidecar) = self.sidecar.take() {
sidecar.kill()?;
}
Ok(())
}
/// restart clash sidecar
/// should reactivate profile after restart
pub fn restart_sidecar(&mut self, profiles: &mut Profiles) -> Result<()> {
self.update_config();
self.drop_sidecar()?;
self.run_sidecar()?;
self.activate(profiles)?;
self.activate_enhanced(profiles, false, true)
}
/// update the clash info
pub fn update_config(&mut self) {
self.config = Clash::read_config();
self.info = Clash::get_info(&self.config);
}
/// patch update the clash config
pub fn patch_config(
&mut self,
patch: Mapping,
verge: &mut Verge,
profiles: &mut Profiles,
) -> Result<()> {
let mix_port_key = Value::from("mixed-port");
let mut port = None;
for (key, value) in patch.into_iter() {
let value = value.clone();
// check whether the mix_port is changed
if key == mix_port_key {
if value.is_number() {
port = value.as_i64().as_ref().map(|n| n.to_string());
} else {
port = value.as_str().as_ref().map(|s| s.to_string());
}
}
self.config.insert(key.clone(), value);
}
self.save_config()?;
if let Some(port) = port {
self.restart_sidecar(profiles)?;
verge.init_sysproxy(Some(port));
}
Ok(())
}
/// revise the `tun` and `dns` config
fn _tun_mode(mut config: Mapping, enable: bool) -> Mapping {
macro_rules! revise {
($map: expr, $key: expr, $val: expr) => {
let ret_key = Value::String($key.into());
$map.insert(ret_key, Value::from($val));
};
}
// if key not exists then append value
macro_rules! append {
($map: expr, $key: expr, $val: expr) => {
let ret_key = Value::String($key.into());
if !$map.contains_key(&ret_key) {
$map.insert(ret_key, Value::from($val));
}
};
}
// tun config
let tun_val = config.get(&Value::from("tun"));
let mut new_tun = Mapping::new();
if tun_val.is_some() && tun_val.as_ref().unwrap().is_mapping() {
new_tun = tun_val.as_ref().unwrap().as_mapping().unwrap().clone();
}
revise!(new_tun, "enable", enable);
if enable {
append!(new_tun, "stack", "gvisor");
append!(new_tun, "dns-hijack", vec!["198.18.0.2:53"]);
append!(new_tun, "auto-route", true);
append!(new_tun, "auto-detect-interface", true);
}
revise!(config, "tun", new_tun);
// dns config
let dns_val = config.get(&Value::from("dns"));
let mut new_dns = Mapping::new();
if dns_val.is_some() && dns_val.as_ref().unwrap().is_mapping() {
new_dns = dns_val.as_ref().unwrap().as_mapping().unwrap().clone();
}
// 借鉴cfw的默认配置
revise!(new_dns, "enable", enable);
if enable {
append!(new_dns, "enhanced-mode", "fake-ip");
append!(
new_dns,
"nameserver",
vec!["114.114.114.114", "223.5.5.5", "8.8.8.8"]
);
append!(new_dns, "fallback", vec![] as Vec<&str>);
#[cfg(target_os = "windows")]
append!(
new_dns,
"fake-ip-filter",
vec![
"dns.msftncsi.com",
"www.msftncsi.com",
"www.msftconnecttest.com"
]
);
}
revise!(config, "dns", new_dns);
config
}
/// activate the profile
/// generate a new profile to the temp_dir
/// then put the path to the clash core
fn _activate(info: ClashInfo, config: Mapping, window: Option<Window>) -> Result<()> {
let verge_config = VergeConfig::new();
let tun_enable = verge_config.enable_tun_mode.unwrap_or(false);
let config = Clash::_tun_mode(config, tun_enable);
let temp_path = dirs::profiles_temp_path();
config::save_yaml(temp_path.clone(), &config, Some("# Clash Verge Temp File"))?;
tauri::async_runtime::spawn(async move {
let server = info.server.unwrap();
let server = format!("http://{server}/configs");
let mut headers = HeaderMap::new();
headers.insert("Content-Type", "application/json".parse().unwrap());
if let Some(secret) = info.secret.as_ref() {
let secret = format!("Bearer {}", secret.clone()).parse().unwrap();
headers.insert("Authorization", secret);
}
let mut data = HashMap::new();
data.insert("path", temp_path.as_os_str().to_str().unwrap());
// retry 5 times
for _ in 0..5 {
match reqwest::ClientBuilder::new().no_proxy().build() {
Ok(client) => {
let builder = client.put(&server).headers(headers.clone()).json(&data);
match builder.send().await {
Ok(resp) => {
if resp.status() != 204 {
log::error!("failed to activate clash for status \"{}\"", resp.status());
}
// emit the window to update something
if let Some(window) = window {
window.emit("verge://refresh-clash-config", "yes").unwrap();
}
// do not retry
break;
}
Err(err) => log::error!("failed to activate for `{err}`"),
}
}
Err(err) => log::error!("failed to activate for `{err}`"),
}
sleep(Duration::from_millis(500)).await;
}
});
Ok(())
}
/// enhanced profiles mode
/// - (sync) refresh config if enhance chain is null
/// - (async) enhanced config
pub fn activate_enhanced(&self, profiles: &Profiles, delay: bool, skip: bool) -> Result<()> {
if self.window.is_none() {
bail!("failed to get the main window");
}
let event_name = help::get_uid("e");
let event_name = format!("enhanced-cb-{event_name}");
// generate the payload
let payload = profiles.gen_enhanced(event_name.clone())?;
let info = self.info.clone();
// do not run enhanced
if payload.chain.len() == 0 {
if skip {
return Ok(());
}
let mut config = self.config.clone();
let filter_data = Clash::strict_filter(payload.current);
for (key, value) in filter_data.into_iter() {
config.insert(key, value);
}
return Clash::_activate(info, config, self.window.clone());
}
let window = self.window.clone().unwrap();
let window_move = self.window.clone();
window.once(&event_name, move |event| {
if let Some(result) = event.payload() {
let result: PrfEnhancedResult = serde_json::from_str(result).unwrap();
if let Some(data) = result.data {
let mut config = Clash::read_config();
let filter_data = Clash::loose_filter(data); // loose filter
for (key, value) in filter_data.into_iter() {
config.insert(key, value);
}
log_if_err!(Clash::_activate(info, config, window_move));
log::info!("profile enhanced status {}", result.status);
}
result.error.map(|err| log::error!("{err}"));
}
});
tauri::async_runtime::spawn(async move {
// wait the window setup during resolve app
if delay {
sleep(Duration::from_secs(2)).await;
}
window.emit("script-handler", payload).unwrap();
});
Ok(())
}
/// activate the profile
/// auto activate enhanced profile
pub fn activate(&self, profiles: &Profiles) -> Result<()> {
let data = profiles.gen_activate()?;
let data = Clash::strict_filter(data);
let info = self.info.clone();
let mut config = self.config.clone();
for (key, value) in data.into_iter() {
config.insert(key, value);
}
Clash::_activate(info, config, self.window.clone())
}
/// only 5 default fields available (clash config fields)
/// convert to lowercase
fn strict_filter(config: Mapping) -> Mapping {
// Only the following fields are allowed:
// proxies/proxy-providers/proxy-groups/rule-providers/rules
let valid_keys = vec![
"proxies",
"proxy-providers",
"proxy-groups",
"rules",
"rule-providers",
];
let mut new_config = Mapping::new();
for (key, value) in config.into_iter() {
key.as_str().map(|key_str| {
// change to lowercase
let mut key_str = String::from(key_str);
key_str.make_ascii_lowercase();
// filter
if valid_keys.contains(&&*key_str) {
new_config.insert(Value::String(key_str), value);
}
});
}
new_config
}
/// more clash config fields available
/// convert to lowercase
fn loose_filter(config: Mapping) -> Mapping {
// all of these can not be revised by script or merge
// http/https/socks port should be under control
let not_allow = vec![
"port",
"socks-port",
"mixed-port",
"allow-lan",
"mode",
"external-controller",
"secret",
"log-level",
];
let mut new_config = Mapping::new();
for (key, value) in config.into_iter() {
key.as_str().map(|key_str| {
// change to lowercase
let mut key_str = String::from(key_str);
key_str.make_ascii_lowercase();
// filter
if !not_allow.contains(&&*key_str) {
new_config.insert(Value::String(key_str), value);
}
});
}
new_config
}
}
impl Default for Clash {
fn default() -> Self {
Clash::new()
}
}
impl Drop for Clash {
fn drop(&mut self) {
if let Err(err) = self.drop_sidecar() {
log::error!("{err}");
}
}
}

View File

@ -0,0 +1,679 @@
use crate::utils::{config, dirs, help, tmpl};
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use serde_yaml::Mapping;
use std::{fs, io::Write};
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PrfItem {
pub uid: Option<String>,
/// profile item type
/// enum value: remote | local | script | merge
#[serde(rename = "type")]
pub itype: Option<String>,
/// profile name
pub name: Option<String>,
/// profile description
#[serde(skip_serializing_if = "Option::is_none")]
pub desc: Option<String>,
/// profile file
pub file: Option<String>,
/// source url
#[serde(skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
/// selected infomation
#[serde(skip_serializing_if = "Option::is_none")]
pub selected: Option<Vec<PrfSelected>>,
/// subscription user info
#[serde(skip_serializing_if = "Option::is_none")]
pub extra: Option<PrfExtra>,
/// updated time
pub updated: Option<usize>,
/// some options of the item
#[serde(skip_serializing_if = "Option::is_none")]
pub option: Option<PrfOption>,
/// the file data
#[serde(skip)]
pub file_data: Option<String>,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct PrfSelected {
pub name: Option<String>,
pub now: Option<String>,
}
#[derive(Default, Debug, Clone, Copy, Deserialize, Serialize)]
pub struct PrfExtra {
pub upload: usize,
pub download: usize,
pub total: usize,
pub expire: usize,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct PrfOption {
/// for `remote` profile's http request
/// see issue #13
#[serde(skip_serializing_if = "Option::is_none")]
pub user_agent: Option<String>,
/// for `remote` profile
#[serde(skip_serializing_if = "Option::is_none")]
pub with_proxy: Option<bool>,
}
impl PrfOption {
pub fn merge(one: Option<Self>, other: Option<Self>) -> Option<Self> {
if one.is_some() && other.is_some() {
let mut one = one.unwrap();
let other = other.unwrap();
if let Some(val) = other.user_agent {
one.user_agent = Some(val);
}
if let Some(val) = other.with_proxy {
one.with_proxy = Some(val);
}
return Some(one);
}
if one.is_none() {
return other;
}
return one;
}
}
impl Default for PrfItem {
fn default() -> Self {
PrfItem {
uid: None,
itype: None,
name: None,
desc: None,
file: None,
url: None,
selected: None,
extra: None,
updated: None,
option: None,
file_data: None,
}
}
}
impl PrfItem {
/// From partial item
/// must contain `itype`
pub async fn from(item: PrfItem, file_data: Option<String>) -> Result<PrfItem> {
if item.itype.is_none() {
bail!("type should not be null");
}
match item.itype.unwrap().as_str() {
"remote" => {
if item.url.is_none() {
bail!("url should not be null");
}
let url = item.url.as_ref().unwrap().as_str();
let name = item.name;
let desc = item.desc;
PrfItem::from_url(url, name, desc, item.option).await
}
"local" => {
let name = item.name.unwrap_or("Local File".into());
let desc = item.desc.unwrap_or("".into());
PrfItem::from_local(name, desc, file_data)
}
"merge" => {
let name = item.name.unwrap_or("Merge".into());
let desc = item.desc.unwrap_or("".into());
PrfItem::from_merge(name, desc)
}
"script" => {
let name = item.name.unwrap_or("Script".into());
let desc = item.desc.unwrap_or("".into());
PrfItem::from_script(name, desc)
}
typ @ _ => bail!("invalid type \"{typ}\""),
}
}
/// ## Local type
/// create a new item from name/desc
pub fn from_local(name: String, desc: String, file_data: Option<String>) -> Result<PrfItem> {
let uid = help::get_uid("l");
let file = format!("{uid}.yaml");
Ok(PrfItem {
uid: Some(uid),
itype: Some("local".into()),
name: Some(name),
desc: Some(desc),
file: Some(file),
url: None,
selected: None,
extra: None,
option: None,
updated: Some(help::get_now()),
file_data: Some(file_data.unwrap_or(tmpl::ITEM_LOCAL.into())),
})
}
/// ## Remote type
/// create a new item from url
pub async fn from_url(
url: &str,
name: Option<String>,
desc: Option<String>,
option: Option<PrfOption>,
) -> Result<PrfItem> {
let with_proxy = match option.as_ref() {
Some(opt) => opt.with_proxy.unwrap_or(false),
None => false,
};
let user_agent = match option.as_ref() {
Some(opt) => opt.user_agent.clone(),
None => None,
};
let mut builder = reqwest::ClientBuilder::new();
if !with_proxy {
builder = builder.no_proxy();
}
builder = builder.user_agent(user_agent.unwrap_or("clash-verge/v0.1.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,
};
let uid = help::get_uid("r");
let file = format!("{uid}.yaml");
let name = name.unwrap_or(uid.clone());
let data = resp.text_with_charset("utf-8").await?;
Ok(PrfItem {
uid: Some(uid),
itype: Some("remote".into()),
name: Some(name),
desc,
file: Some(file),
url: Some(url.into()),
selected: None,
extra,
option,
updated: Some(help::get_now()),
file_data: Some(data),
})
}
/// ## Merge type (enhance)
/// create the enhanced item by using `merge` rule
pub fn from_merge(name: String, desc: String) -> Result<PrfItem> {
let uid = help::get_uid("m");
let file = format!("{uid}.yaml");
Ok(PrfItem {
uid: Some(uid),
itype: Some("merge".into()),
name: Some(name),
desc: Some(desc),
file: Some(file),
url: None,
selected: None,
extra: None,
option: None,
updated: Some(help::get_now()),
file_data: Some(tmpl::ITEM_MERGE.into()),
})
}
/// ## Script type (enhance)
/// create the enhanced item by using javascript(browserjs)
pub fn from_script(name: String, desc: String) -> Result<PrfItem> {
let uid = help::get_uid("s");
let file = format!("{uid}.js"); // js ext
Ok(PrfItem {
uid: Some(uid),
itype: Some("script".into()),
name: Some(name),
desc: Some(desc),
file: Some(file),
url: None,
selected: None,
extra: None,
option: None,
updated: Some(help::get_now()),
file_data: Some(tmpl::ITEM_SCRIPT.into()),
})
}
/// get the file data
pub fn read_file(&self) -> Result<String> {
if self.file.is_none() {
bail!("could not find the file");
}
let file = self.file.clone().unwrap();
let path = dirs::app_profiles_dir().join(file);
fs::read_to_string(path).context("failed to read the file")
}
/// save the file data
pub fn save_file(&self, data: String) -> Result<()> {
if self.file.is_none() {
bail!("could not find the file");
}
let file = self.file.clone().unwrap();
let path = dirs::app_profiles_dir().join(file);
fs::write(path, data.as_bytes()).context("failed to save the file")
}
}
///
/// ## Profiles Config
///
/// 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 {
/// 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![]);
}
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"),
)
}
/// sync the config between file and memory
pub fn sync_file(&mut self) -> Result<()> {
let data = Self::read_file();
if data.current.is_none() && data.items.is_none() {
bail!("failed to read profiles.yaml");
}
self.current = data.current;
self.chain = data.chain;
self.items = data.items;
Ok(())
}
/// get the current uid
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());
for each in items.iter() {
if each.uid == some_uid {
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>>) {
self.chain = chain;
}
/// just change the `field`
pub fn put_valid(&mut self, valid: Option<Vec<String>>) {
self.valid = valid;
}
/// find the item by the uid
pub fn get_item(&self, uid: &String) -> Result<&PrfItem> {
if self.items.is_some() {
let items = self.items.as_ref().unwrap();
let some_uid = Some(uid.clone());
for each in items.iter() {
if each.uid == some_uid {
return Ok(each);
}
}
}
bail!("failed to get the item by \"{}\"", uid);
}
/// append new item
/// if the file_data is some
/// then should save the data to file
pub fn append_item(&mut self, mut item: PrfItem) -> Result<()> {
if item.uid.is_none() {
bail!("the uid should not be null");
}
// save the file data
// move the field value after save
if let Some(file_data) = item.file_data.take() {
if item.file.is_none() {
bail!("the file should not be null");
}
let file = item.file.clone().unwrap();
let path = dirs::app_profiles_dir().join(&file);
fs::File::create(path)
.context(format!("failed to create file \"{}\"", file))?
.write(file_data.as_bytes())
.context(format!("failed to write to file \"{}\"", file))?;
}
if self.items.is_none() {
self.items = Some(vec![]);
}
self.items.as_mut().map(|items| items.push(item));
self.save_file()
}
/// update the item's value
pub fn patch_item(&mut self, uid: String, item: PrfItem) -> Result<()> {
let mut items = self.items.take().unwrap_or(vec![]);
for mut each in items.iter_mut() {
if each.uid == Some(uid.clone()) {
patch!(each, item, itype);
patch!(each, item, name);
patch!(each, item, desc);
patch!(each, item, file);
patch!(each, item, url);
patch!(each, item, selected);
patch!(each, item, extra);
patch!(each, item, updated);
patch!(each, item, option);
self.items = Some(items);
return self.save_file();
}
}
self.items = Some(items);
bail!("failed to found the uid \"{uid}\"")
}
/// be used to update the remote item
/// only patch `updated` `extra` `file_data`
pub fn update_item(&mut self, uid: String, mut item: PrfItem) -> Result<()> {
if self.items.is_none() {
self.items = Some(vec![]);
}
// find the item
let _ = self.get_item(&uid)?;
self.items.as_mut().map(|items| {
let some_uid = Some(uid.clone());
for mut each in items.iter_mut() {
if each.uid == some_uid {
each.extra = item.extra;
each.updated = item.updated;
// save the file data
// move the field value after save
if let Some(file_data) = item.file_data.take() {
let file = each.file.take();
let file = file.unwrap_or(item.file.take().unwrap_or(format!("{}.yaml", &uid)));
// the file must exists
each.file = Some(file.clone());
let path = dirs::app_profiles_dir().join(&file);
fs::File::create(path)
.unwrap()
.write(file_data.as_bytes())
.unwrap();
}
break;
}
}
});
self.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)
}
/// only generate config mapping
pub fn gen_activate(&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 found the uid \"{current}\"");
}
/// gen the enhanced profiles
pub fn gen_enhanced(&self, callback: String) -> Result<PrfEnhanced> {
let current = self.gen_activate()?;
let chain = match self.chain.as_ref() {
Some(chain) => chain
.iter()
.map(|uid| self.get_item(uid))
.filter(|item| item.is_ok())
.map(|item| item.unwrap())
.map(|item| PrfData::from_item(item))
.filter(|o| o.is_some())
.map(|o| o.unwrap())
.collect::<Vec<PrfData>>(),
None => vec![],
};
let valid = self.valid.clone().unwrap_or(vec![]);
Ok(PrfEnhanced {
current,
chain,
valid,
callback,
})
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct PrfEnhanced {
pub current: Mapping,
pub chain: Vec<PrfData>,
pub valid: Vec<String>,
pub callback: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct PrfEnhancedResult {
pub data: Option<Mapping>,
pub status: String,
pub error: Option<String>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct PrfData {
item: PrfItem,
#[serde(skip_serializing_if = "Option::is_none")]
merge: Option<Mapping>,
#[serde(skip_serializing_if = "Option::is_none")]
script: Option<String>,
}
impl PrfData {
pub fn from_item(item: &PrfItem) -> Option<PrfData> {
match item.itype.as_ref() {
Some(itype) => {
let file = item.file.clone()?;
let path = dirs::app_profiles_dir().join(file);
if !path.exists() {
return None;
}
match itype.as_str() {
"script" => Some(PrfData {
item: item.clone(),
script: Some(fs::read_to_string(path).unwrap_or("".into())),
merge: None,
}),
"merge" => Some(PrfData {
item: item.clone(),
merge: Some(config::read_yaml::<Mapping>(path)),
script: None,
}),
_ => None,
}
}
None => None,
}
}
}

382
src-tauri/src/core/verge.rs Normal file
View File

@ -0,0 +1,382 @@
use crate::log_if_err;
use crate::{
core::Clash,
utils::{config, dirs, sysopt::SysProxyConfig},
};
use anyhow::{bail, Result};
use auto_launch::{AutoLaunch, AutoLaunchBuilder};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tauri::{async_runtime::Mutex, utils::platform::current_exe};
use tauri::{AppHandle, Manager};
/// ### `verge.yaml` schema
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct VergeConfig {
// 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>,
/// 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>,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct VergeTheme {
pub primary_color: Option<String>,
pub secondary_color: Option<String>,
pub primary_text: Option<String>,
pub secondary_text: Option<String>,
pub info_color: Option<String>,
pub error_color: Option<String>,
pub warning_color: Option<String>,
pub success_color: Option<String>,
pub font_family: Option<String>,
pub css_injection: Option<String>,
}
impl VergeConfig {
pub fn new() -> Self {
config::read_yaml::<VergeConfig>(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"),
)
}
}
/// Verge App abilities
#[derive(Debug)]
pub struct Verge {
/// manage the verge config
pub config: VergeConfig,
/// current system proxy setting
pub cur_sysproxy: Option<SysProxyConfig>,
/// record the original system proxy
/// recover it when exit
old_sysproxy: Option<SysProxyConfig>,
/// helps to auto launch the app
auto_launch: Option<AutoLaunch>,
/// record whether the guard async is running or not
guard_state: Arc<Mutex<bool>>,
}
impl Default for Verge {
fn default() -> Self {
Verge::new()
}
}
impl Verge {
pub fn new() -> Self {
Verge {
config: VergeConfig::new(),
old_sysproxy: None,
cur_sysproxy: None,
auto_launch: None,
guard_state: Arc::new(Mutex::new(false)),
}
}
/// init the sysproxy
pub fn init_sysproxy(&mut self, port: Option<String>) {
if let Some(port) = port {
let enable = self.config.enable_system_proxy.clone().unwrap_or(false);
self.old_sysproxy = match SysProxyConfig::get_sys() {
Ok(proxy) => Some(proxy),
Err(_) => None,
};
let bypass = self.config.system_proxy_bypass.clone();
let sysproxy = SysProxyConfig::new(enable, port, bypass);
if enable {
if sysproxy.set_sys().is_err() {
log::error!("failed to set system proxy");
}
}
self.cur_sysproxy = Some(sysproxy);
}
// launchs the system proxy guard
Verge::guard_proxy(self.guard_state.clone());
}
/// reset the sysproxy
pub fn reset_sysproxy(&mut self) {
if let Some(sysproxy) = self.old_sysproxy.take() {
match sysproxy.set_sys() {
Ok(_) => self.cur_sysproxy = None,
Err(_) => log::error!("failed to reset proxy"),
}
}
}
/// init the auto launch
pub fn init_launch(&mut self) -> Result<()> {
let app_exe = current_exe().unwrap();
let app_exe = dunce::canonicalize(app_exe).unwrap();
let app_name = app_exe.file_stem().unwrap().to_str().unwrap();
let app_path = app_exe.as_os_str().to_str().unwrap();
// fix issue #26
#[cfg(target_os = "windows")]
let app_path = format!("\"{app_path}\"");
#[cfg(target_os = "windows")]
let app_path = app_path.as_str();
let auto = AutoLaunchBuilder::new()
.set_app_name(app_name)
.set_app_path(app_path)
.build();
if let Some(enable) = self.config.enable_auto_launch.as_ref() {
// fix issue #26
if *enable {
auto.enable()?;
}
}
self.auto_launch = Some(auto);
Ok(())
}
/// update the startup
fn update_launch(&mut self, enable: bool) -> Result<()> {
let conf_enable = self.config.enable_auto_launch.clone().unwrap_or(false);
if enable == conf_enable {
return Ok(());
}
let auto_launch = self.auto_launch.clone().unwrap();
match enable {
true => auto_launch.enable()?,
false => auto_launch.disable()?,
};
Ok(())
}
/// patch verge config
/// There should be only one update at a time here
/// so call the save_file at the end is savely
pub fn patch_config(&mut self, patch: VergeConfig) -> Result<()> {
// only change it
if patch.language.is_some() {
self.config.language = patch.language;
}
if patch.theme_mode.is_some() {
self.config.theme_mode = patch.theme_mode;
}
if patch.theme_blur.is_some() {
self.config.theme_blur = patch.theme_blur;
}
if patch.traffic_graph.is_some() {
self.config.traffic_graph = patch.traffic_graph;
}
if patch.enable_silent_start.is_some() {
self.config.enable_silent_start = patch.enable_silent_start;
}
if patch.theme_setting.is_some() {
self.config.theme_setting = patch.theme_setting;
}
// should update system startup
if patch.enable_auto_launch.is_some() {
let enable = patch.enable_auto_launch.unwrap();
self.update_launch(enable)?;
self.config.enable_auto_launch = Some(enable);
}
// should update system proxy
if patch.enable_system_proxy.is_some() {
let enable = patch.enable_system_proxy.unwrap();
if let Some(mut sysproxy) = self.cur_sysproxy.take() {
sysproxy.enable = enable;
if sysproxy.set_sys().is_err() {
self.cur_sysproxy = Some(sysproxy);
bail!("failed to set system proxy");
}
self.cur_sysproxy = Some(sysproxy);
}
self.config.enable_system_proxy = Some(enable);
}
// should update system proxy too
if patch.system_proxy_bypass.is_some() {
let bypass = patch.system_proxy_bypass.unwrap();
if let Some(mut sysproxy) = self.cur_sysproxy.take() {
if sysproxy.enable {
sysproxy.bypass = bypass.clone();
if sysproxy.set_sys().is_err() {
self.cur_sysproxy = Some(sysproxy);
bail!("failed to set system proxy");
}
}
self.cur_sysproxy = Some(sysproxy);
}
self.config.system_proxy_bypass = Some(bypass);
}
// proxy guard
// only change it
if patch.enable_proxy_guard.is_some() {
self.config.enable_proxy_guard = patch.enable_proxy_guard;
}
if patch.proxy_guard_duration.is_some() {
self.config.proxy_guard_duration = patch.proxy_guard_duration;
}
// relaunch the guard
if patch.enable_system_proxy.is_some() || patch.enable_proxy_guard.is_some() {
Verge::guard_proxy(self.guard_state.clone());
}
// handle the tun mode
if patch.enable_tun_mode.is_some() {
self.config.enable_tun_mode = patch.enable_tun_mode;
}
self.config.save_file()
}
/// update the system tray state
pub fn update_systray(&self, app_handle: &AppHandle) -> Result<()> {
// system proxy
let system_proxy = self.config.enable_system_proxy.as_ref();
system_proxy.map(|system_proxy| {
app_handle
.tray_handle()
.get_item("system_proxy")
.set_selected(*system_proxy)
.unwrap();
});
// tun mode
let tun_mode = self.config.enable_tun_mode.as_ref();
tun_mode.map(|tun_mode| {
app_handle
.tray_handle()
.get_item("tun_mode")
.set_selected(*tun_mode)
.unwrap();
});
// update verge config
let window = app_handle.get_window("main").unwrap();
window.emit("verge://refresh-verge-config", "yes").unwrap();
Ok(())
}
}
impl Verge {
/// launch a system proxy guard
/// read config from file directly
pub fn guard_proxy(guard_state: Arc<Mutex<bool>>) {
use tokio::time::{sleep, Duration};
tauri::async_runtime::spawn(async move {
// if it is running, exit
let mut state = guard_state.lock().await;
if *state {
return;
}
*state = true;
std::mem::drop(state);
// default duration is 10s
let mut wait_secs = 10u64;
loop {
sleep(Duration::from_secs(wait_secs)).await;
log::debug!("guard heartbeat detection");
let verge = Verge::new();
let enable_proxy = verge.config.enable_system_proxy.unwrap_or(false);
let enable_guard = verge.config.enable_proxy_guard.unwrap_or(false);
let guard_duration = verge.config.proxy_guard_duration.unwrap_or(10);
// update duration
wait_secs = guard_duration;
// stop loop
if !enable_guard || !enable_proxy {
break;
}
log::info!("try to guard proxy");
let clash = Clash::new();
match &clash.info.port {
Some(port) => {
let bypass = verge.config.system_proxy_bypass.clone();
let sysproxy = SysProxyConfig::new(true, port.clone(), bypass);
log_if_err!(sysproxy.set_sys());
}
None => log::error!("fail to parse clash port"),
}
}
let mut state = guard_state.lock().await;
*state = false;
});
}
}

View 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();
}
_ => {}
};
}

View File

@ -1,2 +0,0 @@
pub mod emit;
pub mod state;

View File

@ -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>>>);

View File

@ -3,16 +3,14 @@
windows_subsystem = "windows"
)]
extern crate tauri;
mod cmds;
mod config;
mod events;
mod core;
mod states;
mod utils;
use crate::{
events::state,
utils::{resolve, server},
core::VergeConfig,
utils::{dirs, resolve, server},
};
use tauri::{
api, CustomMenuItem, Manager, SystemTray, SystemTrayEvent, SystemTrayMenu, SystemTrayMenuItem,
@ -24,65 +22,149 @@ 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 {
dirs::init_portable_flag();
}
tauri::Builder::default()
.manage(state::VergeConfLock::default())
.manage(state::ClashInfoState::default())
.manage(state::SomthingState::default())
.manage(state::ProfileLock::default())
let tray_menu = SystemTrayMenu::new()
.add_item(CustomMenuItem::new("open_window", "Show"))
.add_item(CustomMenuItem::new("system_proxy", "System Proxy"))
.add_item(CustomMenuItem::new("tun_mode", "Tun Mode"))
.add_item(CustomMenuItem::new("restart_clash", "Restart Clash"))
.add_native_item(SystemTrayMenuItem::Separator)
.add_item(CustomMenuItem::new("quit", "Quit").accelerator("CmdOrControl+Q"));
#[allow(unused_mut)]
let mut builder = tauri::Builder::default()
.manage(states::VergeState::default())
.manage(states::ClashState::default())
.manage(states::ProfilesState::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.unminimize().unwrap();
window.show().unwrap();
window.set_focus().unwrap();
}
"system_proxy" => {
let verge_state = app_handle.state::<states::VergeState>();
let mut verge = verge_state.0.lock().unwrap();
let old_value = verge.config.enable_system_proxy.clone().unwrap_or(false);
let new_value = !old_value;
match verge.patch_config(VergeConfig {
enable_system_proxy: Some(new_value),
..VergeConfig::default()
}) {
Ok(_) => verge.update_systray(app_handle).unwrap(),
Err(err) => log::error!("{err}"),
}
}
"tun_mode" => {
let verge_state = app_handle.state::<states::VergeState>();
let mut verge = verge_state.0.lock().unwrap();
let old_value = verge.config.enable_tun_mode.clone().unwrap_or(false);
let new_value = !old_value;
match verge.patch_config(VergeConfig {
enable_tun_mode: Some(new_value),
..VergeConfig::default()
}) {
Ok(_) => verge.update_systray(app_handle).unwrap(),
Err(err) => log::error!("{err}"),
}
}
"restart_clash" => {
let clash_state = app_handle.state::<states::ClashState>();
let profiles_state = app_handle.state::<states::ProfilesState>();
let mut clash = clash_state.0.lock().unwrap();
let mut profiles = profiles_state.0.lock().unwrap();
crate::log_if_err!(clash.restart_sidecar(&mut profiles));
}
"quit" => {
api::process::kill_children();
resolve::resolve_reset(app_handle);
app_handle.exit(0);
api::process::kill_children();
std::process::exit(0);
}
_ => {}
},
#[cfg(target_os = "windows")]
SystemTrayEvent::LeftClick { .. } => {
let window = app_handle.get_window("main").unwrap();
window.unminimize().unwrap();
window.show().unwrap();
window.set_focus().unwrap();
}
_ => {}
})
.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,
])
// common
cmds::restart_sidecar,
cmds::get_sys_proxy,
cmds::get_cur_proxy,
cmds::kill_sidecars,
cmds::open_app_dir,
cmds::open_logs_dir,
// clash
cmds::get_clash_info,
cmds::patch_clash_config,
// 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::sync_profiles,
cmds::enhance_profiles,
cmds::change_profile_chain,
cmds::change_profile_valid,
cmds::read_profile_file,
cmds::save_profile_file
]);
#[cfg(target_os = "macos")]
{
use tauri::{Menu, MenuItem, Submenu};
let submenu_file = Submenu::new(
"File",
Menu::new()
.add_native_item(MenuItem::Undo)
.add_native_item(MenuItem::Redo)
.add_native_item(MenuItem::Copy)
.add_native_item(MenuItem::Paste)
.add_native_item(MenuItem::Cut)
.add_native_item(MenuItem::SelectAll),
);
builder = builder.menu(Menu::new().add_submenu(submenu_file));
}
builder
.build(tauri::generate_context!())
.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, .. } => {
api.prevent_exit();
}
tauri::Event::Exit => {
tauri::RunEvent::WindowEvent { label, event, .. } => match event {
tauri::WindowEvent::CloseRequested { api, .. } => {
let app_handle = app_handle.clone();
api.prevent_close();
app_handle.get_window(&label).unwrap().hide().unwrap();
}
_ => {}
},
tauri::RunEvent::ExitRequested { .. } => {
resolve::resolve_reset(app_handle);
api::process::kill_children();
}

11
src-tauri/src/states.rs Normal file
View File

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

View File

@ -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())),
}
}

View File

@ -1,9 +1,5 @@
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
@ -12,121 +8,16 @@ pub fn read_yaml<T: DeserializeOwned + Default>(path: PathBuf) -> T {
serde_yaml::from_str::<T>(&yaml_str).unwrap_or(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
};
/// 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)?;
if fs::write(path.clone(), yaml_str.as_bytes()).is_err() {
Err(format!("can not save file `{:?}`", path))
} else {
Ok(())
}
} 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 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}\""))
}

View File

@ -1,18 +1,90 @@
use std::path::{Path, PathBuf};
use std::env::temp_dir;
use std::path::PathBuf;
use tauri::utils::platform::current_exe;
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";
/// portable flag
#[allow(unused)]
static mut PORTABLE_FLAG: bool = false;
/// initialize portable flag
pub unsafe fn init_portable_flag() {
#[cfg(target_os = "windows")]
{
let exe = current_exe().unwrap();
let dir = exe.parent().unwrap();
let dir = PathBuf::from(dir).join(".config/PORTABLE");
if dir.exists() {
PORTABLE_FLAG = true;
}
}
}
/// get the verge app home dir
pub fn app_home_dir() -> PathBuf {
home_dir()
.unwrap()
.join(Path::new(".config"))
.join(Path::new("clash-verge"))
#[cfg(target_os = "windows")]
unsafe {
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")
resource_dir(package_info, &Env::default())
.unwrap()
.join("resources")
}
/// profiles dir
pub fn app_profiles_dir() -> PathBuf {
app_home_dir().join("profiles")
}
/// logs dir
pub fn app_logs_dir() -> PathBuf {
app_home_dir().join("logs")
}
pub fn clash_path() -> PathBuf {
app_home_dir().join(CLASH_CONFIG)
}
pub fn verge_path() -> PathBuf {
app_home_dir().join(VERGE_CONFIG)
}
pub fn profiles_path() -> PathBuf {
app_home_dir().join(PROFILE_YAML)
}
pub fn profiles_temp_path() -> PathBuf {
#[cfg(not(feature = "debug-yml"))]
return temp_dir().join(PROFILE_TEMP);
#[cfg(feature = "debug-yml")]
return app_home_dir().join(PROFILE_TEMP);
}

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

View File

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

View File

@ -1,18 +1,15 @@
extern crate serde_yaml;
use crate::utils::{dirs, tmpl};
use chrono::Local;
use log::LevelFilter;
use log4rs::append::console::ConsoleAppender;
use log4rs::append::file::FileAppender;
use log4rs::config::{Appender, Config, 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) {
let local_time = Local::now().format("%Y-%m-%d-%H%M%S").to_string();
@ -34,7 +31,7 @@ fn init_log(log_dir: &PathBuf) {
.build(
Root::builder()
.appenders(["stdout", "file"])
.build(LevelFilter::Debug),
.build(LevelFilter::Info),
)
.unwrap();
@ -42,65 +39,62 @@ fn init_log(log_dir: &PathBuf) {
}
/// Initialize all the files from resources
fn init_config_file(app_dir: &PathBuf, res_dir: &PathBuf) {
fn init_config(app_dir: &PathBuf) -> std::io::Result<()> {
// target path
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();
fs::create_dir_all(&app_dir).unwrap();
}
if !log_dir.exists() {
fs::create_dir(&log_dir).unwrap();
fs::create_dir_all(&log_dir).unwrap();
}
if !profiles_dir.exists() {
fs::create_dir(&profiles_dir).unwrap();
fs::create_dir_all(&profiles_dir).unwrap();
}
init_log(&log_dir);
init_config_file(&app_dir, &res_dir);
if let Err(err) = init_config(&app_dir) {
log::error!("{err}");
}
// copy the resource file
let mmdb_path = app_dir.join("Country.mmdb");
let mmdb_tmpl = res_dir.join("Country.mmdb");
if !mmdb_path.exists() && mmdb_tmpl.exists() {
fs::copy(mmdb_tmpl, mmdb_path).unwrap();
}
// copy the wintun.dll
#[cfg(target_os = "windows")]
{
let wintun_path = app_dir.join("wintun.dll");
let wintun_tmpl = res_dir.join("wintun.dll");
if !wintun_path.exists() && wintun_tmpl.exists() {
fs::copy(wintun_tmpl, wintun_path).unwrap();
}
}
}

View File

@ -1,10 +1,8 @@
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;

View File

@ -1,5 +1,5 @@
use super::{clash, config, init, server, sysopt};
use crate::events::state;
use super::{init, server};
use crate::{core::Profiles, log_if_err, states};
use tauri::{App, AppHandle, Manager};
/// handle something when start app
@ -10,71 +10,79 @@ 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 states
let clash_state = app.state::<states::ClashState>();
let verge_state = app.state::<states::VergeState>();
let profiles_state = app.state::<states::ProfilesState>();
// 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);
};
let mut clash = clash_state.0.lock().unwrap();
let mut verge = verge_state.0.lock().unwrap();
let mut profiles = profiles_state.0.lock().unwrap();
log_if_err!(clash.run_sidecar());
*profiles = Profiles::read_file();
clash.set_window(app.get_window("main"));
log_if_err!(clash.activate(&profiles));
log_if_err!(clash.activate_enhanced(&profiles, true, true));
verge.init_sysproxy(clash.info.port.clone());
log_if_err!(verge.init_launch());
verge.config.enable_system_proxy.map(|enable| {
log_if_err!(app
.tray_handle()
.get_item("system_proxy")
.set_selected(enable));
});
// resolve 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);
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, verge.config.enable_silent_start.clone());
}
/// reset system proxy
pub fn resolve_reset(app_handle: &AppHandle) {
let state = app_handle.try_state::<state::SomthingState>();
if state.is_none() {
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 verge_state = app_handle.state::<states::VergeState>();
let mut verge = verge_state.0.lock().unwrap();
verge.reset_sysproxy();
}
/// customize the window theme
fn resolve_window(app: &App, hide: Option<bool>) {
let window = app.get_window("main").unwrap();
// silent start
hide.map(|hide| {
if hide {
window.hide().unwrap();
}
});
#[cfg(target_os = "windows")]
{
use window_shadows::set_shadow;
use window_vibrancy::apply_blur;
window.set_decorations(false).unwrap();
set_shadow(&window, true).unwrap();
apply_blur(&window, None).unwrap();
}
#[cfg(target_os = "macos")]
{
use tauri::LogicalSize;
use tauri::Size::Logical;
window.set_decorations(true).unwrap();
window
.set_size(Logical(LogicalSize {
width: 800.0,
height: 610.0,
}))
.unwrap();
// use tauri_plugin_vibrancy::MacOSVibrancy;
// #[allow(deprecated)]
// window.apply_vibrancy(MacOSVibrancy::AppearanceBased);
}
}

View File

@ -4,7 +4,10 @@ use port_scanner::local_port_available;
use tauri::{AppHandle, Manager};
use 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
View 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}"))
}
}

View File

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

View File

@ -1,11 +1,11 @@
{
"package": {
"productName": "clash-verge",
"version": "0.0.1"
"productName": "Clash Verge",
"version": "0.0.29"
},
"build": {
"distDir": "../dist",
"devPath": "http://localhost:3000/proxy",
"devPath": "http://localhost:3000/",
"beforeDevCommand": "yarn run web:dev",
"beforeBuildCommand": "yarn run web:build"
},
@ -27,7 +27,7 @@
],
"resources": ["resources"],
"externalBin": ["sidecar/clash"],
"copyright": "© 2021 zzzgydi All Rights Reserved",
"copyright": "© 2022 zzzgydi All Rights Reserved",
"category": "DeveloperTool",
"shortDescription": "A Clash GUI based on tauri.",
"longDescription": "A Clash GUI based on tauri.",
@ -50,10 +50,24 @@
}
},
"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": [
{
@ -62,14 +76,14 @@
"height": 600,
"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';"
}
}
}

View File

@ -4,6 +4,7 @@ body {
"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
sans-serif;
-webkit-font-smoothing: antialiased;
user-select: none;
}
:root {
@ -28,3 +29,4 @@ body {
}
@import "./layout.scss";
@import "./page.scss";

View File

@ -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: 8px 0;
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 8px;
text-align: center;
box-sizing: border-box;
img,
svg {
width: 100%;
height: 100%;
pointer-events: none;
}
.the-newbtn {
position: absolute;
right: 20px;
bottom: 12px;
transform: scale(0.8);
}
}
.the-menu {
flex: 1 1 75%;
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;
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,67 @@
import dayjs from "dayjs";
import { useLockFn } from "ahooks";
import { styled, ListItem, IconButton, ListItemText } from "@mui/material";
import { CloseRounded } from "@mui/icons-material";
import { ApiType } from "../../services/types";
import { 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;

View File

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

View File

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

View File

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

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

View File

@ -0,0 +1,86 @@
import useSWR from "swr";
import snarkdown from "snarkdown";
import { useMemo } from "react";
import { useRecoilState } from "recoil";
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 { killSidecars, 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 { 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 killSidecars();
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 onClick={onClose}>Cancel</Button>
<Button
autoFocus
variant="contained"
disabled={updateState}
onClick={onUpdate}
>
Update
</Button>
</DialogActions>
</Dialog>
);
};
export default UpdateDialog;

View File

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

View File

@ -0,0 +1,43 @@
import dayjs from "dayjs";
import { useEffect, useState } from "react";
import { useSetRecoilState } from "recoil";
import { listen } from "@tauri-apps/api/event";
import { ApiType } from "../../services/types";
import { getInfomation } from "../../services/api";
import { atomLogData } from "../../services/states";
const MAX_LOG_NUM = 1000;
// setup the log websocket
export default function useLogSetup() {
const [refresh, setRefresh] = useState({});
const setLogData = useSetRecoilState(atomLogData);
useEffect(() => {
let ws: WebSocket = null!;
const handler = (event: MessageEvent<any>) => {
const data = JSON.parse(event.data) as ApiType.LogItem;
const time = dayjs().format("MM-DD HH:mm:ss");
setLogData((l) => {
if (l.length >= MAX_LOG_NUM) l.shift();
return [...l, { ...data, time }];
});
};
getInfomation().then((info) => {
const { server = "", secret = "" } = info;
ws = new WebSocket(`ws://${server}/logs?token=${secret}`);
ws.addEventListener("message", handler);
});
const unlisten = listen("verge://refresh-clash-config", () =>
setRefresh({})
);
return () => {
ws?.close();
unlisten?.then((fn) => fn());
};
}, [refresh]);
}

View File

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

View File

@ -1,11 +1,13 @@
import { styled, Box } from "@mui/material";
import { ApiType } from "../services/types";
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",

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,160 +0,0 @@
import { useState } from "react";
import { Virtuoso } from "react-virtuoso";
import {
alpha,
Box,
Collapse,
Divider,
IconButton,
List,
ListItem,
ListItemButton,
ListItemIcon,
ListItemText,
} from "@mui/material";
import {
SendRounded,
ExpandLessRounded,
ExpandMoreRounded,
MyLocationRounded,
NetworkCheckRounded,
CheckCircleOutlineRounded,
} from "@mui/icons-material";
import { updateProxy } from "../services/api";
import { ApiType } from "../services/types";
interface ItemProps {
proxy: ApiType.ProxyItem;
selected: boolean;
onClick?: (name: string) => void;
}
const Item = ({ proxy, selected, onClick }: ItemProps) => {
return (
<ListItem sx={{ py: 0, pl: 4 }}>
<ListItemButton
dense
selected={selected}
onClick={() => onClick?.(proxy.name)}
sx={[
{
borderRadius: 1,
},
({ palette: { mode, primary } }) => {
const bgcolor =
mode === "light"
? alpha(primary.main, 0.15)
: alpha(primary.main, 0.35);
const color = mode === "light" ? primary.main : primary.light;
return {
"&.Mui-selected": { bgcolor },
"&.Mui-selected .MuiListItemText-secondary": { color },
};
},
]}
>
<ListItemText title={proxy.name} secondary={proxy.name} />
<ListItemIcon
sx={{ justifyContent: "flex-end", color: "primary.main" }}
>
{selected && <CheckCircleOutlineRounded sx={{ fontSize: 16 }} />}
</ListItemIcon>
</ListItemButton>
</ListItem>
);
};
interface Props {
group: ApiType.ProxyGroupItem;
}
const ProxyGroup = ({ group }: Props) => {
const [open, setOpen] = useState(false);
const [now, setNow] = useState(group.now);
const proxies = group.all ?? [];
const onUpdate = async (name: string) => {
// can not call update
if (group.type !== "Selector") {
// Todo
// error Tips
return;
}
const oldValue = now;
try {
setNow(name);
await updateProxy(group.name, name);
} catch {
setNow(oldValue);
// Todo
// error tips
}
};
return (
<>
<ListItem button onClick={() => setOpen(!open)} dense>
<ListItemText
primary={group.name}
secondary={
<>
<SendRounded color="primary" sx={{ mr: 1, fontSize: 14 }} />
<span>{now}</span>
</>
}
secondaryTypographyProps={{
sx: { display: "flex", alignItems: "center" },
}}
/>
{open ? <ExpandLessRounded /> : <ExpandMoreRounded />}
</ListItem>
<Collapse in={open} timeout="auto" unmountOnExit>
<Box sx={{ pl: 4, pr: 3, my: 0.5 }}>
<IconButton size="small" title="location">
<MyLocationRounded />
</IconButton>
<IconButton size="small" title="check">
<NetworkCheckRounded />
</IconButton>
</Box>
{proxies.length >= 10 ? (
<Virtuoso
style={{ height: "400px", marginBottom: "4px" }}
totalCount={proxies.length}
itemContent={(index) => (
<Item
proxy={proxies[index]}
selected={proxies[index].name === now}
onClick={onUpdate}
/>
)}
/>
) : (
<List
component="div"
disablePadding
sx={{ maxHeight: "400px", overflow: "auto", mb: "4px" }}
>
{proxies.map((proxy) => (
<Item
key={proxy.name}
proxy={proxy}
selected={proxy.name === now}
onClick={onUpdate}
/>
))}
</List>
)}
<Divider variant="middle" />
</Collapse>
</>
);
};
export default ProxyGroup;

View File

@ -0,0 +1,135 @@
import useSWR, { useSWRConfig } from "swr";
import { useEffect, useRef, useState } from "react";
import { useLockFn } from "ahooks";
import { Virtuoso } from "react-virtuoso";
import { ApiType } from "../../services/types";
import { updateProxy } from "../../services/api";
import { getProfiles, patchProfile } from "../../services/cmds";
import useSortProxy, { ProxySortType } from "./use-sort-proxy";
import useFilterProxy from "./use-filter-proxy";
import delayManager from "../../services/delay";
import ProxyHead from "./proxy-head";
import ProxyItem from "./proxy-item";
interface Props {
groupName: string;
curProxy?: string;
proxies: ApiType.ProxyItem[];
}
// this component will be used for DIRECT/GLOBAL
const ProxyGlobal = (props: Props) => {
const { groupName, curProxy, proxies } = props;
const { mutate } = useSWRConfig();
const [now, setNow] = useState(curProxy || "DIRECT");
const [showType, setShowType] = useState(true);
const [sortType, setSortType] = useState<ProxySortType>(0);
const [filterText, setFilterText] = useState("");
const virtuosoRef = useRef<any>();
const filterProxies = useFilterProxy(proxies, groupName, filterText);
const sortedProxies = useSortProxy(filterProxies, groupName, sortType);
const { data: profiles } = useSWR("getProfiles", getProfiles);
const onChangeProxy = useLockFn(async (name: string) => {
await updateProxy(groupName, name);
setNow(name);
if (groupName === "DIRECT") return;
// update global selected
const profile = profiles?.items?.find((p) => p.uid === profiles.current);
if (!profile) return;
if (!profile.selected) profile.selected = [];
const index = profile.selected.findIndex((item) => item.name === groupName);
if (index < 0) {
profile.selected.unshift({ name: groupName, now: name });
} else {
profile.selected[index] = { name: groupName, now: name };
}
await patchProfile(profiles!.current!, { selected: profile.selected });
});
const onLocation = (smooth = true) => {
const index = sortedProxies.findIndex((p) => p.name === now);
if (index >= 0) {
virtuosoRef.current?.scrollToIndex?.({
index,
align: "center",
behavior: smooth ? "smooth" : "auto",
});
}
};
const onCheckAll = useLockFn(async () => {
const names = sortedProxies.map((p) => p.name);
await delayManager.checkListDelay({ names, groupName, skipNum: 8 }, () =>
mutate("getProxies")
);
});
useEffect(() => onLocation(false), [groupName]);
useEffect(() => {
if (groupName === "DIRECT") setNow("DIRECT");
else if (groupName === "GLOBAL") {
if (profiles) {
const current = profiles.current;
const profile = profiles.items?.find((p) => p.uid === current);
profile?.selected?.forEach((item) => {
if (item.name === "GLOBAL") {
if (item.now && item.now !== curProxy) {
updateProxy("GLOBAL", item.now).then(() => setNow(item!.now!));
mutate("getProxies");
}
}
});
}
setNow(curProxy || "DIRECT");
}
}, [groupName, curProxy, profiles]);
return (
<>
<ProxyHead
sx={{ px: 3, my: 0.5, button: { mr: 0.5 } }}
showType={showType}
sortType={sortType}
groupName={groupName}
filterText={filterText}
onLocation={onLocation}
onCheckDelay={onCheckAll}
onShowType={setShowType}
onSortType={setSortType}
onFilterText={setFilterText}
/>
<Virtuoso
ref={virtuosoRef}
style={{ height: "calc(100% - 40px)" }}
totalCount={sortedProxies.length}
itemContent={(index) => (
<ProxyItem
groupName={groupName}
proxy={sortedProxies[index]}
selected={sortedProxies[index].name === now}
showType={showType}
onClick={onChangeProxy}
sx={{ py: 0, px: 2 }}
/>
)}
/>
</>
);
};
export default ProxyGlobal;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,107 +0,0 @@
import useSWR, { useSWRConfig } from "swr";
import {
List,
ListItemText,
ListSubheader,
TextField,
Switch,
Select,
MenuItem,
} from "@mui/material";
import { getClashConfig, updateConfigs } from "../services/api";
import { patchClashConfig } from "../services/cmds";
import { ApiType } from "../services/types";
import GuardState from "./guard-state";
import SettingItem from "./setting-item";
interface Props {
onError?: (err: Error) => void;
}
const SettingClash = ({ onError }: Props) => {
const { mutate } = useSWRConfig();
const { data: clashConfig } = useSWR("getClashConfig", getClashConfig);
const {
ipv6 = false,
"allow-lan": allowLan = false,
"log-level": logLevel = "silent",
"mixed-port": mixedPort = 7890,
} = clashConfig ?? {};
const onSwitchFormat = (_e: any, value: boolean) => value;
const onChangeData = (patch: Partial<ApiType.ConfigData>) => {
mutate("getClashConfig", { ...clashConfig, ...patch }, false);
};
const onUpdateData = async (patch: Partial<ApiType.ConfigData>) => {
await updateConfigs(patch);
await patchClashConfig(patch);
};
return (
<List>
<ListSubheader>Clash设置</ListSubheader>
<SettingItem>
<ListItemText primary="局域网连接" />
<GuardState
value={allowLan}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ "allow-lan": e })}
onGuard={(e) => onUpdateData({ "allow-lan": e })}
>
<Switch edge="end" />
</GuardState>
</SettingItem>
<SettingItem>
<ListItemText primary="IPv6" />
<GuardState
value={ipv6}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ ipv6: e })}
onGuard={(e) => onUpdateData({ ipv6: e })}
>
<Switch edge="end" />
</GuardState>
</SettingItem>
<SettingItem>
<ListItemText primary="日志等级" />
<GuardState
value={logLevel}
onCatch={onError}
onFormat={(e: any) => e.target.value}
onChange={(e) => onChangeData({ "log-level": e })}
onGuard={(e) => onUpdateData({ "log-level": e })}
>
<Select size="small" sx={{ width: 120 }}>
<MenuItem value="debug">Debug</MenuItem>
<MenuItem value="info">Info</MenuItem>
<MenuItem value="warning">Warning</MenuItem>
<MenuItem value="error">Error</MenuItem>
<MenuItem value="silent">Silent</MenuItem>
</Select>
</GuardState>
</SettingItem>
<SettingItem>
<ListItemText primary="混合代理端口" />
<TextField
size="small"
value={mixedPort!}
sx={{ width: 120 }}
disabled
/>
</SettingItem>
</List>
);
};
export default SettingClash;

View File

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

View File

@ -1,89 +0,0 @@
import useSWR, { useSWRConfig } from "swr";
import { List, ListItemText, ListSubheader, Switch } from "@mui/material";
import {
getVergeConfig,
patchVergeConfig,
setSysProxy,
} from "../services/cmds";
import { CmdType } from "../services/types";
import GuardState from "./guard-state";
import SettingItem from "./setting-item";
import PaletteSwitch from "./palette-switch";
interface Props {
onError?: (err: Error) => void;
}
const SettingVerge = ({ onError }: Props) => {
const { mutate } = useSWRConfig();
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
const {
theme_mode: mode = "light",
enable_self_startup: startup = false,
enable_system_proxy: proxy = false,
} = vergeConfig ?? {};
const onSwitchFormat = (_e: any, value: boolean) => value;
const onChangeData = (patch: Partial<CmdType.VergeConfig>) => {
mutate("getVergeConfig", { ...vergeConfig, ...patch }, false);
};
return (
<List>
<ListSubheader></ListSubheader>
<SettingItem>
<ListItemText primary="外观主题" />
<GuardState
value={mode === "dark"}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ theme_mode: e ? "dark" : "light" })}
onGuard={async (c) => {
await patchVergeConfig({ theme_mode: c ? "dark" : "light" });
}}
>
<PaletteSwitch edge="end" />
</GuardState>
</SettingItem>
<SettingItem>
<ListItemText primary="开机自启" />
<GuardState
value={startup}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_self_startup: e })}
onGuard={async (e) => {
await patchVergeConfig({ enable_self_startup: e });
}}
>
<Switch edge="end" />
</GuardState>
</SettingItem>
<SettingItem>
<ListItemText primary="设置系统代理" />
<GuardState
value={proxy}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_system_proxy: e })}
onGuard={async (e) => {
await setSysProxy(e);
await patchVergeConfig({ enable_system_proxy: e });
}}
>
<Switch edge="end" />
</GuardState>
</SettingItem>
</List>
);
};
export default SettingVerge;

View File

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

View File

@ -0,0 +1,139 @@
import useSWR, { useSWRConfig } from "swr";
import { useSetRecoilState } from "recoil";
import { useTranslation } from "react-i18next";
import {
ListItemText,
TextField,
Switch,
Select,
MenuItem,
Typography,
} from "@mui/material";
import { ApiType } from "../../services/types";
import { atomClashPort } from "../../services/states";
import { patchClashConfig } from "../../services/cmds";
import { SettingList, SettingItem } from "./setting";
import { getClashConfig, getVersion, updateConfigs } from "../../services/api";
import Notice from "../base/base-notice";
import GuardState from "./guard-state";
interface Props {
onError: (err: Error) => void;
}
const SettingClash = ({ onError }: Props) => {
const { t } = useTranslation();
const { mutate } = useSWRConfig();
const { data: clashConfig } = useSWR("getClashConfig", getClashConfig);
const { data: versionData } = useSWR("getVersion", getVersion);
const {
ipv6,
"allow-lan": allowLan,
"log-level": logLevel,
"mixed-port": mixedPort,
} = clashConfig ?? {};
const setGlobalClashPort = useSetRecoilState(atomClashPort);
const onSwitchFormat = (_e: any, value: boolean) => value;
const onChangeData = (patch: Partial<ApiType.ConfigData>) => {
mutate("getClashConfig", { ...clashConfig, ...patch }, false);
};
const onUpdateData = async (patch: Partial<ApiType.ConfigData>) => {
await updateConfigs(patch);
await patchClashConfig(patch);
};
const onUpdatePort = async (port: number) => {
if (port < 1000) {
throw new Error("The port should not < 1000");
}
if (port > 65536) {
throw new Error("The port should not > 65536");
}
await patchClashConfig({ "mixed-port": port });
setGlobalClashPort(port);
Notice.success("Change Clash port successfully!");
// update the config
mutate("getClashConfig");
};
// get clash core version
const clashVer = versionData?.premium
? `${versionData.version} Premium`
: versionData?.version || "-";
return (
<SettingList title={t("Clash Setting")}>
<SettingItem>
<ListItemText primary={t("Allow Lan")} />
<GuardState
value={allowLan ?? false}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ "allow-lan": e })}
onGuard={(e) => onUpdateData({ "allow-lan": e })}
>
<Switch edge="end" />
</GuardState>
</SettingItem>
<SettingItem>
<ListItemText primary={t("IPv6")} />
<GuardState
value={ipv6 ?? false}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ ipv6: e })}
onGuard={(e) => onUpdateData({ ipv6: e })}
>
<Switch edge="end" />
</GuardState>
</SettingItem>
<SettingItem>
<ListItemText primary={t("Log Level")} />
<GuardState
value={logLevel ?? "info"}
onCatch={onError}
onFormat={(e: any) => e.target.value}
onChange={(e) => onChangeData({ "log-level": e })}
onGuard={(e) => onUpdateData({ "log-level": e })}
>
<Select size="small" sx={{ width: 120 }}>
<MenuItem value="debug">Debug</MenuItem>
<MenuItem value="info">Info</MenuItem>
<MenuItem value="warning">Warning</MenuItem>
<MenuItem value="error">Error</MenuItem>
<MenuItem value="silent">Silent</MenuItem>
</Select>
</GuardState>
</SettingItem>
<SettingItem>
<ListItemText primary={t("Mixed Port")} />
<GuardState
value={mixedPort ?? 0}
onCatch={onError}
onFormat={(e: any) => +e.target.value?.replace(/\D+/, "")}
onChange={(e) => onChangeData({ "mixed-port": e })}
onGuard={onUpdatePort}
waitTime={800}
>
<TextField autoComplete="off" size="small" sx={{ width: 120 }} />
</GuardState>
</SettingItem>
<SettingItem>
<ListItemText primary={t("Clash core")} />
<Typography sx={{ py: 1 }}>{clashVer}</Typography>
</SettingItem>
</SettingList>
);
};
export default SettingClash;

View File

@ -0,0 +1,136 @@
import useSWR, { useSWRConfig } from "swr";
import { useTranslation } from "react-i18next";
import { Box, ListItemText, Switch, TextField } from "@mui/material";
import { getVergeConfig, patchVergeConfig } from "../../services/cmds";
import { SettingList, SettingItem } from "./setting";
import { CmdType } from "../../services/types";
import GuardState from "./guard-state";
import SysproxyTooltip from "./sysproxy-tooltip";
interface Props {
onError?: (err: Error) => void;
}
const SettingSystem = ({ onError }: Props) => {
const { t } = useTranslation();
const { mutate } = useSWRConfig();
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
const {
enable_tun_mode,
enable_auto_launch,
enable_silent_start,
enable_system_proxy,
system_proxy_bypass,
enable_proxy_guard,
} = vergeConfig ?? {};
const onSwitchFormat = (_e: any, value: boolean) => value;
const onChangeData = (patch: Partial<CmdType.VergeConfig>) => {
mutate("getVergeConfig", { ...vergeConfig, ...patch }, false);
};
return (
<SettingList title={t("System Setting")}>
<SettingItem>
<ListItemText primary={t("Tun Mode")} />
<GuardState
value={enable_tun_mode ?? false}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_tun_mode: e })}
onGuard={(e) => patchVergeConfig({ enable_tun_mode: e })}
>
<Switch edge="end" />
</GuardState>
</SettingItem>
<SettingItem>
<ListItemText primary={t("Auto Launch")} />
<GuardState
value={enable_auto_launch ?? false}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_auto_launch: e })}
onGuard={(e) => patchVergeConfig({ enable_auto_launch: e })}
>
<Switch edge="end" />
</GuardState>
</SettingItem>
<SettingItem>
<ListItemText primary={t("Silent Start")} />
<GuardState
value={enable_silent_start ?? false}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_silent_start: e })}
onGuard={(e) => patchVergeConfig({ enable_silent_start: e })}
>
<Switch edge="end" />
</GuardState>
</SettingItem>
<SettingItem>
<ListItemText
primary={
<Box sx={{ display: "flex", alignItems: "center" }}>
{t("System Proxy")}
<SysproxyTooltip />
</Box>
}
/>
<GuardState
value={enable_system_proxy ?? false}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_system_proxy: e })}
onGuard={async (e) => {
await patchVergeConfig({ enable_system_proxy: e });
mutate("getVergeConfig"); // update bypass value
}}
>
<Switch edge="end" />
</GuardState>
</SettingItem>
{enable_system_proxy && (
<SettingItem>
<ListItemText primary={t("Proxy Guard")} />
<GuardState
value={enable_proxy_guard ?? false}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_proxy_guard: e })}
onGuard={(e) => patchVergeConfig({ enable_proxy_guard: e })}
>
<Switch edge="end" />
</GuardState>
</SettingItem>
)}
{enable_system_proxy && (
<SettingItem>
<ListItemText primary={t("Proxy Bypass")} />
<GuardState
value={system_proxy_bypass ?? ""}
onCatch={onError}
onFormat={(e: any) => e.target.value}
onChange={(e) => onChangeData({ system_proxy_bypass: e })}
onGuard={(e) => patchVergeConfig({ system_proxy_bypass: e })}
waitTime={1000}
>
<TextField autoComplete="off" size="small" sx={{ width: 120 }} />
</GuardState>
</SettingItem>
)}
</SettingList>
);
};
export default SettingSystem;

Some files were not shown because too many files have changed in this diff Show More