Compare commits

...
394 Commits
Author SHA1 Message Date
GyDi 30ef3057ac v1.1.1 2022-10-11 23:03:12 +08:00
GyDi 48f3a934c9 chore: update log 2022-10-11 23:02:49 +08:00
GyDi 38d1fde84f fix: api error handle 2022-10-11 22:51:18 +08:00
GyDi dd78670a4b fix: clash meta not load geoip, close #212 2022-10-11 22:24:54 +08:00
GyDi b8a8190a43 fix: sort proxy during loading, close #221 2022-10-11 22:06:55 +08:00
GyDi 2d0989342f fix: not create windows when enable slient start 2022-10-11 21:50:00 +08:00
GyDi 15ff9b06a1 fix: root background color 2022-10-11 20:49:03 +08:00
GyDi 41b19f69de fix: create window correctly 2022-10-11 00:57:34 +08:00
GyDi f2bd6f1fce fix: set_activation_policy 2022-10-10 22:15:21 +08:00
GyDi ec94218a4b chore: rm aarch64 ci 2022-09-28 18:50:33 +08:00
GyDi c2e5c7cf38 chore: test ci 2022-09-28 17:26:32 +08:00
GyDi bac5734527 chore: test ci 2022-09-28 17:12:27 +08:00
GyDi bef4033d94 chore: fix ci 2022-09-28 16:04:05 +08:00
GyDi 64216cba67 chore: fix test ci 2022-09-28 15:19:50 +08:00
Particle_G a9d6167a9f chore: add support for windows arm64, close #216 (#209) 2022-09-28 15:13:24 +08:00
GyDi 6c6b40548f fix: disable spell check 2022-09-28 14:15:22 +08:00
苏业钦 a916d88e85 chore: add support linux arm64 (#215) 2022-09-28 10:40:41 +08:00
GyDi ab2f0548a3 chore: clash meta linux use compatible version 2022-09-27 00:16:22 +08:00
GyDi e30ba07285 feat: optimize config feedback 2022-09-26 20:46:29 +08:00
GyDi 1b336d973d fix: adjust init launch on dev 2022-09-26 01:35:19 +08:00
GyDi 7b1866737f v1.1.0 2022-09-26 01:27:56 +08:00
GyDi eedc4ab648 chore: update log 2022-09-26 01:27:32 +08:00
GyDi 5e429c7a94 fix: ignore disable auto launch error 2022-09-26 01:09:05 +08:00
GyDi 57d23eb043 fix(macos): set auto launch path to application 2022-09-25 23:36:55 +08:00
GyDi 5ebd9be89a fix: i18n 2022-09-25 01:41:46 +08:00
GyDi 5a743779e2 feat: show connections with table layout 2022-09-25 01:35:21 +08:00
GyDi 0495062110 fix: style 2022-09-24 20:55:40 +08:00
GyDi d522191f69 fix: save enable log on localstorage 2022-09-24 19:03:14 +08:00
Priestch bbbdc8b7a6 fix: typo in api.ts (#207) 2022-09-24 18:48:11 +08:00
GyDi c00ed8aa5a chore: use ubuntu latest 2022-09-24 16:08:39 +08:00
GyDi 0beaa94068 feat: show loading on proxy group delay check 2022-09-24 15:31:09 +08:00
GyDi 96e76665d6 fix: refresh clash ui await patch 2022-09-24 14:01:28 +08:00
Shun Li 6423a29600 feat: add chains[0] and process to connections display (#205)
* add chains[0] display

* add metadata.process to connections
2022-09-24 13:06:32 +08:00
GyDi 8bddf30dcf refactor(hotkey): use tauri global shortcut 2022-09-23 15:31:01 +08:00
GyDi a6b2db182d feat: adjust connection page ui 2022-09-23 00:08:52 +08:00
GyDi b9f3f9d859 Merge pull request #197 from FoundTheWOUT/main
Support ordering connection
2022-09-22 22:55:46 +08:00
GyDi 6331447dcd feat: yaml merge key 2022-09-21 22:15:24 +08:00
GyDi 4213ee660f feat: toggle log ws 2022-09-20 22:15:28 +08:00
GyDi 3bd9287c5d chore: update deps 2022-09-20 21:26:38 +08:00
GyDi b23d3f7c8b feat: add rule page 2022-09-18 23:19:02 +08:00
GyDi f8d9e5e027 feat: hotkey viewer 2022-09-18 15:52:53 +08:00
GyDi 8fa7fb3b1f feat: refresh ui when hotkey clicked 2022-09-18 15:50:03 +08:00
FoundTheWOUT 63d92a0872 Support ordering connection 2022-09-15 15:52:12 +08:00
GyDi 509d83365e feat: support hotkey (wip) 2022-09-14 01:19:02 +08:00
GyDi d6ab73c905 fix: remove dead code 2022-09-12 13:42:21 +08:00
GyDi 5a93ba05d5 fix: style 2022-09-12 13:42:13 +08:00
GyDi 2d2fdf0b1e fix: handle is none 2022-09-12 00:45:19 +08:00
GyDi cf96622261 fix: unused 2022-09-12 00:02:25 +08:00
GyDi 47c8ccb0e5 refactor: optimize 2022-09-11 20:58:55 +08:00
GyDi 02fdb8778b fix: style 2022-09-11 18:38:51 +08:00
GyDi 6bed7f0e66 fix: windows logo size 2022-09-11 17:50:58 +08:00
GyDi 7597d335b9 feat: hide window on macos 2022-09-09 16:42:35 +08:00
GyDi f32c5ba244 fix: do not kill sidecar during updating 2022-09-09 16:33:04 +08:00
GyDi ab53ab21e2 fix: delay update config 2022-09-09 16:30:27 +08:00
GyDi acfe5dbb49 fix: reduce logo size 2022-09-09 16:19:13 +08:00
GyDi f9b91fa189 feat: system proxy setting 2022-09-07 01:51:43 +08:00
GyDi 2462e68ba1 fix: window center 2022-09-06 22:18:06 +08:00
GyDi 019b2a1681 chore: update resource 2022-09-06 15:32:22 +08:00
GyDi e94a07b677 fix: log level warn value 2022-09-06 14:42:58 +08:00
GyDi c058c29755 feat: change default singleton port and support to change the port 2022-09-06 00:45:01 +08:00
GyDi 9e7c7ac163 feat: log info 2022-09-05 20:30:39 +08:00
GyDi fcee41f00d feat: kill clash by pid 2022-09-05 16:30:29 +08:00
GyDi ff2c1bf8ed feat: change clash port in dialog 2022-09-05 02:12:25 +08:00
GyDi a2cf26e7ed feat: add proxy item check loading 2022-09-04 23:53:48 +08:00
GyDi 71e6900375 feat: compatible with proxy providers health check 2022-09-04 22:55:54 +08:00
GyDi 3bdc98bd12 v1.0.6 2022-09-03 00:40:50 +08:00
GyDi 68d2a6e951 chore: update log 2022-09-03 00:39:39 +08:00
GyDi acf47ac947 chore: update deps 2022-09-02 23:06:00 +08:00
GyDi fda24e5f5a chore: update deps 2022-09-02 01:35:06 +08:00
GyDi 05eca8e4d8 chore: use ubuntu 18.04 2022-09-02 01:27:06 +08:00
GyDi b915f3b1a9 feat: add empty ui 2022-09-02 01:09:38 +08:00
GyDi ab58968f4d feat: complete i18n 2022-09-02 01:05:45 +08:00
GyDi 820d1e7570 fix: increase delay checker concurrency 2022-09-02 00:41:43 +08:00
GyDi a120c8cf98 fix: external controller allow lan 2022-09-02 00:24:19 +08:00
GyDi 5a35ea116f chore: update clash meta version 2022-09-02 00:11:52 +08:00
GyDi e72ad1f030 fix: remove useless optimizations 2022-08-31 21:44:23 +08:00
GyDi a17362437a chore: test ci 2022-08-29 17:26:09 +08:00
GyDi 8643dc43b1 chore: update clash 2022-08-29 11:11:55 +08:00
GyDi e1c869a358 chore: add test ci os version 2022-08-29 11:02:14 +08:00
GyDi 2f5b8d9abe Merge branch 'main' of github.com:zzzgydi/clash-verge 2022-08-24 22:41:36 +08:00
GyDi db324f54eb chore: update auto launch 2022-08-24 22:41:12 +08:00
GyDi 3242efb1a2 fix: reduce unsafe unwrap 2022-08-23 15:19:04 +08:00
FoundTheWOUT 30f9f1a021 fix: timer restore at app launch 2022-08-23 10:35:36 +08:00
GyDi 3f58d05aa7 fix: adjust log text 2022-08-19 17:11:59 +08:00
GyDi c611a51575 fix: only script profile can display console 2022-08-17 01:45:37 +08:00
GyDi 73458dcd28 v1.0.5 2022-08-16 23:56:29 +08:00
GyDi 23ebeb1cc0 chore: update log 2022-08-16 23:56:04 +08:00
GyDi a7ba9f1886 fix: fill button title attr 2022-08-16 23:46:33 +08:00
GyDi d5192e2244 feat: windows portable version do not check update 2022-08-16 01:53:40 +08:00
GyDi 7eb595170f fix: do not reset system proxy when consistent 2022-08-16 01:27:32 +08:00
GyDi bd576ca808 fix: adjust web ui item style 2022-08-16 01:08:54 +08:00
GyDi 2f8146b11f fix: clash field state error 2022-08-16 00:48:06 +08:00
GyDi 7f321c89cb feat: adjust clash info parsing logs 2022-08-15 20:21:43 +08:00
GyDi fa65f606b8 fix: badge color error 2022-08-15 20:15:44 +08:00
GyDi 7a3285adaf fix: web ui port value error 2022-08-15 20:14:33 +08:00
GyDi 8bf78fef10 fix: delay show window 2022-08-15 01:37:26 +08:00
GyDi 78f97ce4df feat: adjust runtime config 2022-08-15 01:30:37 +08:00
GyDi 66ccbf70f8 feat: support restart app on tray 2022-08-15 01:22:39 +08:00
GyDi cb48600b40 fix: adjust dialog action button variant 2022-08-15 00:55:35 +08:00
GyDi 33ce235713 feat: optimize profile page 2022-08-14 23:10:19 +08:00
GyDi f1a68ece01 fix: script code error 2022-08-12 23:41:25 +08:00
GyDi dd563360af fix: script exception handle 2022-08-12 11:14:34 +08:00
GyDi 7f6dac4271 feat: refactor 2022-08-12 03:20:55 +08:00
GyDi 178fd8e828 feat: adjust tun mode config 2022-08-11 03:26:08 +08:00
GyDi 1641e02a7d feat: reimplement enhanced mode 2022-08-11 02:55:10 +08:00
GyDi cfd04e9bb4 feat: use rquickjs crate 2022-08-10 13:05:48 +08:00
GyDi 38effaf740 feat: reimplement enhanced mode 2022-08-09 21:15:55 +08:00
GyDi a68eb4a73e chore: format 2022-08-09 14:33:47 +08:00
GyDi c02990ef98 fix: change fields 2022-08-09 14:31:59 +08:00
FoundTheWOUT 5aa7d5ffe9 fix: silent start (#150) 2022-08-09 14:14:06 +08:00
GyDi 4942b0fca5 fix: save profile when update 2022-08-08 23:17:22 +08:00
GyDi aed1bdff5a fix: list compare wrong 2022-08-08 23:16:28 +08:00
GyDi 929c840006 fix: button color 2022-08-08 23:15:05 +08:00
GyDi 57aef1d3c2 chore: rm code 2022-08-08 22:30:13 +08:00
GyDi c1734a094c fix: limit theme mode value 2022-08-08 22:28:44 +08:00
GyDi 99c46685ac feat: finish clash field control 2022-08-08 22:14:03 +08:00
GyDi 066b08040a feat: clash field viewer wip 2022-08-08 01:51:30 +08:00
GyDi 35de2334fb fix: add valid clash field 2022-08-07 20:52:50 +08:00
GyDi 5564c966a5 feat: support web ui 2022-08-06 21:56:54 +08:00
GyDi 0891b5e7b7 feat: adjust setting page style 2022-08-06 03:48:03 +08:00
GyDi f3341f201f refactor: ts path alias 2022-08-06 02:35:11 +08:00
GyDi bf0dafabe2 fix: icon style 2022-08-06 01:44:33 +08:00
GyDi 60f6587169 fix: reduce unwrap 2022-07-30 23:32:52 +08:00
GyDi a9bf32919e feat: runtime config viewer 2022-07-25 01:20:13 +08:00
GyDi 7633f9f88b chore: fix updater script 2022-07-18 12:55:59 +08:00
GyDi 9b56233938 v1.0.4 2022-07-17 17:56:07 +08:00
GyDi 65074264b8 chore: update log 2022-07-17 17:52:41 +08:00
GyDi 4f6fceb87f feat: improve log rule 2022-07-17 17:39:44 +08:00
GyDi 659fdd1d37 fix: import mod 2022-07-17 16:51:54 +08:00
GyDi 8bce2ce040 feat: theme mode support follows system 2022-07-17 16:02:17 +08:00
GyDi 55cc83a5d4 chore: update deps 2022-07-17 14:54:09 +08:00
GyDi 6a51e93ded refactor: mode manage on tray 2022-07-13 02:26:54 +08:00
GyDi fcf570e96e chore: rm code 2022-07-13 01:07:29 +08:00
GyDi cbc184e953 fix: add tray separator 2022-07-13 01:05:53 +08:00
GyDi 98f9063352 Merge pull request #128 from Limsanity/main
feat: support switch proxy mode
2022-07-13 01:02:14 +08:00
limsanity c278f1af00 style: resolve formatting problem 2022-07-13 00:54:47 +08:00
limsanity fbb17a0ba5 feat(system tray): support switch rule/global/direct/script mode in system tray 2022-07-13 00:43:27 +08:00
GyDi 8637a9823e chore: update deps 2022-07-11 00:41:21 +08:00
GyDi d717fe7e8c chore: update clash version 2022-07-08 01:42:14 +08:00
GyDi 5e8dfe7267 chore: update aarch rule 2022-07-07 02:54:20 +08:00
GyDi aaa4fbcdbd chore: aarch upload script 2022-07-07 02:53:53 +08:00
GyDi 150f0cf486 fix: instantiate core after init app, close #122 2022-07-06 15:14:33 +08:00
GyDi 711b220a05 chore: update clash version 2022-07-06 00:54:01 +08:00
GyDi b615c485f7 chore: update deps 2022-07-06 00:49:09 +08:00
GyDi 2f3b6b29ae fix: rm macOS transition props 2022-07-05 01:24:23 +08:00
GyDi 7aecd83c4a chore: update deps 2022-07-05 00:52:22 +08:00
GyDi 3b460ab91f chore: change tray icon 2022-06-22 01:26:25 +08:00
GyDi 661c0eb970 v1.0.3 2022-06-20 02:09:12 +08:00
GyDi f4a1f1fdc8 chore: update log 2022-06-20 02:06:46 +08:00
GyDi b5432c3728 chore: update clash version 2022-06-20 01:47:15 +08:00
GyDi 6d0625c409 fix: improve external-controller parse and log 2022-06-20 01:36:56 +08:00
GyDi 2f1ea08b8a chore: update macos icon 2022-06-18 18:41:53 +08:00
GyDi a092da1943 fix: show windows on click 2022-06-18 17:28:37 +08:00
GyDi 43ef3cc562 chore: new logo for mac 2022-06-18 17:28:05 +08:00
GyDi 047774475c chore: update alpha ci 2022-06-17 01:18:19 +08:00
GyDi 91b8504df5 chore: update tauri 2022-06-17 01:16:46 +08:00
GyDi a4fb2dfcf8 fix: adjust update profile notice error 2022-06-15 02:42:04 +08:00
GyDi ba16ec02e5 fix: style issue on mac 2022-06-15 02:41:37 +08:00
GyDi 55b7af2623 chore: update version 2022-06-15 01:15:05 +08:00
GyDi b428eff10e feat: improve yaml file error log 2022-06-14 01:40:02 +08:00
GyDi 35aee15b6d chore: update deps 2022-06-14 01:23:58 +08:00
GyDi 6f53c1bfde Merge pull request #104 from FoundTheWOUT/main
fix: check script run on all OS
2022-06-12 22:25:05 +08:00
FoundTheWOUT db0230ed75 fix: check script run on all OS 2022-06-05 23:55:41 +08:00
GyDi 7fa3c1e12a feat: save proxy page state 2022-06-04 18:55:39 +08:00
GyDi 3b5993652f chore: portable script 2022-06-02 00:56:05 +08:00
GyDi be4ad8947f chore: updater script 2022-06-01 10:06:08 +08:00
GyDi 2ead15e78e v1.0.2 2022-06-01 01:26:05 +08:00
GyDi aa0740ff94 chore: update log 2022-06-01 01:25:39 +08:00
GyDi 6d3f837820 fix: macOS disable transparent 2022-06-01 01:04:46 +08:00
GyDi 359b82c29c chore: rm some files 2022-06-01 00:49:52 +08:00
GyDi b54171bc2c chore: rust cache 2022-06-01 00:47:04 +08:00
GyDi 936b2131e0 chore: adjust ci and script 2022-06-01 00:43:57 +08:00
GyDi aaef6a9e9c chore: enable meta by default 2022-06-01 00:31:12 +08:00
GyDi 9327006e61 chore: rm file 2022-05-30 00:58:48 +08:00
GyDi 5225c841ae chore: adjust code 2022-05-30 00:57:31 +08:00
GyDi 8464e319fd chore: update deps 2022-05-29 23:35:22 +08:00
GyDi 98b8bd90ea fix: window transparent and can not get hwnd 2022-05-25 19:06:06 +08:00
GyDi ae94993b09 fix: create main window 2022-05-25 16:45:18 +08:00
GyDi 72f10aaed1 chore: update deps 2022-05-25 16:12:48 +08:00
GyDi 4a74bae8c7 chore: update clash core 2022-05-25 16:08:58 +08:00
ctaoist 5164aec37b feat: light mode wip (#96)
* 关闭窗口释放UI资源

* windows 还有左键点击事件

* 兼容enhance profile

* bug 修复
2022-05-25 16:06:39 +08:00
GyDi 1581e9b1cd chore: update clash version 2022-05-18 14:14:37 +08:00
GyDi 536e3ffb11 chore: alpha ci 2022-05-18 14:07:41 +08:00
GyDi d6103191ba chore: error text 2022-05-18 09:58:20 +08:00
GyDi 49e37a19a5 chore: ci 2022-05-17 12:35:42 +08:00
GyDi d02431e260 chore: fix alpha ci 2022-05-17 12:34:30 +08:00
GyDi f24f6ead92 chore: alpha ci 2022-05-17 11:41:45 +08:00
GyDi b7bdb7ae50 chore: meta 2022-05-17 02:46:15 +08:00
GyDi 2dcf8ac96f chore: fix ci 2022-05-17 02:21:58 +08:00
GyDi 5421c94853 chore: test ci 2022-05-17 02:17:02 +08:00
GyDi 10f6bc092a chore: alpha 2022-05-17 02:11:29 +08:00
GyDi be9ea4ea8e feat: clash meta core supports 2022-05-17 01:59:49 +08:00
GyDi f5c6fa842a fix: adjust notice 2022-05-17 00:51:37 +08:00
GyDi e0943ce905 fix: label text 2022-05-16 20:26:13 +08:00
GyDi 61e7df77a7 feat: script mode 2022-05-16 20:18:56 +08:00
GyDi a5434360bc chore: test ci 2022-05-16 17:55:14 +08:00
GyDi ba29c66e3b chore: update deps 2022-05-16 17:54:21 +08:00
GyDi b3a72d55ae feat: clash meta core support (wip) 2022-05-16 01:52:50 +08:00
GyDi c382ad1cc8 fix: icon path 2022-05-13 12:28:36 +08:00
GyDi 363e28f323 fix: icon issue 2022-05-13 02:46:06 +08:00
GyDi d695656b8c fix: notice ui blocking 2022-05-13 02:29:43 +08:00
GyDi 31c6cbc0a2 fix: service mode error 2022-05-13 02:11:03 +08:00
GyDi b93284bc2f chore: fix linux build ci 2022-05-11 12:39:41 +08:00
GyDi 99c855b01b chore: test ci 2022-05-11 12:20:20 +08:00
GyDi c2eaedc959 chore: test ci 2022-05-11 12:12:55 +08:00
GyDi a631cd67ec chore: test ci fix deps 2022-05-11 11:30:19 +08:00
GyDi 66fccd3c68 chore: test ci 2022-05-11 11:22:09 +08:00
GyDi 9a4ebf4daa chore: test ci 2022-05-11 10:51:28 +08:00
GyDi 91c14211c6 chore: continue on error 2022-05-11 01:26:11 +08:00
GyDi 1ea07c458b chore: test linux 2022-05-11 00:52:20 +08:00
GyDi 591add6e0c chore: test ci 2022-05-11 00:31:19 +08:00
GyDi b99fff66df v1.0.1 2022-05-10 21:40:33 +08:00
GyDi f54ba05b00 chore: update log 2022-05-10 21:40:07 +08:00
GyDi 6596fb00c7 fix: win11 drag lag 2022-05-09 14:41:26 +08:00
GyDi df0b5a80dc chore: change default height 2022-05-09 14:01:46 +08:00
GyDi 8cdbb31dbe fix: rm unwrap 2022-05-09 14:01:14 +08:00
GyDi 0be4b1222d feat: reduce gpu usage when hidden 2022-05-07 14:43:52 +08:00
GyDi 18a6bfd73a feat: interval update from now field 2022-05-07 14:43:08 +08:00
GyDi 5e2271b237 feat: adjust theme 2022-05-06 14:04:39 +08:00
GyDi 798999d490 fix: edit profile info 2022-05-06 12:46:27 +08:00
GyDi 0e68c5e8bc feat: supports more remote headers close #81 2022-05-06 10:52:59 +08:00
GyDi 9694af82f4 feat: check the remote profile 2022-05-06 01:26:24 +08:00
GyDi 28a4386975 fix: change window default size 2022-05-06 01:15:15 +08:00
GyDi a238f7beba chore: update deps 2022-05-06 01:14:13 +08:00
GyDi 75ba16281b chore: change default user agent 2022-05-06 00:42:20 +08:00
GyDi ad65a278d4 chore: merge
feat: remove outdated config
2022-04-28 16:28:18 +08:00
tianyoulan a2320b3f8d feat: fix typo 2022-04-28 15:35:17 +08:00
tianyoulan ae12853ad0 feat: remove trailing comma 2022-04-28 15:05:10 +08:00
tianyoulan 68adf6dc2f feat: remove outdated config 2022-04-28 15:02:37 +08:00
GyDi f88989bd4b fix: change service installer and uninstaller 2022-04-27 15:46:44 +08:00
GyDi 77ef3847ce v1.0.0 2022-04-26 00:50:48 +08:00
GyDi b8291837fc chore: update log 2022-04-26 00:49:07 +08:00
GyDi 423a7f951a fix: adjust connection scroll 2022-04-26 00:37:28 +08:00
GyDi 557f5fe364 fix: adjust something 2022-04-25 20:00:11 +08:00
GyDi 5308970ad8 fix: adjust debounce wait time 2022-04-25 19:39:21 +08:00
GyDi 6b368953f4 feat: windows service mode ui 2022-04-25 16:12:04 +08:00
GyDi 2d0b63c29d feat: add some commands 2022-04-24 21:03:47 +08:00
GyDi 34e941c8cb feat: windows service mode 2022-04-24 21:00:17 +08:00
GyDi 76cf007fff chore: update check script 2022-04-24 15:35:30 +08:00
GyDi 321963be83 wip: windows service mode 2022-04-23 17:26:32 +08:00
GyDi c733bda6c3 test: windows service 2022-04-21 21:28:44 +08:00
GyDi e67b50b976 chore: adjust guard log 2022-04-21 19:51:20 +08:00
GyDi 9e3c080909 fix: adjust dns config 2022-04-21 19:50:22 +08:00
GyDi cb661aaebd feat: add update interval 2022-04-21 14:26:41 +08:00
GyDi 573571978c chore: adjust 2022-04-21 14:24:35 +08:00
GyDi dc492a2a0a chore: update clash version 2022-04-20 21:02:41 +08:00
GyDi e47747dd0e feat: refactor and supports cron tasks 2022-04-20 20:39:27 +08:00
GyDi 4de944b41e feat: supports cron update profiles 2022-04-20 20:37:16 +08:00
GyDi 5f7a1fa5cd refactor: verge 2022-04-20 11:17:54 +08:00
GyDi b8ad328cde refactor: wip 2022-04-20 01:44:47 +08:00
GyDi 3076fd19c1 refactor: mutex 2022-04-19 14:38:59 +08:00
GyDi fac437b8c1 fix: traffic graph adapt to different fps 2022-04-19 13:55:26 +08:00
GyDi 697c25015e refactor: wip 2022-04-19 01:41:20 +08:00
GyDi d83b404fc3 chore: check script proxy agent supports 2022-04-17 00:37:21 +08:00
GyDi ab7313cbc4 feat: optimize traffic graph quadratic curve 2022-04-16 22:32:44 +08:00
GyDi 1b8d70322b feat: optimize the animation of the traffic graph 2022-04-16 17:28:30 +08:00
GyDi 844ffab4ed fix: optimize clash launch 2022-04-15 01:29:25 +08:00
GyDi f5d0513d1f fix: reset after exit 2022-04-14 01:29:33 +08:00
GyDi 557abd4285 fix: adjust code 2022-04-14 01:29:02 +08:00
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
147 changed files with 13282 additions and 5743 deletions
+84
View File
@@ -0,0 +1,84 @@
name: Alpha CI
on:
push:
branches: [alpha]
env:
CARGO_INCREMENTAL: 0
RUST_BACKTRACE: short
jobs:
release:
strategy:
matrix:
os: [windows-latest, ubuntu-latest, macos-latest]
runs-on: ${{ matrix.os }}
if: startsWith(github.repository, 'zzzgydi')
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
profile: minimal
override: true
- name: Rust Cache
uses: Swatinem/rust-cache@ce325b60658c1b38465c06cc965b79baf32c1e72
with:
working-directory: src-tauri
- name: Install Node
uses: actions/setup-node@v1
with:
node-version: 14
- name: Install Dependencies (ubuntu only)
if: matrix.os == 'ubuntu-latest'
run: |
sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.0-dev build-essential curl wget libssl-dev libgtk-3-dev libappindicator3-dev librsvg2-dev libayatana-appindicator3-dev
- name: Get yarn cache dir path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- name: Yarn Cache
uses: actions/cache@v2
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: Yarn install and check
run: |
yarn install --network-timeout 1000000
yarn run check
- name: Tauri build
uses: tauri-apps/tauri-action@743a37fd53cbdd122910b818b9bef7b7aa019134
# enable cache even though failed
continue-on-error: true
env:
VITE_MULTI_CORE: 1
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
with:
tagName: alpha
releaseName: "Clash Verge Alpha"
releaseBody: "Alpha Version"
releaseDraft: true
prerelease: true
# - name: Portable Bundle
# if: matrix.os == 'windows-latest'
# run: |
# yarn run portable
# env:
# GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+27 -7
View File
@@ -10,7 +10,7 @@ jobs:
release:
strategy:
matrix:
os: [windows-latest, macos-11]
os: [windows-latest, ubuntu-latest, macos-latest]
runs-on: ${{ matrix.os }}
if: |
startsWith(github.repository, 'zzzgydi') &&
@@ -28,12 +28,20 @@ jobs:
- name: Rust Cache
uses: Swatinem/rust-cache@ce325b60658c1b38465c06cc965b79baf32c1e72
with:
working-directory: src-tauri
- name: Install Node
uses: actions/setup-node@v1
with:
node-version: 14
- name: Install Dependencies (ubuntu only)
if: startsWith(matrix.os, 'ubuntu-')
run: |
sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.0-dev build-essential curl wget libssl-dev libgtk-3-dev libappindicator3-dev librsvg2-dev libayatana-appindicator3-dev
- name: Get yarn cache dir path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
@@ -53,9 +61,9 @@ jobs:
yarn run check
- name: Tauri build
uses: tauri-apps/tauri-action@b9ce5d7dc68082d21d30a60103b0ab8c5ddae3a1
uses: tauri-apps/tauri-action@0e558392ccadcb49bcc89e7df15a400e8f0c954d
# enable cache even though failed
continue-on-error: true
# continue-on-error: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
@@ -67,9 +75,21 @@ jobs:
releaseDraft: false
prerelease: true
- name: Portable Bundle
if: matrix.os == 'windows-latest'
# rebuild with env settings
run: |
yarn build
yarn run portable
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
VITE_WIN_PORTABLE: 1
release-update:
needs: release
runs-on: macos-11
runs-on: macos-latest
if: |
startsWith(github.repository, 'zzzgydi') &&
startsWith(github.ref, 'refs/tags/v')
@@ -91,9 +111,9 @@ jobs:
${{ runner.os }}-yarn-
- name: Yarn install
run: yarn
run: yarn install
- name: Release update.json
run: yarn run release
- name: Release updater file
run: yarn run updater
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+82
View File
@@ -0,0 +1,82 @@
name: Test CI
on:
workflow_dispatch:
inputs:
os:
description: "Runs on OS"
required: true
default: windows-latest
type: choice
options:
- windows-latest
- ubuntu-latest
- macos-latest
- ubuntu-18.04
- ubuntu-20.04
- ubuntu-22.04
- macos-10.15
- macos-11
- macos-12
- windows-2019
- windows-2022
env:
CARGO_INCREMENTAL: 0
RUST_BACKTRACE: short
jobs:
release:
runs-on: ${{ github.event.inputs.os }}
if: startsWith(github.repository, 'zzzgydi')
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
profile: minimal
override: true
- name: Rust Cache
uses: Swatinem/rust-cache@v1
with:
working-directory: src-tauri
- name: Install Node
uses: actions/setup-node@v1
with:
node-version: 14
- name: Install Dependencies (ubuntu only)
if: startsWith(github.event.inputs.os, 'ubuntu-')
run: |
sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.0-dev build-essential curl wget libssl-dev libgtk-3-dev libappindicator3-dev librsvg2-dev libayatana-appindicator3-dev
- name: Get yarn cache dir path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- name: Yarn Cache
uses: actions/cache@v2
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: Yarn install and check
run: |
yarn install --network-timeout 1000000
yarn run check
- name: Tauri build
uses: tauri-apps/tauri-action@0e558392ccadcb49bcc89e7df15a400e8f0c954d
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
+32
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 }}
+1
View File
@@ -4,3 +4,4 @@ dist
dist-ssr
*.local
update.json
scripts/_env.sh
+31 -1
View File
@@ -11,7 +11,19 @@ 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, maybe fewer. (WIP)
- Full `clash` config supported, Partial `clash premium` config supported.
- Profiles management and enhancement (by yaml and Javascript). [Doc](https://github.com/zzzgydi/clash-verge/wiki/%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97)
- Simple UI and supports custom theme color.
- Built-in support [Clash.Meta](https://github.com/MetaCubeX/Clash.Meta) core.
- System proxy setting and guard.
## Install
Download from [release](https://github.com/zzzgydi/clash-verge/releases). Supports Windows x64, Linux x86_64 and macOS 11+
Or you can build it yourself. Supports Windows, Linux and macOS 10.15+
Notes: If you could not start the app on Windows, please check that you have [Webview2](https://developer.microsoft.com/en-us/microsoft-edge/webview2/#download-section) installed.
## Development
@@ -33,6 +45,12 @@ Then run
yarn dev
```
Or you can build it
```shell
yarn build
```
## Todos
> This keng is a little big...
@@ -48,6 +66,17 @@ yarn dev
<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
This is a learning project for Rust practice.
@@ -62,6 +91,7 @@ Clash Verge was based on or inspired by these projects and so on:
- [tauri-apps/tauri](https://github.com/tauri-apps/tauri): Build smaller, faster, and more secure desktop applications with a web frontend.
- [Dreamacro/clash](https://github.com/Dreamacro/clash): A rule-based tunnel in Go.
- [MetaCubeX/Clash.Meta](https://github.com/MetaCubeX/Clash.Meta): A rule-based tunnel in Go.
- [Fndroid/clash_for_windows_pkg](https://github.com/Fndroid/clash_for_windows_pkg): A Windows/macOS GUI based on Clash.
- [vitejs/vite](https://github.com/vitejs/vite): Next generation frontend tooling. It's fast!
+236
View File
@@ -0,0 +1,236 @@
## v1.1.1
### Features
- optimize clash config feedback
- hide macOS dock icon
- use clash meta compatible version (Linux)
### Bug Fixes
- fix some other glitches
---
## v1.1.0
### Features
- add rule page
- supports proxy providers delay check
- add proxy delay check loading status
- supports hotkey/shortcut management
- supports displaying connections data in table layout(refer to yacd)
### Bug Fixes
- supports yaml merge key in clash config
- detect the network interface and set the system proxy(macOS)
- fix some other glitches
---
## v1.0.6
### Features
- update clash and clash.meta
### Bug Fixes
- only script profile display console
- automatic configuration update on demand at launch
---
## v1.0.5
### Features
- reimplement profile enhanced mode with quick-js
- optimize the runtime config generation process
- support web ui management
- support clash field management
- support viewing the runtime config
- adjust some pages style
### Bug Fixes
- fix silent start
- fix incorrectly reset system proxy on exit
---
## v1.0.4
### Features
- update clash core and clash meta version
- support switch clash mode on system tray
- theme mode support follows system
### Bug Fixes
- config load error on first use
---
## v1.0.3
### Features
- save some states such as URL test, filter, etc
- update clash core and clash-meta core
- new icon for macOS
---
## v1.0.2
### Features
- supports for switching clash core
- supports release UI processes
- supports script mode setting
### Bug Fixes
- fix service mode bug (Windows)
---
## v1.0.1
### Features
- adjust default theme settings
- reduce gpu usage of traffic graph when hidden
- supports more remote profile response header setting
- check remote profile data format when imported
### Bug Fixes
- service mode install and start issue (Windows)
- fix launch panic (Some Windows)
---
## v1.0.0
### Features
- update clash core
- optimize traffic graph animation
- supports interval update profiles
- supports service mode (Windows)
### Bug Fixes
- reset system proxy when exit from dock (macOS)
- adjust clash dns config process strategy
---
## v0.0.29
### Features
- sort proxy node
- custom proxy test url
- logs page filter
- connections page filter
- default user agent for subscription
- system tray add tun mode toggle
- enable to change the config dir (Windows only)
---
## v0.0.28
### Features
- enable to use clash config fields (UI)
### Bug Fixes
- remove the character
- fix some icon color
---
## v0.0.27
### Features
- supports custom theme color
- tun mode setting control the final config
### Bug Fixes
- fix transition flickers (macOS)
- reduce proxy page render
---
## v0.0.26
### Features
- silent start
- profile editor
- profile enhance mode supports more fields
- optimize profile enhance mode strategy
### Bug Fixes
- fix csp restriction on macOS
- window controllers on Linux
---
## v0.0.25
### Features
- update clash core version
### Bug Fixes
- app updater error
- display window controllers on Linux
### Notes
If you can't update the app properly, please consider downloading the latest version from github release.
---
## v0.0.24
### Features
- Connections page
- add wintun.dll (Windows)
- supports create local profile with selected file (Windows)
- system tray enable set system proxy
### Bug Fixes
- open dir error
- auto launch path (Windows)
- fix some clash config error
- reduce the impact of the enhanced mode
---
## v0.0.23
### Features
- i18n supports
- Remote profile User Agent supports
### Bug Fixes
- clash config file case ignore
- clash `external-controller` only port
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

+37 -23
View File
@@ -1,51 +1,65 @@
{
"name": "clash-verge",
"version": "0.0.21",
"version": "1.1.1",
"license": "GPL-3.0",
"scripts": {
"dev": "tauri dev",
"dev:diff": "tauri dev -f verge-dev",
"build": "tauri build",
"tauri": "tauri",
"web:dev": "vite",
"web:build": "tsc && vite build",
"web:serve": "vite preview",
"aarch": "node scripts/aarch.mjs",
"check": "node scripts/check.mjs",
"updater": "node scripts/updater.mjs",
"publish": "node scripts/publish.mjs",
"release": "node scripts/release.mjs",
"portable": "node scripts/portable.mjs",
"prepare": "husky install"
},
"dependencies": {
"@emotion/react": "^11.8.1",
"@emotion/styled": "^11.8.1",
"@mui/icons-material": "^5.4.4",
"@mui/material": "^5.4.4",
"@tauri-apps/api": "^1.0.0-rc.1",
"ahooks": "^3.1.13",
"axios": "^0.26.0",
"dayjs": "^1.10.8",
"@emotion/react": "^11.10.4",
"@emotion/styled": "^11.10.4",
"@mui/icons-material": "^5.10.3",
"@mui/material": "^5.10.3",
"@mui/x-data-grid": "^5.17.4",
"@tauri-apps/api": "^1.1.0",
"ahooks": "^3.7.0",
"axios": "^0.27.2",
"dayjs": "^1.11.5",
"i18next": "^21.9.1",
"monaco-editor": "^0.34.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-router-dom": "^6.2.2",
"react-virtuoso": "^2.7.0",
"recoil": "^0.6.1",
"swr": "^1.2.1"
"react-i18next": "^11.17.4",
"react-router-dom": "^6.3.0",
"react-virtuoso": "^2.17.2",
"recoil": "^0.7.5",
"snarkdown": "^2.0.0",
"swr": "^1.3.0"
},
"devDependencies": {
"@actions/github": "^5.0.0",
"@tauri-apps/cli": "^1.0.0-rc.5",
"@actions/github": "^5.0.3",
"@tauri-apps/cli": "^1.1.1",
"@types/fs-extra": "^9.0.13",
"@types/js-cookie": "^3.0.1",
"@types/js-cookie": "^3.0.2",
"@types/lodash": "^4.14.180",
"@types/react": "^17.0.0",
"@types/react-dom": "^17.0.0",
"@vitejs/plugin-react": "^1.2.0",
"@vitejs/plugin-react": "^2.0.1",
"adm-zip": "^0.5.9",
"cross-env": "^7.0.3",
"fs-extra": "^10.0.0",
"https-proxy-agent": "^5.0.1",
"husky": "^7.0.0",
"node-fetch": "^3.2.0",
"node-fetch": "^3.2.6",
"prettier": "^2.7.1",
"pretty-quick": "^3.1.3",
"sass": "^1.49.7",
"typescript": "^4.5.5",
"vite": "^2.8.6"
"sass": "^1.54.0",
"typescript": "^4.7.4",
"vite": "^3.0.9",
"vite-plugin-monaco-editor": "^1.1.0",
"vite-plugin-svgr": "^2.2.1"
},
"prettier": {
"tabWidth": 2,
@@ -53,4 +67,4 @@
"singleQuote": false,
"endOfLine": "lf"
}
}
}
+104
View File
@@ -0,0 +1,104 @@
/**
* Build and upload assets for macOS(aarch)
*/
import fs from "fs-extra";
import path from "path";
import { exit } from "process";
import { createRequire } from "module";
import { getOctokit, context } from "@actions/github";
const require = createRequire(import.meta.url);
async function resolve() {
if (!process.env.GITHUB_TOKEN) {
throw new Error("GITHUB_TOKEN is required");
}
if (!process.env.GITHUB_REPOSITORY) {
throw new Error("GITHUB_REPOSITORY is required");
}
if (!process.env.TAURI_PRIVATE_KEY) {
throw new Error("TAURI_PRIVATE_KEY is required");
}
if (!process.env.TAURI_KEY_PASSWORD) {
throw new Error("TAURI_KEY_PASSWORD is required");
}
const { version } = require("../package.json");
const cwd = process.cwd();
const bundlePath = path.join(cwd, "src-tauri/target/release/bundle");
const join = (p) => path.join(bundlePath, p);
const appPathList = [
join("macos/Clash Verge.aarch64.app.tar.gz"),
join("macos/Clash Verge.aarch64.app.tar.gz.sig"),
];
for (const appPath of appPathList) {
if (fs.pathExistsSync(appPath)) {
fs.removeSync(appPath);
}
}
fs.copyFileSync(join("macos/Clash Verge.app.tar.gz"), appPathList[0]);
fs.copyFileSync(join("macos/Clash Verge.app.tar.gz.sig"), appPathList[1]);
const options = { owner: context.repo.owner, repo: context.repo.repo };
const github = getOctokit(process.env.GITHUB_TOKEN);
const { data: release } = await github.rest.repos.getReleaseByTag({
...options,
tag: `v${version}`,
});
if (!release.id) throw new Error("failed to find the release");
await uploadAssets(release.id, [
join(`dmg/Clash Verge_${version}_aarch64.dmg`),
...appPathList,
]);
}
// From tauri-apps/tauri-action
// https://github.com/tauri-apps/tauri-action/blob/dev/packages/action/src/upload-release-assets.ts
async function uploadAssets(releaseId, assets) {
const github = getOctokit(process.env.GITHUB_TOKEN);
// Determine content-length for header to upload asset
const contentLength = (filePath) => fs.statSync(filePath).size;
for (const assetPath of assets) {
const headers = {
"content-type": "application/zip",
"content-length": contentLength(assetPath),
};
const ext = path.extname(assetPath);
const filename = path.basename(assetPath).replace(ext, "");
const assetName = path.dirname(assetPath).includes(`target${path.sep}debug`)
? `${filename}-debug${ext}`
: `${filename}${ext}`;
console.log(`[INFO]: Uploading ${assetName}...`);
try {
await github.rest.repos.uploadReleaseAsset({
headers,
name: assetName,
data: fs.readFileSync(assetPath),
owner: context.repo.owner,
repo: context.repo.repo,
release_id: releaseId,
});
} catch (error) {
console.log(error.message);
}
}
}
if (process.platform === "darwin" && process.arch === "arm64") {
resolve();
} else {
console.error("invalid");
exit(1);
}
+222 -39
View File
@@ -3,13 +3,14 @@ import zlib from "zlib";
import path from "path";
import AdmZip from "adm-zip";
import fetch from "node-fetch";
import proxyAgent from "https-proxy-agent";
import { execSync } from "child_process";
const cwd = process.cwd();
const TEMP_DIR = path.join(cwd, "node_modules/.verge");
const CLASH_URL_PREFIX =
"https://github.com/Dreamacro/clash/releases/download/premium/";
const CLASH_LATEST_DATE = "2022.01.27";
const FORCE = process.argv.includes("--force");
const NO_META = process.argv.includes("--no-meta") || false;
/**
* get the correct clash release infomation
@@ -17,11 +18,17 @@ const CLASH_LATEST_DATE = "2022.01.27";
function resolveClash() {
const { platform, arch } = process;
const CLASH_URL_PREFIX =
"https://github.com/Dreamacro/clash/releases/download/premium/";
const CLASH_LATEST_DATE = "2022.08.26";
// todo
const map = {
"win32-x64": "clash-windows-386",
"win32-x64": "clash-windows-amd64",
"darwin-x64": "clash-darwin-amd64",
"darwin-arm64": "clash-darwin-arm64",
"linux-x64": "clash-linux-amd64",
"linux-arm64": "clash-linux-armv8",
};
const name = map[`${platform}-${arch}`];
@@ -39,54 +46,213 @@ function resolveClash() {
return { url, zip, exefile, zipfile };
}
/**
* get the correct Clash.Meta release infomation
*/
async function resolveClashMeta() {
const { platform, arch } = process;
const urlPrefix = `https://github.com/MetaCubeX/Clash.Meta/releases/download/`;
const latestVersion = "v1.13.1";
const map = {
"win32-x64": "Clash.Meta-windows-amd64",
"darwin-x64": "Clash.Meta-darwin-amd64",
"darwin-arm64": "Clash.Meta-darwin-arm64",
"linux-x64": "Clash.Meta-linux-amd64-compatible",
"linux-arm64": "Clash.Meta-linux-arm64",
};
const name = map[`${platform}-${arch}`];
if (!name) {
throw new Error(`unsupport platform "${platform}-${arch}"`);
}
const isWin = platform === "win32";
const ext = isWin ? "zip" : "gz";
const url = `${urlPrefix}${latestVersion}/${name}-${latestVersion}.${ext}`;
const exefile = `${name}${isWin ? ".exe" : ""}`;
const zipfile = `${name}-${latestVersion}.${ext}`;
return { url, zip: ext, exefile, zipfile };
}
/**
* get the sidecar bin
* clash and Clash Meta
*/
async function resolveSidecar() {
const sidecarDir = path.join(cwd, "src-tauri", "sidecar");
const host = execSync("rustc -vV | grep host").toString().slice(6).trim();
const host = execSync("rustc -vV")
.toString()
.match(/(?<=host: ).+(?=\s*)/g)[0];
const ext = process.platform === "win32" ? ".exe" : "";
const sidecarFile = `clash-${host}${ext}`;
const sidecarPath = path.join(sidecarDir, sidecarFile);
await fs.mkdirp(sidecarDir);
if (await fs.pathExists(sidecarPath)) return;
await clash();
if (!NO_META) await clashMeta();
// 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);
async function clash() {
const sidecarFile = `clash-${host}${ext}`;
const sidecarPath = path.join(sidecarDir, sidecarFile);
await fs.mkdirp(tempDir);
if (!(await fs.pathExists(tempZip))) await downloadFile(binInfo.url, tempZip);
await fs.mkdirp(sidecarDir);
if (!FORCE && (await fs.pathExists(sidecarPath))) return;
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`);
// download sidecar
const binInfo = resolveClash();
const tempDir = path.join(TEMP_DIR, "clash");
const tempZip = path.join(tempDir, binInfo.zipfile);
const tempExe = path.join(tempDir, binInfo.exefile);
await fs.mkdirp(tempDir);
if (!(await fs.pathExists(tempZip)))
await downloadFile(binInfo.url, tempZip);
if (binInfo.zip === "zip") {
const zip = new AdmZip(tempZip);
zip.getEntries().forEach((entry) => {
console.log("[INFO]: entry name", entry.entryName);
});
zip.extractAllTo(tempDir, true);
// save as sidecar
await fs.rename(tempExe, sidecarPath);
console.log(`[INFO]: unzip finished`);
} else {
// gz
const readStream = fs.createReadStream(tempZip);
const writeStream = fs.createWriteStream(sidecarPath);
readStream
.pipe(zlib.createGunzip())
.pipe(writeStream)
.on("finish", () => {
console.log(`[INFO]: gunzip finished`);
execSync(`chmod 755 ${sidecarPath}`);
console.log(`[INFO]: chmod binary finished`);
})
.on("error", (error) => console.error(error));
}
// delete temp dir
await fs.remove(tempDir);
}
// delete temp dir
async function clashMeta() {
const sidecarFile = `clash-meta-${host}${ext}`;
const sidecarPath = path.join(sidecarDir, sidecarFile);
await fs.mkdirp(sidecarDir);
if (!FORCE && (await fs.pathExists(sidecarPath))) return;
// download sidecar
const binInfo = await resolveClashMeta();
const tempDir = path.join(TEMP_DIR, "clash-meta");
const tempZip = path.join(tempDir, binInfo.zipfile);
const tempExe = path.join(tempDir, binInfo.exefile);
await fs.mkdirp(tempDir);
if (!(await fs.pathExists(tempZip)))
await downloadFile(binInfo.url, tempZip);
if (binInfo.zip === "zip") {
const zip = new AdmZip(tempZip);
zip.getEntries().forEach((entry) => {
console.log("[INFO]: entry name", entry.entryName);
});
zip.extractAllTo(tempDir, true);
// save as sidecar
await fs.rename(tempExe, sidecarPath);
console.log(`[INFO]: unzip finished`);
} else {
// gz
const readStream = fs.createReadStream(tempZip);
const writeStream = fs.createWriteStream(sidecarPath);
readStream
.pipe(zlib.createGunzip())
.pipe(writeStream)
.on("finish", () => {
console.log(`[INFO]: gunzip finished`);
execSync(`chmod 755 ${sidecarPath}`);
console.log(`[INFO]: chmod binary finished`);
})
.on("error", (error) => console.error(error));
}
// delete temp dir
await fs.remove(tempDir);
}
}
/**
* only Windows
* get the wintun.dll (not required)
*/
async function resolveWintun() {
const { platform } = process;
if (platform !== "win32") return;
const url = "https://www.wintun.net/builds/wintun-0.14.1.zip";
const tempDir = path.join(TEMP_DIR, "wintun");
const tempZip = path.join(tempDir, "wintun.zip");
const wintunPath = path.join(tempDir, "wintun/bin/amd64/wintun.dll");
const targetPath = path.join(cwd, "src-tauri/resources", "wintun.dll");
if (!FORCE && (await fs.pathExists(targetPath))) return;
await fs.mkdirp(tempDir);
if (!(await fs.pathExists(tempZip))) {
await downloadFile(url, tempZip);
}
// unzip
const zip = new AdmZip(tempZip);
zip.extractAllTo(tempDir, true);
if (!(await fs.pathExists(wintunPath))) {
throw new Error(`path not found "${wintunPath}"`);
}
await fs.rename(wintunPath, targetPath);
await fs.remove(tempDir);
console.log(`[INFO]: resolve wintun.dll finished`);
}
/**
* only Windows
* get the clash-verge-service.exe
*/
async function resolveService() {
const { platform } = process;
if (platform !== "win32") return;
const resDir = path.join(cwd, "src-tauri/resources");
const repo =
"https://github.com/zzzgydi/clash-verge-service/releases/download/latest";
async function help(bin) {
const targetPath = path.join(resDir, bin);
if (!FORCE && (await fs.pathExists(targetPath))) return;
const url = `${repo}/${bin}`;
await downloadFile(url, targetPath);
}
await fs.mkdirp(resDir);
await help("clash-verge-service.exe");
await help("install-service.exe");
await help("uninstall-service.exe");
console.log(`[INFO]: resolve Service finished`);
}
/**
@@ -94,11 +260,13 @@ async function resolveSidecar() {
*/
async function resolveMmdb() {
const url =
"https://github.com/Dreamacro/maxmind-geoip/releases/latest/download/Country.mmdb";
"https://github.com/Dreamacro/maxmind-geoip/releases/download/20220812/Country.mmdb";
const resDir = path.join(cwd, "src-tauri", "resources");
const resPath = path.join(resDir, "Country.mmdb");
if (await fs.pathExists(resPath)) return;
if (!FORCE && (await fs.pathExists(resPath))) return;
await fs.mkdirp(resDir);
await downloadFile(url, resPath);
}
@@ -109,7 +277,20 @@ async function resolveMmdb() {
async function downloadFile(url, path) {
console.log(`[INFO]: downloading from "${url}"`);
const options = {};
const httpProxy =
process.env.HTTP_PROXY ||
process.env.http_proxy ||
process.env.HTTPS_PROXY ||
process.env.https_proxy;
if (httpProxy) {
options.agent = proxyAgent(httpProxy);
}
const response = await fetch(url, {
...options,
method: "GET",
headers: { "Content-Type": "application/octet-stream" },
});
@@ -121,4 +302,6 @@ async function downloadFile(url, path) {
/// main
resolveSidecar().catch(console.error);
resolveWintun().catch(console.error);
resolveMmdb().catch(console.error);
resolveService().catch(console.error);
+109
View File
@@ -0,0 +1,109 @@
import fs from "fs-extra";
import path from "path";
import AdmZip from "adm-zip";
import { createRequire } from "module";
import { getOctokit, context } from "@actions/github";
const META = process.argv.includes("--meta"); // use Clash.Meta
/// Script for ci
/// 打包绿色版/便携版 (only Windows)
async function resolvePortable() {
if (process.platform !== "win32") return;
const releaseDir = "./src-tauri/target/release";
if (!(await fs.pathExists(releaseDir))) {
throw new Error("could not found the release dir");
}
const zip = new AdmZip();
zip.addLocalFile(path.join(releaseDir, "Clash Verge.exe"));
zip.addLocalFile(path.join(releaseDir, "clash.exe"));
zip.addLocalFile(path.join(releaseDir, "clash-meta.exe"));
zip.addLocalFolder(path.join(releaseDir, "resources"), "resources");
const require = createRequire(import.meta.url);
const packageJson = require("../package.json");
const { version } = packageJson;
const zipFile = `Clash.Verge_${version}_x64_portable.zip`;
zip.writeZip(zipFile);
console.log("[INFO]: create portable zip successfully");
// push release assets
if (process.env.GITHUB_TOKEN === undefined) {
throw new Error("GITHUB_TOKEN is required");
}
const options = { owner: context.repo.owner, repo: context.repo.repo };
const github = getOctokit(process.env.GITHUB_TOKEN);
const { data: release } = await github.rest.repos.getReleaseByTag({
...options,
tag: `v${version}`,
});
console.log(release.name);
await github.rest.repos.uploadReleaseAsset({
...options,
release_id: release.id,
name: zipFile,
data: zip.toBuffer(),
});
}
/// 打包包含Clash.Meta的 (only Windows)
async function resolvePortableMeta() {
if (process.platform !== "win32") return;
const releaseDir = "./src-tauri/target/release";
if (!(await fs.pathExists(releaseDir))) {
throw new Error("could not found the release dir");
}
const zip = new AdmZip();
zip.addLocalFile(path.join(releaseDir, "Clash Verge.exe"));
zip.addLocalFile(path.join(releaseDir, "clash.exe"));
zip.addLocalFile(path.join(releaseDir, "clash-meta.exe"));
zip.addLocalFolder(path.join(releaseDir, "resources"), "resources");
const require = createRequire(import.meta.url);
const packageJson = require("../package.json");
const { version } = packageJson;
const zipFile = `Clash.Verge.Meta_${version}_x64_portable.zip`;
zip.writeZip(zipFile);
console.log("[INFO]: create portable zip successfully");
// push release assets
if (process.env.GITHUB_TOKEN === undefined) {
throw new Error("GITHUB_TOKEN is required");
}
const options = { owner: context.repo.owner, repo: context.repo.repo };
const github = getOctokit(process.env.GITHUB_TOKEN);
const { data: release } = await github.rest.repos.getReleaseByTag({
...options,
tag: `v${version}`,
});
console.log(release.name);
await github.rest.repos.uploadReleaseAsset({
...options,
release_id: release.id,
name: zipFile,
data: zip.toBuffer(),
});
}
if (META) resolvePortableMeta().catch(console.error);
else resolvePortable().catch(console.error);
+6
View File
@@ -1,9 +1,11 @@
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");
@@ -26,6 +28,10 @@ async function resolvePublish() {
packageJson.version = nextVersion;
tauriJson.package.version = nextVersion;
// 发布更新前先写更新日志
const nextTag = `v${nextVersion}`;
await resolveUpdateLog(nextTag);
await fs.writeFile(
"./package.json",
JSON.stringify(packageJson, undefined, 2)
-117
View File
@@ -1,117 +0,0 @@
import fetch from "node-fetch";
import { getOctokit, context } from "@actions/github";
const UPDATE_TAG_NAME = "updater";
const UPDATE_JSON_FILE = "update.json";
/// generate update.json
/// upload to update tag's release asset
async function resolveRelease() {
if (process.env.GITHUB_TOKEN === undefined) {
throw new Error("GITHUB_TOKEN is required");
}
const options = { owner: context.repo.owner, repo: context.repo.repo };
const github = getOctokit(process.env.GITHUB_TOKEN);
const { data: tags } = await github.rest.repos.listTags({
...options,
per_page: 10,
page: 1,
});
// get the latest publish tag
const tag = tags.find((t) => t.name.startsWith("v"));
console.log(tag);
console.log();
const { data: latestRelease } = await github.rest.repos.getReleaseByTag({
...options,
tag: tag.name,
});
const updateData = {
name: tag.name,
notes: latestRelease.body, // use the release body directly
pub_date: new Date().toISOString(),
platforms: {
win64: { signature: "", url: "" },
darwin: { signature: "", url: "" },
},
};
const promises = latestRelease.assets.map(async (asset) => {
const { name, browser_download_url } = asset;
// win64 url
if (/\.msi\.zip$/.test(name)) {
updateData.platforms.win64.url = browser_download_url;
}
// darwin url
if (/\.app\.tar\.gz$/.test(name)) {
updateData.platforms.darwin.url = browser_download_url;
}
// win64 signature
if (/\.msi\.zip\.sig$/.test(name)) {
updateData.platforms.win64.signature = await getSignature(
browser_download_url
);
}
// darwin signature
if (/\.app\.tar\.gz\.sig$/.test(name)) {
updateData.platforms.darwin.signature = await getSignature(
browser_download_url
);
}
});
await Promise.allSettled(promises);
console.log(updateData);
// maybe should test the signature as well
const { darwin, win64 } = updateData.platforms;
if (!darwin.url) {
console.log(`[Error]: failed to parse release for darwin`);
delete updateData.platforms.darwin;
}
if (!win64.url) {
console.log(`[Error]: failed to parse release for win64`);
delete updateData.platforms.win64;
}
// update the update.json
const { data: updateRelease } = await github.rest.repos.getReleaseByTag({
...options,
tag: UPDATE_TAG_NAME,
});
for (let asset of updateRelease.assets) {
if (asset.name === UPDATE_JSON_FILE) {
await github.rest.repos.deleteReleaseAsset({
...options,
asset_id: asset.id,
});
break;
}
}
await github.rest.repos.uploadReleaseAsset({
...options,
release_id: updateRelease.id,
name: UPDATE_JSON_FILE,
data: JSON.stringify(updateData, null, 2),
});
}
// get the signature file content
async function getSignature(url) {
const response = await fetch(url, {
method: "GET",
headers: { "Content-Type": "application/octet-stream" },
});
return response.text();
}
resolveRelease().catch(console.error);
+44
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
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") && name.includes("en-US")) {
updateData.platforms.win64.url = browser_download_url;
updateData.platforms["windows-x86_64"].url = browser_download_url;
}
// win64 signature
if (name.endsWith(".msi.zip.sig") && name.includes("en-US")) {
const sig = await getSignature(browser_download_url);
updateData.platforms.win64.signature = sig;
updateData.platforms["windows-x86_64"].signature = sig;
}
// darwin url (intel)
if (name.endsWith(".app.tar.gz") && !name.includes("aarch")) {
updateData.platforms.darwin.url = browser_download_url;
updateData.platforms["darwin-intel"].url = browser_download_url;
}
// darwin signature (intel)
if (name.endsWith(".app.tar.gz.sig") && !name.includes("aarch")) {
const sig = await getSignature(browser_download_url);
updateData.platforms.darwin.signature = sig;
updateData.platforms["darwin-intel"].signature = sig;
}
// darwin url (aarch)
if (name.endsWith("aarch64.app.tar.gz")) {
updateData.platforms["darwin-aarch64"].url = browser_download_url;
}
// darwin signature (aarch)
if (name.endsWith("aarch64.app.tar.gz.sig")) {
const sig = await getSignature(browser_download_url);
updateData.platforms["darwin-aarch64"].signature = sig;
}
// linux url
if (name.endsWith(".AppImage.tar.gz")) {
updateData.platforms.linux.url = browser_download_url;
updateData.platforms["linux-x86_64"].url = browser_download_url;
}
// linux signature
if (name.endsWith(".AppImage.tar.gz.sig")) {
const sig = await getSignature(browser_download_url);
updateData.platforms.linux.signature = sig;
updateData.platforms["linux-x86_64"].signature = sig;
}
});
await Promise.allSettled(promises);
console.log(updateData);
// maybe should test the signature as well
// delete the null field
Object.entries(updateData.platforms).forEach(([key, value]) => {
if (!value.url) {
console.log(`[Error]: failed to parse release for "${key}"`);
delete updateData.platforms[key];
}
});
// 生成一个代理github的更新文件
// 使用 https://hub.fastgit.xyz/ 做github资源的加速
const updateDataNew = JSON.parse(JSON.stringify(updateData));
Object.entries(updateDataNew.platforms).forEach(([key, value]) => {
if (value.url) {
updateDataNew.platforms[key].url = value.url.replace(
"https://github.com/",
"https://hub.fastgit.xyz/"
);
} else {
console.log(`[Error]: updateDataNew.platforms.${key} is null`);
}
});
// update the update.json
const { data: updateRelease } = await github.rest.repos.getReleaseByTag({
...options,
tag: UPDATE_TAG_NAME,
});
// delete the old assets
for (let asset of updateRelease.assets) {
if (asset.name === UPDATE_JSON_FILE) {
await github.rest.repos.deleteReleaseAsset({
...options,
asset_id: asset.id,
});
}
if (asset.name === UPDATE_JSON_PROXY) {
await github.rest.repos
.deleteReleaseAsset({ ...options, asset_id: asset.id })
.catch(console.error); // do not break the pipeline
}
}
// upload new assets
await github.rest.repos.uploadReleaseAsset({
...options,
release_id: updateRelease.id,
name: UPDATE_JSON_FILE,
data: JSON.stringify(updateData, null, 2),
});
await github.rest.repos.uploadReleaseAsset({
...options,
release_id: updateRelease.id,
name: UPDATE_JSON_PROXY,
data: JSON.stringify(updateDataNew, null, 2),
});
}
// get the signature file content
async function getSignature(url) {
const response = await fetch(url, {
method: "GET",
headers: { "Content-Type": "application/octet-stream" },
});
return response.text();
}
resolveUpdater().catch(console.error);
+1 -1
View File
@@ -2,5 +2,5 @@
# will have compiled files and executables
/target/
WixTools
resources/Country.mmdb
resources
sidecar
+1700 -1255
View File
File diff suppressed because it is too large Load Diff
+38 -20
View File
@@ -10,33 +10,51 @@ edition = "2021"
build = "build.rs"
[build-dependencies]
tauri-build = { version = "1.0.0-rc.3", features = [] }
tauri-build = { version = "1", features = [] }
[dependencies]
anyhow = "1.0"
dirs = "4.0.0"
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-rc.3", features = ["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"
anyhow = "1.0"
dirs = "4.0.0"
open = "3.0.3"
log = "0.4.14"
ctrlc = "3.2.3"
dunce = "1.0.2"
log4rs = "1.0.0"
nanoid = "0.4.0"
chrono = "0.4.19"
sysinfo = "0.26.2"
sysproxy = "0.1"
serde_json = "1.0"
serde_yaml = "0.9"
auto-launch = "0.4"
once_cell = "1.14.0"
port_scanner = "0.1.5"
delay_timer = "0.11.1"
parking_lot = "0.12.0"
tokio = { version = "1", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
reqwest = { version = "0.11", features = ["json"] }
tauri = { version = "1.1.1", features = ["global-shortcut-all", "process-all", "shell-all", "system-tray", "updater", "window-all"] }
rquickjs = { version = "0.1.7" }
window-shadows = { version = "0.2.0" }
window-vibrancy = { version = "0.3.0" }
[target.'cfg(windows)'.dependencies]
runas = "0.2.1"
deelevate = "0.2.0"
winreg = { version = "0.10", features = ["transactions"] }
windows-sys = { version = "0.36", features = ["Win32_System_LibraryLoader", "Win32_System_SystemInformation"] }
[features]
default = [ "custom-protocol" ]
custom-protocol = [ "tauri/custom-protocol" ]
default = ["custom-protocol"]
custom-protocol = ["tauri/custom-protocol"]
verge-dev = []
debug-yml = []
[profile.release]
panic = "abort"
codegen-units = 1
lto = true
opt-level = "s"
Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

+242 -216
View File
@@ -1,39 +1,39 @@
use crate::{
core::{ClashInfo, PrfItem, Profiles, VergeConfig},
states::{ClashState, ProfilesState, VergeState},
utils::{dirs, sysopt::SysProxyConfig},
core::Core,
data::{ClashInfo, Data, PrfItem, PrfOption, Profiles, Verge},
utils::{dirs, help},
};
use crate::{ret_err, wrap_err};
use crate::{log_if_err, ret_err, wrap_err};
use anyhow::Result;
use serde_yaml::Mapping;
use std::{path::PathBuf, process::Command};
use tauri::{api, Manager, State};
use std::collections::{HashMap, VecDeque};
use sysproxy::Sysproxy;
type CmdResult<T = ()> = Result<T, String>;
/// 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();
pub fn get_profiles() -> CmdResult<Profiles> {
let global = Data::global();
let profiles = global.profiles.lock();
Ok(profiles.clone())
}
/// synchronize data irregularly
/// manually exec enhanced profile
#[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())
pub fn enhance_profiles() -> CmdResult {
let core = Core::global();
wrap_err!(core.activate())
}
/// import the profile from url
/// and save to `profiles.yaml`
#[tauri::command]
pub async fn import_profile(
url: String,
with_proxy: bool,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let item = wrap_err!(PrfItem::from_url(&url, None, None, with_proxy).await)?;
pub async fn import_profile(url: String, option: Option<PrfOption>) -> CmdResult {
let item = wrap_err!(PrfItem::from_url(&url, None, None, option).await)?;
let mut profiles = profiles_state.0.lock().unwrap();
let global = Data::global();
let mut profiles = global.profiles.lock();
wrap_err!(profiles.append_item(item))
}
@@ -41,295 +41,321 @@ pub async fn import_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
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let item = wrap_err!(PrfItem::from(item).await)?;
let mut profiles = profiles_state.0.lock().unwrap();
pub async fn create_profile(item: PrfItem, file_data: Option<String>) -> CmdResult {
let item = wrap_err!(PrfItem::from(item, file_data).await)?;
let global = Data::global();
let mut profiles = global.profiles.lock();
wrap_err!(profiles.append_item(item))
}
/// Update the profile
#[tauri::command]
pub async fn update_profile(
index: String,
with_proxy: bool,
clash_state: State<'_, ClashState>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let url = {
// must release the lock here
let profiles = profiles_state.0.lock().unwrap();
let item = wrap_err!(profiles.get_item(&index))?;
if item.url.is_none() {
ret_err!("failed to get the item url");
}
item.url.clone().unwrap()
};
let item = wrap_err!(PrfItem::from_url(&url, None, None, with_proxy).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(&profiles, false))?;
}
Ok(())
pub async fn update_profile(index: String, option: Option<PrfOption>) -> CmdResult {
let core = Core::global();
wrap_err!(core.update_profile_item(index, option).await)
}
/// 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();
pub fn select_profile(index: String) -> CmdResult {
let global = Data::global();
let mut profiles = global.profiles.lock();
wrap_err!(profiles.put_current(index))?;
drop(profiles);
let clash = clash_state.0.lock().unwrap();
wrap_err!(clash.activate(&profiles, false))
let core = Core::global();
wrap_err!(core.activate())
}
/// 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();
pub fn change_profile_chain(chain: Option<Vec<String>>) -> CmdResult {
let global = Data::global();
let mut profiles = global.profiles.lock();
wrap_err!(profiles.put_chain(chain))?;
drop(profiles);
profiles.put_chain(chain);
clash.set_window(app_handle.get_window("main"));
wrap_err!(clash.activate_enhanced(&profiles, false))
let core = Core::global();
wrap_err!(core.activate())
}
/// manually exec enhanced profile
/// change the profile valid fields
#[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();
pub fn change_profile_valid(valid: Option<Vec<String>>) -> CmdResult {
let global = Data::global();
let mut profiles = global.profiles.lock();
wrap_err!(profiles.put_valid(valid))?;
drop(profiles);
clash.set_window(app_handle.get_window("main"));
wrap_err!(clash.activate_enhanced(&profiles, false))
let core = Core::global();
wrap_err!(core.activate())
}
/// 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();
pub fn delete_profile(index: String) -> CmdResult {
let global = Data::global();
let mut profiles = global.profiles.lock();
if wrap_err!(profiles.delete_item(index))? {
let clash = clash_state.0.lock().unwrap();
wrap_err!(clash.activate(&profiles, false))?;
}
drop(profiles);
let core = Core::global();
log_if_err!(core.activate());
}
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))
pub fn patch_profile(index: String, profile: PrfItem) -> CmdResult {
let global = Data::global();
let mut profiles = global.profiles.lock();
wrap_err!(profiles.patch_item(index, profile))?;
drop(profiles);
// update cron task
let core = Core::global();
let mut timer = core.timer.lock();
wrap_err!(timer.refresh())
}
/// run vscode command to edit the profile
#[tauri::command]
pub fn view_profile(index: String, profiles_state: State<'_, ProfilesState>) -> Result<(), String> {
let profiles = profiles_state.0.lock().unwrap();
pub fn view_profile(index: String) -> CmdResult {
let global = Data::global();
let profiles = global.profiles.lock();
let item = wrap_err!(profiles.get_item(&index))?;
let file = item.file.clone();
if file.is_none() {
ret_err!("the file is null");
ret_err!("file is null");
}
let path = dirs::app_profiles_dir().join(file.unwrap());
if !path.exists() {
ret_err!("the file not found");
ret_err!("file not found");
}
// use vscode first
if let Ok(code) = which::which("code") {
#[cfg(target_os = "windows")]
{
use std::os::windows::process::CommandExt;
return match Command::new(code)
.creation_flags(0x08000000)
.arg(path)
.spawn()
{
Ok(_) => Ok(()),
Err(_) => Err("failed to open file by VScode".into()),
};
}
#[cfg(not(target_os = "windows"))]
return match Command::new(code).arg(path).spawn() {
Ok(_) => Ok(()),
Err(_) => Err("failed to open file by VScode".into()),
};
}
open_path_cmd(path, "failed to open file by `open`")
wrap_err!(help::open_file(path))
}
/// restart the sidecar
/// read the profile item file data
#[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();
pub fn read_profile_file(index: String) -> CmdResult<String> {
let global = Data::global();
let profiles = global.profiles.lock();
let item = wrap_err!(profiles.get_item(&index))?;
let data = wrap_err!(item.read_file())?;
Ok(data)
}
wrap_err!(clash.restart_sidecar(&mut profiles))
/// save the profile item file data
#[tauri::command]
pub fn save_profile_file(index: String, file_data: Option<String>) -> CmdResult {
if file_data.is_none() {
return Ok(());
}
let global = Data::global();
let profiles = global.profiles.lock();
let item = wrap_err!(profiles.get_item(&index))?;
wrap_err!(item.save_file(file_data.unwrap()))
}
/// get the clash core info from the state
/// the caller can also get the infomation by clash's api
#[tauri::command]
pub fn get_clash_info(clash_state: State<'_, ClashState>) -> Result<ClashInfo, String> {
let clash = clash_state.0.lock().unwrap();
pub fn get_clash_info() -> CmdResult<ClashInfo> {
let global = Data::global();
let clash = global.clash.lock();
Ok(clash.info.clone())
}
/// get the runtime clash config mapping
#[tauri::command]
pub fn get_runtime_config() -> CmdResult<Option<Mapping>> {
let core = Core::global();
let rt = core.runtime.lock();
Ok(rt.config.clone())
}
/// get the runtime clash config yaml string
#[tauri::command]
pub fn get_runtime_yaml() -> CmdResult<Option<String>> {
let core = Core::global();
let rt = core.runtime.lock();
Ok(rt.config_yaml.clone())
}
/// get the runtime config exists keys
#[tauri::command]
pub fn get_runtime_exists() -> CmdResult<Vec<String>> {
let core = Core::global();
let rt = core.runtime.lock();
Ok(rt.exists_keys.clone())
}
/// get the runtime enhanced chain log
#[tauri::command]
pub fn get_runtime_logs() -> CmdResult<HashMap<String, Vec<(String, String)>>> {
let core = Core::global();
let rt = core.runtime.lock();
Ok(rt.chain_logs.clone())
}
/// update the clash core config
/// after putting the change to the clash core
/// then we should save the latest config
#[tauri::command]
pub fn patch_clash_config(
payload: Mapping,
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))
pub fn patch_clash_config(payload: Mapping) -> CmdResult {
let core = Core::global();
wrap_err!(core.patch_clash(payload))
}
/// 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)
pub fn get_verge_config() -> CmdResult<Verge> {
let global = Data::global();
let verge = global.verge.lock();
Ok(verge.clone())
}
/// patch the verge config
/// this command only save the config and not responsible for other things
#[tauri::command]
pub fn patch_verge_config(
payload: VergeConfig,
clash_state: State<'_, ClashState>,
verge_state: State<'_, VergeState>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let tun_mode = payload.enable_tun_mode.clone();
pub fn patch_verge_config(payload: Verge) -> CmdResult {
let core = Core::global();
wrap_err!(core.patch_verge(payload))
}
let mut verge = verge_state.0.lock().unwrap();
wrap_err!(verge.patch_config(payload))?;
#[tauri::command]
pub fn update_hotkeys(hotkeys: Vec<String>) -> CmdResult {
let core = Core::global();
let mut hotkey = core.hotkey.lock();
wrap_err!(hotkey.update(hotkeys))
}
// change tun mode
if tun_mode.is_some() {
let mut clash = clash_state.0.lock().unwrap();
let profiles = profiles_state.0.lock().unwrap();
/// change clash core
#[tauri::command]
pub fn change_clash_core(clash_core: Option<String>) -> CmdResult {
let core = Core::global();
wrap_err!(core.change_core(clash_core))
}
wrap_err!(clash.tun_mode(tun_mode.unwrap()))?;
clash.update_config();
wrap_err!(clash.activate(&profiles, false))?;
}
Ok(())
/// restart the sidecar
#[tauri::command]
pub fn restart_sidecar() -> CmdResult {
let core = Core::global();
wrap_err!(core.restart_clash())
}
/// kill all sidecars when update app
#[tauri::command]
pub fn kill_sidecars() {
api::process::kill_children();
pub fn kill_sidecar() {
tauri::api::process::kill_children();
}
/// get the system proxy
#[tauri::command]
pub fn get_sys_proxy() -> CmdResult<Mapping> {
let current = wrap_err!(Sysproxy::get_system_proxy())?;
let mut map = Mapping::new();
map.insert("enable".into(), current.enable.into());
map.insert(
"server".into(),
format!("{}:{}", current.host, current.port).into(),
);
map.insert("bypass".into(), current.bypass.into());
Ok(map)
}
#[tauri::command]
pub fn get_clash_logs() -> CmdResult<VecDeque<String>> {
let core = Core::global();
let service = core.service.lock();
Ok(service.get_logs())
}
/// open app config dir
#[tauri::command]
pub fn open_app_dir() -> Result<(), String> {
pub fn open_app_dir() -> CmdResult<()> {
let app_dir = dirs::app_home_dir();
open_path_cmd(app_dir, "failed to open app dir")
wrap_err!(open::that(app_dir))
}
/// open logs dir
#[tauri::command]
pub fn open_logs_dir() -> Result<(), String> {
pub fn open_logs_dir() -> CmdResult<()> {
let log_dir = dirs::app_logs_dir();
open_path_cmd(log_dir, "failed to open logs dir")
wrap_err!(open::that(log_dir))
}
/// get open/explorer command
fn open_path_cmd(dir: PathBuf, err_str: &str) -> Result<(), String> {
#[cfg(target_os = "windows")]
{
use std::os::windows::process::CommandExt;
/// open url
#[tauri::command]
pub fn open_web_url(url: String) -> CmdResult<()> {
wrap_err!(open::that(url))
}
match Command::new("explorer")
.creation_flags(0x08000000)
.arg(dir)
.spawn()
{
Ok(_) => Ok(()),
Err(_) => Err(err_str.into()),
/// service mode
#[cfg(windows)]
pub mod service {
use super::*;
use crate::core::win_service::JsonResponse;
#[tauri::command]
pub async fn start_service() -> CmdResult<()> {
wrap_err!(crate::core::Service::start_service().await)
}
#[tauri::command]
pub async fn stop_service() -> CmdResult<()> {
wrap_err!(crate::core::Service::stop_service().await)
}
#[tauri::command]
pub async fn check_service() -> CmdResult<JsonResponse> {
// no log
match crate::core::Service::check_service().await {
Ok(res) => Ok(res),
Err(err) => Err(err.to_string()),
}
}
#[cfg(not(target_os = "windows"))]
match Command::new("open").arg(dir).spawn() {
Ok(_) => Ok(()),
Err(_) => Err(err_str.into()),
#[tauri::command]
pub async fn install_service() -> CmdResult<()> {
wrap_err!(crate::core::Service::install_service().await)
}
#[tauri::command]
pub async fn uninstall_service() -> CmdResult<()> {
wrap_err!(crate::core::Service::uninstall_service().await)
}
}
#[cfg(not(windows))]
pub mod service {
use super::*;
#[tauri::command]
pub async fn start_service() -> CmdResult<()> {
Ok(())
}
#[tauri::command]
pub async fn stop_service() -> CmdResult<()> {
Ok(())
}
#[tauri::command]
pub async fn check_service() -> CmdResult<()> {
Ok(())
}
#[tauri::command]
pub async fn install_service() -> CmdResult<()> {
Ok(())
}
#[tauri::command]
pub async fn uninstall_service() -> CmdResult<()> {
Ok(())
}
}
+118
View File
@@ -0,0 +1,118 @@
use serde_yaml::{Mapping, Value};
pub const HANDLE_FIELDS: [&str; 9] = [
"port",
"socks-port",
"mixed-port",
"mode",
"ipv6",
"log-level",
"allow-lan",
"external-controller",
"secret",
];
pub const DEFAULT_FIELDS: [&str; 5] = [
"proxies",
"proxy-groups",
"rules",
"proxy-providers",
"rule-providers",
];
pub const OTHERS_FIELDS: [&str; 20] = [
"tun",
"dns",
"ebpf",
"hosts",
"script",
"profile",
"payload",
"auto-redir",
"experimental",
"interface-name",
"routing-mark",
"redir-port",
"tproxy-port",
"iptables",
"external-ui",
"bind-address",
"authentication",
"sniffer", // meta
"geodata-mode", // meta
"tcp-concurrent", // meta
];
pub fn use_clash_fields() -> Vec<String> {
DEFAULT_FIELDS
.into_iter()
.chain(HANDLE_FIELDS)
.chain(OTHERS_FIELDS)
.map(|s| s.to_string())
.collect()
}
pub fn use_valid_fields(mut valid: Vec<String>) -> Vec<String> {
let others = Vec::from(OTHERS_FIELDS);
valid.iter_mut().for_each(|s| s.make_ascii_lowercase());
valid
.into_iter()
.filter(|s| others.contains(&s.as_str()))
.chain(DEFAULT_FIELDS.iter().map(|s| s.to_string()))
.collect()
}
pub fn use_filter(config: Mapping, filter: &Vec<String>) -> Mapping {
let mut ret = Mapping::new();
for (key, value) in config.into_iter() {
if let Some(key) = key.as_str() {
if filter.contains(&key.to_string()) {
ret.insert(Value::from(key), value);
}
}
}
ret
}
pub fn use_lowercase(config: Mapping) -> Mapping {
let mut ret = Mapping::new();
for (key, value) in config.into_iter() {
if let Some(key_str) = key.as_str() {
let mut key_str = String::from(key_str);
key_str.make_ascii_lowercase();
ret.insert(Value::from(key_str), value);
}
}
ret
}
pub fn use_sort(config: Mapping) -> Mapping {
let mut ret = Mapping::new();
HANDLE_FIELDS
.into_iter()
.chain(OTHERS_FIELDS)
.chain(DEFAULT_FIELDS)
.for_each(|key| {
let key = Value::from(key);
config.get(&key).map(|value| {
ret.insert(key, value.clone());
});
});
ret
}
pub fn use_keys(config: &Mapping) -> Vec<String> {
config
.iter()
.filter_map(|(key, _)| key.as_str())
.map(|s| {
let mut s = s.to_string();
s.make_ascii_lowercase();
return s;
})
.collect()
}
+93
View File
@@ -0,0 +1,93 @@
use super::{use_filter, use_lowercase};
use serde_yaml::{self, Mapping, Sequence, Value};
#[allow(unused)]
const MERGE_FIELDS: [&str; 6] = [
"prepend-rules",
"append-rules",
"prepend-proxies",
"append-proxies",
"prepend-proxy-groups",
"append-proxy-groups",
];
pub fn use_merge(merge: Mapping, mut config: Mapping) -> Mapping {
// 直接覆盖原字段
use_lowercase(merge.clone())
.into_iter()
.for_each(|(key, value)| {
config.insert(key, value);
});
let merge_list = MERGE_FIELDS.iter().map(|s| s.to_string());
let merge = use_filter(merge, &merge_list.collect());
["rules", "proxies", "proxy-groups"]
.iter()
.for_each(|key_str| {
let key_val = Value::from(key_str.to_string());
let mut list = Sequence::default();
list = config.get(&key_val).map_or(list.clone(), |val| {
val.as_sequence().map_or(list, |v| v.clone())
});
let pre_key = Value::from(format!("prepend-{key_str}"));
let post_key = Value::from(format!("append-{key_str}"));
if let Some(pre_val) = merge.get(&pre_key) {
if pre_val.is_sequence() {
let mut pre_val = pre_val.as_sequence().unwrap().clone();
pre_val.extend(list);
list = pre_val;
}
}
if let Some(post_val) = merge.get(&post_key) {
if post_val.is_sequence() {
list.extend(post_val.as_sequence().unwrap().clone());
}
}
config.insert(key_val, Value::from(list));
});
config
}
#[test]
fn test_merge() -> anyhow::Result<()> {
let merge = r"
prepend-rules:
- prepend
- 1123123
append-rules:
- append
prepend-proxies:
- 9999
append-proxies:
- 1111
rules:
- replace
proxy-groups:
- 123781923810
tun:
enable: true
dns:
enable: true
";
let config = r"
rules:
- aaaaa
script1: test
";
let merge = serde_yaml::from_str::<Mapping>(merge)?;
let config = serde_yaml::from_str::<Mapping>(config)?;
let result = serde_yaml::to_string(&use_merge(merge, config))?;
println!("{result}");
Ok(())
}
+69
View File
@@ -0,0 +1,69 @@
mod field;
mod merge;
mod script;
mod tun;
pub(self) use self::field::*;
use self::merge::*;
use self::script::*;
use self::tun::*;
use crate::data::ChainItem;
use crate::data::ChainType;
use serde_yaml::Mapping;
use std::collections::HashMap;
use std::collections::HashSet;
type ResultLog = Vec<(String, String)>;
pub fn enhance_config(
clash_config: Mapping,
profile_config: Mapping,
chain: Vec<ChainItem>,
valid: Vec<String>,
tun_mode: bool,
) -> (Mapping, Vec<String>, HashMap<String, ResultLog>) {
let mut config = profile_config;
let mut result_map = HashMap::new();
let mut exists_keys = use_keys(&config);
let valid = use_valid_fields(valid);
chain.into_iter().for_each(|item| match item.data {
ChainType::Merge(merge) => {
exists_keys.extend(use_keys(&merge));
config = use_merge(merge, config.to_owned());
config = use_filter(config.to_owned(), &valid);
}
ChainType::Script(script) => {
let mut logs = vec![];
match use_script(script, config.to_owned()) {
Ok((res_config, res_logs)) => {
exists_keys.extend(use_keys(&res_config));
config = use_filter(res_config, &valid);
logs.extend(res_logs);
}
Err(err) => logs.push(("exception".into(), err.to_string())),
}
result_map.insert(item.uid, logs);
}
});
config = use_filter(config, &valid);
for (key, value) in clash_config.into_iter() {
config.insert(key, value);
}
let clash_fields = use_clash_fields();
config = use_filter(config, &clash_fields);
config = use_tun(config, tun_mode);
config = use_sort(config);
let mut exists_set = HashSet::new();
exists_set.extend(exists_keys.into_iter().filter(|s| clash_fields.contains(s)));
exists_keys = exists_set.into_iter().collect();
(config, exists_keys, result_map)
}
+94
View File
@@ -0,0 +1,94 @@
use super::use_lowercase;
use anyhow::Result;
use serde_yaml::Mapping;
pub fn use_script(script: String, config: Mapping) -> Result<(Mapping, Vec<(String, String)>)> {
use rquickjs::{Context, Func, Runtime};
use std::sync::{Arc, Mutex};
let runtime = Runtime::new().unwrap();
let context = Context::full(&runtime).unwrap();
let outputs = Arc::new(Mutex::new(vec![]));
let copy_outputs = outputs.clone();
let result = context.with(|ctx| -> Result<Mapping> {
ctx.globals().set(
"__verge_log__",
Func::from(move |level: String, data: String| {
let mut out = copy_outputs.lock().unwrap();
out.push((level, data));
}),
)?;
ctx.eval(
r#"var console = Object.freeze({
log(data){__verge_log__("log",JSON.stringify(data))},
info(data){__verge_log__("info",JSON.stringify(data))},
error(data){__verge_log__("error",JSON.stringify(data))},
debug(data){__verge_log__("debug",JSON.stringify(data))},
});"#,
)?;
let config = use_lowercase(config.clone());
let config_str = serde_json::to_string(&config)?;
let code = format!(
r#"try{{
{script};
JSON.stringify(main({config_str})||'')
}} catch(err) {{
`__error_flag__ ${{err.toString()}}`
}}"#
);
let result: String = ctx.eval(code.as_str())?;
if result.starts_with("__error_flag__") {
anyhow::bail!(result[15..].to_owned());
}
if result == "\"\"" {
anyhow::bail!("main function should return object");
}
return Ok(serde_json::from_str::<Mapping>(result.as_str())?);
});
let mut out = outputs.lock().unwrap();
match result {
Ok(config) => Ok((use_lowercase(config), out.to_vec())),
Err(err) => {
out.push(("exception".into(), err.to_string()));
Ok((config, out.to_vec()))
}
}
}
#[test]
fn test_script() {
let script = r#"
function main(config) {
if (Array.isArray(config.rules)) {
config.rules = [...config.rules, "add"];
}
console.log(config);
config.proxies = ["111"];
return config;
}
"#;
let config = r#"
rules:
- 111
- 222
tun:
enable: false
dns:
enable: false
"#;
let config = serde_yaml::from_str(config).unwrap();
let (config, results) = use_script(script.into(), config).unwrap();
let config_str = serde_yaml::to_string(&config).unwrap();
println!("{config_str}");
dbg!(results);
}
+81
View File
@@ -0,0 +1,81 @@
use serde_yaml::{Mapping, Value};
macro_rules! revise {
($map: expr, $key: expr, $val: expr) => {
let ret_key = Value::String($key.into());
$map.insert(ret_key, Value::from($val));
};
}
// if key not exists then append value
macro_rules! append {
($map: expr, $key: expr, $val: expr) => {
let ret_key = Value::String($key.into());
if !$map.contains_key(&ret_key) {
$map.insert(ret_key, Value::from($val));
}
};
}
pub fn use_tun(mut config: Mapping, enable: bool) -> Mapping {
let tun_key = Value::from("tun");
let tun_val = config.get(&tun_key);
if !enable && tun_val.is_none() {
return config;
}
let mut tun_val = tun_val.map_or(Mapping::new(), |val| {
val.as_mapping().cloned().unwrap_or(Mapping::new())
});
revise!(tun_val, "enable", enable);
if enable {
append!(tun_val, "stack", "gvisor");
append!(tun_val, "dns-hijack", vec!["198.18.0.2:53"]);
append!(tun_val, "auto-route", true);
append!(tun_val, "auto-detect-interface", true);
}
revise!(config, "tun", tun_val);
if enable {
use_dns_for_tun(config)
} else {
config
}
}
fn use_dns_for_tun(mut config: Mapping) -> Mapping {
let dns_key = Value::from("dns");
let dns_val = config.get(&dns_key);
let mut dns_val = dns_val.map_or(Mapping::new(), |val| {
val.as_mapping().cloned().unwrap_or(Mapping::new())
});
// 开启tun将同时开启dns
revise!(dns_val, "enable", true);
// 借鉴cfw的默认配置
append!(dns_val, "enhanced-mode", "fake-ip");
append!(
dns_val,
"nameserver",
vec!["114.114.114.114", "223.5.5.5", "8.8.8.8"]
);
append!(dns_val, "fallback", vec![] as Vec<&str>);
#[cfg(target_os = "windows")]
append!(
dns_val,
"fake-ip-filter",
vec![
"dns.msftncsi.com",
"www.msftncsi.com",
"www.msftconnecttest.com"
]
);
revise!(config, "dns", dns_val);
config
}
-374
View File
@@ -1,374 +0,0 @@
use super::{PrfEnhancedResult, Profiles, Verge};
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) => Some(val_str.clone()),
_ => 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, false)
}
/// 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<()> {
for (key, value) in patch.iter() {
let value = value.clone();
let key_str = key.as_str().clone().unwrap_or("");
// restart the clash
if key_str == "mixed-port" {
self.restart_sidecar(profiles)?;
let port = if value.is_number() {
match value.as_i64().clone() {
Some(num) => Some(format!("{num}")),
None => None,
}
} else {
match value.as_str().clone() {
Some(num) => Some(num.into()),
None => None,
}
};
verge.init_sysproxy(port);
}
self.config.insert(key.clone(), value);
}
self.save_config()
}
/// enable tun mode
/// only revise the config and restart the
pub fn tun_mode(&mut self, enable: bool) -> Result<()> {
let tun_key = Value::String("tun".into());
let tun_val = self.config.get(&tun_key);
let mut new_val = Mapping::new();
if tun_val.is_some() && tun_val.as_ref().unwrap().is_mapping() {
new_val = tun_val.as_ref().unwrap().as_mapping().unwrap().clone();
}
macro_rules! revise {
($map: expr, $key: expr, $val: expr) => {
let ret_key = Value::String($key.into());
if $map.contains_key(&ret_key) {
$map[&ret_key] = $val;
} else {
$map.insert(ret_key, $val);
}
};
}
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, $val);
}
};
}
revise!(new_val, "enable", Value::from(enable));
append!(new_val, "stack", Value::from("gvisor"));
append!(new_val, "auto-route", Value::from(true));
append!(new_val, "auto-detect-interface", Value::from(true));
revise!(self.config, "tun", Value::from(new_val));
self.save_config()
}
/// activate the profile
/// generate a new profile to the temp_dir
/// then put the path to the clash core
fn _activate(info: ClashInfo, config: Mapping) -> Result<()> {
let temp_path = dirs::profiles_temp_path();
config::save_yaml(temp_path.clone(), &config, Some("# Clash Verge Temp File"))?;
tauri::async_runtime::spawn(async move {
let server = info.server.unwrap();
let server = format!("http://{server}/configs");
let mut headers = HeaderMap::new();
headers.insert("Content-Type", "application/json".parse().unwrap());
if let Some(secret) = info.secret.as_ref() {
let secret = format!("Bearer {}", secret.clone()).parse().unwrap();
headers.insert("Authorization", secret);
}
let mut data = HashMap::new();
data.insert("path", temp_path.as_os_str().to_str().unwrap());
// retry 5 times
for _ in 0..5 {
match reqwest::ClientBuilder::new().no_proxy().build() {
Ok(client) => {
let builder = client.put(&server).headers(headers.clone()).json(&data);
match builder.send().await {
Ok(resp) => {
if resp.status() != 204 {
log::error!("failed to activate clash for status \"{}\"", resp.status());
}
// do not retry
break;
}
Err(err) => log::error!("failed to activate for `{err}`"),
}
}
Err(err) => log::error!("failed to activate for `{err}`"),
}
sleep(Duration::from_millis(500)).await;
}
});
Ok(())
}
/// enhanced profiles mode
/// only change the enhanced profiles
pub fn activate_enhanced(&self, profiles: &Profiles, delay: bool) -> Result<()> {
if self.window.is_none() {
bail!("failed to get the main window");
}
let win = self.window.clone().unwrap();
let event_name = help::get_uid("e");
let event_name = format!("enhanced-cb-{event_name}");
let info = self.info.clone();
let mut config = self.config.clone();
// generate the payload
let payload = profiles.gen_enhanced(event_name.clone())?;
win.once(&event_name, move |event| {
if let Some(result) = event.payload() {
let result: PrfEnhancedResult = serde_json::from_str(result).unwrap();
if let Some(data) = result.data {
for (key, value) in data.into_iter() {
config.insert(key, value);
}
Self::_activate(info, config).unwrap();
}
log::info!("profile enhanced status {}", result.status);
result.error.map(|error| log::error!("{error}"));
}
});
tauri::async_runtime::spawn(async move {
// wait the window setup during resolve app
if delay {
sleep(Duration::from_secs(2)).await;
}
win.emit("script-handler", payload).unwrap();
});
Ok(())
}
/// activate the profile
/// auto activate enhanced profile
pub fn activate(&self, profiles: &Profiles, delay: bool) -> Result<()> {
let gen_map = profiles.gen_activate()?;
let info = self.info.clone();
let mut config = self.config.clone();
for (key, value) in gen_map.into_iter() {
config.insert(key, value);
}
Self::_activate(info, config)?;
self.activate_enhanced(profiles, delay)
}
}
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}");
}
}
}
+107
View File
@@ -0,0 +1,107 @@
use crate::data::*;
use crate::log_if_err;
use anyhow::{bail, Result};
use serde_yaml::Value;
use tauri::{AppHandle, Manager, Window};
#[derive(Debug, Default, Clone)]
pub struct Handle {
pub app_handle: Option<AppHandle>,
}
impl Handle {
pub fn set_inner(&mut self, app_handle: AppHandle) {
self.app_handle = Some(app_handle);
}
pub fn get_window(&self) -> Option<Window> {
self
.app_handle
.as_ref()
.map_or(None, |a| a.get_window("main"))
}
pub fn refresh_clash(&self) {
if let Some(window) = self.get_window() {
log_if_err!(window.emit("verge://refresh-clash-config", "yes"));
}
}
pub fn refresh_verge(&self) {
if let Some(window) = self.get_window() {
log_if_err!(window.emit("verge://refresh-verge-config", "yes"));
}
}
#[allow(unused)]
pub fn refresh_profiles(&self) {
if let Some(window) = self.get_window() {
log_if_err!(window.emit("verge://refresh-profiles-config", "yes"));
}
}
pub fn notice_message(&self, status: String, msg: String) {
if let Some(window) = self.get_window() {
log_if_err!(window.emit("verge://notice-message", (status, msg)));
}
}
// update system tray state (clash config)
pub fn update_systray_clash(&self) -> Result<()> {
if self.app_handle.is_none() {
bail!("update_systray_clash unhandle error");
}
let app_handle = self.app_handle.as_ref().unwrap();
let global = Data::global();
let clash = global.clash.lock();
let mode = clash
.config
.get(&Value::from("mode"))
.map(|val| val.as_str().unwrap_or("rule"))
.unwrap_or("rule");
let tray = app_handle.tray_handle();
tray.get_item("rule_mode").set_selected(mode == "rule")?;
tray
.get_item("global_mode")
.set_selected(mode == "global")?;
tray
.get_item("direct_mode")
.set_selected(mode == "direct")?;
tray
.get_item("script_mode")
.set_selected(mode == "script")?;
Ok(())
}
/// update the system tray state (verge config)
pub fn update_systray(&self) -> Result<()> {
if self.app_handle.is_none() {
bail!("update_systray unhandle error");
}
let app_handle = self.app_handle.as_ref().unwrap();
let tray = app_handle.tray_handle();
let global = Data::global();
let verge = global.verge.lock();
let system_proxy = verge.enable_system_proxy.as_ref();
let tun_mode = verge.enable_tun_mode.as_ref();
tray
.get_item("system_proxy")
.set_selected(*system_proxy.unwrap_or(&false))?;
tray
.get_item("tun_mode")
.set_selected(*tun_mode.unwrap_or(&false))?;
// update verge config
self.refresh_verge();
Ok(())
}
}
+153
View File
@@ -0,0 +1,153 @@
use crate::{data::*, feat, log_if_err};
use anyhow::{bail, Result};
use std::collections::HashMap;
use tauri::{AppHandle, GlobalShortcutManager};
pub struct Hotkey {
current: Vec<String>, // 保存当前的热键设置
manager: Option<AppHandle>,
}
impl Hotkey {
pub fn new() -> Hotkey {
Hotkey {
current: Vec::new(),
manager: None,
}
}
pub fn init(&mut self, app_handle: AppHandle) -> Result<()> {
self.manager = Some(app_handle);
let data = Data::global();
let verge = data.verge.lock();
if let Some(hotkeys) = verge.hotkeys.as_ref() {
for hotkey in hotkeys.iter() {
let mut iter = hotkey.split(',');
let func = iter.next();
let key = iter.next();
if func.is_some() && key.is_some() {
log_if_err!(self.register(key.unwrap(), func.unwrap()));
} else {
log::error!(target: "app", "invalid hotkey \"{}\":\"{}\"", key.unwrap_or("None"), func.unwrap_or("None"));
}
}
self.current = hotkeys.clone();
}
Ok(())
}
fn get_manager(&self) -> Result<impl GlobalShortcutManager> {
if self.manager.is_none() {
bail!("failed to get hotkey manager");
}
Ok(self.manager.as_ref().unwrap().global_shortcut_manager())
}
fn register(&mut self, hotkey: &str, func: &str) -> Result<()> {
let mut manager = self.get_manager()?;
if manager.is_registered(hotkey)? {
manager.unregister(hotkey)?;
}
let f = match func.trim() {
"clash_mode_rule" => || feat::change_clash_mode("rule"),
"clash_mode_global" => || feat::change_clash_mode("global"),
"clash_mode_direct" => || feat::change_clash_mode("direct"),
"clash_mode_script" => || feat::change_clash_mode("script"),
"toggle_system_proxy" => || feat::toggle_system_proxy(),
"enable_system_proxy" => || feat::enable_system_proxy(),
"disable_system_proxy" => || feat::disable_system_proxy(),
"toggle_tun_mode" => || feat::toggle_tun_mode(),
"enable_tun_mode" => || feat::enable_tun_mode(),
"disable_tun_mode" => || feat::disable_tun_mode(),
_ => bail!("invalid function \"{func}\""),
};
manager.register(hotkey, f)?;
log::info!(target: "app", "register hotkey {hotkey} {func}");
Ok(())
}
fn unregister(&mut self, hotkey: &str) -> Result<()> {
self.get_manager()?.unregister(&hotkey)?;
log::info!(target: "app", "unregister hotkey {hotkey}");
Ok(())
}
pub fn update(&mut self, new_hotkeys: Vec<String>) -> Result<()> {
let current = self.current.to_owned();
let old_map = Self::get_map_from_vec(&current);
let new_map = Self::get_map_from_vec(&new_hotkeys);
let (del, add) = Self::get_diff(old_map, new_map);
del.iter().for_each(|key| {
let _ = self.unregister(key);
});
add.iter().for_each(|(key, func)| {
log_if_err!(self.register(key, func));
});
self.current = new_hotkeys;
Ok(())
}
fn get_map_from_vec<'a>(hotkeys: &'a Vec<String>) -> HashMap<&'a str, &'a str> {
let mut map = HashMap::new();
hotkeys.iter().for_each(|hotkey| {
let mut iter = hotkey.split(',');
let func = iter.next();
let key = iter.next();
if func.is_some() && key.is_some() {
let func = func.unwrap().trim();
let key = key.unwrap().trim();
map.insert(key, func);
}
});
map
}
fn get_diff<'a>(
old_map: HashMap<&'a str, &'a str>,
new_map: HashMap<&'a str, &'a str>,
) -> (Vec<&'a str>, Vec<(&'a str, &'a str)>) {
let mut del_list = vec![];
let mut add_list = vec![];
old_map.iter().for_each(|(&key, func)| {
match new_map.get(key) {
Some(new_func) => {
if new_func != func {
del_list.push(key);
add_list.push((key, *new_func));
}
}
None => del_list.push(key),
};
});
new_map.iter().for_each(|(&key, &func)| {
if old_map.get(key).is_none() {
add_list.push((key, func));
}
});
(del_list, add_list)
}
}
impl Drop for Hotkey {
fn drop(&mut self) {
if let Ok(mut manager) = self.get_manager() {
let _ = manager.unregister_all();
}
}
}
+340 -6
View File
@@ -1,7 +1,341 @@
mod clash;
mod profiles;
mod verge;
use self::handle::Handle;
use self::hotkey::Hotkey;
use self::sysopt::Sysopt;
use self::timer::Timer;
use crate::config::enhance_config;
use crate::data::*;
use crate::log_if_err;
use anyhow::{bail, Result};
use once_cell::sync::Lazy;
use parking_lot::Mutex;
use serde_yaml::{Mapping, Value};
use std::sync::Arc;
pub use self::clash::*;
pub use self::profiles::*;
pub use self::verge::*;
mod handle;
mod hotkey;
mod service;
mod sysopt;
mod timer;
pub use self::service::*;
static CORE: Lazy<Core> = Lazy::new(|| Core {
service: Arc::new(Mutex::new(Service::new())),
sysopt: Arc::new(Mutex::new(Sysopt::new())),
timer: Arc::new(Mutex::new(Timer::new())),
hotkey: Arc::new(Mutex::new(Hotkey::new())),
runtime: Arc::new(Mutex::new(RuntimeResult::default())),
handle: Arc::new(Mutex::new(Handle::default())),
});
#[derive(Clone)]
pub struct Core {
pub service: Arc<Mutex<Service>>,
pub sysopt: Arc<Mutex<Sysopt>>,
pub timer: Arc<Mutex<Timer>>,
pub hotkey: Arc<Mutex<Hotkey>>,
pub runtime: Arc<Mutex<RuntimeResult>>,
pub handle: Arc<Mutex<Handle>>,
}
impl Core {
pub fn global() -> Core {
CORE.clone()
}
/// initialize the core state
pub fn init(&self, app_handle: tauri::AppHandle) {
// kill old clash process
Service::kill_old_clash();
let mut handle = self.handle.lock();
handle.set_inner(app_handle.clone());
drop(handle);
let mut service = self.service.lock();
log_if_err!(service.start());
drop(service);
log_if_err!(self.activate());
let mut sysopt = self.sysopt.lock();
log_if_err!(sysopt.init_launch());
log_if_err!(sysopt.init_sysproxy());
drop(sysopt);
let handle = self.handle.lock();
log_if_err!(handle.update_systray());
log_if_err!(handle.update_systray_clash());
drop(handle);
let mut hotkey = self.hotkey.lock();
log_if_err!(hotkey.init(app_handle));
drop(hotkey);
// timer initialize
let mut timer = self.timer.lock();
log_if_err!(timer.restore());
}
/// restart the clash sidecar
pub fn restart_clash(&self) -> Result<()> {
let mut service = self.service.lock();
service.restart()?;
drop(service);
self.activate()
}
/// change the clash core
pub fn change_core(&self, clash_core: Option<String>) -> Result<()> {
let clash_core = clash_core.unwrap_or("clash".into());
if &clash_core != "clash" && &clash_core != "clash-meta" {
bail!("invalid clash core name \"{clash_core}\"");
}
let global = Data::global();
let mut verge = global.verge.lock();
verge.patch_config(Verge {
clash_core: Some(clash_core.clone()),
..Verge::default()
})?;
drop(verge);
let mut service = self.service.lock();
service.clear_logs();
service.restart()?;
drop(service);
self.activate()
}
/// Patch Clash
/// handle the clash config changed
pub fn patch_clash(&self, patch: Mapping) -> Result<()> {
let has_port = patch.contains_key(&Value::from("mixed-port"));
let has_mode = patch.contains_key(&Value::from("mode"));
let port = {
let global = Data::global();
let mut clash = global.clash.lock();
clash.patch_config(patch)?;
clash.info.port.clone()
};
// todo: port check
if has_port && port.is_some() {
let mut service = self.service.lock();
service.restart()?;
drop(service);
self.activate()?;
let mut sysopt = self.sysopt.lock();
sysopt.init_sysproxy()?;
}
if has_mode {
let handle = self.handle.lock();
handle.update_systray_clash()?;
}
Ok(())
}
/// Patch Verge
pub fn patch_verge(&self, patch: Verge) -> Result<()> {
// save the patch
let global = Data::global();
let mut verge = global.verge.lock();
verge.patch_config(patch.clone())?;
drop(verge);
let tun_mode = patch.enable_tun_mode;
let auto_launch = patch.enable_auto_launch;
let system_proxy = patch.enable_system_proxy;
let proxy_bypass = patch.system_proxy_bypass;
let proxy_guard = patch.enable_proxy_guard;
#[cfg(target_os = "windows")]
{
let service_mode = patch.enable_service_mode;
// 重启服务
if service_mode.is_some() {
let mut service = self.service.lock();
service.restart()?;
drop(service);
}
if tun_mode.is_some() && *tun_mode.as_ref().unwrap_or(&false) {
let wintun_dll = crate::utils::dirs::app_home_dir().join("wintun.dll");
if !wintun_dll.exists() {
bail!("failed to enable TUN for missing `wintun.dll`");
}
}
if service_mode.is_some() || tun_mode.is_some() {
self.activate()?;
}
}
#[cfg(not(target_os = "windows"))]
if tun_mode.is_some() {
self.activate()?;
}
let mut sysopt = self.sysopt.lock();
if auto_launch.is_some() {
sysopt.update_launch()?;
}
if system_proxy.is_some() || proxy_bypass.is_some() {
sysopt.update_sysproxy()?;
sysopt.guard_proxy();
}
if proxy_guard.unwrap_or(false) {
sysopt.guard_proxy();
}
if system_proxy.is_some() || tun_mode.is_some() {
let handle = self.handle.lock();
handle.update_systray()?;
}
if patch.hotkeys.is_some() {
let mut hotkey = self.hotkey.lock();
hotkey.update(patch.hotkeys.unwrap())?;
}
Ok(())
}
// update rule/global/direct/script mode
pub fn update_mode(&self, mode: &str) -> Result<()> {
// save config to file
let info = {
let global = Data::global();
let mut clash = global.clash.lock();
clash.config.insert(Value::from("mode"), Value::from(mode));
clash.save_config()?;
clash.info.clone()
};
let mut mapping = Mapping::new();
mapping.insert(Value::from("mode"), Value::from(mode));
let handle = self.handle.clone();
tauri::async_runtime::spawn(async move {
log_if_err!(Service::patch_config(info, mapping.to_owned()).await);
// update tray
let handle = handle.lock();
handle.refresh_clash();
log_if_err!(handle.update_systray_clash());
});
Ok(())
}
/// activate the profile
/// auto activate enhanced profile
/// 触发clash配置更新
pub fn activate(&self) -> Result<()> {
let global = Data::global();
let verge = global.verge.lock();
let clash = global.clash.lock();
let profiles = global.profiles.lock();
let tun_mode = verge.enable_tun_mode.clone().unwrap_or(false);
let profile_activate = profiles.gen_activate()?;
let clash_config = clash.config.clone();
let clash_info = clash.info.clone();
drop(clash);
drop(verge);
drop(profiles);
let (config, exists_keys, logs) = enhance_config(
clash_config,
profile_activate.current,
profile_activate.chain,
profile_activate.valid,
tun_mode,
);
let mut runtime = self.runtime.lock();
*runtime = RuntimeResult {
config: Some(config.clone()),
config_yaml: Some(serde_yaml::to_string(&config).unwrap_or("".into())),
exists_keys,
chain_logs: logs,
};
drop(runtime);
let mut service = self.service.lock();
service.check_start()?;
drop(service);
let handle = self.handle.clone();
tauri::async_runtime::spawn(async move {
match Service::set_config(clash_info, config).await {
Ok(_) => {
let handle = handle.lock();
handle.refresh_clash();
handle.notice_message("set_config::ok".into(), "ok".into());
}
Err(err) => {
let handle = handle.lock();
handle.notice_message("set_config::error".into(), format!("{err}"));
log::error!(target: "app", "last {err}")
}
}
});
Ok(())
}
/// Static function
/// update profile item
pub async fn update_profile_item(&self, uid: String, option: Option<PrfOption>) -> Result<()> {
let global = Data::global();
let (url, opt) = {
let profiles = global.profiles.lock();
let item = profiles.get_item(&uid)?;
if let Some(typ) = item.itype.as_ref() {
// maybe only valid for `local` profile
if *typ != "remote" {
// reactivate the config
if Some(uid) == profiles.get_current() {
drop(profiles);
self.activate()?;
}
return Ok(());
}
}
if item.url.is_none() {
bail!("failed to get the profile item url");
}
(item.url.clone().unwrap(), item.option.clone())
};
let merged_opt = PrfOption::merge(opt, option);
let item = PrfItem::from_url(&url, None, None, merged_opt).await?;
let mut profiles = global.profiles.lock();
profiles.update_item(uid.clone(), item)?;
// reactivate the profile
if Some(uid) == profiles.get_current() {
drop(profiles);
self.activate()?;
}
Ok(())
}
}
-608
View File
@@ -1,608 +0,0 @@
use crate::utils::{config, dirs, help, tmpl};
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use serde_yaml::{Mapping, Value};
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>>,
/// user info
#[serde(skip_serializing_if = "Option::is_none")]
pub extra: Option<PrfExtra>,
/// updated time
pub updated: Option<usize>,
/// 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,
}
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,
file_data: None,
}
}
}
impl PrfItem {
/// From partial item
/// must contain `itype`
pub async fn from(item: PrfItem) -> 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, false).await
}
"local" => {
let name = item.name.unwrap_or("Local File".into());
let desc = item.desc.unwrap_or("".into());
PrfItem::from_local(name, desc)
}
"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) -> 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,
updated: Some(help::get_now()),
file_data: Some(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>,
with_proxy: bool,
) -> Result<PrfItem> {
let mut builder = reqwest::ClientBuilder::new();
if !with_proxy {
builder = builder.no_proxy();
}
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,
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,
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,
updated: Some(help::get_now()),
file_data: Some(tmpl::ITEM_SCRIPT.into()),
})
}
}
///
/// ## Profiles Config
///
/// Define the `profiles.yaml` schema
///
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct Profiles {
/// same as PrfConfig.current
current: Option<String>,
/// same as PrfConfig.chain
chain: Option<Vec<String>>,
/// profile list
items: Option<Vec<PrfItem>>,
}
macro_rules! patch {
($lv: expr, $rv: expr, $key: tt) => {
if ($rv.$key).is_some() {
$lv.$key = $rv.$key;
}
};
}
impl Profiles {
/// 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;
}
/// 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);
each.updated = Some(help::get_now());
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());
}
let mut new_config = Mapping::new();
let def_config = config::read_yaml::<Mapping>(file_path.clone());
// Only the following fields are allowed:
// proxies/proxy-providers/proxy-groups/rule-providers/rules
let valid_keys = vec![
"proxies",
"proxy-providers",
"proxy-groups",
"rule-providers",
"rules",
];
valid_keys.iter().for_each(|key| {
let key = Value::String(key.to_string());
if def_config.contains_key(&key) {
let value = def_config[&key].clone();
new_config.insert(key, value);
}
});
return Ok(new_config);
}
}
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![],
};
Ok(PrfEnhanced {
current,
chain,
callback,
})
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct PrfEnhanced {
current: Mapping,
chain: Vec<PrfData>,
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,
}
}
}
+533
View File
@@ -0,0 +1,533 @@
use crate::data::{ClashInfo, Data};
use crate::log_if_err;
use crate::utils::{config, dirs};
use anyhow::{bail, Result};
use parking_lot::RwLock;
use reqwest::header::HeaderMap;
use serde_yaml::Mapping;
use std::fs;
use std::io::Write;
use std::sync::Arc;
use std::{
collections::{HashMap, VecDeque},
time::Duration,
};
use tauri::api::process::{Command, CommandChild, CommandEvent};
use tokio::time::sleep;
const LOGS_QUEUE_LEN: usize = 100;
#[derive(Debug)]
pub struct Service {
sidecar: Option<CommandChild>,
logs: Arc<RwLock<VecDeque<String>>>,
}
impl Service {
pub fn new() -> Service {
let queue = VecDeque::with_capacity(LOGS_QUEUE_LEN + 10);
Service {
sidecar: None,
logs: Arc::new(RwLock::new(queue)),
}
}
pub fn start(&mut self) -> Result<()> {
#[cfg(not(target_os = "windows"))]
self.start_clash_by_sidecar()?;
#[cfg(target_os = "windows")]
{
let enable = {
let data = Data::global();
let verge = data.verge.lock();
verge.enable_service_mode.clone().unwrap_or(false)
};
if !enable {
return self.start_clash_by_sidecar();
}
tauri::async_runtime::spawn(async move {
match Self::check_service().await {
Ok(status) => {
// 未启动clash
if status.code != 0 {
log_if_err!(Self::start_clash_by_service().await);
}
}
Err(err) => log::error!(target: "app", "{err}"),
}
});
}
Ok(())
}
pub fn stop(&mut self) -> Result<()> {
#[cfg(not(target_os = "windows"))]
self.stop_clash_by_sidecar()?;
#[cfg(target_os = "windows")]
{
let _ = self.stop_clash_by_sidecar();
let enable = {
let data = Data::global();
let verge = data.verge.lock();
verge.enable_service_mode.clone().unwrap_or(false)
};
if enable {
tauri::async_runtime::spawn(async move {
log_if_err!(Self::stop_clash_by_service().await);
});
}
}
Ok(())
}
pub fn restart(&mut self) -> Result<()> {
self.stop()?;
self.start()
}
pub fn get_logs(&self) -> VecDeque<String> {
self.logs.read().clone()
}
#[allow(unused)]
pub fn set_logs(&self, text: String) {
let mut logs = self.logs.write();
if logs.len() > LOGS_QUEUE_LEN {
(*logs).pop_front();
}
(*logs).push_back(text);
}
pub fn clear_logs(&self) {
let mut logs = self.logs.write();
(*logs).clear();
}
/// start the clash sidecar
fn start_clash_by_sidecar(&mut self) -> Result<()> {
if self.sidecar.is_some() {
let sidecar = self.sidecar.take().unwrap();
let _ = sidecar.kill();
}
let clash_core: String = {
let global = Data::global();
let verge = global.verge.lock();
verge.clash_core.clone().unwrap_or("clash".into())
};
let app_dir = dirs::app_home_dir();
let app_dir = app_dir.as_os_str().to_str().unwrap();
// fix #212
let args = match clash_core.as_str() {
"clash-meta" => vec!["-m", "-d", app_dir],
_ => vec!["-d", app_dir],
};
let cmd = Command::new_sidecar(clash_core)?;
let (mut rx, cmd_child) = cmd.args(args).spawn()?;
// 将pid写入文件中
let pid = cmd_child.pid();
log_if_err!(|| -> Result<()> {
let path = dirs::clash_pid_path();
fs::File::create(path)?.write(format!("{pid}").as_bytes())?;
Ok(())
}());
self.sidecar = Some(cmd_child);
// clash log
let logs = self.logs.clone();
tauri::async_runtime::spawn(async move {
let write_log = |text: String| {
let mut logs = logs.write();
if logs.len() >= LOGS_QUEUE_LEN {
(*logs).pop_front();
}
(*logs).push_back(text);
};
while let Some(event) = rx.recv().await {
match event {
CommandEvent::Stdout(line) => {
let can_short = line.starts_with("time=") && line.len() > 33;
let stdout = if can_short { &line[33..] } else { &line };
log::info!(target: "app" ,"[clash]: {}", stdout);
write_log(line);
}
CommandEvent::Stderr(err) => {
log::error!(target: "app" ,"[clash error]: {}", err);
write_log(err);
}
_ => {}
}
}
});
Ok(())
}
/// stop the clash sidecar
fn stop_clash_by_sidecar(&mut self) -> Result<()> {
if let Some(sidecar) = self.sidecar.take() {
sidecar.kill()?;
}
Ok(())
}
pub fn check_start(&mut self) -> Result<()> {
#[cfg(target_os = "windows")]
{
let global = Data::global();
let verge = global.verge.lock();
let service_mode = verge.enable_service_mode.unwrap_or(false);
if !service_mode && self.sidecar.is_none() {
self.start()?;
}
}
#[cfg(not(target_os = "windows"))]
if self.sidecar.is_none() {
self.start()?;
}
Ok(())
}
/// update clash config
/// using PUT methods
pub async fn set_config(info: ClashInfo, config: Mapping) -> Result<()> {
let temp_path = dirs::profiles_temp_path();
config::save_yaml(temp_path.clone(), &config, Some("# Clash Verge Temp File"))?;
let (server, headers) = Self::clash_client_info(info)?;
let mut data = HashMap::new();
data.insert("path", temp_path.as_os_str().to_str().unwrap());
macro_rules! report_err {
($i: expr, $e: expr) => {
match $i {
4 => bail!($e),
_ => log::error!(target: "app", $e),
}
};
}
// retry 5 times
for i in 0..5 {
let headers = headers.clone();
match reqwest::ClientBuilder::new().no_proxy().build() {
Ok(client) => {
let builder = client.put(&server).headers(headers).json(&data);
match builder.send().await {
Ok(resp) => match resp.status().as_u16() {
204 => break,
// 配置有问题不重试
400 => bail!("failed to update clash config with status 400"),
status @ _ => report_err!(i, "failed to activate clash with status \"{status}\""),
},
Err(err) => report_err!(i, "{err}"),
}
}
Err(err) => report_err!(i, "{err}"),
}
sleep(Duration::from_millis(500)).await;
}
Ok(())
}
/// patch clash config
pub async fn patch_config(info: ClashInfo, config: Mapping) -> Result<()> {
let (server, headers) = Self::clash_client_info(info)?;
let client = reqwest::ClientBuilder::new().no_proxy().build()?;
let builder = client.patch(&server).headers(headers.clone()).json(&config);
builder.send().await?;
Ok(())
}
/// get clash client url and headers from clash info
fn clash_client_info(info: ClashInfo) -> Result<(String, HeaderMap)> {
if info.server.is_none() {
let status = &info.status;
if info.port.is_none() {
bail!("failed to parse config.yaml file with status {status}");
} else {
bail!("failed to parse the server with status {status}");
}
}
let server = info.server.unwrap();
let server = format!("http://{server}/configs");
let mut headers = HeaderMap::new();
headers.insert("Content-Type", "application/json".parse().unwrap());
if let Some(secret) = info.secret.as_ref() {
let secret = format!("Bearer {}", secret.clone()).parse().unwrap();
headers.insert("Authorization", secret);
}
Ok((server, headers))
}
/// kill old clash process
pub fn kill_old_clash() {
use sysinfo::{Pid, PidExt, ProcessExt, System, SystemExt};
if let Ok(pid) = fs::read(dirs::clash_pid_path()) {
if let Ok(pid) = String::from_utf8_lossy(&pid).parse() {
let mut system = System::new();
system.refresh_all();
let proc = system.process(Pid::from_u32(pid));
if let Some(proc) = proc {
proc.kill();
}
}
}
}
}
impl Drop for Service {
fn drop(&mut self) {
log_if_err!(self.stop());
}
}
/// ### Service Mode
///
#[cfg(target_os = "windows")]
pub mod win_service {
use super::*;
use anyhow::Context;
use deelevate::{PrivilegeLevel, Token};
use runas::Command as RunasCommand;
use serde::{Deserialize, Serialize};
use std::os::windows::process::CommandExt;
use std::{env::current_exe, process::Command as StdCommand};
const SERVICE_NAME: &str = "clash_verge_service";
const SERVICE_URL: &str = "http://127.0.0.1:33211";
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ResponseBody {
pub bin_path: String,
pub config_dir: String,
pub log_file: String,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct JsonResponse {
pub code: u64,
pub msg: String,
pub data: Option<ResponseBody>,
}
impl Service {
/// Install the Clash Verge Service
/// 该函数应该在协程或者线程中执行,避免UAC弹窗阻塞主线程
pub async fn install_service() -> Result<()> {
let binary_path = dirs::service_path();
let install_path = binary_path.with_file_name("install-service.exe");
if !install_path.exists() {
bail!("installer exe not found");
}
let token = Token::with_current_process()?;
let level = token.privilege_level()?;
let status = match level {
PrivilegeLevel::NotPrivileged => RunasCommand::new(install_path).status()?,
_ => StdCommand::new(install_path)
.creation_flags(0x08000000)
.status()?,
};
if !status.success() {
bail!(
"failed to install service with status {}",
status.code().unwrap()
);
}
Ok(())
}
/// Uninstall the Clash Verge Service
/// 该函数应该在协程或者线程中执行,避免UAC弹窗阻塞主线程
pub async fn uninstall_service() -> Result<()> {
let binary_path = dirs::service_path();
let uninstall_path = binary_path.with_file_name("uninstall-service.exe");
if !uninstall_path.exists() {
bail!("uninstaller exe not found");
}
let token = Token::with_current_process()?;
let level = token.privilege_level()?;
let status = match level {
PrivilegeLevel::NotPrivileged => RunasCommand::new(uninstall_path).status()?,
_ => StdCommand::new(uninstall_path)
.creation_flags(0x08000000)
.status()?,
};
if !status.success() {
bail!(
"failed to uninstall service with status {}",
status.code().unwrap()
);
}
Ok(())
}
/// [deprecated]
/// start service
/// 该函数应该在协程或者线程中执行,避免UAC弹窗阻塞主线程
pub async fn start_service() -> Result<()> {
let token = Token::with_current_process()?;
let level = token.privilege_level()?;
let args = ["start", SERVICE_NAME];
let status = match level {
PrivilegeLevel::NotPrivileged => RunasCommand::new("sc").args(&args).status()?,
_ => StdCommand::new("sc").args(&args).status()?,
};
match status.success() {
true => Ok(()),
false => bail!(
"failed to start service with status {}",
status.code().unwrap()
),
}
}
/// stop service
pub async fn stop_service() -> Result<()> {
let url = format!("{SERVICE_URL}/stop_service");
let res = reqwest::ClientBuilder::new()
.no_proxy()
.build()?
.post(url)
.send()
.await?
.json::<JsonResponse>()
.await
.context("failed to connect to the Clash Verge Service")?;
if res.code != 0 {
bail!(res.msg);
}
Ok(())
}
/// check the windows service status
pub async fn check_service() -> Result<JsonResponse> {
let url = format!("{SERVICE_URL}/get_clash");
let response = reqwest::ClientBuilder::new()
.no_proxy()
.build()?
.get(url)
.send()
.await?
.json::<JsonResponse>()
.await
.context("failed to connect to the Clash Verge Service")?;
Ok(response)
}
/// start the clash by service
pub(super) async fn start_clash_by_service() -> Result<()> {
let status = Self::check_service().await?;
if status.code == 0 {
Self::stop_clash_by_service().await?;
sleep(Duration::from_secs(1)).await;
}
let clash_core = {
let global = Data::global();
let verge = global.verge.lock();
verge.clash_core.clone().unwrap_or("clash".into())
};
let clash_bin = format!("{clash_core}.exe");
let bin_path = current_exe().unwrap().with_file_name(clash_bin);
let bin_path = bin_path.as_os_str().to_str().unwrap();
let config_dir = dirs::app_home_dir();
let config_dir = config_dir.as_os_str().to_str().unwrap();
let log_path = dirs::service_log_file();
let log_path = log_path.as_os_str().to_str().unwrap();
let mut map = HashMap::new();
map.insert("bin_path", bin_path);
map.insert("config_dir", config_dir);
map.insert("log_file", log_path);
let url = format!("{SERVICE_URL}/start_clash");
let res = reqwest::ClientBuilder::new()
.no_proxy()
.build()?
.post(url)
.json(&map)
.send()
.await?
.json::<JsonResponse>()
.await
.context("failed to connect to the Clash Verge Service")?;
if res.code != 0 {
bail!(res.msg);
}
Ok(())
}
/// stop the clash by service
pub(super) async fn stop_clash_by_service() -> Result<()> {
let url = format!("{SERVICE_URL}/stop_clash");
let res = reqwest::ClientBuilder::new()
.no_proxy()
.build()?
.post(url)
.send()
.await?
.json::<JsonResponse>()
.await
.context("failed to connect to the Clash Verge Service")?;
if res.code != 0 {
bail!(res.msg);
}
Ok(())
}
}
}
+286
View File
@@ -0,0 +1,286 @@
use crate::{data::*, log_if_err};
use anyhow::{anyhow, bail, Result};
use auto_launch::{AutoLaunch, AutoLaunchBuilder};
use std::sync::Arc;
use sysproxy::Sysproxy;
use tauri::{async_runtime::Mutex, utils::platform::current_exe};
pub struct Sysopt {
/// current system proxy setting
cur_sysproxy: Option<Sysproxy>,
/// record the original system proxy
/// recover it when exit
old_sysproxy: Option<Sysproxy>,
/// helps to auto launch the app
auto_launch: Option<AutoLaunch>,
/// record whether the guard async is running or not
guard_state: Arc<Mutex<bool>>,
}
#[cfg(target_os = "windows")]
static DEFAULT_BYPASS: &str = "localhost;127.*;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 = "127.0.0.1,localhost,<local>";
impl Sysopt {
pub fn new() -> Sysopt {
Sysopt {
cur_sysproxy: None,
old_sysproxy: None,
auto_launch: None,
guard_state: Arc::new(Mutex::new(false)),
}
}
/// init the sysproxy
pub fn init_sysproxy(&mut self) -> Result<()> {
let data = Data::global();
let clash = data.clash.lock();
let port = clash.info.port.clone();
if port.is_none() {
bail!("clash port is none");
}
let verge = data.verge.lock();
let enable = verge.enable_system_proxy.clone().unwrap_or(false);
let bypass = verge.system_proxy_bypass.clone();
let bypass = bypass.unwrap_or(DEFAULT_BYPASS.into());
let port = port.unwrap().parse::<u16>()?;
let host = String::from("127.0.0.1");
self.cur_sysproxy = Some(Sysproxy {
enable,
host,
port,
bypass,
});
if enable {
self.old_sysproxy = Sysproxy::get_system_proxy().map_or(None, |p| Some(p));
self.cur_sysproxy.as_ref().unwrap().set_system_proxy()?;
}
// launchs the system proxy guard
self.guard_proxy();
Ok(())
}
/// update the system proxy
pub fn update_sysproxy(&mut self) -> Result<()> {
if self.cur_sysproxy.is_none() {
return self.init_sysproxy();
}
let data = Data::global();
let verge = data.verge.lock();
let enable = verge.enable_system_proxy.clone().unwrap_or(false);
let bypass = verge.system_proxy_bypass.clone();
let bypass = bypass.unwrap_or(DEFAULT_BYPASS.into());
let mut sysproxy = self.cur_sysproxy.take().unwrap();
sysproxy.enable = enable;
sysproxy.bypass = bypass;
self.cur_sysproxy = Some(sysproxy);
self.cur_sysproxy.as_ref().unwrap().set_system_proxy()?;
Ok(())
}
/// reset the sysproxy
pub fn reset_sysproxy(&mut self) -> Result<()> {
if self.cur_sysproxy.is_none() {
return Ok(());
}
let mut cur = self.cur_sysproxy.take().unwrap();
match self.old_sysproxy.take() {
Some(old) => {
// 如果原代理设置和当前的设置是一样的,需要关闭
// 否则就恢复原代理设置
if old.enable && old.host == cur.host && old.port == cur.port {
cur.enable = false;
cur.set_system_proxy()?;
} else {
old.set_system_proxy()?;
}
}
None => {
if cur.enable {
cur.enable = false;
cur.set_system_proxy()?;
}
}
}
Ok(())
}
/// init the auto launch
pub fn init_launch(&mut self) -> Result<()> {
let data = Data::global();
let verge = data.verge.lock();
let enable = verge.enable_auto_launch.clone().unwrap_or(false);
let app_exe = current_exe()?;
let app_exe = dunce::canonicalize(app_exe)?;
let app_name = app_exe
.file_stem()
.and_then(|f| f.to_str())
.ok_or(anyhow!("failed to get file stem"))?;
let app_path = app_exe
.as_os_str()
.to_str()
.ok_or(anyhow!("failed to get app_path"))?
.to_string();
// fix issue #26
#[cfg(target_os = "windows")]
let app_path = format!("\"{app_path}\"");
// use the /Applications/Clash Verge.app path
#[cfg(target_os = "macos")]
let app_path = (|| -> Option<String> {
let path = std::path::PathBuf::from(&app_path);
let path = path.parent()?.parent()?.parent()?;
let extension = path.extension()?.to_str()?;
match extension == "app" {
true => Some(path.as_os_str().to_str()?.to_string()),
false => None,
}
})()
.unwrap_or(app_path);
let auto = AutoLaunchBuilder::new()
.set_app_name(app_name)
.set_app_path(&app_path)
.build()?;
self.auto_launch = Some(auto);
// 避免在开发时将自启动关了
#[cfg(feature = "verge-dev")]
if !enable {
return Ok(());
}
let auto = self.auto_launch.as_ref().unwrap();
// macos每次启动都更新登录项,避免重复设置登录项
#[cfg(target_os = "macos")]
{
let _ = auto.disable();
if enable {
auto.enable()?;
}
}
#[cfg(not(target_os = "macos"))]
{
match enable {
true => auto.enable()?,
false => auto.disable()?,
};
}
Ok(())
}
/// update the startup
pub fn update_launch(&mut self) -> Result<()> {
if self.auto_launch.is_none() {
return self.init_launch();
}
let data = Data::global();
let verge = data.verge.lock();
let enable = verge.enable_auto_launch.clone().unwrap_or(false);
let auto_launch = self.auto_launch.as_ref().unwrap();
match enable {
true => auto_launch.enable()?,
false => crate::log_if_err!(auto_launch.disable()), // 忽略关闭的错误
};
Ok(())
}
/// launch a system proxy guard
/// read config from file directly
pub fn guard_proxy(&self) {
use tokio::time::{sleep, Duration};
let guard_state = self.guard_state.clone();
tauri::async_runtime::spawn(async move {
// if it is running, exit
let mut state = guard_state.lock().await;
if *state {
return;
}
*state = true;
drop(state);
// default duration is 10s
let mut wait_secs = 10u64;
loop {
sleep(Duration::from_secs(wait_secs)).await;
let global = Data::global();
let verge = global.verge.lock();
let enable = verge.enable_system_proxy.clone().unwrap_or(false);
let guard = verge.enable_proxy_guard.clone().unwrap_or(false);
let guard_duration = verge.proxy_guard_duration.clone().unwrap_or(10);
let bypass = verge.system_proxy_bypass.clone();
drop(verge);
// stop loop
if !enable || !guard {
break;
}
// update duration
wait_secs = guard_duration;
let clash = global.clash.lock();
let port = clash.info.port.clone();
let port = port.unwrap_or("".into()).parse::<u16>();
drop(clash);
log::debug!(target: "app", "try to guard the system proxy");
match port {
Ok(port) => {
let sysproxy = Sysproxy {
enable: true,
host: "127.0.0.1".into(),
port,
bypass: bypass.unwrap_or(DEFAULT_BYPASS.into()),
};
log_if_err!(sysproxy.set_system_proxy());
}
Err(_) => log::error!(target: "app", "failed to parse clash port"),
}
}
let mut state = guard_state.lock().await;
*state = false;
});
}
}
+172
View File
@@ -0,0 +1,172 @@
use super::Core;
use crate::utils::help::get_now;
use crate::{data::Data, log_if_err};
use anyhow::{Context, Result};
use delay_timer::prelude::{DelayTimer, DelayTimerBuilder, TaskBuilder};
use std::collections::HashMap;
type TaskID = u64;
pub struct Timer {
/// cron manager
delay_timer: DelayTimer,
/// save the current state
timer_map: HashMap<String, (TaskID, u64)>,
/// increment id
timer_count: TaskID,
}
impl Timer {
pub fn new() -> Self {
Timer {
delay_timer: DelayTimerBuilder::default().build(),
timer_map: HashMap::new(),
timer_count: 1,
}
}
/// Correctly update all cron tasks
pub fn refresh(&mut self) -> Result<()> {
let diff_map = self.gen_diff();
for (uid, diff) in diff_map.into_iter() {
match diff {
DiffFlag::Del(tid) => {
let _ = self.timer_map.remove(&uid);
log_if_err!(self.delay_timer.remove_task(tid));
}
DiffFlag::Add(tid, val) => {
let _ = self.timer_map.insert(uid.clone(), (tid, val));
log_if_err!(self.add_task(uid, tid, val));
}
DiffFlag::Mod(tid, val) => {
let _ = self.timer_map.insert(uid.clone(), (tid, val));
log_if_err!(self.delay_timer.remove_task(tid));
log_if_err!(self.add_task(uid, tid, val));
}
}
}
Ok(())
}
/// restore timer
pub fn restore(&mut self) -> Result<()> {
self.refresh()?;
let cur_timestamp = get_now(); // seconds
let global = Data::global();
let profiles = global.profiles.lock();
profiles
.get_items()
.unwrap_or(&vec![])
.iter()
.filter(|item| item.uid.is_some() && item.updated.is_some() && item.option.is_some())
.filter(|item| {
// mins to seconds
let interval = item.option.as_ref().unwrap().update_interval.unwrap_or(0) as usize * 60;
let updated = item.updated.unwrap();
return interval > 0 && cur_timestamp - updated >= interval;
})
.for_each(|item| {
let uid = item.uid.as_ref().unwrap();
if let Some((task_id, _)) = self.timer_map.get(uid) {
log_if_err!(self.delay_timer.advance_task(*task_id));
}
});
Ok(())
}
/// generate a uid -> update_interval map
fn gen_map(&self) -> HashMap<String, u64> {
let global = Data::global();
let profiles = global.profiles.lock();
let mut new_map = HashMap::new();
if let Some(items) = profiles.get_items() {
for item in items.iter() {
if item.option.is_some() {
let option = item.option.as_ref().unwrap();
let interval = option.update_interval.unwrap_or(0);
if interval > 0 {
new_map.insert(item.uid.clone().unwrap(), interval);
}
}
}
}
new_map
}
/// generate the diff map for refresh
fn gen_diff(&mut self) -> HashMap<String, DiffFlag> {
let mut diff_map = HashMap::new();
let new_map = self.gen_map();
let cur_map = &self.timer_map;
cur_map.iter().for_each(|(uid, (tid, val))| {
let new_val = new_map.get(uid).unwrap_or(&0);
if *new_val == 0 {
diff_map.insert(uid.clone(), DiffFlag::Del(*tid));
} else if new_val != val {
diff_map.insert(uid.clone(), DiffFlag::Mod(*tid, *new_val));
}
});
let mut count = self.timer_count;
new_map.iter().for_each(|(uid, val)| {
if cur_map.get(uid).is_none() {
diff_map.insert(uid.clone(), DiffFlag::Add(count, *val));
count += 1;
}
});
self.timer_count = count;
diff_map
}
/// add a cron task
fn add_task(&self, uid: String, tid: TaskID, minutes: u64) -> Result<()> {
let core = Core::global();
let task = TaskBuilder::default()
.set_task_id(tid)
.set_maximum_parallel_runnable_num(1)
.set_frequency_repeated_by_minutes(minutes)
// .set_frequency_repeated_by_seconds(minutes) // for test
.spawn_async_routine(move || Self::async_task(core.to_owned(), uid.to_owned()))
.context("failed to create timer task")?;
self
.delay_timer
.add_task(task)
.context("failed to add timer task")?;
Ok(())
}
/// the task runner
async fn async_task(core: Core, uid: String) {
log::info!(target: "app", "running timer task `{uid}`");
log_if_err!(core.update_profile_item(uid, None).await);
}
}
#[derive(Debug)]
enum DiffFlag {
Del(TaskID),
Add(TaskID, u64),
Mod(TaskID, u64),
}
-326
View File
@@ -1,326 +0,0 @@
use crate::{
core::Clash,
log_if_err,
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};
/// ### `verge.yaml` schema
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct VergeConfig {
/// `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>,
/// 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>,
}
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 for"),
}
}
}
/// init the auto launch
pub fn init_launch(&mut self) {
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();
let auto = AutoLaunchBuilder::new()
.set_app_name(app_name)
.set_app_path(app_path)
.build();
self.auto_launch = Some(auto);
}
/// sync the startup when run the app
pub fn sync_launch(&self) -> Result<()> {
let enable = self.config.enable_auto_launch.clone().unwrap_or(false);
if !enable {
return Ok(());
}
if self.auto_launch.is_none() {
bail!("should init the auto launch first");
}
let auto_launch = self.auto_launch.clone().unwrap();
let is_enabled = auto_launch.is_enabled().unwrap_or(false);
if !is_enabled {
auto_launch.enable()?;
}
Ok(())
}
/// 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.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;
}
// 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);
log::error!("failed to set system proxy");
bail!("failed to set system proxy");
}
self.cur_sysproxy = Some(sysproxy);
}
self.config.enable_system_proxy = Some(enable);
}
// should update system proxy too
if patch.system_proxy_bypass.is_some() {
let bypass = patch.system_proxy_bypass.unwrap();
if let Some(mut sysproxy) = self.cur_sysproxy.take() {
if sysproxy.enable {
sysproxy.bypass = bypass.clone();
if sysproxy.set_sys().is_err() {
self.cur_sysproxy = Some(sysproxy);
log::error!("failed to set system proxy");
bail!("failed to set system proxy");
}
}
self.cur_sysproxy = Some(sysproxy);
}
self.config.system_proxy_bypass = Some(bypass);
}
// proxy guard
// only change it
if patch.enable_proxy_guard.is_some() {
self.config.enable_proxy_guard = patch.enable_proxy_guard;
}
if patch.proxy_guard_duration.is_some() {
self.config.proxy_guard_duration = patch.proxy_guard_duration;
}
// relaunch the guard
if patch.enable_system_proxy.is_some() || patch.enable_proxy_guard.is_some() {
Verge::guard_proxy(self.guard_state.clone());
}
// handle the tun mode
if patch.enable_tun_mode.is_some() {
self.config.enable_tun_mode = patch.enable_tun_mode;
}
self.config.save_file()
}
}
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;
});
}
}
+167
View File
@@ -0,0 +1,167 @@
use crate::utils::{config, dirs};
use anyhow::Result;
use serde::{Deserialize, Serialize};
use serde_yaml::{Mapping, Value};
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct ClashInfo {
/// clash sidecar status
pub status: String,
/// clash core port
pub port: Option<String>,
/// same as `external-controller`
pub server: Option<String>,
/// clash secret
pub secret: Option<String>,
}
impl ClashInfo {
/// parse the clash's config.yaml
/// get some information
pub fn from(config: &Mapping) -> ClashInfo {
let key_port_1 = Value::from("mixed-port");
let key_port_2 = Value::from("port");
let key_server = Value::from("external-controller");
let key_secret = Value::from("secret");
let mut status: u32 = 0;
let port = match config.get(&key_port_1) {
Some(value) => match value {
Value::String(val_str) => Some(val_str.clone()),
Value::Number(val_num) => Some(val_num.to_string()),
_ => {
status |= 0b1;
None
}
},
_ => {
status |= 0b10;
None
}
};
let port = match port {
Some(_) => port,
None => match config.get(&key_port_2) {
Some(value) => match value {
Value::String(val_str) => Some(val_str.clone()),
Value::Number(val_num) => Some(val_num.to_string()),
_ => {
status |= 0b100;
None
}
},
_ => {
status |= 0b1000;
None
}
},
};
// `external-controller` could be
// "127.0.0.1:9090" or ":9090"
let server = match config.get(&key_server) {
Some(value) => match value.as_str() {
Some(val_str) => {
if val_str.starts_with(":") {
Some(format!("127.0.0.1{val_str}"))
} else if val_str.starts_with("0.0.0.0:") {
Some(format!("127.0.0.1:{}", &val_str[8..]))
} else if val_str.starts_with("[::]:") {
Some(format!("127.0.0.1:{}", &val_str[5..]))
} else {
Some(val_str.into())
}
}
None => {
status |= 0b10000;
None
}
},
None => {
status |= 0b100000;
None
}
};
let secret = match config.get(&key_secret) {
Some(value) => match value {
Value::String(val_str) => Some(val_str.clone()),
Value::Bool(val_bool) => Some(val_bool.to_string()),
Value::Number(val_num) => Some(val_num.to_string()),
_ => None,
},
_ => None,
};
ClashInfo {
status: format!("{status}"),
port,
server,
secret,
}
}
}
#[derive(Debug)]
pub struct Clash {
/// maintain the clash config
pub config: Mapping,
/// some info
pub info: ClashInfo,
}
impl Clash {
pub fn new() -> Clash {
let config = Clash::read_config();
let info = ClashInfo::from(&config);
Clash { config, info }
}
/// get clash config
pub fn read_config() -> Mapping {
config::read_merge_mapping(dirs::clash_path())
}
/// save the clash config
pub fn save_config(&self) -> Result<()> {
config::save_yaml(
dirs::clash_path(),
&self.config,
Some("# Default Config For Clash Core\n\n"),
)
}
/// patch update the clash config
/// if the port is changed then return true
pub fn patch_config(&mut self, patch: Mapping) -> Result<()> {
let port_key = Value::from("mixed-port");
let server_key = Value::from("external-controller");
let secret_key = Value::from("secret");
let change_info = patch.contains_key(&port_key)
|| patch.contains_key(&server_key)
|| patch.contains_key(&secret_key);
for (key, value) in patch.into_iter() {
self.config.insert(key, value);
}
if change_info {
self.info = ClashInfo::from(&self.config);
}
self.save_config()
}
}
impl Default for Clash {
fn default() -> Self {
Clash::new()
}
}
+32
View File
@@ -0,0 +1,32 @@
mod clash;
mod prfitem;
mod profiles;
mod verge;
pub use self::clash::*;
pub use self::prfitem::*;
pub use self::profiles::*;
pub use self::verge::*;
use once_cell::sync::Lazy;
use parking_lot::Mutex;
use std::sync::Arc;
static DATA: Lazy<Data> = Lazy::new(|| Data {
clash: Arc::new(Mutex::new(Clash::new())),
verge: Arc::new(Mutex::new(Verge::new())),
profiles: Arc::new(Mutex::new(Profiles::new())),
});
#[derive(Debug, Clone)]
pub struct Data {
pub clash: Arc<Mutex<Clash>>,
pub verge: Arc<Mutex<Verge>>,
pub profiles: Arc<Mutex<Profiles>>,
}
impl Data {
pub fn global() -> Data {
DATA.clone()
}
}
+372
View File
@@ -0,0 +1,372 @@
use crate::utils::{config, dirs, help, tmpl};
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use serde_yaml::Mapping;
use std::fs;
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PrfItem {
pub uid: Option<String>,
/// profile item type
/// enum value: remote | local | script | merge
#[serde(rename = "type")]
pub itype: Option<String>,
/// profile name
pub name: Option<String>,
/// profile file
pub file: Option<String>,
/// profile description
#[serde(skip_serializing_if = "Option::is_none")]
pub desc: Option<String>,
/// source url
#[serde(skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
/// selected infomation
#[serde(skip_serializing_if = "Option::is_none")]
pub selected: Option<Vec<PrfSelected>>,
/// subscription user info
#[serde(skip_serializing_if = "Option::is_none")]
pub extra: Option<PrfExtra>,
/// updated time
pub updated: Option<usize>,
/// some options of the item
#[serde(skip_serializing_if = "Option::is_none")]
pub option: Option<PrfOption>,
/// the file data
#[serde(skip)]
pub file_data: Option<String>,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct PrfSelected {
pub name: Option<String>,
pub now: Option<String>,
}
#[derive(Default, Debug, Clone, Copy, Deserialize, Serialize)]
pub struct PrfExtra {
pub upload: usize,
pub download: usize,
pub total: usize,
pub expire: usize,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct PrfOption {
/// for `remote` profile's http request
/// see issue #13
#[serde(skip_serializing_if = "Option::is_none")]
pub user_agent: Option<String>,
/// for `remote` profile
#[serde(skip_serializing_if = "Option::is_none")]
pub with_proxy: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub update_interval: Option<u64>,
}
impl PrfOption {
pub fn merge(one: Option<Self>, other: Option<Self>) -> Option<Self> {
if one.is_none() {
return other;
}
if one.is_some() && other.is_some() {
let mut one = one.unwrap();
let other = other.unwrap();
if let Some(val) = other.user_agent {
one.user_agent = Some(val);
}
if let Some(val) = other.with_proxy {
one.with_proxy = Some(val);
}
if let Some(val) = other.update_interval {
one.update_interval = Some(val);
}
return Some(one);
}
return one;
}
}
impl Default for PrfItem {
fn default() -> Self {
PrfItem {
uid: None,
itype: None,
name: None,
desc: None,
file: None,
url: None,
selected: None,
extra: None,
updated: None,
option: None,
file_data: None,
}
}
}
impl PrfItem {
/// From partial item
/// must contain `itype`
pub async fn from(item: PrfItem, file_data: Option<String>) -> Result<PrfItem> {
if item.itype.is_none() {
bail!("type should not be null");
}
match item.itype.unwrap().as_str() {
"remote" => {
if item.url.is_none() {
bail!("url should not be null");
}
let url = item.url.as_ref().unwrap().as_str();
let name = item.name;
let desc = item.desc;
PrfItem::from_url(url, name, desc, item.option).await
}
"local" => {
let name = item.name.unwrap_or("Local File".into());
let desc = item.desc.unwrap_or("".into());
PrfItem::from_local(name, desc, file_data)
}
"merge" => {
let name = item.name.unwrap_or("Merge".into());
let desc = item.desc.unwrap_or("".into());
PrfItem::from_merge(name, desc)
}
"script" => {
let name = item.name.unwrap_or("Script".into());
let desc = item.desc.unwrap_or("".into());
PrfItem::from_script(name, desc)
}
typ @ _ => bail!("invalid profile item type \"{typ}\""),
}
}
/// ## Local type
/// create a new item from name/desc
pub fn from_local(name: String, desc: String, file_data: Option<String>) -> Result<PrfItem> {
let uid = help::get_uid("l");
let file = format!("{uid}.yaml");
Ok(PrfItem {
uid: Some(uid),
itype: Some("local".into()),
name: Some(name),
desc: Some(desc),
file: Some(file),
url: None,
selected: None,
extra: None,
option: None,
updated: Some(help::get_now()),
file_data: Some(file_data.unwrap_or(tmpl::ITEM_LOCAL.into())),
})
}
/// ## Remote type
/// create a new item from url
pub async fn from_url(
url: &str,
name: Option<String>,
desc: Option<String>,
option: Option<PrfOption>,
) -> Result<PrfItem> {
let with_proxy = match option.as_ref() {
Some(opt) => opt.with_proxy.unwrap_or(false),
None => false,
};
let user_agent = match option.as_ref() {
Some(opt) => opt.user_agent.clone(),
None => None,
};
let mut builder = reqwest::ClientBuilder::new();
if !with_proxy {
builder = builder.no_proxy();
}
builder = builder.user_agent(user_agent.unwrap_or("clash-verge/v1.0.0".into()));
let resp = builder.build()?.get(url).send().await?;
let header = resp.headers();
// parse the Subscription Userinfo
let extra = match header.get("Subscription-Userinfo") {
Some(value) => {
let sub_info = value.to_str().unwrap_or("");
Some(PrfExtra {
upload: help::parse_str(sub_info, "upload=").unwrap_or(0),
download: help::parse_str(sub_info, "download=").unwrap_or(0),
total: help::parse_str(sub_info, "total=").unwrap_or(0),
expire: help::parse_str(sub_info, "expire=").unwrap_or(0),
})
}
None => None,
};
// parse the Content-Disposition
let filename = match header.get("Content-Disposition") {
Some(value) => {
let filename = value.to_str().unwrap_or("");
help::parse_str::<String>(filename, "filename=")
}
None => None,
};
// parse the profile-update-interval
let option = match header.get("profile-update-interval") {
Some(value) => match value.to_str().unwrap_or("").parse::<u64>() {
Ok(val) => Some(PrfOption {
update_interval: Some(val * 60), // hour -> min
..PrfOption::default()
}),
Err(_) => None,
},
None => None,
};
let uid = help::get_uid("r");
let file = format!("{uid}.yaml");
let name = name.unwrap_or(filename.unwrap_or("Remote File".into()));
let data = resp.text_with_charset("utf-8").await?;
// check the data whether the valid yaml format
if !serde_yaml::from_str::<Mapping>(&data).is_ok() {
bail!("the remote profile data is invalid yaml");
}
Ok(PrfItem {
uid: Some(uid),
itype: Some("remote".into()),
name: Some(name),
desc,
file: Some(file),
url: Some(url.into()),
selected: None,
extra,
option,
updated: Some(help::get_now()),
file_data: Some(data),
})
}
/// ## Merge type (enhance)
/// create the enhanced item by using `merge` rule
pub fn from_merge(name: String, desc: String) -> Result<PrfItem> {
let uid = help::get_uid("m");
let file = format!("{uid}.yaml");
Ok(PrfItem {
uid: Some(uid),
itype: Some("merge".into()),
name: Some(name),
desc: Some(desc),
file: Some(file),
url: None,
selected: None,
extra: None,
option: None,
updated: Some(help::get_now()),
file_data: Some(tmpl::ITEM_MERGE.into()),
})
}
/// ## Script type (enhance)
/// create the enhanced item by using javascript(browserjs)
pub fn from_script(name: String, desc: String) -> Result<PrfItem> {
let uid = help::get_uid("s");
let file = format!("{uid}.js"); // js ext
Ok(PrfItem {
uid: Some(uid),
itype: Some("script".into()),
name: Some(name),
desc: Some(desc),
file: Some(file),
url: None,
selected: None,
extra: None,
option: None,
updated: Some(help::get_now()),
file_data: Some(tmpl::ITEM_SCRIPT.into()),
})
}
/// get the file data
pub fn read_file(&self) -> Result<String> {
if self.file.is_none() {
bail!("could not find the file");
}
let file = self.file.clone().unwrap();
let path = dirs::app_profiles_dir().join(file);
fs::read_to_string(path).context("failed to read the file")
}
/// save the file data
pub fn save_file(&self, data: String) -> Result<()> {
if self.file.is_none() {
bail!("could not find the file");
}
let file = self.file.clone().unwrap();
let path = dirs::app_profiles_dir().join(file);
fs::write(path, data.as_bytes()).context("failed to save the file")
}
/// get the data for enhanced mode
pub fn to_enhance(&self) -> Option<ChainItem> {
let itype = self.itype.as_ref()?.as_str();
let file = self.file.clone()?;
let uid = self.uid.clone().unwrap_or("".into());
let path = dirs::app_profiles_dir().join(file);
if !path.exists() {
return None;
}
match itype {
"script" => Some(ChainItem {
uid,
data: ChainType::Script(fs::read_to_string(path).unwrap_or("".into())),
}),
"merge" => Some(ChainItem {
uid,
data: ChainType::Merge(config::read_merge_mapping(path)),
}),
_ => None,
}
}
}
#[derive(Debug, Clone)]
pub struct ChainItem {
pub uid: String,
pub data: ChainType,
}
#[derive(Debug, Clone)]
pub enum ChainType {
Merge(Mapping),
Script(String),
}
+328
View File
@@ -0,0 +1,328 @@
use super::prfitem::PrfItem;
use super::ChainItem;
use crate::utils::{config, dirs, help};
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use serde_yaml::Mapping;
use std::collections::HashMap;
use std::{fs, io::Write};
///
/// ## Profiles Config
///
/// Define the `profiles.yaml` schema
///
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct Profiles {
/// same as PrfConfig.current
current: Option<String>,
/// same as PrfConfig.chain
chain: Option<Vec<String>>,
/// record valid fields for clash
valid: Option<Vec<String>>,
/// profile list
items: Option<Vec<PrfItem>>,
}
macro_rules! patch {
($lv: expr, $rv: expr, $key: tt) => {
if ($rv.$key).is_some() {
$lv.$key = $rv.$key;
}
};
}
impl Profiles {
pub fn new() -> Self {
Profiles::read_file()
}
/// read the config from the file
pub fn read_file() -> Self {
let mut profiles = config::read_yaml::<Self>(dirs::profiles_path());
if profiles.items.is_none() {
profiles.items = Some(vec![]);
}
// compatiable with the old old old version
profiles.items.as_mut().map(|items| {
for mut item in items.iter_mut() {
if item.uid.is_none() {
item.uid = Some(help::get_uid("d"));
}
}
});
profiles
}
/// save the config to the file
pub fn save_file(&self) -> Result<()> {
config::save_yaml(
dirs::profiles_path(),
self,
Some("# Profiles Config for Clash Verge\n\n"),
)
}
/// get the current uid
pub fn get_current(&self) -> Option<String> {
self.current.clone()
}
/// only change the main to the target id
pub fn put_current(&mut self, uid: String) -> Result<()> {
if self.items.is_none() {
self.items = Some(vec![]);
}
let items = self.items.as_ref().unwrap();
let some_uid = Some(uid.clone());
if items.iter().find(|&each| each.uid == some_uid).is_some() {
self.current = some_uid;
return self.save_file();
}
bail!("invalid uid \"{uid}\"");
}
/// just change the `chain`
pub fn put_chain(&mut self, chain: Option<Vec<String>>) -> Result<()> {
self.chain = chain;
self.save_file()
}
/// just change the `field`
pub fn put_valid(&mut self, valid: Option<Vec<String>>) -> Result<()> {
self.valid = valid;
self.save_file()
}
/// get items ref
pub fn get_items(&self) -> Option<&Vec<PrfItem>> {
self.items.as_ref()
}
/// find the item by the uid
pub fn get_item(&self, uid: &String) -> Result<&PrfItem> {
if self.items.is_some() {
let items = self.items.as_ref().unwrap();
let some_uid = Some(uid.clone());
for each in items.iter() {
if each.uid == some_uid {
return Ok(each);
}
}
}
bail!("failed to get the profile item \"uid:{uid}\"");
}
/// append new item
/// if the file_data is some
/// then should save the data to file
pub fn append_item(&mut self, mut item: PrfItem) -> Result<()> {
if item.uid.is_none() {
bail!("the uid should not be null");
}
// save the file data
// move the field value after save
if let Some(file_data) = item.file_data.take() {
if item.file.is_none() {
bail!("the file should not be null");
}
let file = item.file.clone().unwrap();
let path = dirs::app_profiles_dir().join(&file);
fs::File::create(path)
.context(format!("failed to create file \"{}\"", file))?
.write(file_data.as_bytes())
.context(format!("failed to write to file \"{}\"", file))?;
}
if self.items.is_none() {
self.items = Some(vec![]);
}
self.items.as_mut().map(|items| items.push(item));
self.save_file()
}
/// update the item value
pub fn patch_item(&mut self, uid: String, item: PrfItem) -> Result<()> {
let mut items = self.items.take().unwrap_or(vec![]);
for mut each in items.iter_mut() {
if each.uid == Some(uid.clone()) {
patch!(each, item, itype);
patch!(each, item, name);
patch!(each, item, desc);
patch!(each, item, file);
patch!(each, item, url);
patch!(each, item, selected);
patch!(each, item, extra);
patch!(each, item, updated);
patch!(each, item, option);
self.items = Some(items);
return self.save_file();
}
}
self.items = Some(items);
bail!("failed to find the profile item \"uid:{uid}\"")
}
/// be used to update the remote item
/// only patch `updated` `extra` `file_data`
pub fn update_item(&mut self, uid: String, mut item: PrfItem) -> Result<()> {
if self.items.is_none() {
self.items = Some(vec![]);
}
// find the item
let _ = self.get_item(&uid)?;
if let Some(items) = self.items.as_mut() {
let some_uid = Some(uid.clone());
for mut each in items.iter_mut() {
if each.uid == some_uid {
each.extra = item.extra;
each.updated = item.updated;
// save the file data
// move the field value after save
if let Some(file_data) = item.file_data.take() {
let file = each.file.take();
let file = file.unwrap_or(item.file.take().unwrap_or(format!("{}.yaml", &uid)));
// the file must exists
each.file = Some(file.clone());
let path = dirs::app_profiles_dir().join(&file);
fs::File::create(path)
.context(format!("failed to create file \"{}\"", file))?
.write(file_data.as_bytes())
.context(format!("failed to write to file \"{}\"", file))?;
}
break;
}
}
}
self.save_file()
}
/// delete item
/// if delete the current then return true
pub fn delete_item(&mut self, uid: String) -> Result<bool> {
let current = self.current.as_ref().unwrap_or(&uid);
let current = current.clone();
let mut items = self.items.take().unwrap_or(vec![]);
let mut index = None;
// get the index
for i in 0..items.len() {
if items[i].uid == Some(uid.clone()) {
index = Some(i);
break;
}
}
if let Some(index) = index {
items.remove(index).file.map(|file| {
let path = dirs::app_profiles_dir().join(file);
if path.exists() {
let _ = fs::remove_file(path);
}
});
}
// delete the original uid
if current == uid {
self.current = match items.len() > 0 {
true => items[0].uid.clone(),
false => None,
};
}
self.items = Some(items);
self.save_file()?;
Ok(current == uid)
}
/// generate the current Mapping data
fn gen_current(&self) -> Result<Mapping> {
let config = Mapping::new();
if self.current.is_none() || self.items.is_none() {
return Ok(config);
}
let current = self.current.clone().unwrap();
for item in self.items.as_ref().unwrap().iter() {
if item.uid == Some(current.clone()) {
let file_path = match item.file.clone() {
Some(file) => dirs::app_profiles_dir().join(file),
None => bail!("failed to get the file field"),
};
if !file_path.exists() {
bail!("failed to read the file \"{}\"", file_path.display());
}
return Ok(config::read_merge_mapping(file_path.clone()));
}
}
bail!("failed to find current profile \"uid:{current}\"");
}
/// generate the data for activate clash config
pub fn gen_activate(&self) -> Result<PrfActivate> {
let current = self.gen_current()?;
let chain = match self.chain.as_ref() {
Some(chain) => chain
.iter()
.filter_map(|uid| self.get_item(uid).ok())
.filter_map(|item| item.to_enhance())
.collect::<Vec<ChainItem>>(),
None => vec![],
};
let valid = self.valid.clone().unwrap_or(vec![]);
Ok(PrfActivate {
current,
chain,
valid,
})
}
}
#[derive(Default, Clone)]
pub struct PrfActivate {
pub current: Mapping,
pub chain: Vec<ChainItem>,
pub valid: Vec<String>,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct RuntimeResult {
pub config: Option<Mapping>,
pub config_yaml: Option<String>,
// 记录在配置中(包括merge和script生成的)出现过的keys
// 这些keys不一定都生效
pub exists_keys: Vec<String>,
pub chain_logs: HashMap<String, Vec<(String, String)>>,
}
+127
View File
@@ -0,0 +1,127 @@
use crate::utils::{config, dirs};
use anyhow::Result;
use serde::{Deserialize, Serialize};
/// ### `verge.yaml` schema
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct Verge {
/// app listening port
/// for app singleton
pub app_singleton_port: Option<u16>,
// i18n
pub language: Option<String>,
/// `light` or `dark` or `system`
pub theme_mode: Option<String>,
/// enable blur mode
/// maybe be able to set the alpha
pub theme_blur: Option<bool>,
/// enable traffic graph default is true
pub traffic_graph: Option<bool>,
/// clash tun mode
pub enable_tun_mode: Option<bool>,
/// windows service mode
#[serde(skip_serializing_if = "Option::is_none")]
pub enable_service_mode: Option<bool>,
/// can the app auto startup
pub enable_auto_launch: Option<bool>,
/// not show the window on launch
pub enable_silent_start: Option<bool>,
/// set system proxy
pub enable_system_proxy: Option<bool>,
/// enable proxy guard
pub enable_proxy_guard: Option<bool>,
/// set system proxy bypass
pub system_proxy_bypass: Option<String>,
/// proxy guard duration
pub proxy_guard_duration: Option<u64>,
/// theme setting
pub theme_setting: Option<VergeTheme>,
/// web ui list
pub web_ui_list: Option<Vec<String>>,
/// clash core path
#[serde(skip_serializing_if = "Option::is_none")]
pub clash_core: Option<String>,
/// hotkey map
/// format: {func},{key}
pub hotkeys: Option<Vec<String>>,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct VergeTheme {
pub primary_color: Option<String>,
pub secondary_color: Option<String>,
pub primary_text: Option<String>,
pub secondary_text: Option<String>,
pub info_color: Option<String>,
pub error_color: Option<String>,
pub warning_color: Option<String>,
pub success_color: Option<String>,
pub font_family: Option<String>,
pub css_injection: Option<String>,
}
impl Verge {
pub fn new() -> Self {
config::read_yaml::<Verge>(dirs::verge_path())
}
/// Save Verge App Config
pub fn save_file(&self) -> Result<()> {
config::save_yaml(
dirs::verge_path(),
self,
Some("# The Config for Clash Verge App\n\n"),
)
}
/// patch verge config
/// only save to file
pub fn patch_config(&mut self, patch: Verge) -> Result<()> {
macro_rules! patch {
($key: tt) => {
if patch.$key.is_some() {
self.$key = patch.$key;
}
};
}
patch!(language);
patch!(theme_mode);
patch!(theme_blur);
patch!(traffic_graph);
patch!(enable_tun_mode);
patch!(enable_service_mode);
patch!(enable_auto_launch);
patch!(enable_silent_start);
patch!(enable_system_proxy);
patch!(enable_proxy_guard);
patch!(system_proxy_bypass);
patch!(proxy_guard_duration);
patch!(theme_setting);
patch!(web_ui_list);
patch!(clash_core);
patch!(hotkeys);
self.save_file()
}
}
+93
View File
@@ -0,0 +1,93 @@
use crate::core::*;
use crate::data::*;
use crate::log_if_err;
// 切换模式
pub fn change_clash_mode(mode: &str) {
let core = Core::global();
log_if_err!(core.update_mode(mode));
}
// 切换系统代理
pub fn toggle_system_proxy() {
let core = Core::global();
let data = Data::global();
let verge = data.verge.lock();
let enable = !verge.enable_system_proxy.clone().unwrap_or(false);
drop(verge);
log_if_err!(core.patch_verge(Verge {
enable_system_proxy: Some(enable),
..Verge::default()
}));
let handle = core.handle.lock();
let _ = handle.refresh_verge();
}
// 打开系统代理
pub fn enable_system_proxy() {
let core = Core::global();
log_if_err!(core.patch_verge(Verge {
enable_system_proxy: Some(true),
..Verge::default()
}));
let handle = core.handle.lock();
let _ = handle.refresh_verge();
}
// 关闭系统代理
pub fn disable_system_proxy() {
let core = Core::global();
log_if_err!(core.patch_verge(Verge {
enable_system_proxy: Some(false),
..Verge::default()
}));
let handle = core.handle.lock();
let _ = handle.refresh_verge();
}
// 切换tun模式
pub fn toggle_tun_mode() {
let core = Core::global();
let data = Data::global();
let verge = data.verge.lock();
let enable = !verge.enable_tun_mode.clone().unwrap_or(false);
drop(verge);
log_if_err!(core.patch_verge(Verge {
enable_tun_mode: Some(enable),
..Verge::default()
}));
let handle = core.handle.lock();
let _ = handle.refresh_verge();
}
// 打开tun模式
pub fn enable_tun_mode() {
let core = Core::global();
log_if_err!(core.patch_verge(Verge {
enable_tun_mode: Some(true),
..Verge::default()
}));
let handle = core.handle.lock();
let _ = handle.refresh_verge();
}
// 关闭tun模式
pub fn disable_tun_mode() {
let core = Core::global();
log_if_err!(core.patch_verge(Verge {
enable_tun_mode: Some(false),
..Verge::default()
}));
let handle = core.handle.lock();
let _ = handle.refresh_verge();
}
+100 -51
View File
@@ -4,86 +4,102 @@
)]
mod cmds;
mod config;
mod core;
mod states;
mod data;
mod feat;
mod utils;
use crate::utils::{resolve, server};
use crate::{
data::Verge,
utils::{resolve, server},
};
use tauri::{
api, CustomMenuItem, Manager, SystemTray, SystemTrayEvent, SystemTrayMenu, SystemTrayMenuItem,
};
fn main() -> std::io::Result<()> {
if server::check_singleton().is_err() {
println!("app exists");
return Ok(());
{
let verge = Verge::new();
if server::check_singleton(verge.app_singleton_port).is_err() {
println!("app exists");
return Ok(());
}
}
#[cfg(target_os = "windows")]
unsafe {
use crate::utils::dirs;
dirs::init_portable_flag();
}
let tray_menu = SystemTrayMenu::new()
.add_item(CustomMenuItem::new("open_window", "Show"))
.add_native_item(SystemTrayMenuItem::Separator)
.add_item(CustomMenuItem::new("rule_mode", "Rule Mode"))
.add_item(CustomMenuItem::new("global_mode", "Global Mode"))
.add_item(CustomMenuItem::new("direct_mode", "Direct Mode"))
.add_item(CustomMenuItem::new("script_mode", "Script Mode"))
.add_native_item(SystemTrayMenuItem::Separator)
.add_item(CustomMenuItem::new("system_proxy", "System Proxy"))
.add_item(CustomMenuItem::new("tun_mode", "Tun Mode"))
.add_item(CustomMenuItem::new("restart_clash", "Restart Clash"))
.add_item(CustomMenuItem::new("restart_app", "Restart App"))
.add_native_item(SystemTrayMenuItem::Separator)
.add_item(CustomMenuItem::new("quit", "Quit").accelerator("CmdOrControl+Q"));
#[allow(unused_mut)]
let mut builder = tauri::Builder::default()
.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(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();
resolve::create_window(app_handle);
}
"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();
match clash.restart_sidecar(&mut profiles) {
Ok(_) => {
let window = app_handle.get_window("main").unwrap();
window.emit("restart_clash", "yes").unwrap();
}
Err(err) => log::error!("{}", err),
}
mode @ ("rule_mode" | "global_mode" | "direct_mode" | "script_mode") => {
let mode = &mode[0..mode.len() - 5];
feat::change_clash_mode(mode);
}
"system_proxy" => feat::toggle_system_proxy(),
"tun_mode" => feat::toggle_tun_mode(),
"restart_app" => {
api::process::restart(&app_handle.env());
}
"quit" => {
resolve::resolve_reset(app_handle);
api::process::kill_children();
std::process::exit(0);
resolve::resolve_reset();
app_handle.exit(0);
}
_ => {}
},
#[cfg(target_os = "windows")]
SystemTrayEvent::LeftClick { .. } => {
if cfg![target_os = "windows"] {
let window = app_handle.get_window("main").unwrap();
window.unminimize().unwrap();
window.show().unwrap();
window.set_focus().unwrap();
}
resolve::create_window(app_handle);
}
_ => {}
})
.invoke_handler(tauri::generate_handler![
// common
cmds::restart_sidecar,
cmds::get_sys_proxy,
cmds::get_cur_proxy,
cmds::kill_sidecars,
cmds::open_app_dir,
cmds::open_logs_dir,
cmds::open_web_url,
cmds::kill_sidecar,
cmds::restart_sidecar,
// clash
cmds::get_clash_info,
cmds::get_clash_logs,
cmds::patch_clash_config,
cmds::change_clash_core,
cmds::get_runtime_config,
cmds::get_runtime_yaml,
cmds::get_runtime_exists,
cmds::get_runtime_logs,
// verge
cmds::get_verge_config,
cmds::patch_verge_config,
cmds::update_hotkeys,
// profile
cmds::view_profile,
cmds::patch_profile,
@@ -93,9 +109,17 @@ fn main() -> std::io::Result<()> {
cmds::delete_profile,
cmds::select_profile,
cmds::get_profiles,
cmds::sync_profiles,
cmds::enhance_profiles,
cmds::change_profile_chain
cmds::change_profile_chain,
cmds::change_profile_valid,
cmds::read_profile_file,
cmds::save_profile_file,
// service mode
cmds::service::start_service,
cmds::service::stop_service,
cmds::service::check_service,
cmds::service::install_service,
cmds::service::uninstall_service,
]);
#[cfg(target_os = "macos")]
@@ -115,21 +139,46 @@ fn main() -> std::io::Result<()> {
builder = builder.menu(Menu::new().add_submenu(submenu_file));
}
builder
#[allow(unused_mut)]
let mut app = builder
.build(tauri::generate_context!())
.expect("error while running tauri application")
.run(|app_handle, e| match e {
tauri::RunEvent::CloseRequested { label, api, .. } => {
let app_handle = app_handle.clone();
api.prevent_close();
app_handle.get_window(&label).unwrap().hide().unwrap();
.expect("error while running tauri application");
#[cfg(target_os = "macos")]
app.set_activation_policy(tauri::ActivationPolicy::Accessory);
let app_handle = app.app_handle();
ctrlc::set_handler(move || {
resolve::resolve_reset();
app_handle.exit(0);
})
.expect("error while exiting.");
#[allow(unused)]
app.run(|app_handle, e| match e {
tauri::RunEvent::ExitRequested { api, .. } => {
api.prevent_exit();
}
tauri::RunEvent::Exit => {
resolve::resolve_reset();
api::process::kill_children();
}
#[cfg(target_os = "macos")]
tauri::RunEvent::WindowEvent { label, event, .. } => {
if label == "main" {
match event {
tauri::WindowEvent::CloseRequested { api, .. } => {
api.prevent_close();
app_handle.get_window("main").map(|win| {
let _ = win.hide();
});
}
_ => {}
}
}
tauri::RunEvent::ExitRequested { .. } => {
resolve::resolve_reset(app_handle);
api::process::kill_children();
}
_ => {}
});
}
_ => {}
});
Ok(())
}
-11
View File
@@ -1,11 +0,0 @@
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>>);
+38 -2
View File
@@ -1,11 +1,47 @@
use anyhow::{Context, Result};
use serde::{de::DeserializeOwned, Serialize};
use serde_yaml::{Mapping, Value};
use std::{fs, path::PathBuf};
/// read data from yaml as struct T
pub fn read_yaml<T: DeserializeOwned + Default>(path: PathBuf) -> T {
let yaml_str = fs::read_to_string(path).unwrap_or("".into());
serde_yaml::from_str::<T>(&yaml_str).unwrap_or(T::default())
if !path.exists() {
log::error!(target: "app", "file not found \"{}\"", path.display());
return T::default();
}
let yaml_str = fs::read_to_string(&path).unwrap_or("".into());
match serde_yaml::from_str::<T>(&yaml_str) {
Ok(val) => val,
Err(_) => {
log::error!(target: "app", "failed to read yaml file \"{}\"", path.display());
T::default()
}
}
}
/// read mapping from yaml fix #165
pub fn read_merge_mapping(path: PathBuf) -> Mapping {
let map = Mapping::new();
if !path.exists() {
log::error!(target: "app", "file not found \"{}\"", path.display());
return map;
}
let yaml_str = fs::read_to_string(&path).unwrap_or("".into());
match serde_yaml::from_str::<Value>(&yaml_str) {
Ok(mut val) => {
crate::log_if_err!(val.apply_merge());
val.as_mapping().unwrap_or(&map).to_owned()
}
Err(_) => {
log::error!(target: "app", "failed to read yaml file \"{}\"", path.display());
map
}
}
}
/// save the data to the file
+93 -13
View File
@@ -1,23 +1,74 @@
use std::env::temp_dir;
use std::path::{Path, PathBuf};
use std::path::PathBuf;
use tauri::{
api::path::{home_dir, resource_dir},
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";
static mut RESOURCE_DIR: Option<PathBuf> = None;
/// portable flag
#[allow(unused)]
static mut PORTABLE_FLAG: bool = false;
/// initialize portable flag
#[allow(unused)]
pub unsafe fn init_portable_flag() {
#[cfg(target_os = "windows")]
{
use tauri::utils::platform::current_exe;
let exe = current_exe().unwrap();
let dir = exe.parent().unwrap();
let dir = PathBuf::from(dir).join(".config/PORTABLE");
if dir.exists() {
PORTABLE_FLAG = true;
}
}
}
/// get the verge app home dir
pub fn app_home_dir() -> PathBuf {
home_dir()
.unwrap()
.join(Path::new(".config"))
.join(Path::new("clash-verge"))
#[cfg(target_os = "windows")]
unsafe {
use tauri::utils::platform::current_exe;
if !PORTABLE_FLAG {
home_dir().unwrap().join(".config").join(APP_DIR)
} else {
let app_exe = current_exe().unwrap();
let app_exe = dunce::canonicalize(app_exe).unwrap();
let app_dir = app_exe.parent().unwrap();
PathBuf::from(app_dir).join(".config").join(APP_DIR)
}
}
#[cfg(not(target_os = "windows"))]
home_dir().unwrap().join(".config").join(APP_DIR)
}
/// get the resources dir
pub fn app_resources_dir(package_info: &PackageInfo) -> PathBuf {
resource_dir(package_info, &Env::default())
let res_dir = resource_dir(package_info, &Env::default())
.unwrap()
.join("resources")
.join("resources");
unsafe {
RESOURCE_DIR = Some(res_dir.clone());
}
res_dir
}
/// profiles dir
@@ -30,11 +81,6 @@ pub fn app_logs_dir() -> PathBuf {
app_home_dir().join("logs")
}
static CLASH_CONFIG: &str = "config.yaml";
static VERGE_CONFIG: &str = "verge.yaml";
static PROFILE_YAML: &str = "profiles.yaml";
static PROFILE_TEMP: &str = "clash-verge-runtime.yaml";
pub fn clash_path() -> PathBuf {
app_home_dir().join(CLASH_CONFIG)
}
@@ -48,5 +94,39 @@ pub fn profiles_path() -> PathBuf {
}
pub fn profiles_temp_path() -> PathBuf {
temp_dir().join(PROFILE_TEMP)
#[cfg(not(feature = "debug-yml"))]
return temp_dir().join(PROFILE_TEMP);
#[cfg(feature = "debug-yml")]
return app_home_dir().join(PROFILE_TEMP);
}
pub fn clash_pid_path() -> PathBuf {
unsafe { RESOURCE_DIR.clone().unwrap().join("clash.pid") }
}
#[cfg(windows)]
static SERVICE_PATH: &str = "clash-verge-service.exe";
#[cfg(windows)]
pub fn service_path() -> PathBuf {
unsafe {
let res_dir = RESOURCE_DIR.clone().unwrap();
res_dir.join(SERVICE_PATH)
}
}
#[cfg(windows)]
pub fn service_log_file() -> PathBuf {
use chrono::Local;
let log_dir = app_logs_dir().join("service");
let local_time = Local::now().format("%Y-%m-%d-%H%M%S").to_string();
let log_file = format!("{}.log", local_time);
let log_file = log_dir.join(log_file);
std::fs::create_dir_all(&log_dir).unwrap();
log_file
}
+36 -3
View File
@@ -1,4 +1,7 @@
use anyhow::{bail, Result};
use nanoid::nanoid;
use std::path::PathBuf;
use std::process::Command;
use std::str::FromStr;
use std::time::{SystemTime, UNIX_EPOCH};
@@ -41,11 +44,41 @@ pub fn parse_str<T: FromStr>(target: &str, key: &str) -> Option<T> {
}
}
/// open file
/// use vscode by default
pub fn open_file(path: PathBuf) -> Result<()> {
// use vscode first
if let Ok(code) = which::which("code") {
#[cfg(target_os = "windows")]
{
use std::os::windows::process::CommandExt;
if let Err(err) = Command::new(code)
.creation_flags(0x08000000)
.arg(path)
.spawn()
{
bail!("failed to open file by VScode for `{err}`");
}
}
#[cfg(not(target_os = "windows"))]
if let Err(err) = Command::new(code).arg(path).spawn() {
bail!("failed to open file by VScode for `{err}`");
}
return Ok(());
}
open::that(path)?;
Ok(())
}
#[macro_export]
macro_rules! log_if_err {
($result: expr) => {
if let Err(err) = $result {
log::error!("{err}");
log::error!(target: "app", "{err}");
}
};
}
@@ -58,7 +91,7 @@ macro_rules! wrap_err {
match $stat {
Ok(a) => Ok(a),
Err(err) => {
log::error!("{}", err.to_string());
log::error!(target: "app", "{}", err.to_string());
Err(format!("{}", err.to_string()))
}
}
@@ -68,7 +101,7 @@ macro_rules! wrap_err {
/// return the string literal error
#[macro_export]
macro_rules! ret_err {
($str: literal) => {
($str: expr) => {
return Err($str.into())
};
}
+31 -19
View File
@@ -1,9 +1,10 @@
use crate::utils::{dirs, tmpl};
use anyhow::Result;
use chrono::Local;
use log::LevelFilter;
use log4rs::append::console::ConsoleAppender;
use log4rs::append::file::FileAppender;
use log4rs::config::{Appender, Config, Root};
use log4rs::config::{Appender, Config, Logger, Root};
use log4rs::encode::pattern::PatternEncoder;
use std::fs;
use std::io::Write;
@@ -11,7 +12,7 @@ use std::path::PathBuf;
use tauri::PackageInfo;
/// initialize this instance's log file
fn init_log(log_dir: &PathBuf) {
fn init_log(log_dir: &PathBuf) -> Result<()> {
let local_time = Local::now().format("%Y-%m-%d-%H%M%S").to_string();
let log_file = format!("{}.log", local_time);
let log_file = log_dir.join(log_file);
@@ -22,24 +23,26 @@ fn init_log(log_dir: &PathBuf) {
.build();
let tofile = FileAppender::builder()
.encoder(Box::new(PatternEncoder::new(time_format)))
.build(log_file)
.unwrap();
.build(log_file)?;
let config = Config::builder()
.appender(Appender::builder().build("stdout", Box::new(stdout)))
.appender(Appender::builder().build("file", Box::new(tofile)))
.build(
Root::builder()
.appenders(["stdout", "file"])
.build(LevelFilter::Info),
.logger(
Logger::builder()
.appenders(["file", "stdout"])
.additive(false)
.build("app", LevelFilter::Info),
)
.unwrap();
.build(Root::builder().appender("stdout").build(LevelFilter::Info))?;
log4rs::init_config(config).unwrap();
log4rs::init_config(config)?;
Ok(())
}
/// Initialize all the files from resources
fn init_config(app_dir: &PathBuf) -> std::io::Result<()> {
fn init_config(app_dir: &PathBuf) -> Result<()> {
// target path
let clash_path = app_dir.join("config.yaml");
let verge_path = app_dir.join("verge.yaml");
@@ -67,24 +70,33 @@ pub fn init_app(package_info: &PackageInfo) {
let res_dir = dirs::app_resources_dir(package_info);
if !app_dir.exists() {
fs::create_dir(&app_dir).unwrap();
let _ = fs::create_dir_all(&app_dir);
}
if !log_dir.exists() {
fs::create_dir(&log_dir).unwrap();
let _ = fs::create_dir_all(&log_dir);
}
if !profiles_dir.exists() {
fs::create_dir(&profiles_dir).unwrap();
let _ = fs::create_dir_all(&profiles_dir);
}
init_log(&log_dir);
if let Err(err) = init_config(&app_dir) {
log::error!("{err}");
}
crate::log_if_err!(init_log(&log_dir));
crate::log_if_err!(init_config(&app_dir));
// copy the resource file
let mmdb_path = app_dir.join("Country.mmdb");
let mmdb_tmpl = res_dir.join("Country.mmdb");
if !mmdb_path.exists() && mmdb_tmpl.exists() {
fs::copy(mmdb_tmpl, mmdb_path).unwrap();
let _ = fs::copy(mmdb_tmpl, mmdb_path);
}
// copy the wintun.dll
#[cfg(target_os = "windows")]
{
let wintun_path = app_dir.join("wintun.dll");
let wintun_tmpl = res_dir.join("wintun.dll");
if !wintun_path.exists() && wintun_tmpl.exists() {
let _ = fs::copy(wintun_tmpl, wintun_path);
}
}
}
+1 -1
View File
@@ -4,5 +4,5 @@ pub mod help;
pub mod init;
pub mod resolve;
pub mod server;
pub mod sysopt;
pub mod tmpl;
mod winhelp;
+74 -54
View File
@@ -1,82 +1,102 @@
use super::{init, server};
use crate::{core::Profiles, log_if_err, states};
use crate::{core::Core, data::Data, utils::init, utils::server};
use tauri::{App, AppHandle, Manager};
/// handle something when start app
pub fn resolve_setup(app: &App) {
resolve_window(app);
// setup a simple http server for singleton
server::embed_server(&app.handle());
// init app config
init::init_app(app.package_info());
// init states
let clash_state = app.state::<states::ClashState>();
let verge_state = app.state::<states::VergeState>();
let profiles_state = app.state::<states::ProfilesState>();
let silent_start = {
let global = Data::global();
let verge = global.verge.lock();
let singleton = verge.app_singleton_port.clone();
let mut clash = clash_state.0.lock().unwrap();
let mut verge = verge_state.0.lock().unwrap();
let mut profiles = profiles_state.0.lock().unwrap();
// setup a simple http server for singleton
server::embed_server(&app.handle(), singleton);
log_if_err!(clash.run_sidecar());
verge.enable_silent_start.clone().unwrap_or(false)
};
*profiles = Profiles::read_file();
// core should be initialized after init_app fix #122
let core = Core::global();
core.init(app.app_handle());
clash.set_window(app.get_window("main"));
log_if_err!(clash.activate(&profiles, true));
verge.init_sysproxy(clash.info.port.clone());
// enable tun mode
if verge.config.enable_tun_mode.clone().unwrap_or(false)
&& verge.cur_sysproxy.is_some()
&& verge.cur_sysproxy.as_ref().unwrap().enable
{
log::info!("enable tun mode");
clash.tun_mode(true).unwrap();
if !silent_start {
create_window(&app.app_handle());
}
verge.init_launch();
log_if_err!(verge.sync_launch());
}
/// reset system proxy
pub fn resolve_reset(app_handle: &AppHandle) {
let verge_state = app_handle.state::<states::VergeState>();
let mut verge = verge_state.0.lock().unwrap();
pub fn resolve_reset() {
let core = Core::global();
let mut sysopt = core.sysopt.lock();
crate::log_if_err!(sysopt.reset_sysproxy());
drop(sysopt);
verge.reset_sysproxy();
let mut service = core.service.lock();
crate::log_if_err!(service.stop());
}
/// customize the window theme
fn resolve_window(app: &App) {
let window = app.get_window("main").unwrap();
/// create main window
pub fn create_window(app_handle: &AppHandle) {
if let Some(window) = app_handle.get_window("main") {
let _ = window.unminimize();
let _ = window.show();
let _ = window.set_focus();
return;
}
let builder = tauri::window::WindowBuilder::new(
app_handle,
"main".to_string(),
tauri::WindowUrl::App("index.html".into()),
)
.title("Clash Verge")
.center()
.fullscreen(false)
.min_inner_size(600.0, 520.0);
#[cfg(target_os = "windows")]
{
use crate::utils::winhelp;
use std::time::Duration;
use tokio::time::sleep;
use window_shadows::set_shadow;
use window_vibrancy::apply_blur;
window.set_decorations(false).unwrap();
set_shadow(&window, true).unwrap();
apply_blur(&window).unwrap();
match builder
.decorations(false)
.transparent(true)
.inner_size(800.0, 636.0)
.build()
{
Ok(_) => {
let app_handle = app_handle.clone();
tauri::async_runtime::spawn(async move {
sleep(Duration::from_secs(1)).await;
if let Some(window) = app_handle.get_window("main") {
let _ = window.show();
let _ = set_shadow(&window, true);
if !winhelp::is_win11() {
let _ = apply_blur(&window, None);
}
}
});
}
Err(err) => log::error!(target: "app", "{err}"),
}
}
#[cfg(target_os = "macos")]
{
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);
}
crate::log_if_err!(builder.decorations(true).inner_size(800.0, 642.0).build());
#[cfg(target_os = "linux")]
crate::log_if_err!(builder
.decorations(false)
.transparent(true)
.inner_size(800.0, 636.0)
.build());
}
+16 -12
View File
@@ -1,16 +1,22 @@
extern crate warp;
use super::resolve;
use port_scanner::local_port_available;
use tauri::{AppHandle, Manager};
use tauri::AppHandle;
use warp::Filter;
const SERVER_PORT: u16 = 33333;
#[cfg(not(feature = "verge-dev"))]
const SERVER_PORT: u16 = 33331;
#[cfg(feature = "verge-dev")]
const SERVER_PORT: u16 = 11233;
/// check whether there is already exists
pub fn check_singleton() -> Result<(), ()> {
if !local_port_available(SERVER_PORT) {
pub fn check_singleton(port: Option<u16>) -> Result<(), ()> {
let port = port.unwrap_or(SERVER_PORT);
if !local_port_available(port) {
tauri::async_runtime::block_on(async {
let url = format!("http://127.0.0.1:{}/commands/visible", SERVER_PORT);
let url = format!("http://127.0.0.1:{}/commands/visible", port);
reqwest::get(url).await.unwrap();
Err(())
})
@@ -21,18 +27,16 @@ pub fn check_singleton() -> Result<(), ()> {
/// The embed server only be used to implement singleton process
/// maybe it can be used as pac server later
pub fn embed_server(app: &AppHandle) {
let window = app.get_window("main").unwrap();
pub fn embed_server(app_handle: &AppHandle, port: Option<u16>) {
let app_handle = app_handle.clone();
let port = port.unwrap_or(SERVER_PORT);
tauri::async_runtime::spawn(async move {
let commands = warp::path!("commands" / "visible").map(move || {
window.show().unwrap();
window.set_focus().unwrap();
resolve::create_window(&app_handle);
return format!("ok");
});
warp::serve(commands)
.bind(([127, 0, 0, 1], SERVER_PORT))
.await;
warp::serve(commands).bind(([127, 0, 0, 1], port)).await;
});
}
-211
View File
@@ -1,211 +0,0 @@
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 = "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 {
pub enable: bool,
pub server: String,
pub bypass: String,
}
impl Default for SysProxyConfig {
fn default() -> Self {
SysProxyConfig {
enable: false,
server: String::from(""),
bypass: String::from(""),
}
}
}
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")]
/// Get the windows system proxy config
pub fn get_sys() -> io::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",
KEY_READ,
)?;
Ok(SysProxyConfig {
enable: cur_var.get_value::<u32, _>("ProxyEnable")? == 1u32,
server: cur_var.get_value("ProxyServer")?,
bypass: cur_var.get_value("ProxyOverride")?,
})
}
#[cfg(target_os = "macos")]
/// Get the macos system proxy config
pub fn get_sys() -> io::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()?;
let bypass = std::str::from_utf8(&bypass_output.stdout).unwrap_or(DEFAULT_BYPASS);
Ok(SysProxyConfig {
enable,
server,
bypass: bypass.into(),
})
}
#[cfg(target_os = "windows")]
/// Set the windows system proxy config
pub fn set_sys(&self) -> io::Result<()> {
use winreg::enums::*;
use winreg::RegKey;
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
let cur_var = hkcu.open_subkey_with_flags(
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",
KEY_SET_VALUE,
)?;
let enable: u32 = if self.enable { 1u32 } else { 0u32 };
cur_var.set_value("ProxyEnable", &enable)?;
cur_var.set_value("ProxyServer", &self.server)?;
cur_var.set_value("ProxyOverride", &self.bypass)
}
#[cfg(target_os = "macos")]
/// Set the macos system proxy config
pub fn set_sys(&self) -> io::Result<()> {
let enable = self.enable;
let server = self.server.as_str();
macproxy::set_proxy("-setwebproxy", MACOS_SERVICE, enable, server)?;
macproxy::set_proxy("-setsecurewebproxy", MACOS_SERVICE, enable, server)?;
macproxy::set_proxy("-setsocksfirewallproxy", MACOS_SERVICE, enable, server)
}
}
#[cfg(target_os = "macos")]
mod macproxy {
use super::*;
use std::process::Command;
/// use networksetup
/// get the target proxy config
pub(super) fn get_proxy(args: &[&str; 2]) -> io::Result<(String, String)> {
let output = Command::new("networksetup").args(args).output()?;
match std::str::from_utf8(&output.stdout) {
Ok(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))
}
Err(_) => Err(io::Error::from_raw_os_error(1)),
}
}
/// use networksetup
/// set the target proxy config
pub(super) fn set_proxy(
target: &str, // like: -setwebproxy
device: &str,
enable: bool,
server: &str,
) -> io::Result<()> {
let mut split = server.split(":");
let domain = split.next();
let port = split.next();
// can not parse the field
if domain.is_none() || port.is_none() {
return Err(io::Error::from_raw_os_error(1));
}
let args = vec![target, device, domain.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
pub(super) 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());
}
}
+2 -2
View File
@@ -21,6 +21,7 @@ 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
@@ -28,7 +29,6 @@ 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
@@ -59,7 +59,7 @@ append-proxy-groups:
";
/// enhanced profile
pub const ITEM_SCRIPT: &str = "// Should define the `main` function
pub const ITEM_SCRIPT: &str = "// 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
+69
View File
@@ -0,0 +1,69 @@
#![cfg(target_os = "windows")]
#![allow(non_snake_case)]
#![allow(non_camel_case_types)]
//!
//! From https://github.com/tauri-apps/window-vibrancy/blob/dev/src/windows.rs
//!
use windows_sys::Win32::{
Foundation::*,
System::{LibraryLoader::*, SystemInformation::*},
};
fn get_function_impl(library: &str, function: &str) -> Option<FARPROC> {
assert_eq!(library.chars().last(), Some('\0'));
assert_eq!(function.chars().last(), Some('\0'));
let module = unsafe { LoadLibraryA(library.as_ptr()) };
if module == 0 {
return None;
}
Some(unsafe { GetProcAddress(module, function.as_ptr()) })
}
macro_rules! get_function {
($lib:expr, $func:ident) => {
get_function_impl(concat!($lib, '\0'), concat!(stringify!($func), '\0')).map(|f| unsafe {
std::mem::transmute::<::windows_sys::Win32::Foundation::FARPROC, $func>(f)
})
};
}
/// Returns a tuple of (major, minor, buildnumber)
fn get_windows_ver() -> Option<(u32, u32, u32)> {
type RtlGetVersion = unsafe extern "system" fn(*mut OSVERSIONINFOW) -> i32;
let handle = get_function!("ntdll.dll", RtlGetVersion);
if let Some(rtl_get_version) = handle {
unsafe {
let mut vi = OSVERSIONINFOW {
dwOSVersionInfoSize: 0,
dwMajorVersion: 0,
dwMinorVersion: 0,
dwBuildNumber: 0,
dwPlatformId: 0,
szCSDVersion: [0; 128],
};
let status = (rtl_get_version)(&mut vi as _);
if status >= 0 {
Some((vi.dwMajorVersion, vi.dwMinorVersion, vi.dwBuildNumber))
} else {
None
}
}
} else {
None
}
}
pub fn is_win11() -> bool {
let v = get_windows_ver().unwrap_or_default();
v.2 >= 22000
}
#[test]
fn test_version() {
dbg!(get_windows_ver().unwrap_or_default());
}
+30 -26
View File
@@ -1,7 +1,7 @@
{
"package": {
"productName": "clash-verge",
"version": "0.0.21"
"productName": "Clash Verge",
"version": "1.1.1"
},
"build": {
"distDir": "../dist",
@@ -11,7 +11,7 @@
},
"tauri": {
"systemTray": {
"iconPath": "icons/icon.png",
"iconPath": "icons/tray-icon.ico",
"iconAsTemplate": true
},
"bundle": {
@@ -22,23 +22,26 @@
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon-new.icns",
"icons/icon.ico"
],
"resources": ["resources"],
"externalBin": ["sidecar/clash"],
"resources": [
"resources"
],
"externalBin": [
"sidecar/clash",
"sidecar/clash-meta"
],
"copyright": "© 2022 zzzgydi All Rights Reserved",
"category": "DeveloperTool",
"shortDescription": "A Clash GUI based on tauri.",
"longDescription": "A Clash GUI based on tauri.",
"deb": {
"depends": [],
"useBootstrapper": false
"depends": []
},
"macOS": {
"frameworks": [],
"minimumSystemVersion": "",
"useBootstrapper": false,
"exceptionDomain": "",
"signingIdentity": null,
"entitlements": null
@@ -46,13 +49,20 @@
"windows": {
"certificateThumbprint": null,
"digestAlgorithm": "sha256",
"timestampUrl": ""
"timestampUrl": "",
"wix": {
"language": [
"zh-CN",
"en-US"
]
}
}
},
"updater": {
"active": true,
"endpoints": [
"https://github.com/zzzgydi/clash-verge/releases/download/updater/update.json"
"https://github.com/zzzgydi/clash-verge/releases/download/updater/update.json",
"https://hub.fastgit.xyz/zzzgydi/clash-verge/releases/download/updater/update-proxy.json"
],
"dialog": false,
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDExNUFBNTBBN0FDNEFBRTUKUldUbHFzUjZDcVZhRVRJM25NS3NkSFlFVElxUkNZMzZ6bHUwRVJjb2F3alJXVzRaeDdSaTA2YWYK"
@@ -63,23 +73,17 @@
},
"window": {
"all": true
},
"process": {
"all": true
},
"globalShortcut": {
"all": true
}
},
"windows": [
{
"title": "Clash Verge",
"width": 800,
"height": 600,
"resizable": true,
"fullscreen": false,
"decorations": false,
"transparent": true,
"minWidth": 600,
"minHeight": 520
}
],
"windows": [],
"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';"
}
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB

+8 -1
View File
@@ -11,6 +11,7 @@ body {
--primary-main: #5b5c9d;
--text-primary: #637381;
--selection-color: #f5f5f5;
--scroller-color: #90939980;
}
::selection {
@@ -25,8 +26,14 @@ body {
}
*::-webkit-scrollbar-thumb {
border-radius: 6px;
background-color: rgba(#909399, 0.5);
background-color: var(--scroller-color);
}
@import "./layout.scss";
@import "./page.scss";
@media (prefers-color-scheme: dark) {
:root {
background-color: rgba(18, 18, 18, 1);
}
}
+29 -13
View File
@@ -10,37 +10,42 @@
height: 100%;
max-width: 225px;
min-width: 125px;
padding: 8px 0;
padding: 16px 0 8px;
flex-direction: column;
box-sizing: border-box;
user-select: none;
overflow: hidden;
$maxLogo: 100px;
.the-logo {
position: relative;
flex: 0 1 180px;
flex: 0 1 $maxLogo;
width: 100%;
max-width: 168px;
max-height: 168px;
max-width: $maxLogo + 32px;
max-height: $maxLogo;
margin: 0 auto;
padding: 0 8px;
padding: 0 16px;
text-align: center;
box-sizing: border-box;
img {
img,
svg {
width: 100%;
height: 100%;
pointer-events: none;
}
.the-newbtn {
position: absolute;
right: 20px;
bottom: 12px;
right: 10px;
bottom: 0px;
transform: scale(0.8);
}
}
.the-menu {
flex: 1 1 75%;
flex: 1 1 80%;
overflow-y: auto;
margin-bottom: 8px;
}
@@ -72,7 +77,7 @@
.the-content {
position: absolute;
top: 30px;
top: 0;
left: 0;
right: 2px;
bottom: 10px;
@@ -80,8 +85,19 @@
}
}
.macos.layout {
.layout__right .the-content {
top: 0;
.linux,
.windows,
.unknown {
&.layout {
$maxLogo: 115px;
.layout__left .the-logo {
flex: 0 1 $maxLogo;
max-width: $maxLogo + 32px;
max-height: $maxLogo;
}
.layout__right .the-content {
top: 30px;
}
}
}
+31
View File
@@ -0,0 +1,31 @@
import { alpha, Box, Typography } from "@mui/material";
import { BlurOnRounded } from "@mui/icons-material";
interface Props {
text?: React.ReactNode;
extra?: React.ReactNode;
}
const BaseEmpty = (props: Props) => {
const { text = "Empty", extra } = props;
return (
<Box
sx={({ palette }) => ({
width: "100%",
height: "100%",
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
color: alpha(palette.text.secondary, 0.75),
})}
>
<BlurOnRounded sx={{ fontSize: "4em" }} />
<Typography sx={{ fontSize: "1.25em" }}>{text}</Typography>
{extra}
</Box>
);
};
export default BaseEmpty;
+50
View File
@@ -0,0 +1,50 @@
import { styled } from "@mui/material";
const Loading = styled("div")`
position: relative;
display: flex;
height: 100%;
min-height: 18px;
box-sizing: border-box;
align-items: center;
& > div {
box-sizing: border-box;
width: 6px;
height: 6px;
margin: 2px;
border-radius: 100%;
animation: loading 0.7s -0.15s infinite linear;
}
& > div:nth-child(2n-1) {
animation-delay: -0.5s;
}
@keyframes loading {
50% {
opacity: 0.2;
transform: scale(0.75);
}
100% {
opacity: 1;
transform: scale(1);
}
}
`;
const LoadingItem = styled("div")(({ theme }) => ({
background: theme.palette.text.secondary,
}));
const BaseLoading = () => {
return (
<Loading>
<LoadingItem />
<LoadingItem />
<LoadingItem />
</Loading>
);
};
export default BaseLoading;
+8 -5
View File
@@ -11,7 +11,7 @@ interface InnerProps {
}
const NoticeInner = (props: InnerProps) => {
const { type, message, duration = 2000, onClose } = props;
const { type, message, duration = 1500, onClose } = props;
const [visible, setVisible] = useState(true);
const onBtnClose = () => {
@@ -26,12 +26,13 @@ const NoticeInner = (props: InnerProps) => {
type === "info" ? (
message
) : (
<Box sx={{ display: "flex", alignItems: "center" }}>
<Box sx={{ width: 328, display: "flex", alignItems: "center" }}>
{type === "error" && <ErrorRounded color="error" />}
{type === "success" && <CheckCircleRounded color="success" />}
<Typography
sx={{ ml: 1, wordWrap: "break-word", wordBreak: "break-all" }}
component="span"
sx={{ ml: 1, wordWrap: "break-word", width: "calc(100% - 35px)" }}
>
{message}
</Typography>
@@ -79,14 +80,16 @@ const Notice: NoticeInstance = (props) => {
const onUnmount = () => {
const result = ReactDOM.unmountComponentAtNode(container);
if (result && parent) parent.removeChild(container);
if (result && parent) setTimeout(() => parent.removeChild(container), 500);
};
ReactDOM.render(<NoticeInner {...props} onClose={onUnmount} />, container);
};
(["info", "error", "success"] as const).forEach((type) => {
Notice[type] = (message, duration) => Notice({ type, message, duration });
Notice[type] = (message, duration) => {
setTimeout(() => Notice({ type, message, duration }), 0);
};
});
export default Notice;
+64 -2
View File
@@ -1,4 +1,26 @@
import { ApiType } from "../../services/types";
import dayjs from "dayjs";
import { useLockFn } from "ahooks";
import {
styled,
ListItem,
IconButton,
ListItemText,
Box,
alpha,
} from "@mui/material";
import { CloseRounded } from "@mui/icons-material";
import { deleteConnection } from "@/services/api";
import parseTraffic from "@/utils/parse-traffic";
const Tag = styled("span")(({ theme }) => ({
fontSize: "10px",
padding: "0 4px",
lineHeight: 1.375,
border: "1px solid",
borderRadius: 4,
borderColor: alpha(theme.palette.text.secondary, 0.35),
marginRight: "4px",
}));
interface Props {
value: ApiType.ConnectionsItem;
@@ -7,7 +29,47 @@ interface Props {
const ConnectionItem = (props: Props) => {
const { value } = props;
return <div>{value.metadata.host || value.metadata.destinationIP}</div>;
const { id, metadata, chains, start, curUpload, curDownload } = value;
const onDelete = useLockFn(async () => deleteConnection(id));
const showTraffic = curUpload! >= 100 || curDownload! >= 100;
return (
<ListItem
dense
secondaryAction={
<IconButton edge="end" color="inherit" onClick={onDelete}>
<CloseRounded />
</IconButton>
}
>
<ListItemText
sx={{ userSelect: "text" }}
primary={metadata.host || metadata.destinationIP}
secondary={
<Box sx={{ display: "flex", flexWrap: "wrap" }}>
<Tag sx={{ textTransform: "uppercase", color: "success" }}>
{metadata.network}
</Tag>
<Tag>{metadata.type}</Tag>
{!!metadata.process && <Tag>{metadata.process}</Tag>}
{chains.length > 0 && <Tag>{chains[value.chains.length - 1]}</Tag>}
<Tag>{dayjs(start).fromNow()}</Tag>
{showTraffic && (
<Tag>
{parseTraffic(curUpload!)} / {parseTraffic(curDownload!)}
</Tag>
)}
</Box>
}
/>
</ListItem>
);
};
export default ConnectionItem;
@@ -0,0 +1,144 @@
import dayjs from "dayjs";
import { useMemo } from "react";
import { DataGrid, GridColDef } from "@mui/x-data-grid";
import parseTraffic from "@/utils/parse-traffic";
interface Props {
connections: ApiType.ConnectionsItem[];
}
const ConnectionTable = (props: Props) => {
const { connections } = props;
const columns: GridColDef[] = [
{
field: "host",
headerName: "Host",
flex: 200,
minWidth: 200,
resizable: false,
disableColumnMenu: true,
},
{
field: "download",
headerName: "Download",
width: 88,
align: "right",
headerAlign: "right",
disableColumnMenu: true,
valueFormatter: (params: any) => parseTraffic(params.value).join(" "),
},
{
field: "upload",
headerName: "Upload",
width: 88,
align: "right",
headerAlign: "right",
disableColumnMenu: true,
valueFormatter: (params: any) => parseTraffic(params.value).join(" "),
},
{
field: "dlSpeed",
headerName: "DL Speed",
align: "right",
width: 88,
headerAlign: "right",
disableColumnMenu: true,
valueFormatter: (params: any) =>
parseTraffic(params.value).join(" ") + "/s",
},
{
field: "ulSpeed",
headerName: "UL Speed",
width: 88,
align: "right",
headerAlign: "right",
disableColumnMenu: true,
valueFormatter: (params: any) =>
parseTraffic(params.value).join(" ") + "/s",
},
{
field: "chains",
headerName: "Chains",
width: 360,
disableColumnMenu: true,
},
{
field: "rule",
headerName: "Rule",
width: 225,
disableColumnMenu: true,
},
{
field: "process",
headerName: "Process",
width: 120,
disableColumnMenu: true,
},
{
field: "time",
headerName: "Time",
width: 120,
align: "right",
headerAlign: "right",
disableColumnMenu: true,
valueFormatter: (params) => dayjs(params.value).fromNow(),
},
{
field: "source",
headerName: "Source",
width: 150,
disableColumnMenu: true,
},
{
field: "destinationIP",
headerName: "Destination IP",
width: 125,
disableColumnMenu: true,
},
{
field: "type",
headerName: "Type",
width: 160,
disableColumnMenu: true,
},
];
const connRows = useMemo(() => {
return connections.map((each) => {
const { metadata, rulePayload } = each;
const chains = [...each.chains].reverse().join(" / ");
const rule = rulePayload ? `${each.rule}(${rulePayload})` : each.rule;
return {
id: each.id,
host: metadata.host
? `${metadata.host}:${metadata.destinationPort}`
: `${metadata.destinationIP}:${metadata.destinationPort}`,
download: each.download,
upload: each.upload,
dlSpeed: each.curDownload,
ulSpeed: each.curUpload,
chains,
rule,
process: metadata.process || metadata.processPath,
time: each.start,
source: `${metadata.sourceIP}:${metadata.sourcePort}`,
destinationIP: metadata.destinationIP,
type: `${metadata.type}(${metadata.network})`,
};
});
}, [connections]);
return (
<DataGrid
rows={connRows}
columns={columns}
density="compact"
sx={{ border: "none", "div:focus": { outline: "none !important" } }}
hideFooter
/>
);
};
export default ConnectionTable;
+1 -1
View File
@@ -30,7 +30,7 @@ const LayoutControl = () => {
<Button
size="small"
sx={{ minWidth, svg: { transform: "scale(1.05)" } }}
onClick={() => appWindow.hide()}
onClick={() => appWindow.close()}
>
<CloseRounded fontSize="small" />
</Button>
+25 -19
View File
@@ -1,23 +1,24 @@
import useSWR from "swr";
import { useEffect, useState } from "react";
import { useEffect, useRef, useState } from "react";
import { useRecoilValue } from "recoil";
import { Box, Typography } from "@mui/material";
import { ArrowDownward, ArrowUpward } from "@mui/icons-material";
import { listen } from "@tauri-apps/api/event";
import { ApiType } from "../../services/types";
import { getInfomation } from "../../services/api";
import { getVergeConfig } from "../../services/cmds";
import { atomClashPort } from "../../services/states";
import { getInformation } from "@/services/api";
import { getVergeConfig } from "@/services/cmds";
import { atomClashPort } from "@/services/states";
import TrafficGraph from "./traffic-graph";
import useLogSetup from "./use-log-setup";
import useTrafficGraph from "./use-traffic-graph";
import parseTraffic from "../../utils/parse-traffic";
import parseTraffic from "@/utils/parse-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({});
const trafficRef = useRef<any>();
// whether hide traffic graph
const { data } = useSWR("getVergeConfig", getVergeConfig);
const trafficGraph = data?.traffic_graph ?? true;
@@ -26,24 +27,26 @@ const LayoutTraffic = () => {
useLogSetup();
useEffect(() => {
let unlisten: () => void = null!;
// should reconnect the traffic ws
listen("restart_clash", () => setRefresh({})).then((fn) => (unlisten = fn));
const unlisten = listen("verge://refresh-clash-config", () =>
setRefresh({})
);
return () => unlisten?.();
return () => {
unlisten.then((fn) => fn());
};
}, []);
useEffect(() => {
let ws: WebSocket | null = null;
getInfomation().then((result) => {
getInformation().then((result) => {
const { server = "", secret = "" } = result;
ws = new WebSocket(`ws://${server}/traffic?token=${secret}`);
ws.addEventListener("message", (event) => {
const data = JSON.parse(event.data) as ApiType.TrafficItem;
appendData(data);
trafficRef.current?.appendData(data);
setTraffic(data);
});
});
@@ -69,12 +72,15 @@ const LayoutTraffic = () => {
};
return (
<Box width="110px" position="relative" onClick={toggleStyle}>
<Box
width="110px"
position="relative"
onClick={trafficRef.current?.toggleStyle}
>
{trafficGraph && (
<canvas
ref={canvasRef}
style={{ width: "100%", height: 60, marginBottom: 6 }}
/>
<div style={{ width: "100%", height: 60, marginBottom: 6 }}>
<TrafficGraph instance={trafficRef} />
</div>
)}
<Box mb={1.5} display="flex" alignItems="center" whiteSpace="nowrap">
+201
View File
@@ -0,0 +1,201 @@
import { useEffect, useRef } from "react";
import { useTheme } from "@mui/material";
const maxPoint = 30;
const refLineAlpha = 1;
const refLineWidth = 2;
const upLineAlpha = 0.6;
const upLineWidth = 4;
const downLineAlpha = 1;
const downLineWidth = 4;
const defaultList = Array(maxPoint + 2).fill({ up: 0, down: 0 });
type TrafficData = { up: number; down: number };
interface Props {
instance: React.MutableRefObject<{
appendData: (data: TrafficData) => void;
toggleStyle: () => void;
}>;
}
/**
* draw the traffic graph
*/
const TrafficGraph = (props: Props) => {
const { instance } = props;
const countRef = useRef(0);
const styleRef = useRef(true);
const listRef = useRef<TrafficData[]>(defaultList);
const canvasRef = useRef<HTMLCanvasElement>(null!);
const { palette } = useTheme();
useEffect(() => {
let timer: any;
let cache: TrafficData | null = null;
const zero = { up: 0, down: 0 };
const handleData = () => {
const data = cache ? cache : zero;
cache = null;
const list = listRef.current;
if (list.length > maxPoint + 2) list.shift();
list.push(data);
countRef.current = 0;
timer = setTimeout(handleData, 1000);
};
instance.current = {
appendData: (data: TrafficData) => {
cache = data;
},
toggleStyle: () => {
styleRef.current = !styleRef.current;
},
};
handleData();
return () => {
instance.current = null!;
if (timer) clearTimeout(timer);
};
}, []);
useEffect(() => {
let raf = 0;
const canvas = canvasRef.current!;
if (!canvas) return;
const context = canvas.getContext("2d")!;
if (!context) return;
const { primary, secondary, divider } = palette;
const refLineColor = divider || "rgba(0, 0, 0, 0.12)";
const upLineColor = secondary.main || "#9c27b0";
const downLineColor = primary.main || "#5b5c9d";
const width = canvas.width;
const height = canvas.height;
const dx = width / maxPoint;
const dy = height / 7;
const l1 = dy;
const l2 = dy * 4;
const countY = (v: number) => {
const h = height;
if (v == 0) return h - 1;
if (v <= 10) return h - (v / 10) * dy;
if (v <= 100) return h - (v / 100 + 1) * dy;
if (v <= 1024) return h - (v / 1024 + 2) * dy;
if (v <= 10240) return h - (v / 10240 + 3) * dy;
if (v <= 102400) return h - (v / 102400 + 4) * dy;
if (v <= 1048576) return h - (v / 1048576 + 5) * dy;
if (v <= 10485760) return h - (v / 10485760 + 6) * dy;
return 1;
};
const drawBezier = (list: number[], offset: number) => {
const points = list.map((y, i) => [
(dx * (i - 1) - offset + 3) | 0,
countY(y),
]);
let x = points[0][0];
let y = points[0][1];
context.moveTo(x, y);
for (let i = 1; i < points.length; i++) {
const p1 = points[i];
const p2 = points[i + 1] || p1;
const x1 = (p1[0] + p2[0]) / 2;
const y1 = (p1[1] + p2[1]) / 2;
context.quadraticCurveTo(p1[0], p1[1], x1, y1);
x = x1;
y = y1;
}
};
const drawLine = (list: number[], offset: number) => {
const points = list.map((y, i) => [
(dx * (i - 1) - offset) | 0,
countY(y),
]);
context.moveTo(points[0][0], points[0][1]);
for (let i = 1; i < points.length; i++) {
const p = points[i];
context.lineTo(p[0], p[1]);
}
};
const drawGraph = (lastTime: number) => {
const listUp = listRef.current.map((v) => v.up);
const listDown = listRef.current.map((v) => v.down);
const lineStyle = styleRef.current;
const now = Date.now();
const diff = now - lastTime;
const temp = Math.min((diff / 1000) * dx + countRef.current, dx);
const offset = countRef.current === 0 ? 0 : temp;
countRef.current = temp;
context.clearRect(0, 0, width, height);
// Reference lines
context.beginPath();
context.globalAlpha = refLineAlpha;
context.lineWidth = refLineWidth;
context.strokeStyle = refLineColor;
context.moveTo(0, l1);
context.lineTo(width, l1);
context.moveTo(0, l2);
context.lineTo(width, l2);
context.stroke();
context.closePath();
context.beginPath();
context.globalAlpha = upLineAlpha;
context.lineWidth = upLineWidth;
context.strokeStyle = upLineColor;
lineStyle ? drawBezier(listUp, offset) : drawLine(listUp, offset);
context.stroke();
context.closePath();
context.beginPath();
context.globalAlpha = downLineAlpha;
context.lineWidth = downLineWidth;
context.strokeStyle = downLineColor;
lineStyle ? drawBezier(listDown, offset) : drawLine(listDown, offset);
context.stroke();
context.closePath();
raf = requestAnimationFrame(() => drawGraph(now));
};
drawGraph(Date.now());
return () => {
cancelAnimationFrame(raf);
};
}, [palette]);
return <canvas ref={canvasRef} style={{ width: "100%", height: "100%" }} />;
};
export default TrafficGraph;
+3 -1
View File
@@ -32,7 +32,9 @@ const UpdateButton = (props: Props) => {
New
</Button>
<UpdateDialog open={dialogOpen} onClose={() => setDialogOpen(false)} />
{dialogOpen && (
<UpdateDialog open={dialogOpen} onClose={() => setDialogOpen(false)} />
)}
</>
);
};
+33 -16
View File
@@ -1,16 +1,20 @@
import useSWR from "swr";
import { useState } from "react";
import snarkdown from "snarkdown";
import { useMemo } from "react";
import { useRecoilState } from "recoil";
import { useTranslation } from "react-i18next";
import {
Box,
Button,
Dialog,
DialogActions,
DialogContent,
DialogContentText,
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 {
@@ -18,49 +22,62 @@ interface Props {
onClose: () => void;
}
let uploadingState = false;
const UpdateLog = styled(Box)(() => ({
"h1,h2,h3,ul,ol,p": { margin: "0.5em 0", color: "inherit" },
}));
const UpdateDialog = (props: Props) => {
const { open, onClose } = props;
const { t } = useTranslation();
const { data: updateInfo } = useSWR("checkUpdate", checkUpdate, {
errorRetryCount: 2,
revalidateIfStale: false,
focusThrottleInterval: 36e5, // 1 hour
});
const [uploading, setUploading] = useState(uploadingState);
const [updateState, setUpdateState] = useRecoilState(atomUpdateState);
const onUpdate = async () => {
setUploading(true);
uploadingState = true;
if (updateState) return;
setUpdateState(true);
try {
await killSidecars();
await installUpdate();
await relaunch();
} catch (err: any) {
await restartSidecar();
Notice.error(err?.message || err.toString());
} finally {
setUploading(false);
uploadingState = false;
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" }}>
<DialogContentText>{updateInfo?.manifest?.body}</DialogContentText>
<UpdateLog dangerouslySetInnerHTML={{ __html: parseContent }} />
</DialogContent>
<DialogActions>
<Button onClick={onClose}>Cancel</Button>
<Button variant="outlined" onClick={onClose}>
{t("Cancel")}
</Button>
<Button
variant="contained"
autoFocus
variant="contained"
disabled={updateState}
onClick={onUpdate}
disabled={uploading}
>
Update
{t("Update")}
</Button>
</DialogActions>
</Dialog>
+103
View File
@@ -0,0 +1,103 @@
import useSWR from "swr";
import { useEffect, useMemo } from "react";
import { useRecoilState } from "recoil";
import { createTheme } from "@mui/material";
import { appWindow } from "@tauri-apps/api/window";
import { getVergeConfig } from "@/services/cmds";
import { atomThemeMode } from "@/services/states";
import { defaultTheme, defaultDarkTheme } from "@/pages/_theme";
/**
* custome theme
*/
export default function useCustomTheme() {
const { data } = useSWR("getVergeConfig", getVergeConfig);
const { theme_mode, theme_setting } = data ?? {};
const [mode, setMode] = useRecoilState(atomThemeMode);
useEffect(() => {
const themeMode = ["light", "dark", "system"].includes(theme_mode!)
? theme_mode!
: "light";
if (themeMode !== "system") {
setMode(themeMode);
return;
}
appWindow.theme().then((m) => m && setMode(m));
const unlisten = appWindow.onThemeChanged((e) => setMode(e.payload));
return () => {
unlisten.then((fn) => fn());
};
}, [theme_mode]);
const theme = useMemo(() => {
const setting = theme_setting || {};
const dt = mode === "light" ? defaultTheme : defaultDarkTheme;
const theme = createTheme({
breakpoints: {
values: { xs: 0, sm: 650, md: 900, lg: 1200, xl: 1536 },
},
palette: {
mode,
primary: { main: setting.primary_color || dt.primary_color },
secondary: { main: setting.secondary_color || dt.secondary_color },
info: { main: setting.info_color || dt.info_color },
error: { main: setting.error_color || dt.error_color },
warning: { main: setting.warning_color || dt.warning_color },
success: { main: setting.success_color || dt.success_color },
text: {
primary: setting.primary_text || dt.primary_text,
secondary: setting.secondary_text || dt.secondary_text,
},
},
typography: {
// todo
fontFamily: setting.font_family
? `${setting.font_family}, ${dt.font_family}`
: dt.font_family,
},
});
// css
const selectColor = mode === "light" ? "#f5f5f5" : "#d5d5d5";
const scrollColor = mode === "light" ? "#90939980" : "#54545480";
const rootEle = document.documentElement;
rootEle.style.setProperty("--selection-color", selectColor);
rootEle.style.setProperty("--scroller-color", scrollColor);
rootEle.style.setProperty("--primary-main", theme.palette.primary.main);
// inject css
let style = document.querySelector("style#verge-theme");
if (!style) {
style = document.createElement("style");
style.id = "verge-theme";
document.head.appendChild(style!);
}
if (style) {
style.innerHTML = setting.css_injection || "";
}
// update svg icon
const { palette } = theme;
setTimeout(() => {
const dom = document.querySelector("#Gradient2");
if (dom) {
dom.innerHTML = `
<stop offset="0%" stop-color="${palette.primary.main}" />
<stop offset="80%" stop-color="${palette.primary.dark}" />
<stop offset="100%" stop-color="${palette.primary.dark}" />
`;
}
}, 0);
return theme;
}, [mode, theme_setting]);
return { theme };
}
+22 -23
View File
@@ -1,20 +1,24 @@
import dayjs from "dayjs";
import { useEffect } from "react";
import { useSetRecoilState } from "recoil";
import { useEffect, useState } from "react";
import { useRecoilValue, 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";
import { getInformation } from "@/services/api";
import { getClashLogs } from "@/services/cmds";
import { atomEnableLog, atomLogData } from "@/services/states";
const MAX_LOG_NUM = 1000;
// setup the log websocket
export default function useLogSetup() {
const [refresh, setRefresh] = useState({});
const enableLog = useRecoilValue(atomEnableLog);
const setLogData = useSetRecoilState(atomLogData);
useEffect(() => {
let ws: WebSocket = null!;
let unlisten: () => void = null!;
if (!enableLog) return;
getClashLogs().then(setLogData);
const handler = (event: MessageEvent<any>) => {
const data = JSON.parse(event.data) as ApiType.LogItem;
@@ -25,25 +29,20 @@ export default function useLogSetup() {
});
};
(async () => {
const { server = "", secret = "" } = await getInfomation();
ws = new WebSocket(`ws://${server}/logs?token=${secret}`);
const ws = getInformation().then((info) => {
const { server = "", secret = "" } = info;
const ws = new WebSocket(`ws://${server}/logs?token=${secret}`);
ws.addEventListener("message", handler);
return ws;
});
// reconnect the websocket
unlisten = await listen("restart_clash", async () => {
const { server = "", secret = "" } = await getInfomation();
ws?.close();
ws = new WebSocket(`ws://${server}/logs?token=${secret}`);
ws.addEventListener("message", handler);
});
})();
const unlisten = listen("verge://refresh-clash-config", () =>
setRefresh({})
);
return () => {
ws?.close();
unlisten?.();
ws.then((ws) => ws?.close());
unlisten.then((fn) => fn());
};
}, []);
}, [refresh, enableLog]);
}
-146
View File
@@ -1,146 +0,0 @@
import { useRef } from "react";
const minPoint = 10;
const maxPoint = 36;
const refLineAlpha = 0.5;
const refLineWidth = 2;
const refLineColor = "#ccc";
const upLineAlpha = 0.6;
const upLineWidth = 4;
const upLineColor = "#9c27b0";
const downLineAlpha = 1;
const downLineWidth = 4;
const downLineColor = "#5b5c9d";
/**
* draw the traffic graph
*/
export default function useTrafficGraph() {
type TrafficData = { up: number; down: number };
const listRef = useRef<TrafficData[]>([]);
const styleRef = useRef(true);
const canvasRef = useRef<HTMLCanvasElement>(null!);
const drawGraph = () => {
const canvas = canvasRef.current!;
if (!canvas) return;
const context = canvas.getContext("2d")!;
const width = canvas.width;
const height = canvas.height;
const l1 = height * 0.2;
const l2 = height * 0.6;
const dl = height * 0.4;
context.clearRect(0, 0, width, height);
// Reference lines
context.beginPath();
context.globalAlpha = refLineAlpha;
context.lineWidth = refLineWidth;
context.strokeStyle = refLineColor;
context.moveTo(0, l1);
context.lineTo(width, l1);
context.moveTo(0, l2);
context.lineTo(width, l2);
context.stroke();
context.closePath();
const countY = (value: number) => {
let v = value;
if (v < 1024) v = (v / 1024) * dl;
else if (v < 1048576) v = dl + (v / 1048576) * dl;
else v = 2 * dl + (v / 10485760) * l1;
return height - v;
};
const drawBezier = (list: number[]) => {
const len = list.length;
const size = Math.min(Math.max(len, minPoint), maxPoint);
const axis = width / size;
let lx = 0;
let ly = height;
let llx = 0;
let lly = height;
list.forEach((val, index) => {
const x = (axis * index) | 0;
const y = countY(val);
const s = 0.25;
if (index === 0) context.moveTo(x, y);
else {
let nx = (axis * (index + 1)) | 0;
let ny = index < len - 1 ? countY(list[index + 1]) | 0 : 0;
const ax = (lx + (x - llx) * s) | 0;
const ay = (ly + (y - lly) * s) | 0;
const bx = (x - (nx - lx) * s) | 0;
const by = (y - (ny - ly) * s) | 0;
context.bezierCurveTo(ax, ay, bx, by, x, y);
}
llx = lx;
lly = ly;
lx = x;
ly = y;
});
};
const drawLine = (list: number[]) => {
const len = list.length;
const size = Math.min(Math.max(len, minPoint), maxPoint);
const axis = width / size;
list.forEach((val, index) => {
const x = (axis * index) | 0;
const y = countY(val);
if (index === 0) context.moveTo(x, y);
else context.lineTo(x, y);
});
};
const listUp = listRef.current.map((v) => v.up);
const listDown = listRef.current.map((v) => v.down);
const lineStyle = styleRef.current;
context.beginPath();
context.globalAlpha = upLineAlpha;
context.lineWidth = upLineWidth;
context.strokeStyle = upLineColor;
lineStyle ? drawLine(listUp) : drawBezier(listUp);
context.stroke();
context.closePath();
context.beginPath();
context.globalAlpha = downLineAlpha;
context.lineWidth = downLineWidth;
context.strokeStyle = downLineColor;
lineStyle ? drawLine(listDown) : drawBezier(listDown);
context.stroke();
context.closePath();
};
const appendData = (data: TrafficData) => {
const list = listRef.current;
if (list.length > maxPoint) list.shift();
list.push(data);
drawGraph();
};
const toggleStyle = () => {
styleRef.current = !styleRef.current;
drawGraph();
};
return {
canvasRef,
appendData,
toggleStyle,
};
}
+2 -1
View File
@@ -1,11 +1,12 @@
import { styled, Box } from "@mui/material";
import { ApiType } from "../../services/types";
const Item = styled(Box)(({ theme }) => ({
padding: "8px 0",
margin: "0 12px",
lineHeight: 1.35,
borderBottom: `1px solid ${theme.palette.divider}`,
fontSize: "0.875rem",
userSelect: "text",
"& .time": {},
"& .type": {
display: "inline-block",
+129
View File
@@ -0,0 +1,129 @@
import useSWR from "swr";
import { useLockFn } from "ahooks";
import { useTranslation } from "react-i18next";
import { Box, Grid, IconButton, Stack } from "@mui/material";
import { RestartAltRounded } from "@mui/icons-material";
import {
getProfiles,
deleteProfile,
enhanceProfiles,
changeProfileChain,
getRuntimeLogs,
} from "@/services/cmds";
import ProfileMore from "./profile-more";
import Notice from "../base/base-notice";
interface Props {
items: CmdType.ProfileItem[];
chain: string[];
}
const EnhancedMode = (props: Props) => {
const { items, chain } = props;
const { t } = useTranslation();
const { mutate: mutateProfiles } = useSWR("getProfiles", getProfiles);
const { data: chainLogs = {}, mutate: mutateLogs } = useSWR(
"getRuntimeLogs",
getRuntimeLogs
);
// handler
const onEnhance = useLockFn(async () => {
try {
await enhanceProfiles();
mutateLogs();
// Notice.success("Refresh clash config", 1000);
} catch (err: any) {
Notice.error(err.message || err.toString());
}
});
const onEnhanceEnable = useLockFn(async (uid: string) => {
if (chain.includes(uid)) return;
const newChain = [...chain, uid];
await changeProfileChain(newChain);
mutateProfiles((conf = {}) => ({ ...conf, chain: newChain }), true);
mutateLogs();
});
const onEnhanceDisable = useLockFn(async (uid: string) => {
if (!chain.includes(uid)) return;
const newChain = chain.filter((i) => i !== uid);
await changeProfileChain(newChain);
mutateProfiles((conf = {}) => ({ ...conf, chain: newChain }), true);
mutateLogs();
});
const onEnhanceDelete = useLockFn(async (uid: string) => {
try {
await onEnhanceDisable(uid);
await deleteProfile(uid);
mutateProfiles();
mutateLogs();
} 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);
mutateProfiles((conf = {}) => ({ ...conf, chain: newChain }), true);
mutateLogs();
});
const onMoveEnd = useLockFn(async (uid: string) => {
if (!chain.includes(uid)) return;
const newChain = chain.filter((i) => i !== uid).concat([uid]);
await changeProfileChain(newChain);
mutateProfiles((conf = {}) => ({ ...conf, chain: newChain }), true);
mutateLogs();
});
return (
<Box sx={{ mt: 2 }}>
<Stack
spacing={1}
direction="row"
alignItems="center"
justifyContent="flex-end"
sx={{ mb: 0.5 }}
>
<IconButton
size="small"
color="inherit"
title={t("Refresh profiles")}
onClick={onEnhance}
>
<RestartAltRounded />
</IconButton>
</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}
logInfo={chainLogs[item.uid]}
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;
+96
View File
@@ -0,0 +1,96 @@
import { useEffect, useRef } from "react";
import { useLockFn } from "ahooks";
import { useRecoilValue } from "recoil";
import { useTranslation } from "react-i18next";
import {
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
} from "@mui/material";
import { atomThemeMode } from "@/services/states";
import { 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 themeMode = useRecoilValue(atomThemeMode);
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: themeMode === "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} variant="outlined">
{t("Cancel")}
</Button>
<Button onClick={onSave} variant="contained">
{t("Save")}
</Button>
</DialogActions>
</Dialog>
);
};
export default FileEditor;
+63
View File
@@ -0,0 +1,63 @@
import { useRef, useState } from "react";
import { useLockFn } from "ahooks";
import { useTranslation } from "react-i18next";
import { Box, Button, Typography } from "@mui/material";
interface Props {
onChange: (value: string) => void;
}
const FileInput = (props: Props) => {
const { onChange } = props;
const { t } = useTranslation();
// 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()}
>
{t("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;
+165
View File
@@ -0,0 +1,165 @@
import { mutate } from "swr";
import { useEffect, useState } from "react";
import { useLockFn, useSetState } from "ahooks";
import { useTranslation } from "react-i18next";
import {
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
IconButton,
TextField,
} from "@mui/material";
import { Settings } from "@mui/icons-material";
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 InfoEditor = (props: Props) => {
const { open, itemData, onClose } = props;
const { t } = useTranslation();
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.type === "remote" &&
(!!itemData.option?.user_agent || !!itemData.option?.update_interval)
);
}
}, [itemData]);
const onUpdate = useLockFn(async () => {
try {
const { uid } = itemData;
const { name, desc, url } = form;
const option_ =
itemData.type === "remote" || itemData.type === "local"
? 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_ });
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 }}>{t("Edit Info")}</DialogTitle>
<DialogContent sx={{ width: 336, pb: 1 }}>
<TextField
{...textFieldProps}
disabled
label={t("Type")}
value={type}
sx={{ input: { textTransform: "capitalize" } }}
/>
<TextField
{...textFieldProps}
autoFocus
label={t("Name")}
value={form.name}
onChange={(e) => setForm({ name: e.target.value })}
onKeyDown={(e) => e.key === "Enter" && onUpdate()}
/>
<TextField
{...textFieldProps}
label={t("Descriptions")}
value={form.desc}
onChange={(e) => setForm({ desc: e.target.value })}
onKeyDown={(e) => e.key === "Enter" && onUpdate()}
/>
{type === "remote" && (
<TextField
{...textFieldProps}
label={t("Subscription URL")}
value={form.url}
onChange={(e) => setForm({ url: e.target.value })}
onKeyDown={(e) => e.key === "Enter" && onUpdate()}
/>
)}
{showOpt && (
<TextField
{...textFieldProps}
label="User Agent"
value={option.user_agent}
placeholder="clash-verge/v1.0.0"
onChange={(e) => setOption({ user_agent: e.target.value })}
onKeyDown={(e) => e.key === "Enter" && onUpdate()}
/>
)}
{((type === "remote" && showOpt) || type === "local") && (
<TextField
{...textFieldProps}
label={t("Update Interval(mins)")}
value={option.update_interval}
onChange={(e) => {
const str = e.target.value?.replace(/\D/, "");
setOption({ update_interval: !!str ? +str : undefined });
}}
onKeyDown={(e) => e.key === "Enter" && onUpdate()}
/>
)}
</DialogContent>
<DialogActions sx={{ px: 2, pb: 2, position: "relative" }}>
{form.type === "remote" && (
<IconButton
size="small"
color="inherit"
sx={{ position: "absolute", left: 18 }}
onClick={() => setShowOpt((o) => !o)}
>
<Settings />
</IconButton>
)}
<Button onClick={onClose} variant="outlined">
{t("Cancel")}
</Button>
<Button onClick={onUpdate} variant="contained">
{t("Save")}
</Button>
</DialogActions>
</Dialog>
);
};
export default InfoEditor;
+71
View File
@@ -0,0 +1,71 @@
import { useTranslation } from "react-i18next";
import {
Button,
Chip,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
Divider,
Typography,
} from "@mui/material";
import BaseEmpty from "../base/base-empty";
import { Fragment } from "react";
interface Props {
open: boolean;
logInfo: [string, string][];
onClose: () => void;
}
const LogViewer = (props: Props) => {
const { open, logInfo, onClose } = props;
const { t } = useTranslation();
return (
<Dialog open={open} onClose={onClose}>
<DialogTitle>{t("Script Console")}</DialogTitle>
<DialogContent
sx={{
width: 400,
height: 300,
overflowX: "hidden",
userSelect: "text",
pb: 1,
}}
>
{logInfo.map(([level, log], index) => (
<Fragment key={index.toString()}>
<Typography color="text.secondary" component="div">
<Chip
label={level}
size="small"
variant="outlined"
color={
level === "error" || level === "exception"
? "error"
: "default"
}
sx={{ mr: 1 }}
/>
{log}
</Typography>
<Divider sx={{ my: 0.5 }} />
</Fragment>
))}
{logInfo.length === 0 && <BaseEmpty />}
</DialogContent>
<DialogActions>
<Button onClick={onClose} variant="outlined">
{t("Back")}
</Button>
</DialogActions>
</Dialog>
);
};
export default LogViewer;
+43
View File
@@ -0,0 +1,43 @@
import { alpha, Box, styled } from "@mui/material";
const ProfileBox = styled(Box)(({ theme, "aria-selected": selected }) => {
const { mode, primary, text, grey, background } = theme.palette;
const key = `${mode}-${!!selected}`;
const backgroundColor = {
"light-true": alpha(primary.main, 0.2),
"light-false": alpha(background.paper, 0.75),
"dark-true": alpha(primary.main, 0.45),
"dark-false": alpha(grey[700], 0.45),
}[key]!;
const color = {
"light-true": text.secondary,
"light-false": text.secondary,
"dark-true": alpha(text.secondary, 0.85),
"dark-false": alpha(text.secondary, 0.65),
}[key]!;
const h2color = {
"light-true": primary.main,
"light-false": text.primary,
"dark-true": primary.light,
"dark-false": text.primary,
}[key]!;
return {
width: "100%",
display: "block",
cursor: "pointer",
textAlign: "left",
borderRadius: theme.shape.borderRadius,
boxShadow: theme.shadows[2],
padding: "8px 16px",
boxSizing: "border-box",
backgroundColor,
color,
"& h2": { color: h2color },
};
});
export default ProfileBox;
-104
View File
@@ -1,104 +0,0 @@
import { mutate } from "swr";
import { useEffect } from "react";
import { useLockFn, useSetState } from "ahooks";
import {
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
TextField,
} from "@mui/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
const ProfileEdit = (props: Props) => {
const { open, itemData, onClose } = props;
const [form, setForm] = useSetState({ ...itemData });
useEffect(() => {
if (itemData) {
setForm({ ...itemData });
}
}, [itemData]);
const onUpdate = useLockFn(async () => {
try {
const { uid } = itemData;
const { name, desc, url } = form;
await patchProfile(uid, { uid, name, desc, url });
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 })}
/>
)}
</DialogContent>
<DialogActions sx={{ px: 2, pb: 2 }}>
<Button onClick={onClose}>Cancel</Button>
<Button onClick={onUpdate} variant="contained">
Update
</Button>
</DialogActions>
</Dialog>
);
};
export default ProfileEdit;
+136 -131
View File
@@ -1,11 +1,11 @@
import dayjs from "dayjs";
import { useLockFn } from "ahooks";
import { useSWRConfig } from "swr";
import { mutate } from "swr";
import { useEffect, useState } from "react";
import { useLockFn } from "ahooks";
import { useRecoilState } from "recoil";
import { useTranslation } from "react-i18next";
import {
alpha,
Box,
styled,
Typography,
LinearProgress,
IconButton,
@@ -14,34 +14,19 @@ import {
Menu,
} from "@mui/material";
import { RefreshRounded } from "@mui/icons-material";
import { CmdType } from "../../services/types";
import { updateProfile, deleteProfile, viewProfile } from "../../services/cmds";
import relativeTime from "dayjs/plugin/relativeTime";
import parseTraffic from "../../utils/parse-traffic";
import ProfileEdit from "./profile-edit";
import { atomLoadingCache } from "@/services/states";
import { updateProfile, deleteProfile, viewProfile } from "@/services/cmds";
import parseTraffic from "@/utils/parse-traffic";
import ProfileBox from "./profile-box";
import InfoEditor from "./info-editor";
import FileEditor from "./file-editor";
import Notice from "../base/base-notice";
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); }
`;
// save the state of each item loading
const loadingCache: Record<string, boolean> = {};
interface Props {
selected: boolean;
itemData: CmdType.ProfileItem;
@@ -51,41 +36,64 @@ interface Props {
const ProfileItem = (props: Props) => {
const { selected, itemData, onSelect } = props;
const { mutate } = useSWRConfig();
const [loading, setLoading] = useState(loadingCache[itemData.uid] ?? false);
const { t } = useTranslation();
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;
// local file mode
// remote file mode
const hasUrl = !!itemData.url;
const hasExtra = !!extra; // only subscription url has extra info
const { name = "Profile", extra, updated = 0 } = itemData;
const { upload = 0, download = 0, total = 0 } = extra ?? {};
const from = parseUrl(itemData.url);
const expire = parseExpire(extra?.expire);
const progress = Math.round(((download + upload) * 100) / (total + 0.1));
const fromnow = updated > 0 ? dayjs(updated * 1000).fromNow() : "";
// local file mode
// remote file mode
// subscription url mode
const hasUrl = !!itemData.url;
const hasExtra = !!extra; // only subscription url has extra info
const loading = loadingCache[itemData.uid] ?? false;
// interval update from now field
const [, setRefresh] = useState({});
useEffect(() => {
loadingCache[itemData.uid] = loading;
}, [itemData, loading]);
if (!hasUrl) return;
let timer: any = null;
const handler = () => {
const now = Date.now();
const lastUpdate = updated * 1000;
// 大于一天的不管
if (now - lastUpdate >= 24 * 36e5) return;
const wait = now - lastUpdate >= 36e5 ? 30e5 : 5e4;
timer = setTimeout(() => {
setRefresh({});
handler();
}, wait);
};
handler();
return () => {
if (timer) clearTimeout(timer);
};
}, [hasUrl, updated]);
const [editOpen, setEditOpen] = useState(false);
const onEdit = () => {
const [fileOpen, setFileOpen] = useState(false);
const onEditInfo = () => {
setAnchorEl(null);
setEditOpen(true);
};
const onView = async () => {
const onEditFile = () => {
setAnchorEl(null);
try {
await viewProfile(itemData.uid);
} catch (err: any) {
Notice.error(err?.message || err.toString());
}
setFileOpen(true);
};
const onForceSelect = () => {
@@ -93,19 +101,31 @@ const ProfileItem = (props: Props) => {
onSelect(true);
};
const onUpdateWrapper = (withProxy: boolean) => async () => {
const onOpenFile = useLockFn(async () => {
setAnchorEl(null);
if (loading) return;
setLoading(true);
try {
await updateProfile(itemData.uid, withProxy);
setLoading(false);
mutate("getProfiles");
await viewProfile(itemData.uid);
} catch (err: any) {
setLoading(false);
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) {
const errmsg = err?.message || err.toString();
Notice.error(
errmsg.replace(/error sending request for url (\S+?): /, "")
);
} finally {
setLoadingCache((cache) => ({ ...cache, [itemData.uid]: false }));
}
});
const onDelete = useLockFn(async () => {
setAnchorEl(null);
@@ -117,6 +137,23 @@ const ProfileItem = (props: Props) => {
}
});
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 },
];
const boxStyle = {
height: 26,
display: "flex",
@@ -124,51 +161,10 @@ const ProfileItem = (props: Props) => {
justifyContent: "space-between",
};
const urlModeMenu = [
{ label: "Select", handler: onForceSelect },
{ label: "Edit", handler: onEdit },
{ label: "File", handler: onView },
{ label: "Update", handler: onUpdateWrapper(false) },
{ label: "Update(Proxy)", handler: onUpdateWrapper(true) },
{ label: "Delete", handler: onDelete },
];
const fileModeMenu = [
{ label: "Select", handler: onForceSelect },
{ label: "Edit", handler: onEdit },
{ label: "File", handler: onView },
{ label: "Delete", handler: onDelete },
];
return (
<>
<Wrapper
sx={({ palette }) => {
const { mode, primary, text, grey } = palette;
const key = `${mode}-${selected}`;
const bgcolor = {
"light-true": alpha(primary.main, 0.15),
"light-false": palette.background.paper,
"dark-true": alpha(primary.main, 0.35),
"dark-false": alpha(grey[700], 0.35),
}[key]!;
const color = {
"light-true": text.secondary,
"light-false": text.secondary,
"dark-true": alpha(text.secondary, 0.6),
"dark-false": alpha(text.secondary, 0.6),
}[key]!;
const h2color = {
"light-true": primary.main,
"light-false": text.primary,
"dark-true": primary.light,
"dark-false": text.primary,
}[key]!;
return { bgcolor, color, "& h2": { color: h2color } };
}}
<ProfileBox
aria-selected={selected}
onClick={() => onSelect(false)}
onContextMenu={(event) => {
const { clientX, clientY } = event;
@@ -177,9 +173,9 @@ const ProfileItem = (props: Props) => {
event.preventDefault();
}}
>
<Box display="flex" justifyContent="space-between">
<Box position="relative">
<Typography
width="calc(100% - 40px)"
width="calc(100% - 36px)"
variant="h6"
component="h2"
noWrap
@@ -192,58 +188,61 @@ const ProfileItem = (props: Props) => {
{hasUrl && (
<IconButton
sx={{
width: 26,
height: 26,
position: "absolute",
p: "3px",
top: -1,
right: -5,
animation: loading ? `1s linear infinite ${round}` : "none",
}}
size="small"
color="inherit"
disabled={loading}
onClick={(e) => {
e.stopPropagation();
onUpdateWrapper(false)();
onUpdate(false);
}}
>
<RefreshRounded />
<RefreshRounded color="inherit" />
</IconButton>
)}
</Box>
{/* the second line show url's info or description */}
{hasUrl ? (
<Box sx={boxStyle}>
<Typography noWrap title={`From: ${from}`}>
{from}
</Typography>
<Box sx={boxStyle}>
{hasUrl ? (
<>
<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
flex="1 0 auto"
fontSize={14}
textAlign="right"
title={`Updated Time: ${parseExpire(updated)}`}
>
{updated > 0 ? dayjs(updated * 1000).fromNow() : ""}
</Typography>
</>
) : (
<Typography noWrap title={itemData.desc}>
{itemData.desc}
</Typography>
</Box>
)}
)}
</Box>
{/* the third line show extra info or last updated time */}
{hasExtra ? (
<Box sx={{ ...boxStyle, fontSize: 14 }}>
<span title="used / total">
<span title="Used / Total">
{parseTraffic(upload + download)} / {parseTraffic(total)}
</span>
<span title="expire time">{expire}</span>
<span title="Expire Time">{expire}</span>
</Box>
) : (
<Box sx={{ ...boxStyle, fontSize: 14, justifyContent: "flex-end" }}>
<span title="updated time">{parseExpire(updated)}</span>
<span title="Updated Time">{parseExpire(updated)}</span>
</Box>
)}
@@ -252,7 +251,7 @@ const ProfileItem = (props: Props) => {
value={progress}
color="inherit"
/>
</Wrapper>
</ProfileBox>
<Menu
open={!!anchorEl}
@@ -260,6 +259,7 @@ const ProfileItem = (props: Props) => {
onClose={() => setAnchorEl(null)}
anchorPosition={position}
anchorReference="anchorPosition"
transitionDuration={225}
onContextMenu={(e) => {
setAnchorEl(null);
e.preventDefault();
@@ -271,18 +271,23 @@ const ProfileItem = (props: Props) => {
onClick={item.handler}
sx={{ minWidth: 133 }}
>
{item.label}
{t(item.label)}
</MenuItem>
))}
</Menu>
{editOpen && (
<ProfileEdit
open={editOpen}
itemData={itemData}
onClose={() => setEditOpen(false)}
/>
)}
<InfoEditor
open={editOpen}
itemData={itemData}
onClose={() => setEditOpen(false)}
/>
<FileEditor
uid={uid}
open={fileOpen}
mode="yaml"
onClose={() => setFileOpen(false)}
/>
</>
);
};
+103 -99
View File
@@ -1,43 +1,34 @@
import dayjs from "dayjs";
import { useEffect, useState } from "react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useLockFn } from "ahooks";
import {
alpha,
Box,
Badge,
Chip,
styled,
Typography,
MenuItem,
Menu,
IconButton,
} from "@mui/material";
import { CmdType } from "../../services/types";
import { viewProfile } from "../../services/cmds";
import relativeTime from "dayjs/plugin/relativeTime";
import ProfileEdit from "./profile-edit";
import { FeaturedPlayListRounded } from "@mui/icons-material";
import { viewProfile } from "@/services/cmds";
import InfoEditor from "./info-editor";
import FileEditor from "./file-editor";
import ProfileBox from "./profile-box";
import LogViewer from "./log-viewer";
import Notice from "../base/base-notice";
import enhance from "../../services/enhance";
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",
}));
interface Props {
selected: boolean;
itemData: CmdType.ProfileItem;
enableNum: number;
logInfo?: [string, string][];
onEnable: () => void;
onDisable: () => void;
onMoveTop: () => void;
onMoveEnd: () => void;
onDelete: () => void;
onEnhance: () => void;
}
// profile enhanced item
@@ -45,60 +36,66 @@ const ProfileMore = (props: Props) => {
const {
selected,
itemData,
enableNum,
logInfo = [],
onEnable,
onDisable,
onMoveTop,
onMoveEnd,
onDelete,
onEnhance,
} = props;
const { uid, type } = itemData;
const { t, i18n } = useTranslation();
const [anchorEl, setAnchorEl] = useState<any>(null);
const [position, setPosition] = useState({ left: 0, top: 0 });
const [editOpen, setEditOpen] = useState(false);
const [status, setStatus] = useState(enhance.status(uid));
const [fileOpen, setFileOpen] = useState(false);
const [logOpen, setLogOpen] = useState(false);
// unlisten when unmount
useEffect(() => enhance.listen(uid, setStatus), [uid]);
// error during enhanced mode
const hasError = selected && status?.status === "error";
const onEdit = () => {
const onEditInfo = () => {
setAnchorEl(null);
setEditOpen(true);
};
const onView = async () => {
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 closeWrapper = (fn: () => void) => () => {
const fnWrapper = (fn: () => void) => () => {
setAnchorEl(null);
return fn();
};
const hasError = !!logInfo.find((e) => e[0] === "exception");
const showMove = enableNum > 1 && !hasError;
const enableMenu = [
{ label: "Disable", handler: closeWrapper(onDisable) },
{ label: "Refresh", handler: closeWrapper(onEnhance) },
{ label: "Edit", handler: onEdit },
{ label: "File", handler: onView },
{ label: "To Top", show: !hasError, handler: closeWrapper(onMoveTop) },
{ label: "To End", show: !hasError, handler: closeWrapper(onMoveEnd) },
{ label: "Delete", handler: closeWrapper(onDelete) },
{ 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: closeWrapper(onEnable) },
{ label: "Edit", handler: onEdit },
{ label: "File", handler: onView },
{ label: "Delete", handler: closeWrapper(onDelete) },
{ 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 = {
@@ -111,39 +108,9 @@ const ProfileMore = (props: Props) => {
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 } };
}}
<ProfileBox
aria-selected={selected}
onDoubleClick={onEditFile}
// onClick={() => onSelect(false)}
onContextMenu={(event) => {
const { clientX, clientY } = event;
@@ -152,7 +119,12 @@ const ProfileMore = (props: Props) => {
event.preventDefault();
}}
>
<Box display="flex" justifyContent="space-between" alignItems="center">
<Box
display="flex"
justifyContent="space-between"
alignItems="center"
mb={0.5}
>
<Typography
width="calc(100% - 52px)"
variant="h6"
@@ -168,39 +140,57 @@ const ProfileMore = (props: Props) => {
color="primary"
size="small"
variant="outlined"
sx={{ textTransform: "capitalize" }}
sx={{ height: 20, textTransform: "capitalize" }}
/>
</Box>
<Box sx={boxStyle}>
{hasError ? (
<Typography
noWrap
color="error"
sx={{ width: "calc(100% - 75px)" }}
title={status.message}
>
{status.message}
</Typography>
{selected && type === "script" ? (
hasError ? (
<Badge color="error" variant="dot" overlap="circular">
<IconButton
size="small"
edge="start"
color="error"
title="Console"
onClick={() => setLogOpen(true)}
>
<FeaturedPlayListRounded fontSize="inherit" />
</IconButton>
</Badge>
) : (
<IconButton
size="small"
edge="start"
color="inherit"
title="Console"
onClick={() => setLogOpen(true)}
>
<FeaturedPlayListRounded fontSize="inherit" />
</IconButton>
)
) : (
<Typography
noWrap
title={itemData.desc}
sx={{ width: "calc(100% - 75px)" }}
sx={i18n.language === "zh" ? { width: "calc(100% - 75px)" } : {}}
>
{itemData.desc}
</Typography>
)}
<Typography
noWrap
component="span"
title="updated time"
title={`Updated Time: ${parseExpire(itemData.updated)}`}
style={{ fontSize: 14 }}
>
{parseExpire(itemData.updated)}
{!!itemData.updated
? dayjs(itemData.updated! * 1000).fromNow()
: ""}
</Typography>
</Box>
</Wrapper>
</ProfileBox>
<Menu
open={!!anchorEl}
@@ -208,6 +198,7 @@ const ProfileMore = (props: Props) => {
onClose={() => setAnchorEl(null)}
anchorPosition={position}
anchorReference="anchorPosition"
transitionDuration={225}
onContextMenu={(e) => {
setAnchorEl(null);
e.preventDefault();
@@ -221,16 +212,29 @@ const ProfileMore = (props: Props) => {
onClick={item.handler}
sx={{ minWidth: 133 }}
>
{item.label}
{t(item.label)}
</MenuItem>
))}
</Menu>
{editOpen && (
<ProfileEdit
open={editOpen}
itemData={itemData}
onClose={() => setEditOpen(false)}
<InfoEditor
open={editOpen}
itemData={itemData}
onClose={() => setEditOpen(false)}
/>
<FileEditor
uid={uid}
open={fileOpen}
mode={type === "merge" ? "yaml" : "javascript"}
onClose={() => setFileOpen(false)}
/>
{selected && (
<LogViewer
open={logOpen}
logInfo={logInfo}
onClose={() => setLogOpen(false)}
/>
)}
</>
+77 -21
View File
@@ -1,4 +1,6 @@
import { useSWRConfig } from "swr";
import { useRef, useState } from "react";
import { mutate } from "swr";
import { useTranslation } from "react-i18next";
import { useLockFn, useSetState } from "ahooks";
import {
Button,
@@ -7,13 +9,16 @@ import {
DialogContent,
DialogTitle,
FormControl,
IconButton,
InputLabel,
MenuItem,
Select,
TextField,
} from "@mui/material";
import { createProfile } from "../../services/cmds";
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;
@@ -25,14 +30,20 @@ interface Props {
const ProfileNew = (props: Props) => {
const { open, onClose } = props;
const { mutate } = useSWRConfig();
const { t } = useTranslation();
const [form, setForm] = useSetState({
type: "remote",
name: "",
desc: "",
type: "remote",
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");
@@ -40,8 +51,23 @@ const ProfileNew = (props: Props) => {
}
try {
await createProfile({ ...form });
setForm({ name: "", desc: "", type: "remote", url: "" });
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) {
@@ -58,21 +84,14 @@ const ProfileNew = (props: Props) => {
return (
<Dialog open={open} onClose={onClose}>
<DialogTitle sx={{ pb: 0.5 }}>Create Profile</DialogTitle>
<DialogTitle sx={{ pb: 0.5 }}>{t("Create Profile")}</DialogTitle>
<DialogContent sx={{ width: 336, pb: 1 }}>
<TextField
{...textFieldProps}
autoFocus
label="Name"
value={form.name}
onChange={(e) => setForm({ name: e.target.value })}
/>
<FormControl size="small" fullWidth sx={{ mt: 2, mb: 1 }}>
<InputLabel>Type</InputLabel>
<Select
label="Type"
autoFocus
label={t("Type")}
value={form.type}
onChange={(e) => setForm({ type: e.target.value })}
>
@@ -85,7 +104,16 @@ const ProfileNew = (props: Props) => {
<TextField
{...textFieldProps}
label="Descriptions"
label={t("Name")}
autoComplete="off"
value={form.name}
onChange={(e) => setForm({ name: e.target.value })}
/>
<TextField
{...textFieldProps}
label={t("Descriptions")}
autoComplete="off"
value={form.desc}
onChange={(e) => setForm({ desc: e.target.value })}
/>
@@ -93,17 +121,45 @@ const ProfileNew = (props: Props) => {
{form.type === "remote" && (
<TextField
{...textFieldProps}
label="Subscription Url"
label={t("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 }}>
<Button onClick={onClose}>Cancel</Button>
<DialogActions sx={{ px: 2, pb: 2, position: "relative" }}>
{form.type === "remote" && (
<IconButton
size="small"
color="inherit"
sx={{ position: "absolute", left: 18 }}
onClick={() => setShowOpt((o) => !o)}
>
<Settings />
</IconButton>
)}
<Button onClick={onClose} variant="outlined">
{t("Cancel")}
</Button>
<Button onClick={onCreate} variant="contained">
Create
{t("Save")}
</Button>
</DialogActions>
</Dialog>
+86 -86
View File
@@ -1,20 +1,14 @@
import useSWR, { useSWRConfig } from "swr";
import { useEffect, useRef, useState } from "react";
import { useSWRConfig } from "swr";
import { useLockFn } from "ahooks";
import { Virtuoso } from "react-virtuoso";
import { Box, IconButton, TextField } from "@mui/material";
import {
MyLocationRounded,
NetworkCheckRounded,
FilterAltRounded,
FilterAltOffRounded,
VisibilityRounded,
VisibilityOffRounded,
} from "@mui/icons-material";
import { ApiType } from "../../services/types";
import { updateProxy } from "../../services/api";
import delayManager from "../../services/delay";
import { providerHealthCheck, updateProxy } from "@/services/api";
import { getProfiles, patchProfile } from "@/services/cmds";
import delayManager from "@/services/delay";
import useSortProxy from "./use-sort-proxy";
import useHeadState from "./use-head-state";
import useFilterProxy from "./use-filter-proxy";
import ProxyHead from "./proxy-head";
import ProxyItem from "./proxy-item";
interface Props {
@@ -23,26 +17,52 @@ interface Props {
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 [showFilter, setShowFilter] = useState(false);
const [filterText, setFilterText] = useState("");
const [headState, setHeadState] = useHeadState(groupName);
const virtuosoRef = useRef<any>();
const filterProxies = useFilterProxy(proxies, groupName, filterText);
const filterProxies = useFilterProxy(
proxies,
groupName,
headState.filterText
);
const sortedProxies = useSortProxy(
filterProxies,
groupName,
headState.sortType
);
const { data: profiles } = useSWR("getProfiles", getProfiles);
const onChangeProxy = useLockFn(async (name: string) => {
await updateProxy("GLOBAL", name);
mutate("getProxies");
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 = filterProxies.findIndex((p) => p.name === now);
const index = sortedProxies.findIndex((p) => p.name === now);
if (index >= 0) {
virtuosoRef.current?.scrollToIndex?.({
@@ -54,90 +74,70 @@ const ProxyGlobal = (props: Props) => {
};
const onCheckAll = useLockFn(async () => {
const names = filterProxies.map((p) => p.name);
await delayManager.checkListDelay(
{ names, groupName, skipNum: 8, maxTimeout: 600 },
() => mutate("getProxies")
const providers = new Set(
sortedProxies.map((p) => p.provider!).filter(Boolean)
);
mutate("getProxies");
if (providers.size) {
Promise.allSettled(
[...providers].map((p) => providerHealthCheck(p))
).then(() => mutate("getProxies"));
}
await delayManager.checkListDelay(
{
names: sortedProxies.filter((p) => !p.provider).map((p) => p.name),
groupName,
skipNum: 16,
},
() => mutate("getProxies")
);
});
useEffect(() => onLocation(false), [groupName]);
useEffect(() => {
if (!showFilter) setFilterText("");
}, [showFilter]);
useEffect(() => {
if (groupName === "DIRECT") setNow("DIRECT");
if (groupName === "GLOBAL") setNow(curProxy || "DIRECT");
}, [groupName, curProxy]);
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 (
<>
<Box
sx={{
px: 3,
my: 0.5,
display: "flex",
alignItems: "center",
button: { mr: 0.5 },
}}
>
<IconButton
size="small"
title="location"
onClick={() => onLocation(true)}
>
<MyLocationRounded />
</IconButton>
<IconButton size="small" title="check" onClick={onCheckAll}>
<NetworkCheckRounded />
</IconButton>
<IconButton
size="small"
title="check"
onClick={() => setShowType(!showType)}
>
{showType ? <VisibilityRounded /> : <VisibilityOffRounded />}
</IconButton>
<IconButton
size="small"
title="check"
onClick={() => setShowFilter(!showFilter)}
>
{showFilter ? <FilterAltRounded /> : <FilterAltOffRounded />}
</IconButton>
{showFilter && (
<TextField
autoFocus
hiddenLabel
value={filterText}
size="small"
variant="outlined"
placeholder="Filter conditions"
onChange={(e) => setFilterText(e.target.value)}
sx={{ ml: 0.5, flex: "1 1 auto", input: { py: 0.65, px: 1 } }}
/>
)}
</Box>
<ProxyHead
sx={{ px: 3, my: 0.5, button: { mr: 0.5 } }}
groupName={groupName}
headState={headState}
onLocation={onLocation}
onCheckDelay={onCheckAll}
onHeadState={setHeadState}
/>
<Virtuoso
ref={virtuosoRef}
style={{ height: "calc(100% - 40px)" }}
totalCount={filterProxies.length}
totalCount={sortedProxies.length}
itemContent={(index) => (
<ProxyItem
groupName={groupName}
proxy={filterProxies[index]}
selected={filterProxies[index].name === now}
showType={showType}
proxy={sortedProxies[index]}
selected={sortedProxies[index].name === now}
showType={headState.showType}
onClick={onChangeProxy}
sx={{ py: 0, px: 2 }}
/>
+61 -95
View File
@@ -6,28 +6,22 @@ import {
Box,
Collapse,
Divider,
IconButton,
List,
ListItem,
ListItemText,
TextField,
} from "@mui/material";
import {
SendRounded,
ExpandLessRounded,
ExpandMoreRounded,
MyLocationRounded,
NetworkCheckRounded,
FilterAltRounded,
FilterAltOffRounded,
VisibilityRounded,
VisibilityOffRounded,
} from "@mui/icons-material";
import { ApiType } from "../../services/types";
import { updateProxy } from "../../services/api";
import { getProfiles, patchProfile } from "../../services/cmds";
import delayManager from "../../services/delay";
import { providerHealthCheck, updateProxy } from "@/services/api";
import { getProfiles, patchProfile } from "@/services/cmds";
import delayManager from "@/services/delay";
import useSortProxy from "./use-sort-proxy";
import useHeadState from "./use-head-state";
import useFilterProxy from "./use-filter-proxy";
import ProxyHead from "./proxy-head";
import ProxyItem from "./proxy-item";
interface Props {
@@ -36,15 +30,21 @@ interface Props {
const ProxyGroup = ({ group }: Props) => {
const { mutate } = useSWRConfig();
const [open, setOpen] = useState(false);
const [now, setNow] = useState(group.now);
const [showType, setShowType] = useState(false);
const [showFilter, setShowFilter] = useState(false);
const [filterText, setFilterText] = useState("");
const proxies = group.all ?? [];
const [headState, setHeadState] = useHeadState(group.name);
const virtuosoRef = useRef<any>();
const filterProxies = useFilterProxy(proxies, group.name, filterText);
const filterProxies = useFilterProxy(
group.all,
group.name,
headState.filterText
);
const sortedProxies = useSortProxy(
filterProxies,
group.name,
headState.sortType
);
const { data: profiles } = useSWR("getProfiles", getProfiles);
@@ -75,14 +75,14 @@ const ProxyGroup = ({ group }: Props) => {
} else {
profile.selected[index] = { name: group.name, now: name };
}
await patchProfile(profiles!.current!, profile);
await patchProfile(profiles!.current!, { selected: profile.selected });
} catch (err) {
console.error(err);
}
});
const onLocation = (smooth = true) => {
const index = filterProxies.findIndex((p) => p.name === now);
const index = sortedProxies.findIndex((p) => p.name === now);
if (index >= 0) {
virtuosoRef.current?.scrollToIndex?.({
@@ -94,31 +94,40 @@ const ProxyGroup = ({ group }: Props) => {
};
const onCheckAll = useLockFn(async () => {
const names = filterProxies.map((p) => p.name);
const groupName = group.name;
await delayManager.checkListDelay(
{ names, groupName, skipNum: 8, maxTimeout: 600 },
() => mutate("getProxies")
const providers = new Set(
sortedProxies.map((p) => p.provider!).filter(Boolean)
);
mutate("getProxies");
});
if (providers.size) {
Promise.allSettled(
[...providers].map((p) => providerHealthCheck(p))
).then(() => mutate("getProxies"));
}
useEffect(() => {
if (!showFilter) setFilterText("");
}, [showFilter]);
await delayManager.checkListDelay(
{
names: sortedProxies.filter((p) => !p.provider).map((p) => p.name),
groupName: group.name,
skipNum: 16,
},
() => mutate("getProxies")
);
});
// auto scroll to current index
useEffect(() => {
if (open) {
if (headState.open) {
setTimeout(() => onLocation(false), 5);
}
}, [open]);
}, [headState.open]);
return (
<>
<ListItem button onClick={() => setOpen(!open)} dense>
<ListItem
button
dense
onClick={() => setHeadState({ open: !headState.open })}
>
<ListItemText
primary={group.name}
secondary={
@@ -132,63 +141,20 @@ const ProxyGroup = ({ group }: Props) => {
}}
/>
{open ? <ExpandLessRounded /> : <ExpandMoreRounded />}
{headState.open ? <ExpandLessRounded /> : <ExpandMoreRounded />}
</ListItem>
<Collapse in={open} timeout="auto" unmountOnExit>
<Box
sx={{
pl: 4,
pr: 3,
my: 0.5,
display: "flex",
alignItems: "center",
button: { mr: 0.5 },
}}
>
<IconButton
size="small"
title="location"
onClick={() => onLocation(true)}
>
<MyLocationRounded />
</IconButton>
<Collapse in={headState.open} timeout="auto" unmountOnExit>
<ProxyHead
sx={{ pl: 4, pr: 3, my: 0.5, button: { mr: 0.5 } }}
groupName={group.name}
headState={headState}
onLocation={onLocation}
onCheckDelay={onCheckAll}
onHeadState={setHeadState}
/>
<IconButton size="small" title="check" onClick={onCheckAll}>
<NetworkCheckRounded />
</IconButton>
<IconButton
size="small"
title="check"
onClick={() => setShowType(!showType)}
>
{showType ? <VisibilityRounded /> : <VisibilityOffRounded />}
</IconButton>
<IconButton
size="small"
title="check"
onClick={() => setShowFilter(!showFilter)}
>
{showFilter ? <FilterAltRounded /> : <FilterAltOffRounded />}
</IconButton>
{showFilter && (
<TextField
autoFocus
hiddenLabel
value={filterText}
size="small"
variant="outlined"
placeholder="Filter conditions"
onChange={(e) => setFilterText(e.target.value)}
sx={{ ml: 0.5, flex: "1 1 auto", input: { py: 0.65, px: 1 } }}
/>
)}
</Box>
{!filterProxies.length && (
{!sortedProxies.length && (
<Box
sx={{
py: 3,
@@ -201,17 +167,17 @@ const ProxyGroup = ({ group }: Props) => {
</Box>
)}
{filterProxies.length >= 10 ? (
{sortedProxies.length >= 10 ? (
<Virtuoso
ref={virtuosoRef}
style={{ height: "320px", marginBottom: "4px" }}
totalCount={filterProxies.length}
totalCount={sortedProxies.length}
itemContent={(index) => (
<ProxyItem
groupName={group.name}
proxy={filterProxies[index]}
selected={filterProxies[index].name === now}
showType={showType}
proxy={sortedProxies[index]}
selected={sortedProxies[index].name === now}
showType={headState.showType}
sx={{ py: 0, pl: 4 }}
onClick={onChangeProxy}
/>
@@ -223,13 +189,13 @@ const ProxyGroup = ({ group }: Props) => {
disablePadding
sx={{ maxHeight: "320px", overflow: "auto", mb: "4px" }}
>
{filterProxies.map((proxy) => (
{sortedProxies.map((proxy) => (
<ProxyItem
key={proxy.name}
groupName={group.name}
proxy={proxy}
selected={proxy.name === now}
showType={showType}
showType={headState.showType}
sx={{ py: 0, pl: 4 }}
onClick={onChangeProxy}
/>
+161
View File
@@ -0,0 +1,161 @@
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
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 { HeadState } from "./use-head-state";
import type { ProxySortType } from "./use-sort-proxy";
interface Props {
sx?: SxProps;
groupName: string;
headState: HeadState;
onLocation: () => void;
onCheckDelay: () => void;
onHeadState: (val: Partial<HeadState>) => void;
}
const ProxyHead = (props: Props) => {
const { sx = {}, groupName, headState, onHeadState } = props;
const { showType, sortType, filterText, textState, testUrl } = headState;
const { t } = useTranslation();
const [autoFocus, setAutoFocus] = useState(false);
useEffect(() => {
// fix the focus conflict
const timer = setTimeout(() => setAutoFocus(true), 100);
return () => clearTimeout(timer);
}, []);
useEffect(() => {
delayManager.setUrl(groupName, testUrl);
}, [groupName, headState.testUrl]);
return (
<Box sx={{ display: "flex", alignItems: "center", ...sx }}>
<IconButton
size="small"
color="inherit"
title={t("Location")}
onClick={props.onLocation}
>
<MyLocationRounded />
</IconButton>
<IconButton
size="small"
color="inherit"
title={t("Delay check")}
onClick={() => {
// Remind the user that it is custom test url
if (testUrl?.trim() && textState !== "filter") {
onHeadState({ textState: "url" });
}
props.onCheckDelay();
}}
>
<NetworkCheckRounded />
</IconButton>
<IconButton
size="small"
color="inherit"
title={
[t("Sort by default"), t("Sort by delay"), t("Sort by name")][
sortType
]
}
onClick={() =>
onHeadState({ sortType: ((sortType + 1) % 3) as ProxySortType })
}
>
{sortType === 0 && <SortRounded />}
{sortType === 1 && <AccessTimeRounded />}
{sortType === 2 && <SortByAlphaRounded />}
</IconButton>
<IconButton
size="small"
color="inherit"
title={t("Delay check URL")}
onClick={() =>
onHeadState({ textState: textState === "url" ? null : "url" })
}
>
{textState === "url" ? (
<WifiTetheringRounded />
) : (
<WifiTetheringOffRounded />
)}
</IconButton>
<IconButton
size="small"
color="inherit"
title={t("Proxy detail")}
onClick={() => onHeadState({ showType: !showType })}
>
{showType ? <VisibilityRounded /> : <VisibilityOffRounded />}
</IconButton>
<IconButton
size="small"
color="inherit"
title={t("Filter")}
onClick={() =>
onHeadState({ textState: textState === "filter" ? null : "filter" })
}
>
{textState === "filter" ? (
<FilterAltRounded />
) : (
<FilterAltOffRounded />
)}
</IconButton>
{textState === "filter" && (
<TextField
autoFocus={autoFocus}
hiddenLabel
value={filterText}
size="small"
variant="outlined"
placeholder={t("Filter conditions")}
onChange={(e) => onHeadState({ filterText: e.target.value })}
sx={{ ml: 0.5, flex: "1 1 auto", input: { py: 0.65, px: 1 } }}
/>
)}
{textState === "url" && (
<TextField
autoFocus={autoFocus}
hiddenLabel
autoSave="off"
autoComplete="off"
value={testUrl}
size="small"
variant="outlined"
placeholder={t("Delay check URL")}
onChange={(e) => onHeadState({ testUrl: e.target.value })}
sx={{ ml: 0.5, flex: "1 1 auto", input: { py: 0.65, px: 1 } }}
/>
)}
</Box>
);
};
export default ProxyHead;
+83 -42
View File
@@ -1,4 +1,5 @@
import { useEffect, useRef, useState } from "react";
import { useEffect, useState } from "react";
import { useLockFn } from "ahooks";
import { CheckCircleOutlineRounded } from "@mui/icons-material";
import {
alpha,
@@ -11,8 +12,8 @@ import {
SxProps,
Theme,
} from "@mui/material";
import { ApiType } from "../../services/types";
import delayManager from "../../services/delay";
import delayManager from "@/services/delay";
import BaseLoading from "../base/base-loading";
interface Props {
groupName: string;
@@ -24,8 +25,9 @@ interface Props {
}
const Widget = styled(Box)(() => ({
padding: "4px 6px",
padding: "3px 6px",
fontSize: 14,
borderRadius: "4px",
}));
const TypeBox = styled(Box)(({ theme }) => ({
@@ -42,28 +44,33 @@ const TypeBox = styled(Box)(({ theme }) => ({
const ProxyItem = (props: Props) => {
const { groupName, proxy, selected, showType = true, sx, onClick } = props;
// -1/<=0 为 不显示
// -2 为 loading
const [delay, setDelay] = useState(-1);
useEffect(() => {
if (proxy) {
if (!proxy) return;
if (!proxy.provider) {
setDelay(delayManager.getDelay(proxy.name, groupName));
return;
}
const { history = [] } = proxy;
if (history.length > 0) {
// 0ms以error显示
setDelay(history[history.length - 1].delay || 1e6);
}
}, [proxy]);
const delayRef = useRef(false);
const onDelay = (e: any) => {
e.preventDefault();
e.stopPropagation();
if (delayRef.current) return;
delayRef.current = true;
delayManager
const onDelay = useLockFn(async () => {
setDelay(-2);
return delayManager
.checkDelay(proxy.name, groupName)
.then((result) => setDelay(result))
.catch(() => setDelay(1e6))
.finally(() => (delayRef.current = false));
};
.catch(() => setDelay(1e6));
});
return (
<ListItem sx={sx}>
@@ -79,14 +86,9 @@ const ProxyItem = (props: Props) => {
? 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" },
@@ -102,6 +104,9 @@ const ProxyItem = (props: Props) => {
<>
{proxy.name}
{showType && !!proxy.provider && (
<TypeBox component="span">{proxy.provider}</TypeBox>
)}
{showType && <TypeBox component="span">{proxy.type}</TypeBox>}
{showType && proxy.udp && <TypeBox component="span">UDP</TypeBox>}
</>
@@ -111,28 +116,64 @@ const ProxyItem = (props: Props) => {
<ListItemIcon
sx={{ justifyContent: "flex-end", color: "primary.main" }}
>
<Widget className="the-check" onClick={onDelay}>
Check
</Widget>
{delay === -2 && (
<Widget>
<BaseLoading />
</Widget>
)}
<Widget
className="the-delay"
onClick={onDelay}
color={
delay > 500
? "error.main"
: delay < 100
? "success.main"
: "text.secondary"
}
>
{delay > 1e5 ? "Error" : delay > 3000 ? "Timeout" : `${delay}ms`}
</Widget>
{!proxy.provider && delay !== -2 && (
// provider的节点不支持检测
<Widget
className="the-check"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
onDelay();
}}
sx={({ palette }) => ({
display: "none", // hover才显示
":hover": { bgcolor: alpha(palette.primary.main, 0.15) },
})}
>
Check
</Widget>
)}
<CheckCircleOutlineRounded
className="the-icon"
sx={{ fontSize: 16 }}
/>
{delay > 0 && (
// 显示延迟
<Widget
className="the-delay"
onClick={(e) => {
if (proxy.provider) return;
e.preventDefault();
e.stopPropagation();
onDelay();
}}
color={
delay > 500
? "error.main"
: delay < 100
? "success.main"
: "text.secondary"
}
sx={({ palette }) =>
!proxy.provider
? { ":hover": { bgcolor: alpha(palette.primary.main, 0.15) } }
: {}
}
>
{delay > 1e5 ? "Error" : delay > 3000 ? "Timeout" : `${delay}ms`}
</Widget>
)}
{delay !== -2 && delay <= 0 && selected && (
// 展示已选择的icon
<CheckCircleOutlineRounded
className="the-icon"
sx={{ fontSize: 16 }}
/>
)}
</ListItemIcon>
</ListItemButton>
</ListItem>
+2 -2
View File
@@ -1,6 +1,5 @@
import { useMemo } from "react";
import { ApiType } from "../../services/types";
import delayManager from "../../services/delay";
import delayManager from "@/services/delay";
const regex1 = /delay([=<>])(\d+|timeout|error)/i;
const regex2 = /type=(.*)/i;
@@ -15,6 +14,7 @@ export default function useFilterProxy(
filterText: string
) {
return useMemo(() => {
if (!proxies) return [];
if (!filterText) return proxies;
const res1 = regex1.exec(filterText);
+80
View File
@@ -0,0 +1,80 @@
import { useCallback, useEffect, useState } from "react";
import { useRecoilValue } from "recoil";
import { atomCurrentProfile } from "@/services/states";
import { ProxySortType } from "./use-sort-proxy";
export interface HeadState {
open?: boolean;
showType: boolean;
sortType: ProxySortType;
filterText: string;
textState: "url" | "filter" | null;
testUrl: string;
}
type HeadStateStorage = Record<string, Record<string, HeadState>>;
const HEAD_STATE_KEY = "proxy-head-state";
const DEFAULT_STATE: HeadState = {
open: false,
showType: false,
sortType: 0,
filterText: "",
textState: null,
testUrl: "",
};
export default function useHeadState(groupName: string) {
const current = useRecoilValue(atomCurrentProfile);
const [state, setState] = useState<HeadState>(DEFAULT_STATE);
useEffect(() => {
if (!current) {
setState(DEFAULT_STATE);
return;
}
try {
const data = JSON.parse(
localStorage.getItem(HEAD_STATE_KEY)!
) as HeadStateStorage;
const value = data[current][groupName] || DEFAULT_STATE;
if (value && typeof value === "object") {
setState({ ...DEFAULT_STATE, ...value });
} else {
setState(DEFAULT_STATE);
}
} catch {}
}, [current, groupName]);
const setHeadState = useCallback(
(obj: Partial<HeadState>) => {
setState((old) => {
const ret = { ...old, ...obj };
setTimeout(() => {
try {
const item = localStorage.getItem(HEAD_STATE_KEY);
let data = (item ? JSON.parse(item) : {}) as HeadStateStorage;
if (!data || typeof data !== "object") data = {};
if (!data[current]) data[current] = {};
data[current][groupName] = ret;
localStorage.setItem(HEAD_STATE_KEY, JSON.stringify(data));
} catch {}
});
return ret;
});
},
[current, groupName]
);
return [state, setHeadState] as const;
}
+37
View File
@@ -0,0 +1,37 @@
import { useMemo } from "react";
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 || ad === -2) return 1;
if (bd === -1 || bd === -2) return -1;
return ad - bd;
});
} else {
list.sort((a, b) => a.name.localeCompare(b.name));
}
return list;
}, [proxies, groupName, sortType]);
}
+72
View File
@@ -0,0 +1,72 @@
import { styled, Box, Typography } from "@mui/material";
const Item = styled(Box)(({ theme }) => ({
display: "flex",
padding: "6px 16px",
color: theme.palette.text.primary,
marginBottom: "6px",
}));
const COLOR = [
"primary",
"secondary",
"info",
"warning",
"error",
"success",
"text",
];
interface Props {
index: number;
value: ApiType.RuleItem;
}
const parseColor = (text: string) => {
let sum = 0;
for (let i = 0; i < text.length; i++) {
sum += text.charCodeAt(i);
}
return COLOR[sum % COLOR.length];
};
const RuleItem = (props: Props) => {
const { index, value } = props;
return (
<Item>
<Typography
color="text.secondary"
variant="body2"
sx={{ lineHeight: 2, minWidth: 30, mr: 2.25, textAlign: "center" }}
>
{index}
</Typography>
<Box>
<Typography component="h6" variant="subtitle1" color="text.primary">
{value.payload || "-"}
</Typography>
<Typography
component="span"
variant="body2"
color="text.secondary"
sx={{ mr: 3, minWidth: 120, display: "inline-block" }}
>
{value.type}
</Typography>
<Typography
component="span"
variant="body2"
color={parseColor(value.proxy)}
>
{value.proxy}
</Typography>
</Box>
</Item>
);
};
export default RuleItem;

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