70 Commits

Author SHA1 Message Date
GyDi
b52a081e7b v0.0.18 2022-02-25 02:13:41 +08:00
GyDi
f981a44861 chore: ci 2022-02-25 02:12:55 +08:00
GyDi
d7c5ce0750 feat: clash tun mode supports 2022-02-25 02:09:39 +08:00
GyDi
9ccc66ca1e feat: use enhanced guard-state 2022-02-25 01:22:33 +08:00
GyDi
8606af3616 feat: guard state supports debounce guard 2022-02-25 01:21:13 +08:00
GyDi
f6e821ba6b feat: adjust clash version display 2022-02-24 23:04:18 +08:00
GyDi
e8dbcf819b feat: hide command window 2022-02-24 22:46:12 +08:00
GyDi
bbe2ef4e8e fix: use full clash config 2022-02-23 23:23:07 +08:00
GyDi
dd15455031 feat: enhance log data 2022-02-23 02:00:45 +08:00
GyDi
12ac7bb338 chore: update readme 2022-02-22 21:54:33 +08:00
GyDi
46ef348f0d v0.0.17 2022-02-22 02:08:31 +08:00
GyDi
1a55cca8af fix: reconnect websocket when restart clash 2022-02-22 02:05:22 +08:00
GyDi
81ee989f1f chore: enhance publish ci 2022-02-22 01:56:06 +08:00
GyDi
c9c06f8a3d fix: wrong exe path 2022-02-21 22:33:37 +08:00
GyDi
72127979c3 chore: use tauri cli 2022-02-21 22:31:00 +08:00
GyDi
1ad3ddef94 v0.0.16 2022-02-21 01:33:11 +08:00
GyDi
97ec5eabf7 feat: change window style 2022-02-20 23:46:13 +08:00
GyDi
e12e3a3f2d feat: fill verge template 2022-02-20 20:12:55 +08:00
GyDi
4ff625f23b feat: enable customize guard duration 2022-02-20 20:11:39 +08:00
GyDi
e38dcd85ac feat: system proxy guard 2022-02-20 18:53:21 +08:00
GyDi
0245baf1b6 feat: enable show or hide traffic graph 2022-02-19 18:14:40 +08:00
GyDi
10b55c043c fix: patch verge config 2022-02-19 17:32:23 +08:00
GyDi
457655b416 feat: traffic line graph 2022-02-19 17:02:24 +08:00
GyDi
7e4506c860 chore: update deps 2022-02-19 00:34:09 +08:00
GyDi
794d376348 feat: adjust profile item ui 2022-02-19 00:23:47 +08:00
GyDi
c60578f5b5 feat: adjust fetch profile url 2022-02-19 00:09:36 +08:00
GyDi
3a9a392a77 feat: inline config file template 2022-02-18 23:57:13 +08:00
GyDi
a13d4698be chore: update check script 2022-02-18 23:49:39 +08:00
GyDi
c046a1993e fix: fetch profile panic 2022-02-17 13:44:26 +08:00
GyDi
f709117cc4 feat: kill sidecars when update app 2022-02-17 02:10:25 +08:00
GyDi
30dd298fca feat: delete file 2022-02-17 01:58:12 +08:00
GyDi
0ff8bb8090 feat: lock some async functions 2022-02-17 01:42:25 +08:00
GyDi
74bbd3c3a2 chore: tauri updater env 2022-02-16 11:02:00 +08:00
GyDi
2e82eaf59a chore: add pubkey 2022-02-16 10:59:31 +08:00
GyDi
7f1df1f1bd v0.0.15 2022-02-16 03:22:25 +08:00
GyDi
3c79238a44 feat: support open dir 2022-02-16 03:21:34 +08:00
GyDi
0aa2565df3 fix: spawn command 2022-02-16 02:43:52 +08:00
GyDi
22b11db16e feat: change allow list 2022-02-16 02:42:56 +08:00
GyDi
d0e678b5e9 feat: support check delay 2022-02-16 02:22:01 +08:00
GyDi
e7bba968b3 fix: import error 2022-02-15 01:36:19 +08:00
GyDi
4934a24293 feat: scroll to proxy item 2022-02-15 01:34:10 +08:00
GyDi
ccb68bcda9 chore: update deps 2022-02-15 00:33:58 +08:00
GyDi
66bf4ba3ad fix: not open file when new profile 2022-02-15 00:21:34 +08:00
GyDi
78a0cfd052 feat: edit system proxy bypass 2022-02-14 01:26:24 +08:00
GyDi
8548373742 feat: disable user select 2022-02-13 19:52:35 +08:00
GyDi
2dfd725ee0 fix: reset value correctly 2022-02-13 19:40:31 +08:00
GyDi
5b779b4f14 feat: new profile able to edit name and desc 2022-02-13 19:33:24 +08:00
GyDi
fc48aa7155 chore: adjust files 2022-02-13 19:27:24 +08:00
GyDi
6193a842f4 feat: update tauri version 2022-02-13 18:45:03 +08:00
GyDi
eb86b471fe fix: something 2022-02-12 21:12:39 +08:00
GyDi
2b52584547 fix: menu without fragment 2022-02-10 01:42:52 +08:00
GyDi
6e3cc57f48 feat: display clash core version 2022-02-10 01:35:55 +08:00
GyDi
f2c04621a5 feat: adjust profile item menu 2022-02-10 01:14:57 +08:00
GyDi
3ed6938d4a v0.0.14 2022-02-09 02:11:01 +08:00
GyDi
99fec25ed5 feat: profile item ui 2022-02-09 02:08:27 +08:00
GyDi
73758ad1fd fix: proxy list error 2022-02-09 02:02:29 +08:00
GyDi
c53fe0ed1f feat: support new profile 2022-02-07 17:26:05 +08:00
GyDi
6082c2bcac feat: support open command for viewing 2022-02-07 16:45:20 +08:00
GyDi
069abed784 chore: add item template yaml 2022-02-02 20:56:06 +08:00
GyDi
7d8fa4d78a fix: something 2022-01-31 23:34:58 +08:00
GyDi
76081f8d89 fix: macos auto launch fail 2022-01-31 23:32:41 +08:00
GyDi
5ef4285558 chore: update deps and app name 2022-01-31 23:27:11 +08:00
GyDi
aa7df4282e chore: cargo update 2022-01-28 22:02:17 +08:00
GyDi
0ef1d5d0de chore: update clash version 2022-01-28 22:00:15 +08:00
GyDi
cceb4bb81f v0.0.13 2022-01-25 02:11:00 +08:00
GyDi
f0f45e007d feat: global proxies use virtual list 2022-01-25 02:08:10 +08:00
GyDi
6a8ffe1642 feat: enable change proxy mode 2022-01-25 01:51:44 +08:00
GyDi
3a73868c10 feat: update styles 2022-01-25 01:48:26 +08:00
GyDi
ab1b5897a6 feat: manage clash mode 2022-01-24 23:13:13 +08:00
GyDi
f94734a5c8 chore: update readme 2022-01-22 23:57:39 +08:00
64 changed files with 3154 additions and 4435 deletions

View File

@@ -1,4 +1,4 @@
name: CI name: Release CI
on: [push] on: [push]
@@ -53,15 +53,17 @@ jobs:
yarn run check yarn run check
- name: Tauri build - name: Tauri build
uses: tauri-apps/tauri-action@v0 uses: tauri-apps/tauri-action@b9ce5d7dc68082d21d30a60103b0ab8c5ddae3a1
# enable cache even though failed # enable cache even though failed
continue-on-error: true continue-on-error: true
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
with: with:
tagName: v__VERSION__ tagName: v__VERSION__
releaseName: "Clash Verge v__VERSION__" releaseName: "Clash Verge v__VERSION__"
releaseBody: "Clash Verge now supports Windows and macos(intel)." releaseBody: "Clash Verge now supports Windows and macos."
releaseDraft: false releaseDraft: false
prerelease: true prerelease: true
@@ -93,6 +95,5 @@ jobs:
- name: Release update.json - name: Release update.json
run: yarn run release run: yarn run release
continue-on-error: true
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -11,19 +11,17 @@ A <a href="https://github.com/Dreamacro/clash">Clash</a> GUI based on <a href="h
## Features ## Features
Now it's no different from the others, even fewer. (WIP) Now it's no different from the others, maybe fewer. (WIP)
## Development ## Development
You should install Rust and Nodejs. Then install tauri cli and packages. You should install Rust and Nodejs, see [here](https://tauri.studio/docs/getting-started/prerequisites) for more details. Then install Nodejs packages.
```shell ```shell
cargo install tauri-cli --git https://github.com/tauri-apps/tauri
yarn install yarn install
``` ```
Then download the clash binary... Or you can download it from [clash premium release](https://github.com/Dreamacro/clash/releases/tag/premium) and rename it according to [tauri config](https://tauri.studio/en/docs/api/config#tauri.bundle.externalBin). Then download the clash binary... Or you can download it from [clash premium release](https://github.com/Dreamacro/clash/releases/tag/premium) and rename it according to [tauri config](https://tauri.studio/docs/api/config/#tauri.bundle.externalBin).
```shell ```shell
yarn run check yarn run check
@@ -56,8 +54,17 @@ This is a learning project for Rust practice.
## Contributions ## Contributions
PR welcome! Issue and PR welcome!
## Acknowledgement
Clash Verge was based on or inspired by these projects and so on:
- [tauri-apps/tauri](https://github.com/tauri-apps/tauri): Build smaller, faster, and more secure desktop applications with a web frontend.
- [Dreamacro/clash](https://github.com/Dreamacro/clash): A rule-based tunnel in Go.
- [Fndroid/clash_for_windows_pkg](https://github.com/Fndroid/clash_for_windows_pkg): A Windows/macOS GUI based on Clash.
- [vitejs/vite](https://github.com/vitejs/vite): Next generation frontend tooling. It's fast!
## License ## License
GPL-3.0 License GPL-3.0 License. See [License here](./LICENSE) for details.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

After

Width:  |  Height:  |  Size: 28 KiB

View File

@@ -1,10 +1,10 @@
{ {
"name": "clash-verge", "name": "clash-verge",
"version": "0.0.12", "version": "0.0.18",
"license": "GPL-3.0", "license": "GPL-3.0",
"scripts": { "scripts": {
"dev": "cargo tauri dev", "dev": "tauri dev",
"build": "cargo tauri build", "build": "tauri build",
"tauri": "tauri", "tauri": "tauri",
"web:dev": "vite", "web:dev": "vite",
"web:build": "tsc && vite build", "web:build": "tsc && vite build",
@@ -17,35 +17,35 @@
"dependencies": { "dependencies": {
"@emotion/react": "^11.7.0", "@emotion/react": "^11.7.0",
"@emotion/styled": "^11.6.0", "@emotion/styled": "^11.6.0",
"@mui/icons-material": "^5.2.1", "@mui/icons-material": "^5.4.1",
"@mui/material": "^5.2.3", "@mui/material": "^5.4.1",
"@tauri-apps/api": "^1.0.0-beta.8", "@tauri-apps/api": "^1.0.0-rc.1",
"ahooks": "^3.1.7", "ahooks": "^3.1.9",
"axios": "^0.24.0", "axios": "^0.26.0",
"dayjs": "^1.10.7", "dayjs": "^1.10.7",
"react": "^17.0.0", "react": "^17.0.2",
"react-dom": "^17.0.0", "react-dom": "^17.0.2",
"react-router-dom": "^6.0.2", "react-router-dom": "^6.2.1",
"react-virtuoso": "^2.3.1", "react-virtuoso": "^2.7.0",
"recoil": "^0.5.2", "recoil": "^0.6.1",
"swr": "^1.1.2-beta.0" "swr": "^1.2.1"
}, },
"devDependencies": { "devDependencies": {
"@actions/github": "^5.0.0", "@actions/github": "^5.0.0",
"@tauri-apps/cli": "^1.0.0-beta.10", "@tauri-apps/cli": "^1.0.0-rc.5",
"@types/fs-extra": "^9.0.13", "@types/fs-extra": "^9.0.13",
"@types/js-cookie": "^3.0.1", "@types/js-cookie": "^3.0.1",
"@types/react": "^17.0.0", "@types/react": "^17.0.0",
"@types/react-dom": "^17.0.0", "@types/react-dom": "^17.0.0",
"@vitejs/plugin-react": "^1.1.1", "@vitejs/plugin-react": "^1.2.0",
"adm-zip": "^0.5.9", "adm-zip": "^0.5.9",
"fs-extra": "^10.0.0", "fs-extra": "^10.0.0",
"husky": "^7.0.0", "husky": "^7.0.0",
"node-fetch": "^3.1.0", "node-fetch": "^3.2.0",
"pretty-quick": "^3.1.3", "pretty-quick": "^3.1.3",
"sass": "^1.44.0", "sass": "^1.49.7",
"typescript": "^4.5.2", "typescript": "^4.5.5",
"vite": "^2.7.1" "vite": "^2.8.0"
}, },
"prettier": { "prettier": {
"tabWidth": 2, "tabWidth": 2,

View File

@@ -9,7 +9,7 @@ const cwd = process.cwd();
const CLASH_URL_PREFIX = const CLASH_URL_PREFIX =
"https://github.com/Dreamacro/clash/releases/download/premium/"; "https://github.com/Dreamacro/clash/releases/download/premium/";
const CLASH_LATEST_DATE = "2022.01.03"; const CLASH_LATEST_DATE = "2022.01.27";
/** /**
* get the correct clash release infomation * get the correct clash release infomation
@@ -50,7 +50,7 @@ async function resolveSidecar() {
const sidecarFile = `clash-${host}${ext}`; const sidecarFile = `clash-${host}${ext}`;
const sidecarPath = path.join(sidecarDir, sidecarFile); const sidecarPath = path.join(sidecarDir, sidecarFile);
if (!(await fs.pathExists(sidecarDir))) await fs.mkdir(sidecarDir); await fs.mkdirp(sidecarDir);
if (await fs.pathExists(sidecarPath)) return; if (await fs.pathExists(sidecarPath)) return;
// download sidecar // download sidecar
@@ -59,7 +59,7 @@ async function resolveSidecar() {
const tempZip = path.join(tempDir, binInfo.zipfile); const tempZip = path.join(tempDir, binInfo.zipfile);
const tempExe = path.join(tempDir, binInfo.exefile); const tempExe = path.join(tempDir, binInfo.exefile);
if (!(await fs.pathExists(tempDir))) await fs.mkdir(tempDir); await fs.mkdirp(tempDir);
if (!(await fs.pathExists(tempZip))) await downloadFile(binInfo.url, tempZip); if (!(await fs.pathExists(tempZip))) await downloadFile(binInfo.url, tempZip);
if (binInfo.zip === "zip") { if (binInfo.zip === "zip") {
@@ -96,8 +96,10 @@ async function resolveMmdb() {
const url = const url =
"https://github.com/Dreamacro/maxmind-geoip/releases/latest/download/Country.mmdb"; "https://github.com/Dreamacro/maxmind-geoip/releases/latest/download/Country.mmdb";
const resPath = path.join(cwd, "src-tauri", "resources", "Country.mmdb"); const resDir = path.join(cwd, "src-tauri", "resources");
const resPath = path.join(resDir, "Country.mmdb");
if (await fs.pathExists(resPath)) return; if (await fs.pathExists(resPath)) return;
await fs.mkdirp(resDir);
await downloadFile(url, resPath); await downloadFile(url, resPath);
} }
@@ -118,5 +120,5 @@ async function downloadFile(url, path) {
} }
/// main /// main
resolveSidecar(); resolveSidecar().catch(console.error);
resolveMmdb(); resolveMmdb().catch(console.error);

View File

@@ -1,7 +1,8 @@
import { createRequire } from "module"; import fetch from "node-fetch";
import { getOctokit, context } from "@actions/github"; import { getOctokit, context } from "@actions/github";
const require = createRequire(import.meta.url); const UPDATE_TAG_NAME = "updater";
const UPDATE_JSON_FILE = "update.json";
/// generate update.json /// generate update.json
/// upload to update tag's release asset /// upload to update tag's release asset
@@ -10,46 +11,85 @@ async function resolveRelease() {
throw new Error("GITHUB_TOKEN is required"); throw new Error("GITHUB_TOKEN is required");
} }
const packageJson = require("../package.json"); const options = { owner: context.repo.owner, repo: context.repo.repo };
const github = getOctokit(process.env.GITHUB_TOKEN);
const { data: tags } = await github.rest.repos.listTags({
...options,
per_page: 10,
page: 1,
});
// get the latest publish tag
const tag = tags.find((t) => t.name.startsWith("v"));
console.log(tag);
console.log();
const { data: latestRelease } = await github.rest.repos.getReleaseByTag({
...options,
tag: tag.name,
});
const { version } = packageJson;
const urlPrefix = "https://github.com/zzzgydi/clash-verge/releases/download";
const updateData = { const updateData = {
name: `v${version}`, name: tag.name,
notes: `Version ${version} is available now!!!`, notes: latestRelease.body, // use the release body directly
pub_date: new Date().toISOString(), pub_date: new Date().toISOString(),
platforms: { platforms: {
win64: { win64: { signature: "", url: "" },
signature: "", darwin: { signature: "", url: "" },
url: `${urlPrefix}/v${version}/clash-verge_${version}_x64.msi.zip`,
},
darwin: {
signature: "",
url: `${urlPrefix}/v${version}/clash-verge.app.tar.gz`,
},
}, },
}; };
console.log(`Generating Version "${version}" update.json`); const promises = latestRelease.assets.map(async (asset) => {
const { name, browser_download_url } = asset;
const github = getOctokit(process.env.GITHUB_TOKEN); // win64 url
if (/\.msi\.zip$/.test(name)) {
const { data: release } = await github.rest.repos.getReleaseByTag({ updateData.platforms.win64.url = browser_download_url;
owner: context.repo.owner, }
repo: context.repo.repo, // darwin url
tag: "updater", if (/\.app\.tar\.gz$/.test(name)) {
}); updateData.platforms.darwin.url = browser_download_url;
const { data: assets } = await github.rest.repos.listReleaseAssets({ }
owner: context.repo.owner, // win64 signature
repo: context.repo.repo, if (/\.msi\.zip\.sig$/.test(name)) {
release_id: release.id, 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
);
}
}); });
for (let asset of assets) { await Promise.allSettled(promises);
if (asset.name === "update.json") { console.log(updateData);
// maybe should test the signature as well
const { darwin, win64 } = 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({ await github.rest.repos.deleteReleaseAsset({
owner: context.repo.owner, ...options,
repo: context.repo.repo,
asset_id: asset.id, asset_id: asset.id,
}); });
break; break;
@@ -57,12 +97,21 @@ async function resolveRelease() {
} }
await github.rest.repos.uploadReleaseAsset({ await github.rest.repos.uploadReleaseAsset({
owner: context.repo.owner, ...options,
repo: context.repo.repo, release_id: updateRelease.id,
release_id: release.id, name: UPDATE_JSON_FILE,
name: "update.json",
data: JSON.stringify(updateData, null, 2), data: JSON.stringify(updateData, null, 2),
}); });
} }
resolveRelease(); // get the signature file content
async function getSignature(url) {
const response = await fetch(url, {
method: "GET",
headers: { "Content-Type": "application/octet-stream" },
});
return response.text();
}
resolveRelease().catch(console.error);

1398
src-tauri/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,26 +1,25 @@
[package] [package]
name = "app" name = "clash-verge"
version = "0.1.0" version = "0.1.0"
description = "clash verge" description = "clash verge"
authors = ["zzzgydi"] authors = ["zzzgydi"]
license = "GPL-3.0" license = "GPL-3.0"
repository = "https://github.com/zzzgydi/clash-verge.git" repository = "https://github.com/zzzgydi/clash-verge.git"
default-run = "app" default-run = "clash-verge"
edition = "2021" edition = "2021"
build = "build.rs" build = "build.rs"
[build-dependencies] [build-dependencies]
tauri-build = { version = "1.0.0-beta.4" } tauri-build = { version = "1.0.0-rc.3", features = [] }
[dependencies] [dependencies]
dirs = "4.0.0" dirs = "4.0.0"
dunce = "1.0.2"
chrono = "0.4.19" chrono = "0.4.19"
serde_json = "1.0" serde_json = "1.0"
serde_yaml = "0.8" serde_yaml = "0.8"
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
# tauri = { version = "1.0.0-beta.8", features = ["api-all", "system-tray"] } tauri = { version = "1.0.0-rc.3", features = ["shell-all", "system-tray", "updater", "window-all"] }
# tauri = { git = "https://github.com/tauri-apps/tauri", rev = "5e0d59ec", features = ["api-all", "system-tray"] }
tauri = { git = "https://github.com/tauri-apps/tauri", branch = "next", features = ["api-all", "system-tray", "updater"] }
tauri-plugin-shadows = { git = "https://github.com/tauri-apps/tauri-plugin-shadows", features = ["tauri-impl"] } tauri-plugin-shadows = { git = "https://github.com/tauri-apps/tauri-plugin-shadows", features = ["tauri-impl"] }
tauri-plugin-vibrancy = { git = "https://github.com/tauri-apps/tauri-plugin-vibrancy", features = ["tauri-impl"] } tauri-plugin-vibrancy = { git = "https://github.com/tauri-apps/tauri-plugin-vibrancy", features = ["tauri-impl"] }

View File

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

View File

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

View File

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

View File

@@ -4,8 +4,8 @@ use crate::{
utils::{dirs::app_home_dir, fetch::fetch_profile, sysopt::SysProxyConfig}, utils::{dirs::app_home_dir, fetch::fetch_profile, sysopt::SysProxyConfig},
}; };
use serde_yaml::Mapping; use serde_yaml::Mapping;
use std::process::Command; use std::{path::PathBuf, process::Command};
use tauri::State; use tauri::{api, State};
/// get all profiles from `profiles.yaml` /// get all profiles from `profiles.yaml`
/// do not acquire the lock of ProfileLock /// do not acquire the lock of ProfileLock
@@ -34,13 +34,23 @@ pub async fn import_profile(
with_proxy: bool, with_proxy: bool,
profiles_state: State<'_, ProfilesState>, profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> { ) -> Result<(), String> {
match fetch_profile(&url, with_proxy).await { let result = fetch_profile(&url, with_proxy).await?;
Some(result) => { let mut profiles = profiles_state.0.lock().unwrap();
let mut profiles = profiles_state.0.lock().unwrap(); profiles.import_from_url(url, result)
profiles.import_from_url(url, result) }
}
None => Err(format!("failed to fetch profile from `{}`", url)), /// new a profile
} /// append a temp profile item file to the `profiles` dir
/// view the temp profile file by using vscode or other editor
#[tauri::command]
pub async fn new_profile(
name: String,
desc: String,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let mut profiles = profiles_state.0.lock().unwrap();
profiles.append_item(name, desc)?;
Ok(())
} }
/// Update the profile /// Update the profile
@@ -68,23 +78,22 @@ pub async fn update_profile(
Err(_) => return Err("failed to get profiles lock".into()), Err(_) => return Err("failed to get profiles lock".into()),
}; };
match fetch_profile(&url, with_proxy).await { let result = fetch_profile(&url, with_proxy).await?;
Some(result) => match profiles_state.0.lock() {
Ok(mut profiles) => {
profiles.update_item(index, result)?;
// reactivate the profile match profiles_state.0.lock() {
let current = profiles.current.clone().unwrap_or(0); Ok(mut profiles) => {
if current == index { profiles.update_item(index, result)?;
let clash = clash_state.0.lock().unwrap();
profiles.activate(&clash) // reactivate the profile
} else { let current = profiles.current.clone().unwrap_or(0);
Ok(()) if current == index {
} let clash = clash_state.0.lock().unwrap();
profiles.activate(&clash)
} else {
Ok(())
} }
Err(_) => Err("failed to get profiles lock".into()), }
}, Err(_) => Err("failed to get profiles lock".into()),
None => Err(format!("failed to fetch profile from `{}`", url)),
} }
} }
@@ -155,16 +164,18 @@ pub fn view_profile(index: usize, profiles_state: State<'_, ProfilesState>) -> R
let path = app_home_dir().join("profiles").join(file); let path = app_home_dir().join("profiles").join(file);
if !path.exists() { if !path.exists() {
return Err("failed to open the file".into()); return Err("the file not found".into());
} }
match which::which("code") { // use vscode first
Ok(code) => match Command::new(code).arg(path).status() { if let Ok(code) = which::which("code") {
return match Command::new(code).arg(path).spawn() {
Ok(_) => Ok(()), Ok(_) => Ok(()),
Err(_) => Err("failed to open file by VScode".into()), Err(_) => Err("failed to open file by VScode".into()),
}, };
Err(_) => Err("please install VScode for edit".into()),
} }
open_path_cmd(path, "failed to open file by `open`")
} }
/// restart the sidecar /// restart the sidecar
@@ -233,19 +244,82 @@ pub fn get_cur_proxy(verge_state: State<'_, VergeState>) -> Result<Option<SysPro
/// get the verge config /// get the verge config
#[tauri::command] #[tauri::command]
pub fn get_verge_config(verge_state: State<'_, VergeState>) -> Result<VergeConfig, String> { pub fn get_verge_config(verge_state: State<'_, VergeState>) -> Result<VergeConfig, String> {
match verge_state.0.lock() { let verge = verge_state.0.lock().unwrap();
Ok(arc) => Ok(arc.config.clone()), let mut config = verge.config.clone();
Err(_) => Err("failed to get verge lock".into()),
if config.system_proxy_bypass.is_none() && verge.cur_sysproxy.is_some() {
config.system_proxy_bypass = Some(verge.cur_sysproxy.clone().unwrap().bypass)
} }
Ok(config)
} }
/// patch the verge config /// patch the verge config
/// this command only save the config and not responsible for other things /// this command only save the config and not responsible for other things
#[tauri::command] #[tauri::command]
pub async fn patch_verge_config( pub fn patch_verge_config(
payload: VergeConfig, payload: VergeConfig,
clash_state: State<'_, ClashState>,
verge_state: State<'_, VergeState>, verge_state: State<'_, VergeState>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> { ) -> Result<(), String> {
let tun_mode = payload.enable_tun_mode.clone();
let mut verge = verge_state.0.lock().unwrap(); let mut verge = verge_state.0.lock().unwrap();
verge.patch_config(payload) verge.patch_config(payload)?;
// change tun mode
if tun_mode.is_some() {
let mut clash = clash_state.0.lock().unwrap();
let profiles = profiles_state.0.lock().unwrap();
clash.tun_mode(tun_mode.unwrap())?;
clash.update_config();
profiles.activate(&clash)?;
}
Ok(())
}
/// kill all sidecars when update app
#[tauri::command]
pub fn kill_sidecars() {
api::process::kill_children();
}
/// open app config dir
#[tauri::command]
pub fn open_app_dir() -> Result<(), String> {
let app_dir = app_home_dir();
open_path_cmd(app_dir, "failed to open app dir")
}
/// open logs dir
#[tauri::command]
pub fn open_logs_dir() -> Result<(), String> {
let log_dir = app_home_dir().join("logs");
open_path_cmd(log_dir, "failed to open logs 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;
match Command::new("explorer")
.creation_flags(0x08000000)
.arg(dir)
.spawn()
{
Ok(_) => Ok(()),
Err(_) => Err(err_str.into()),
}
}
#[cfg(not(target_os = "windows"))]
match Command::new("open").arg(dir).spawn() {
Ok(_) => Ok(()),
Err(_) => Err(err_str.into()),
}
} }

View File

@@ -203,6 +203,48 @@ impl Clash {
} }
self.save_config() self.save_config()
} }
/// enable tun mode
/// only revise the config and restart the
pub fn tun_mode(&mut self, enable: bool) -> Result<(), String> {
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()
}
} }
impl Default for Clash { impl Default for Clash {

View File

@@ -1,12 +1,13 @@
use super::{Clash, ClashInfo}; use super::{Clash, ClashInfo};
use crate::utils::{config, dirs}; use crate::utils::{config, dirs, tmpl};
use reqwest::header::HeaderMap; use reqwest::header::HeaderMap;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_yaml::{Mapping, Value}; use serde_yaml::{Mapping, Value};
use std::collections::HashMap; use std::collections::HashMap;
use std::env::temp_dir; use std::env::temp_dir;
use std::fs::File; use std::fs::{remove_file, File};
use std::io::Write; use std::io::Write;
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH}; use std::time::{SystemTime, UNIX_EPOCH};
/// Define the `profiles.yaml` schema /// Define the `profiles.yaml` schema
@@ -23,6 +24,8 @@ pub struct Profiles {
pub struct ProfileItem { pub struct ProfileItem {
/// profile name /// profile name
pub name: Option<String>, pub name: Option<String>,
/// profile description
pub desc: Option<String>,
/// profile file /// profile file
pub file: Option<String>, pub file: Option<String>,
/// current mode /// current mode
@@ -57,7 +60,7 @@ pub struct ProfileResponse {
pub name: String, pub name: String,
pub file: String, pub file: String,
pub data: String, pub data: String,
pub extra: ProfileExtra, pub extra: Option<ProfileExtra>,
} }
static PROFILE_YAML: &str = "profiles.yaml"; static PROFILE_YAML: &str = "profiles.yaml";
@@ -109,11 +112,12 @@ impl Profiles {
items.push(ProfileItem { items.push(ProfileItem {
name: Some(result.name), name: Some(result.name),
desc: Some("imported url".into()),
file: Some(result.file), file: Some(result.file),
mode: Some(format!("rule")), mode: Some(format!("rule")),
url: Some(url), url: Some(url),
selected: Some(vec![]), selected: Some(vec![]),
extra: Some(result.extra), extra: result.extra,
updated: Some(now as usize), updated: Some(now as usize),
}); });
@@ -138,6 +142,40 @@ impl Profiles {
self.save_file() self.save_file()
} }
/// append new item
/// return the new item's index
pub fn append_item(&mut self, name: String, desc: String) -> Result<(usize, PathBuf), String> {
let mut items = self.items.take().unwrap_or(vec![]);
// create a new profile file
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
let file = format!("{}.yaml", now);
let path = dirs::app_home_dir().join("profiles").join(&file);
match File::create(&path).unwrap().write(tmpl::ITEM_CONFIG) {
Ok(_) => {
items.push(ProfileItem {
name: Some(name),
desc: Some(desc),
file: Some(file),
mode: None,
url: None,
selected: Some(vec![]),
extra: None,
updated: Some(now as usize),
});
let index = items.len();
self.items = Some(items);
Ok((index, path))
}
Err(_) => Err("failed to create file".into()),
}
}
/// update the target profile /// update the target profile
/// and save to config file /// and save to config file
/// only support the url item /// only support the url item
@@ -156,7 +194,7 @@ impl Profiles {
File::create(file_path).unwrap().write(file_data).unwrap(); File::create(file_path).unwrap().write(file_data).unwrap();
items[index].name = Some(result.name); items[index].name = Some(result.name);
items[index].extra = Some(result.extra); items[index].extra = result.extra;
items[index].updated = Some(now); items[index].updated = Some(now);
self.items = Some(items); self.items = Some(items);
@@ -202,7 +240,18 @@ impl Profiles {
return Err("index out of bound".into()); return Err("index out of bound".into());
} }
items.remove(index); let mut rm_item = items.remove(index);
// delete the file
if let Some(file) = rm_item.file.take() {
let file_path = dirs::app_home_dir().join("profiles").join(file);
if file_path.exists() {
if let Err(err) = remove_file(file_path) {
log::error!("{err}");
}
}
}
let mut should_change = false; let mut should_change = false;
@@ -280,7 +329,9 @@ pub async fn activate_profile(
// begin to generate the new profile config // begin to generate the new profile config
let def_config = config::read_yaml::<Mapping>(file_path.clone()); let def_config = config::read_yaml::<Mapping>(file_path.clone());
let mut new_config = Mapping::new();
// use the clash config except 5 keys below
let mut new_config = clash_config.clone();
// Only the following fields are allowed: // Only the following fields are allowed:
// proxies/proxy-providers/proxy-groups/rule-providers/rules // proxies/proxy-providers/proxy-groups/rule-providers/rules
@@ -299,23 +350,6 @@ pub async fn activate_profile(
} }
}); });
// add some of the clash `config.yaml` config to it
let valid_keys = vec![
"mixed-port",
"log-level",
"allow-lan",
"external-controller",
"secret",
"ipv6",
];
valid_keys.iter().for_each(|key| {
let key = Value::String(key.to_string());
if clash_config.contains_key(&key) {
let value = clash_config[&key].clone();
new_config.insert(key, value);
}
});
config::save_yaml( config::save_yaml(
temp_path.clone(), temp_path.clone(),
&new_config, &new_config,

View File

@@ -1,7 +1,11 @@
use crate::utils::{config, dirs, sysopt::SysProxyConfig}; use crate::{
core::Clash,
utils::{config, dirs, sysopt::SysProxyConfig},
};
use auto_launch::{AutoLaunch, AutoLaunchBuilder}; use auto_launch::{AutoLaunch, AutoLaunchBuilder};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tauri::api::path::resource_dir; use std::sync::Arc;
use tauri::{async_runtime::Mutex, utils::platform::current_exe};
/// ### `verge.yaml` schema /// ### `verge.yaml` schema
#[derive(Default, Debug, Clone, Deserialize, Serialize)] #[derive(Default, Debug, Clone, Deserialize, Serialize)]
@@ -13,14 +17,26 @@ pub struct VergeConfig {
/// maybe be able to set the alpha /// maybe be able to set the alpha
pub theme_blur: Option<bool>, pub theme_blur: Option<bool>,
/// enable traffic graph default is true
pub traffic_graph: Option<bool>,
/// clash tun mode
pub enable_tun_mode: Option<bool>,
/// can the app auto startup /// can the app auto startup
pub enable_auto_launch: Option<bool>, pub enable_auto_launch: Option<bool>,
/// set system proxy /// set system proxy
pub enable_system_proxy: Option<bool>, pub enable_system_proxy: Option<bool>,
/// enable proxy guard
pub enable_proxy_guard: Option<bool>,
/// set system proxy bypass /// set system proxy bypass
pub system_proxy_bypass: Option<String>, pub system_proxy_bypass: Option<String>,
/// proxy guard duration
pub proxy_guard_duration: Option<u64>,
} }
static VERGE_CONFIG: &str = "verge.yaml"; static VERGE_CONFIG: &str = "verge.yaml";
@@ -50,6 +66,9 @@ pub struct Verge {
pub cur_sysproxy: Option<SysProxyConfig>, pub cur_sysproxy: Option<SysProxyConfig>,
pub auto_launch: Option<AutoLaunch>, pub auto_launch: Option<AutoLaunch>,
/// record whether the guard async is running or not
guard_state: Arc<Mutex<bool>>,
} }
impl Default for Verge { impl Default for Verge {
@@ -65,6 +84,7 @@ impl Verge {
old_sysproxy: None, old_sysproxy: None,
cur_sysproxy: None, cur_sysproxy: None,
auto_launch: None, auto_launch: None,
guard_state: Arc::new(Mutex::new(false)),
} }
} }
@@ -89,6 +109,9 @@ impl Verge {
self.cur_sysproxy = Some(sysproxy); self.cur_sysproxy = Some(sysproxy);
} }
// launchs the system proxy guard
Verge::guard_proxy(self.guard_state.clone());
} }
/// reset the sysproxy /// reset the sysproxy
@@ -102,11 +125,11 @@ impl Verge {
} }
/// init the auto launch /// init the auto launch
pub fn init_launch(&mut self, package_info: &tauri::PackageInfo) { pub fn init_launch(&mut self) {
let app_name = "clash-verge"; let app_exe = current_exe().unwrap();
let app_path = get_app_path(app_name); let app_exe = dunce::canonicalize(app_exe).unwrap();
let app_path = resource_dir(package_info).unwrap().join(app_path); let app_name = app_exe.file_stem().unwrap().to_str().unwrap();
let app_path = app_path.as_os_str().to_str().unwrap(); let app_path = app_exe.as_os_str().to_str().unwrap();
let auto = AutoLaunchBuilder::new() let auto = AutoLaunchBuilder::new()
.set_app_name(app_name) .set_app_name(app_name)
@@ -149,36 +172,20 @@ impl Verge {
let auto_launch = self.auto_launch.clone().unwrap(); let auto_launch = self.auto_launch.clone().unwrap();
let result = if enable { let result = match enable {
auto_launch.enable() true => auto_launch.enable(),
} else { false => auto_launch.disable(),
auto_launch.disable()
}; };
match result { match result {
Ok(_) => Ok(()), Ok(_) => Ok(()),
Err(_) => Err("failed to set system startup info".into()), Err(err) => {
log::error!("{err}");
Err("failed to set system startup info".into())
}
} }
} }
// fn guard_thread(&mut self) -> Result<(), String> {
// let sysproxy = self.cur_sysproxy.clone();
// use std::{thread, time};
// tauri::async_runtime::spawn(async move {
// if let Some(sysproxy) = sysproxy {
// sysproxy.set_sys();
// }
// let ten_millis = time::Duration::from_millis(10);
// let now = time::Instant::now();
// thread::sleep(ten_millis);
// });
// Ok(())
// }
/// patch verge config /// patch verge config
/// There should be only one update at a time here /// There should be only one update at a time here
/// so call the save_file at the end is savely /// so call the save_file at the end is savely
@@ -190,6 +197,9 @@ impl Verge {
if patch.theme_blur.is_some() { if patch.theme_blur.is_some() {
self.config.theme_blur = patch.theme_blur; self.config.theme_blur = patch.theme_blur;
} }
if patch.traffic_graph.is_some() {
self.config.traffic_graph = patch.traffic_graph;
}
// should update system startup // should update system startup
if patch.enable_auto_launch.is_some() { if patch.enable_auto_launch.is_some() {
@@ -201,9 +211,12 @@ impl Verge {
// should update system proxy // should update system proxy
if patch.enable_system_proxy.is_some() { if patch.enable_system_proxy.is_some() {
let enable = patch.enable_system_proxy.unwrap(); let enable = patch.enable_system_proxy.unwrap();
if let Some(mut sysproxy) = self.cur_sysproxy.take() { if let Some(mut sysproxy) = self.cur_sysproxy.take() {
sysproxy.enable = enable; sysproxy.enable = enable;
if sysproxy.set_sys().is_err() { if sysproxy.set_sys().is_err() {
self.cur_sysproxy = Some(sysproxy);
log::error!("failed to set system proxy"); log::error!("failed to set system proxy");
return Err("failed to set system proxy".into()); return Err("failed to set system proxy".into());
} }
@@ -212,23 +225,108 @@ impl Verge {
self.config.enable_system_proxy = Some(enable); self.config.enable_system_proxy = Some(enable);
} }
// todo
// should update system proxy too // should update system proxy too
if patch.system_proxy_bypass.is_some() { if patch.system_proxy_bypass.is_some() {
self.config.system_proxy_bypass = patch.system_proxy_bypass; let bypass = patch.system_proxy_bypass.unwrap();
if let Some(mut sysproxy) = self.cur_sysproxy.take() {
if sysproxy.enable {
sysproxy.bypass = bypass.clone();
if sysproxy.set_sys().is_err() {
self.cur_sysproxy = Some(sysproxy);
log::error!("failed to set system proxy");
return Err("failed to set system proxy".into());
}
}
self.cur_sysproxy = Some(sysproxy);
}
self.config.system_proxy_bypass = Some(bypass);
}
// proxy guard
// only change it
if patch.enable_proxy_guard.is_some() {
self.config.enable_proxy_guard = patch.enable_proxy_guard;
}
if patch.proxy_guard_duration.is_some() {
self.config.proxy_guard_duration = patch.proxy_guard_duration;
}
// relaunch the guard
if patch.enable_system_proxy.is_some() || patch.enable_proxy_guard.is_some() {
Verge::guard_proxy(self.guard_state.clone());
}
// handle the tun mode
if patch.enable_tun_mode.is_some() {
self.config.enable_tun_mode = patch.enable_tun_mode;
} }
self.config.save_file() self.config.save_file()
} }
} }
// Get the target app_path impl Verge {
fn get_app_path(app_name: &str) -> String { /// launch a system proxy guard
#[cfg(target_os = "linux")] /// read config from file directly
let ext = ""; pub fn guard_proxy(guard_state: Arc<Mutex<bool>>) {
#[cfg(target_os = "macos")] use tokio::time::{sleep, Duration};
let ext = ".app";
#[cfg(target_os = "windows")] tauri::async_runtime::spawn(async move {
let ext = ".exe"; // if it is running, exit
String::from(app_name) + ext let mut state = guard_state.lock().await;
if *state {
return;
}
*state = true;
std::mem::drop(state);
// default duration is 10s
let mut wait_secs = 10u64;
loop {
sleep(Duration::from_secs(wait_secs)).await;
log::debug!("[Guard]: heartbeat detection");
let verge = Verge::new();
let enable_proxy = verge.config.enable_system_proxy.unwrap_or(false);
let enable_guard = verge.config.enable_proxy_guard.unwrap_or(false);
let guard_duration = verge.config.proxy_guard_duration.unwrap_or(10);
// update duration
wait_secs = guard_duration;
// stop loop
if !enable_guard || !enable_proxy {
break;
}
log::info!("[Guard]: 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);
if let Err(err) = sysproxy.set_sys() {
log::error!("[Guard]: {err}");
log::error!("[Guard]: fail to set system proxy");
}
}
None => log::error!("[Guard]: fail to parse clash port"),
}
}
let mut state = guard_state.lock().await;
*state = false;
});
}
} }

View File

@@ -53,17 +53,19 @@ fn main() -> std::io::Result<()> {
} }
} }
"quit" => { "quit" => {
api::process::kill_children();
resolve::resolve_reset(app_handle); resolve::resolve_reset(app_handle);
app_handle.exit(0); api::process::kill_children();
std::process::exit(0);
} }
_ => {} _ => {}
}, },
SystemTrayEvent::LeftClick { .. } => { SystemTrayEvent::LeftClick { .. } => {
let window = app_handle.get_window("main").unwrap(); if cfg![target_os = "windows"] {
window.unminimize().unwrap(); let window = app_handle.get_window("main").unwrap();
window.show().unwrap(); window.unminimize().unwrap();
window.set_focus().unwrap(); window.show().unwrap();
window.set_focus().unwrap();
}
} }
_ => {} _ => {}
}) })
@@ -72,6 +74,9 @@ fn main() -> std::io::Result<()> {
cmds::restart_sidecar, cmds::restart_sidecar,
cmds::get_sys_proxy, cmds::get_sys_proxy,
cmds::get_cur_proxy, cmds::get_cur_proxy,
cmds::kill_sidecars,
cmds::open_app_dir,
cmds::open_logs_dir,
// clash // clash
cmds::get_clash_info, cmds::get_clash_info,
cmds::patch_clash_config, cmds::patch_clash_config,
@@ -79,6 +84,7 @@ fn main() -> std::io::Result<()> {
cmds::get_verge_config, cmds::get_verge_config,
cmds::patch_verge_config, cmds::patch_verge_config,
// profile // profile
cmds::new_profile,
cmds::view_profile, cmds::view_profile,
cmds::patch_profile, cmds::patch_profile,
cmds::import_profile, cmds::import_profile,
@@ -91,12 +97,12 @@ fn main() -> std::io::Result<()> {
.build(tauri::generate_context!()) .build(tauri::generate_context!())
.expect("error while running tauri application") .expect("error while running tauri application")
.run(|app_handle, e| match e { .run(|app_handle, e| match e {
tauri::Event::CloseRequested { label, api, .. } => { tauri::RunEvent::CloseRequested { label, api, .. } => {
let app_handle = app_handle.clone(); let app_handle = app_handle.clone();
api.prevent_close(); api.prevent_close();
app_handle.get_window(&label).unwrap().hide().unwrap(); app_handle.get_window(&label).unwrap().hide().unwrap();
} }
tauri::Event::ExitRequested { .. } => { tauri::RunEvent::ExitRequested { .. } => {
resolve::resolve_reset(app_handle); resolve::resolve_reset(app_handle);
api::process::kill_children(); api::process::kill_children();
} }

View File

@@ -1,7 +1,7 @@
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use tauri::{ use tauri::{
api::path::{home_dir, resource_dir}, api::path::{home_dir, resource_dir},
PackageInfo, Env, PackageInfo,
}; };
/// get the verge app home dir /// get the verge app home dir
@@ -14,5 +14,7 @@ pub fn app_home_dir() -> PathBuf {
/// get the resources dir /// get the resources dir
pub fn app_resources_dir(package_info: &PackageInfo) -> PathBuf { pub fn app_resources_dir(package_info: &PackageInfo) -> PathBuf {
resource_dir(package_info).unwrap().join("resources") resource_dir(package_info, &Env::default())
.unwrap()
.join("resources")
} }

View File

@@ -22,66 +22,63 @@ fn parse_string<T: FromStr>(target: &str, key: &str) -> Option<T> {
} }
} }
/// fetch and parse the profile /// fetch and parse the profile url
pub async fn fetch_profile(url: &str, with_proxy: bool) -> Option<ProfileResponse> { /// maybe it contains some Subscription infomations, maybe not
pub async fn fetch_profile(url: &str, with_proxy: bool) -> Result<ProfileResponse, String> {
let builder = reqwest::ClientBuilder::new(); let builder = reqwest::ClientBuilder::new();
let client = match with_proxy { let client = match with_proxy {
true => builder.build(), true => builder.build(),
false => builder.no_proxy().build(), false => builder.no_proxy().build(),
}; };
let resp = match client {
Ok(client) => match client.get(url).send().await { let resp = match client.unwrap().get(url).send().await {
Ok(res) => res, Ok(res) => res,
Err(_) => return None, Err(_) => return Err("failed to create https client".into()),
},
Err(_) => return None,
}; };
let header = resp.headers(); let header = resp.headers();
// parse the Subscription Userinfo // parse the Subscription Userinfo
let extra = { let extra = match header.get("Subscription-Userinfo") {
let sub_info = match header.get("Subscription-Userinfo") { Some(value) => {
Some(value) => value.to_str().unwrap_or(""), let sub_info = value.to_str().unwrap_or("");
None => "",
};
ProfileExtra { Some(ProfileExtra {
upload: parse_string(sub_info, "upload=").unwrap_or(0), upload: parse_string(sub_info, "upload=").unwrap_or(0),
download: parse_string(sub_info, "download=").unwrap_or(0), download: parse_string(sub_info, "download=").unwrap_or(0),
total: parse_string(sub_info, "total=").unwrap_or(0), total: parse_string(sub_info, "total=").unwrap_or(0),
expire: parse_string(sub_info, "expire=").unwrap_or(0), expire: parse_string(sub_info, "expire=").unwrap_or(0),
})
} }
None => None,
}; };
// parse the `name` and `file` let file = {
let (name, file) = {
let now = SystemTime::now() let now = SystemTime::now()
.duration_since(UNIX_EPOCH) .duration_since(UNIX_EPOCH)
.unwrap() .unwrap()
.as_secs(); .as_secs();
let file = format!("{}.yaml", now); format!("{}.yaml", now)
let name = header.get("Content-Disposition").unwrap().to_str().unwrap(); };
let name = parse_string::<String>(name, "filename=");
match name { let name = match header.get("Content-Disposition") {
Some(f) => (f, file), Some(name) => {
None => (file.clone(), file), let name = name.to_str().unwrap();
parse_string::<String>(name, "filename=").unwrap_or(file.clone())
} }
None => file.clone(),
}; };
// get the data // get the data
let data = match resp.text_with_charset("utf-8").await { match resp.text_with_charset("utf-8").await {
Ok(d) => d, Ok(data) => Ok(ProfileResponse {
Err(_) => return None, file,
}; name,
data,
Some(ProfileResponse { extra,
file, }),
name, Err(_) => Err("failed to parse the response data".into()),
data, }
extra,
})
} }
#[test] #[test]

View File

@@ -1,6 +1,6 @@
extern crate serde_yaml; extern crate serde_yaml;
use crate::utils::dirs; use crate::utils::{dirs, tmpl};
use chrono::Local; use chrono::Local;
use log::LevelFilter; use log::LevelFilter;
use log4rs::append::console::ConsoleAppender; use log4rs::append::console::ConsoleAppender;
@@ -41,44 +41,22 @@ fn init_log(log_dir: &PathBuf) {
} }
/// Initialize all the files from resources /// Initialize all the files from resources
fn init_config_file(app_dir: &PathBuf, res_dir: &PathBuf) { fn init_config(app_dir: &PathBuf) -> std::io::Result<()> {
// target path // target path
let clash_path = app_dir.join("config.yaml"); let clash_path = app_dir.join("config.yaml");
let verge_path = app_dir.join("verge.yaml"); let verge_path = app_dir.join("verge.yaml");
let profile_path = app_dir.join("profiles.yaml"); let profile_path = app_dir.join("profiles.yaml");
let mmdb_path = app_dir.join("Country.mmdb");
// template path
let clash_tmpl = res_dir.join("config_tmp.yaml");
let verge_tmpl = res_dir.join("verge_tmp.yaml");
let profiles_tmpl = res_dir.join("profiles_tmp.yaml");
let mmdb_tmpl = res_dir.join("Country.mmdb");
if !clash_path.exists() { if !clash_path.exists() {
if clash_tmpl.exists() { File::create(clash_path)?.write(tmpl::CLASH_CONFIG)?;
fs::copy(clash_tmpl, clash_path).unwrap();
} else {
// make sure that the config.yaml not null
let content = b"\
mixed-port: 7890\n\
log-level: info\n\
allow-lan: false\n\
external-controller: 127.0.0.1:9090\n\
secret: \"\"\n";
File::create(clash_path).unwrap().write(content).unwrap();
}
} }
if !verge_path.exists() {
// only copy it File::create(verge_path)?.write(tmpl::VERGE_CONFIG)?;
if !verge_path.exists() && verge_tmpl.exists() {
fs::copy(verge_tmpl, verge_path).unwrap();
} }
if !profile_path.exists() && profiles_tmpl.exists() { if !profile_path.exists() {
fs::copy(profiles_tmpl, profile_path).unwrap(); File::create(profile_path)?.write(tmpl::PROFILES_CONFIG)?;
}
if !mmdb_path.exists() && mmdb_tmpl.exists() {
fs::copy(mmdb_tmpl, mmdb_path).unwrap();
} }
Ok(())
} }
/// initialize app /// initialize app
@@ -101,5 +79,14 @@ pub fn init_app(package_info: &PackageInfo) {
} }
init_log(&log_dir); init_log(&log_dir);
init_config_file(&app_dir, &res_dir); if let Err(err) = init_config(&app_dir) {
log::error!("{err}");
}
// copy the resource file
let mmdb_path = app_dir.join("Country.mmdb");
let mmdb_tmpl = res_dir.join("Country.mmdb");
if !mmdb_path.exists() && mmdb_tmpl.exists() {
fs::copy(mmdb_tmpl, mmdb_path).unwrap();
}
} }

View File

@@ -5,3 +5,4 @@ pub mod init;
pub mod resolve; pub mod resolve;
pub mod server; pub mod server;
pub mod sysopt; pub mod sysopt;
pub mod tmpl;

View File

@@ -1,23 +1,10 @@
use super::{init, server}; use super::{init, server};
use crate::{core::Profiles, states}; use crate::{core::Profiles, states};
use tauri::{App, AppHandle, Manager}; use tauri::{App, AppHandle, Manager};
use tauri_plugin_shadows::Shadows;
/// handle something when start app /// handle something when start app
pub fn resolve_setup(app: &App) { pub fn resolve_setup(app: &App) {
// set shadow when window decorations resolve_window(app);
let window = app.get_window("main").unwrap();
window.set_shadow(true);
// enable system blur
use tauri_plugin_vibrancy::Vibrancy;
#[cfg(target_os = "windows")]
window.apply_blur();
#[cfg(target_os = "macos")]
{
use tauri_plugin_vibrancy::MacOSVibrancy;
window.apply_vibrancy(MacOSVibrancy::AppearanceBased);
}
// setup a simple http server for singleton // setup a simple http server for singleton
server::embed_server(&app.handle()); server::embed_server(&app.handle());
@@ -35,18 +22,27 @@ pub fn resolve_setup(app: &App) {
let mut profiles = profiles_state.0.lock().unwrap(); let mut profiles = profiles_state.0.lock().unwrap();
if let Err(err) = clash.run_sidecar() { if let Err(err) = clash.run_sidecar() {
log::error!("{}", err); log::error!("{err}");
} }
*profiles = Profiles::read_file(); *profiles = Profiles::read_file();
if let Err(err) = profiles.activate(&clash) { if let Err(err) = profiles.activate(&clash) {
log::error!("{}", err); log::error!("{err}");
} }
verge.init_sysproxy(clash.info.port.clone()); verge.init_sysproxy(clash.info.port.clone());
verge.init_launch(app.package_info()); // 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();
}
verge.init_launch();
if let Err(err) = verge.sync_launch() { if let Err(err) = verge.sync_launch() {
log::error!("{}", err); log::error!("{err}");
} }
} }
@@ -57,3 +53,34 @@ pub fn resolve_reset(app_handle: &AppHandle) {
verge.reset_sysproxy(); verge.reset_sysproxy();
} }
/// customize the window theme
fn resolve_window(app: &App) {
let window = app.get_window("main").unwrap();
#[cfg(target_os = "windows")]
{
use tauri_plugin_shadows::Shadows;
use tauri_plugin_vibrancy::Vibrancy;
window.set_decorations(false).unwrap();
window.set_shadow(true);
window.apply_blur();
}
#[cfg(target_os = "macos")]
{
use tauri::LogicalSize;
use tauri::Size::Logical;
window.set_decorations(true).unwrap();
window
.set_size(Logical(LogicalSize {
width: 800.0,
height: 610.0,
}))
.unwrap();
// use tauri_plugin_vibrancy::MacOSVibrancy;
// #[allow(deprecated)]
// window.apply_vibrancy(MacOSVibrancy::AppearanceBased);
}
}

View File

@@ -0,0 +1,42 @@
///! Some config file template
/// template for clash core `config.yaml`
pub const CLASH_CONFIG: &[u8] = br#"# Default Config For Clash Core
mixed-port: 7890
log-level: info
allow-lan: false
external-controller: 127.0.0.1:9090
mode: rule
secret: ""
"#;
/// template for `profiles.yaml`
pub const PROFILES_CONFIG: &[u8] = b"# Profiles Config for Clash Verge
current: 0
items: ~
";
/// template for `verge.yaml`
pub const VERGE_CONFIG: &[u8] = b"# Defaulf Config For Clash Verge
theme_mode: light
theme_blur: false
traffic_graph: true
enable_self_startup: false
enable_system_proxy: false
enable_proxy_guard: false
proxy_guard_duration: 10
system_proxy_bypass: localhost;127.*;10.*;192.168.*;<local>
";
/// template for new a profile item
pub const ITEM_CONFIG: &[u8] = b"# Profile Template for clash verge\n\n
# proxies defination (optional, the same as clash)
proxies:\n
# proxy-groups (optional, the same as clash)
proxy-groups:\n
# rules (optional, the same as clash)
rules:\n\n
";

View File

@@ -1,7 +1,7 @@
{ {
"package": { "package": {
"productName": "clash-verge", "productName": "clash-verge",
"version": "0.0.12" "version": "0.0.18"
}, },
"build": { "build": {
"distDir": "../dist", "distDir": "../dist",
@@ -54,10 +54,16 @@
"endpoints": [ "endpoints": [
"https://github.com/zzzgydi/clash-verge/releases/download/updater/update.json" "https://github.com/zzzgydi/clash-verge/releases/download/updater/update.json"
], ],
"dialog": false "dialog": false,
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDExNUFBNTBBN0FDNEFBRTUKUldUbHFzUjZDcVZhRVRJM25NS3NkSFlFVElxUkNZMzZ6bHUwRVJjb2F3alJXVzRaeDdSaTA2YWYK"
}, },
"allowlist": { "allowlist": {
"all": true "shell": {
"all": true
},
"window": {
"all": true
}
}, },
"windows": [ "windows": [
{ {

View File

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

View File

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

View File

@@ -9,6 +9,8 @@
width: 90%; width: 90%;
max-width: 850px; max-width: 850px;
margin: 0 auto; margin: 0 auto;
padding-right: 4px;
box-sizing: border-box;
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;

View File

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

View File

@@ -1,4 +1,4 @@
import { ApiType } from "../services/types"; import { ApiType } from "../../services/types";
interface Props { interface Props {
value: ApiType.ConnectionsItem; value: ApiType.ConnectionsItem;

View File

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

View File

@@ -10,6 +10,7 @@ import {
DialogContentText, DialogContentText,
DialogTitle, DialogTitle,
} from "@mui/material"; } from "@mui/material";
import { killSidecars } from "../../services/cmds";
interface Props { interface Props {
open: boolean; open: boolean;
@@ -31,6 +32,7 @@ const UpdateDialog = (props: Props) => {
try { try {
setUploading(true); setUploading(true);
uploadingState = true; uploadingState = true;
await killSidecars();
await installUpdate(); await installUpdate();
await relaunch(); await relaunch();
} catch (error) { } catch (error) {

View File

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

View File

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

View File

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

View File

@@ -13,10 +13,10 @@ import {
} from "@mui/material"; } from "@mui/material";
import { useSWRConfig } from "swr"; import { useSWRConfig } from "swr";
import { RefreshRounded } from "@mui/icons-material"; import { RefreshRounded } from "@mui/icons-material";
import { CmdType } from "../services/types"; import { CmdType } from "../../services/types";
import { updateProfile, deleteProfile, viewProfile } from "../services/cmds"; import { updateProfile, deleteProfile, viewProfile } from "../../services/cmds";
import Notice from "./notice"; import Notice from "../base/base-notice";
import parseTraffic from "../utils/parse-traffic"; import parseTraffic from "../../utils/parse-traffic";
import relativeTime from "dayjs/plugin/relativeTime"; import relativeTime from "dayjs/plugin/relativeTime";
dayjs.extend(relativeTime); dayjs.extend(relativeTime);
@@ -59,6 +59,12 @@ const ProfileItem: React.FC<Props> = (props) => {
const progress = Math.round(((download + upload) * 100) / (total + 0.1)); const progress = Math.round(((download + upload) * 100) / (total + 0.1));
const fromnow = updated > 0 ? dayjs(updated * 1000).fromNow() : ""; 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 onView = async () => { const onView = async () => {
setAnchorEl(null); setAnchorEl(null);
try { try {
@@ -111,6 +117,26 @@ const ProfileItem: React.FC<Props> = (props) => {
event.preventDefault(); event.preventDefault();
}; };
const boxStyle = {
height: 26,
display: "flex",
alignItems: "center",
justifyContent: "space-between",
};
const urlModeMenu = [
{ label: "Select", handler: onForceSelect },
{ label: "View", 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: onView },
{ label: "Delete", handler: onDelete },
];
return ( return (
<> <>
<Wrapper <Wrapper
@@ -155,52 +181,64 @@ const ProfileItem: React.FC<Props> = (props) => {
{name} {name}
</Typography> </Typography>
<IconButton {/* only if has url can it be updated */}
sx={{ {hasUrl && (
width: 30, <IconButton
height: 30, sx={{
animation: loading ? `1s linear infinite ${round}` : "none", width: 26,
}} height: 26,
color="inherit" animation: loading ? `1s linear infinite ${round}` : "none",
disabled={loading} }}
onClick={(e) => { color="inherit"
e.stopPropagation(); disabled={loading}
onUpdateWrapper(false)(); onClick={(e) => {
}} e.stopPropagation();
> onUpdateWrapper(false)();
<RefreshRounded /> }}
</IconButton> >
<RefreshRounded />
</IconButton>
)}
</Box> </Box>
<Box display="flex" justifyContent="space-between" alignItems="center"> {/* the second line show url's info or description */}
<Typography noWrap title={`From: ${from}`}> {hasUrl ? (
{from} <Box sx={boxStyle}>
</Typography> <Typography noWrap title={`From: ${from}`}>
{from}
</Typography>
<Typography <Typography
noWrap noWrap
flex="1 0 auto" flex="1 0 auto"
fontSize={14} fontSize={14}
textAlign="right" textAlign="right"
title="updated time" title="updated time"
> >
{fromnow} {fromnow}
</Typography> </Typography>
</Box> </Box>
) : (
<Box sx={boxStyle}>
<Typography noWrap title={itemData.desc}>
{itemData.desc}
</Typography>
</Box>
)}
<Box {/* the third line show extra info or last updated time */}
sx={{ {hasExtra ? (
my: 0.5, <Box sx={{ ...boxStyle, fontSize: 14 }}>
fontSize: 14, <span title="used / total">
display: "flex", {parseTraffic(upload + download)} / {parseTraffic(total)}
justifyContent: "space-between", </span>
}} <span title="expire time">{expire}</span>
> </Box>
<span title="used / total"> ) : (
{parseTraffic(upload + download)} / {parseTraffic(total)} <Box sx={{ ...boxStyle, fontSize: 14, justifyContent: "flex-end" }}>
</span> <span title="updated time">{parseExpire(updated)}</span>
<span title="expire time">{expire}</span> </Box>
</Box> )}
<LinearProgress <LinearProgress
variant="determinate" variant="determinate"
@@ -216,11 +254,15 @@ const ProfileItem: React.FC<Props> = (props) => {
anchorPosition={position} anchorPosition={position}
anchorReference="anchorPosition" anchorReference="anchorPosition"
> >
<MenuItem onClick={onForceSelect}>Select</MenuItem> {(hasUrl ? urlModeMenu : fileModeMenu).map((item) => (
<MenuItem onClick={onView}>View</MenuItem> <MenuItem
<MenuItem onClick={onUpdateWrapper(false)}>Update</MenuItem> key={item.label}
<MenuItem onClick={onUpdateWrapper(true)}>Update(Proxy)</MenuItem> onClick={item.handler}
<MenuItem onClick={onDelete}>Delete</MenuItem> sx={{ minWidth: 133 }}
>
{item.label}
</MenuItem>
))}
</Menu> </Menu>
</> </>
); );

View File

@@ -0,0 +1,71 @@
import { useEffect, useState } from "react";
import {
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
TextField,
} from "@mui/material";
import Notice from "../base/base-notice";
interface Props {
open: boolean;
onClose: () => void;
onSubmit: (name: string, desc: string) => void;
}
const ProfileNew = (props: Props) => {
const { open, onClose, onSubmit } = props;
const [name, setName] = useState("");
const [desc, setDesc] = useState("");
const onCreate = () => {
if (!name.trim()) {
Notice.error("`Name` should not be null");
return;
}
onSubmit(name, desc);
};
useEffect(() => {
if (!open) {
setName("");
setDesc("");
}
}, [open]);
return (
<Dialog open={open} onClose={onClose}>
<DialogTitle>Create Profile</DialogTitle>
<DialogContent sx={{ width: 320, pb: 0.5 }}>
<TextField
autoFocus
fullWidth
label="Name"
margin="dense"
variant="outlined"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<TextField
fullWidth
label="Descriptions"
margin="normal"
variant="outlined"
value={desc}
onChange={(e) => setDesc(e.target.value)}
/>
</DialogContent>
<DialogActions sx={{ px: 2, pb: 2 }}>
<Button onClick={onClose}>Cancel</Button>
<Button onClick={onCreate} variant="contained">
Create
</Button>
</DialogActions>
</Dialog>
);
};
export default ProfileNew;

View File

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

View File

@@ -1,4 +1,5 @@
import { useState } from "react"; import { useRef, useState } from "react";
import { useSWRConfig } from "swr";
import { Virtuoso } from "react-virtuoso"; import { Virtuoso } from "react-virtuoso";
import { import {
Box, Box,
@@ -16,9 +17,10 @@ import {
MyLocationRounded, MyLocationRounded,
NetworkCheckRounded, NetworkCheckRounded,
} from "@mui/icons-material"; } from "@mui/icons-material";
import { updateProxy } from "../services/api"; import { ApiType } from "../../services/types";
import { ApiType } from "../services/types"; import { updateProxy } from "../../services/api";
import { getProfiles, patchProfile } from "../services/cmds"; import { getProfiles, patchProfile } from "../../services/cmds";
import delayManager from "../../services/delay";
import ProxyItem from "./proxy-item"; import ProxyItem from "./proxy-item";
interface Props { interface Props {
@@ -26,25 +28,34 @@ interface Props {
} }
const ProxyGroup = ({ group }: Props) => { const ProxyGroup = ({ group }: Props) => {
const { mutate } = useSWRConfig();
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [now, setNow] = useState(group.now); const [now, setNow] = useState(group.now);
const virtuosoRef = useRef<any>();
const proxies = group.all ?? []; const proxies = group.all ?? [];
const onUpdate = async (name: string) => { const selectLockRef = useRef(false);
// can not call update const onSelect = async (name: string) => {
if (group.type !== "Selector") { // Todo: support another proxy group type
// Todo if (group.type !== "Selector") return;
// error Tips
return; if (selectLockRef.current) return;
} selectLockRef.current = true;
const oldValue = now; const oldValue = now;
try { try {
setNow(name); setNow(name);
await updateProxy(group.name, name); await updateProxy(group.name, name);
} catch {
setNow(oldValue);
return; // do not update profile
} finally {
selectLockRef.current = false;
}
const profiles = await getProfiles().catch(console.error); try {
if (!profiles) return; const profiles = await getProfiles();
const profile = profiles.items![profiles.current!]!; const profile = profiles.items![profiles.current!]!;
if (!profile) return; if (!profile) return;
if (!profile.selected) profile.selected = []; if (!profile.selected) profile.selected = [];
@@ -58,15 +69,47 @@ const ProxyGroup = ({ group }: Props) => {
} else { } else {
profile.selected[index] = { name: group.name, now: name }; profile.selected[index] = { name: group.name, now: name };
} }
await patchProfile(profiles.current!, profile);
patchProfile(profiles.current!, profile).catch(console.error); } catch (err) {
} catch { console.error(err);
setNow(oldValue);
// Todo
// error tips
} }
}; };
const onLocation = () => {
const index = proxies.findIndex((p) => p.name === now);
if (index >= 0) {
virtuosoRef.current?.scrollToIndex?.({
index,
align: "center",
behavior: "smooth",
});
}
};
const checkLockRef = useRef(false);
const onCheckAll = async () => {
if (checkLockRef.current) return;
checkLockRef.current = true;
// rerender quickly
if (proxies.length) setTimeout(() => mutate("getProxies"), 500);
let names = proxies.map((p) => p.name);
while (names.length) {
const list = names.slice(0, 8);
names = names.slice(8);
await Promise.all(
list.map((n) => delayManager.checkDelay(n, group.name))
);
mutate("getProxies");
}
checkLockRef.current = false;
};
return ( return (
<> <>
<ListItem button onClick={() => setOpen(!open)} dense> <ListItem button onClick={() => setOpen(!open)} dense>
@@ -88,24 +131,26 @@ const ProxyGroup = ({ group }: Props) => {
<Collapse in={open} timeout="auto" unmountOnExit> <Collapse in={open} timeout="auto" unmountOnExit>
<Box sx={{ pl: 4, pr: 3, my: 0.5 }}> <Box sx={{ pl: 4, pr: 3, my: 0.5 }}>
<IconButton size="small" title="location"> <IconButton size="small" title="location" onClick={onLocation}>
<MyLocationRounded /> <MyLocationRounded />
</IconButton> </IconButton>
<IconButton size="small" title="check"> <IconButton size="small" title="check" onClick={onCheckAll}>
<NetworkCheckRounded /> <NetworkCheckRounded />
</IconButton> </IconButton>
</Box> </Box>
{proxies.length >= 10 ? ( {proxies.length >= 10 ? (
<Virtuoso <Virtuoso
ref={virtuosoRef}
style={{ height: "320px", marginBottom: "4px" }} style={{ height: "320px", marginBottom: "4px" }}
totalCount={proxies.length} totalCount={proxies.length}
itemContent={(index) => ( itemContent={(index) => (
<ProxyItem <ProxyItem
groupName={group.name}
proxy={proxies[index]} proxy={proxies[index]}
selected={proxies[index].name === now} selected={proxies[index].name === now}
sx={{ py: 0, pl: 4 }} sx={{ py: 0, pl: 4 }}
onClick={onUpdate} onClick={onSelect}
/> />
)} )}
/> />
@@ -118,10 +163,11 @@ const ProxyGroup = ({ group }: Props) => {
{proxies.map((proxy) => ( {proxies.map((proxy) => (
<ProxyItem <ProxyItem
key={proxy.name} key={proxy.name}
groupName={group.name}
proxy={proxy} proxy={proxy}
selected={proxy.name === now} selected={proxy.name === now}
sx={{ py: 0, pl: 4 }} sx={{ py: 0, pl: 4 }}
onClick={onUpdate} onClick={onSelect}
/> />
))} ))}
</List> </List>

View File

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

View File

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

View File

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

View File

@@ -1,5 +1,5 @@
import useSWR, { useSWRConfig } from "swr"; import useSWR, { useSWRConfig } from "swr";
import { Box, ListItemText, Switch } from "@mui/material"; import { Box, ListItemText, Switch, TextField } from "@mui/material";
import { getVergeConfig, patchVergeConfig } from "../../services/cmds"; import { getVergeConfig, patchVergeConfig } from "../../services/cmds";
import { SettingList, SettingItem } from "./setting"; import { SettingList, SettingItem } from "./setting";
import { CmdType } from "../../services/types"; import { CmdType } from "../../services/types";
@@ -15,8 +15,11 @@ const SettingSystem = ({ onError }: Props) => {
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig); const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
const { const {
enable_auto_launch: startup = false, enable_tun_mode = false,
enable_system_proxy: proxy = false, enable_auto_launch = false,
enable_system_proxy = false,
system_proxy_bypass = "",
enable_proxy_guard = false,
} = vergeConfig ?? {}; } = vergeConfig ?? {};
const onSwitchFormat = (_e: any, value: boolean) => value; const onSwitchFormat = (_e: any, value: boolean) => value;
@@ -26,10 +29,24 @@ const SettingSystem = ({ onError }: Props) => {
return ( return (
<SettingList title="System Setting"> <SettingList title="System Setting">
<SettingItem>
<ListItemText primary="Tun Mode" />
<GuardState
value={enable_tun_mode}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_tun_mode: e })}
onGuard={(e) => patchVergeConfig({ enable_tun_mode: e })}
>
<Switch edge="end" />
</GuardState>
</SettingItem>
<SettingItem> <SettingItem>
<ListItemText primary="Auto Launch" /> <ListItemText primary="Auto Launch" />
<GuardState <GuardState
value={startup} value={enable_auto_launch}
valueProps="checked" valueProps="checked"
onCatch={onError} onCatch={onError}
onFormat={onSwitchFormat} onFormat={onSwitchFormat}
@@ -50,16 +67,51 @@ const SettingSystem = ({ onError }: Props) => {
} }
/> />
<GuardState <GuardState
value={proxy} value={enable_system_proxy}
valueProps="checked" valueProps="checked"
onCatch={onError} onCatch={onError}
onFormat={onSwitchFormat} onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_system_proxy: e })} onChange={(e) => onChangeData({ enable_system_proxy: e })}
onGuard={(e) => patchVergeConfig({ enable_system_proxy: e })} onGuard={async (e) => {
await patchVergeConfig({ enable_system_proxy: e });
mutate("getVergeConfig"); // update bypass value
}}
> >
<Switch edge="end" /> <Switch edge="end" />
</GuardState> </GuardState>
</SettingItem> </SettingItem>
{enable_system_proxy && (
<SettingItem>
<ListItemText primary="Proxy Guard" />
<GuardState
value={enable_proxy_guard}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_proxy_guard: e })}
onGuard={(e) => patchVergeConfig({ enable_proxy_guard: e })}
>
<Switch edge="end" />
</GuardState>
</SettingItem>
)}
{enable_system_proxy && (
<SettingItem>
<ListItemText primary="Proxy Bypass" />
<GuardState
value={system_proxy_bypass ?? ""}
onCatch={onError}
onFormat={(e: any) => e.target.value}
onChange={(e) => onChangeData({ system_proxy_bypass: e })}
onGuard={(e) => patchVergeConfig({ system_proxy_bypass: e })}
waitTime={1000}
>
<TextField autoComplete="off" size="small" sx={{ width: 120 }} />
</GuardState>
</SettingItem>
)}
</SettingList> </SettingList>
); );
}; };

View File

@@ -1,11 +1,17 @@
import useSWR, { useSWRConfig } from "swr"; import useSWR, { useSWRConfig } from "swr";
import { ListItemText, Switch, Typography } from "@mui/material"; import { IconButton, ListItemText, Switch, Typography } from "@mui/material";
import { getVergeConfig, patchVergeConfig } from "../../services/cmds"; import {
getVergeConfig,
openAppDir,
openLogsDir,
patchVergeConfig,
} from "../../services/cmds";
import { ArrowForward } from "@mui/icons-material";
import { SettingList, SettingItem } from "./setting"; import { SettingList, SettingItem } from "./setting";
import { CmdType } from "../../services/types"; import { CmdType } from "../../services/types";
import { version } from "../../../package.json"; import { version } from "../../../package.json";
import GuardState from "./guard-state";
import PaletteSwitch from "./palette-switch"; import PaletteSwitch from "./palette-switch";
import GuardState from "./guard-state";
interface Props { interface Props {
onError?: (err: Error) => void; onError?: (err: Error) => void;
@@ -15,7 +21,7 @@ const SettingVerge = ({ onError }: Props) => {
const { mutate } = useSWRConfig(); const { mutate } = useSWRConfig();
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig); const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
const { theme_mode: mode = "light", theme_blur: blur = false } = const { theme_mode = "light", theme_blur = false, traffic_graph } =
vergeConfig ?? {}; vergeConfig ?? {};
const onSwitchFormat = (_e: any, value: boolean) => value; const onSwitchFormat = (_e: any, value: boolean) => value;
@@ -28,13 +34,13 @@ const SettingVerge = ({ onError }: Props) => {
<SettingItem> <SettingItem>
<ListItemText primary="Theme Mode" /> <ListItemText primary="Theme Mode" />
<GuardState <GuardState
value={mode === "dark"} value={theme_mode === "dark"}
valueProps="checked" valueProps="checked"
onCatch={onError} onCatch={onError}
onFormat={onSwitchFormat} onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ theme_mode: e ? "dark" : "light" })} onChange={(e) => onChangeData({ theme_mode: e ? "dark" : "light" })}
onGuard={(c) => onGuard={(e) =>
patchVergeConfig({ theme_mode: c ? "dark" : "light" }) patchVergeConfig({ theme_mode: e ? "dark" : "light" })
} }
> >
<PaletteSwitch edge="end" /> <PaletteSwitch edge="end" />
@@ -44,7 +50,7 @@ const SettingVerge = ({ onError }: Props) => {
<SettingItem> <SettingItem>
<ListItemText primary="Theme Blur" /> <ListItemText primary="Theme Blur" />
<GuardState <GuardState
value={blur} value={theme_blur}
valueProps="checked" valueProps="checked"
onCatch={onError} onCatch={onError}
onFormat={onSwitchFormat} onFormat={onSwitchFormat}
@@ -55,6 +61,34 @@ const SettingVerge = ({ onError }: Props) => {
</GuardState> </GuardState>
</SettingItem> </SettingItem>
<SettingItem>
<ListItemText primary="Traffic Graph" />
<GuardState
value={traffic_graph ?? true}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ traffic_graph: e })}
onGuard={(e) => patchVergeConfig({ traffic_graph: e })}
>
<Switch edge="end" />
</GuardState>
</SettingItem>
<SettingItem>
<ListItemText primary="Open App Dir" />
<IconButton color="inherit" size="small" onClick={openAppDir}>
<ArrowForward />
</IconButton>
</SettingItem>
<SettingItem>
<ListItemText primary="Open Logs Dir" />
<IconButton color="inherit" size="small" onClick={openLogsDir}>
<ArrowForward />
</IconButton>
</SettingItem>
<SettingItem> <SettingItem>
<ListItemText primary="Version" /> <ListItemText primary="Version" />
<Typography sx={{ py: "6px" }}>v{version}</Typography> <Typography sx={{ py: "6px" }}>v{version}</Typography>

View File

@@ -1,25 +1,26 @@
import useSWR, { SWRConfig, useSWRConfig } from "swr"; import useSWR, { SWRConfig, useSWRConfig } from "swr";
import { useEffect, useMemo } from "react"; import { useEffect, useMemo } from "react";
import { Route, Routes } from "react-router-dom"; import { Route, Routes } from "react-router-dom";
import { useRecoilState } from "recoil";
import { alpha, createTheme, List, Paper, ThemeProvider } from "@mui/material"; import { alpha, createTheme, List, Paper, ThemeProvider } from "@mui/material";
import { listen } from "@tauri-apps/api/event"; import { listen } from "@tauri-apps/api/event";
import { appWindow } from "@tauri-apps/api/window"; import { appWindow } from "@tauri-apps/api/window";
import { atomPaletteMode, atomThemeBlur } from "../states/setting";
import { getVergeConfig } from "../services/cmds";
import { getAxios } from "../services/api";
import { routers } from "./_routers"; import { routers } from "./_routers";
import { getAxios } from "../services/api";
import { getVergeConfig } from "../services/cmds";
import LogoSvg from "../assets/image/logo.svg"; import LogoSvg from "../assets/image/logo.svg";
import Traffic from "../components/traffic"; import LayoutItem from "../components/layout/layout-item";
import LayoutItem from "../components/layout-item"; import LayoutControl from "../components/layout/layout-control";
import UpdateButton from "../components/update-button"; import LayoutTraffic from "../components/layout/layout-traffic";
import LayoutControl from "../components/layout-control"; import UpdateButton from "../components/layout/update-button";
const isMacos = navigator.userAgent.includes("Mac OS X");
const Layout = () => { const Layout = () => {
const { mutate } = useSWRConfig(); const { mutate } = useSWRConfig();
const [mode, setMode] = useRecoilState(atomPaletteMode); const { data } = useSWR("getVergeConfig", getVergeConfig);
const [blur, setBlur] = useRecoilState(atomThemeBlur);
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig); const blur = !!data?.theme_blur;
const mode = data?.theme_mode ?? "light";
useEffect(() => { useEffect(() => {
window.addEventListener("keydown", (e) => { window.addEventListener("keydown", (e) => {
@@ -36,12 +37,6 @@ const Layout = () => {
}); });
}, []); }, []);
useEffect(() => {
if (!vergeConfig) return;
setBlur(!!vergeConfig.theme_blur);
setMode(vergeConfig.theme_mode ?? "light");
}, [vergeConfig]);
const theme = useMemo(() => { const theme = useMemo(() => {
// const background = mode === "light" ? "#f5f5f5" : "#000"; // const background = mode === "light" ? "#f5f5f5" : "#000";
const selectColor = mode === "light" ? "#f5f5f5" : "#d5d5d5"; const selectColor = mode === "light" ? "#f5f5f5" : "#d5d5d5";
@@ -74,7 +69,7 @@ const Layout = () => {
<Paper <Paper
square square
elevation={0} elevation={0}
className="layout" className={`${isMacos ? "macos " : ""}layout`}
onPointerDown={onDragging} onPointerDown={onDragging}
sx={[ sx={[
(theme) => ({ (theme) => ({
@@ -98,16 +93,18 @@ const Layout = () => {
</List> </List>
<div className="the-traffic" data-windrag> <div className="the-traffic" data-windrag>
<Traffic /> <LayoutTraffic />
</div> </div>
</div> </div>
<div className="layout__right" data-windrag> <div className="layout__right" data-windrag>
<div className="the-bar"> {!isMacos && (
<LayoutControl /> <div className="the-bar">
</div> <LayoutControl />
</div>
)}
<div className="the-content" data-windrag> <div className="the-content">
<Routes> <Routes>
{routers.map(({ label, link, ele: Ele }) => ( {routers.map(({ label, link, ele: Ele }) => (
<Route key={label} path={link} element={<Ele />} /> <Route key={label} path={link} element={<Ele />} />

View File

@@ -3,8 +3,8 @@ import { Paper } from "@mui/material";
import { Virtuoso } from "react-virtuoso"; import { Virtuoso } from "react-virtuoso";
import { ApiType } from "../services/types"; import { ApiType } from "../services/types";
import { getInfomation } from "../services/api"; import { getInfomation } from "../services/api";
import BasePage from "../components/base-page"; import BasePage from "../components/base/base-page";
import ConnectionItem from "../components/connection-item"; import ConnectionItem from "../components/connection/connection-item";
const ConnectionsPage = () => { const ConnectionsPage = () => {
const initConn = { uploadTotal: 0, downloadTotal: 0, connections: [] }; const initConn = { uploadTotal: 0, downloadTotal: 0, connections: [] };

View File

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

View File

@@ -6,12 +6,14 @@ import {
selectProfile, selectProfile,
patchProfile, patchProfile,
importProfile, importProfile,
newProfile,
} from "../services/cmds"; } from "../services/cmds";
import { getProxies, updateProxy } from "../services/api"; import { getProxies, updateProxy } from "../services/api";
import noop from "../utils/noop"; import noop from "../utils/noop";
import Notice from "../components/notice"; import Notice from "../components/base/base-notice";
import BasePage from "../components/base-page"; import BasePage from "../components/base/base-page";
import ProfileItem from "../components/profile-item"; import ProfileItem from "../components/profile/profile-item";
import ProfileNew from "../components/profile/profile-new";
const ProfilePage = () => { const ProfilePage = () => {
const [url, setUrl] = useState(""); const [url, setUrl] = useState("");
@@ -94,6 +96,23 @@ const ProfilePage = () => {
} }
}; };
const lockNewRef = useRef(false);
const [dialogOpen, setDialogOpen] = useState(false);
const onNew = async (name: string, desc: string) => {
if (lockNewRef.current) return;
lockNewRef.current = true;
try {
await newProfile(name, desc);
setDialogOpen(false);
mutate("getProfiles");
} catch (err: any) {
err && Notice.error(err.toString());
} finally {
lockNewRef.current = false;
}
};
return ( return (
<BasePage title="Profiles"> <BasePage title="Profiles">
<Box sx={{ display: "flex", mb: 3 }}> <Box sx={{ display: "flex", mb: 3 }}>
@@ -105,15 +124,19 @@ const ProfilePage = () => {
fullWidth fullWidth
value={url} value={url}
onChange={(e) => setUrl(e.target.value)} onChange={(e) => setUrl(e.target.value)}
sx={{ mr: 2 }} sx={{ mr: 1 }}
/> />
<Button <Button
disabled={!url || disabled} disabled={!url || disabled}
variant="contained" variant="contained"
onClick={onImport} onClick={onImport}
sx={{ mr: 1 }}
> >
Import Import
</Button> </Button>
<Button variant="contained" onClick={() => setDialogOpen(true)}>
New
</Button>
</Box> </Box>
<Grid container spacing={3}> <Grid container spacing={3}>
@@ -128,6 +151,12 @@ const ProfilePage = () => {
</Grid> </Grid>
))} ))}
</Grid> </Grid>
<ProfileNew
open={dialogOpen}
onClose={() => setDialogOpen(false)}
onSubmit={onNew}
/>
</BasePage> </BasePage>
); );
}; };

View File

@@ -1,46 +1,127 @@
import useSWR, { useSWRConfig } from "swr"; import useSWR, { useSWRConfig } from "swr";
import { useEffect } from "react"; import { useEffect, useMemo, useRef, useState } from "react";
import { List, Paper } from "@mui/material"; import { Virtuoso } from "react-virtuoso";
import { Button, ButtonGroup, List, Paper } from "@mui/material";
import { getClashConfig, updateConfigs, updateProxy } from "../services/api";
import { patchClashConfig } from "../services/cmds";
import { getProxies } from "../services/api"; import { getProxies } from "../services/api";
import BasePage from "../components/base-page"; import BasePage from "../components/base/base-page";
import ProxyItem from "../components/proxy-item"; import ProxyItem from "../components/proxy/proxy-item";
import ProxyGroup from "../components/proxy-group"; import ProxyGroup from "../components/proxy/proxy-group";
const ProxyPage = () => { const ProxyPage = () => {
const { mutate } = useSWRConfig(); const { mutate } = useSWRConfig();
const { data: proxiesData } = useSWR("getProxies", getProxies); const { data: proxiesData } = useSWR("getProxies", getProxies);
const { groups = [], proxies = [] } = proxiesData ?? {}; const { data: clashConfig } = useSWR("getClashConfig", getClashConfig);
const [curProxy, setCurProxy] = useState<string>("DIRECT");
const curMode = clashConfig?.mode.toLowerCase();
// proxy groups
const { groups = [] } = proxiesData ?? {};
// proxies and sorted
const filterProxies = useMemo(() => {
if (!proxiesData?.proxies) return [];
const list = Object.values(proxiesData.proxies);
const retList = list.filter(
(p) => !p.all?.length && p.name !== "DIRECT" && p.name !== "REJECT"
);
const direct = list.filter((p) => p.name === "DIRECT");
const reject = list.filter((p) => p.name === "REJECT");
return direct.concat(retList).concat(reject);
}, [proxiesData]);
const modeList = ["rule", "global", "direct"];
const asGroup = curMode === "rule" && groups.length;
// make sure that fetch the proxies successfully
useEffect(() => { useEffect(() => {
// fix the empty proxies on the first sight if (
// this bud only show on the build version (curMode === "rule" && !groups.length) ||
// call twice to avoid something unknown or the delay of the clash startup (curMode === "global" && filterProxies.length < 4)
setTimeout(() => mutate("getProxies"), 250); ) {
setTimeout(() => mutate("getProxies"), 1000); setTimeout(() => mutate("getProxies"), 500);
}, []); }
}, [groups, filterProxies, curMode]);
// update the current proxy
useEffect(() => {
if (curMode === "direct") setCurProxy("DIRECT");
if (curMode === "global") {
const globalNow = proxiesData?.proxies?.GLOBAL?.now;
setCurProxy(globalNow || "DIRECT");
}
}, [curMode, proxiesData]);
const changeLockRef = useRef(false);
const onChangeMode = async (mode: string) => {
if (changeLockRef.current) return;
changeLockRef.current = true;
try {
// switch rapidly
await updateConfigs({ mode });
await patchClashConfig({ mode });
mutate("getClashConfig");
} finally {
changeLockRef.current = false;
}
};
const onChangeProxy = async (name: string) => {
if (curMode !== "global") return;
await updateProxy("GLOBAL", name);
setCurProxy(name);
};
// difference style
const pageStyle = asGroup ? {} : { height: "100%" };
const paperStyle: any = asGroup
? { mb: 0.5 }
: { py: 1, height: "100%", boxSizing: "border-box" };
return ( return (
<BasePage title={groups.length ? "Proxy Groups" : "Proxies"}> <BasePage
<Paper sx={{ borderRadius: 1, boxShadow: 2, mb: 1 }}> contentStyle={pageStyle}
{groups.length > 0 && ( title={asGroup ? "Proxy Groups" : "Proxies"}
header={
<ButtonGroup size="small">
{modeList.map((mode) => (
<Button
key={mode}
variant={mode === curMode ? "contained" : "outlined"}
onClick={() => onChangeMode(mode)}
sx={{ textTransform: "capitalize" }}
>
{mode}
</Button>
))}
</ButtonGroup>
}
>
<Paper sx={{ borderRadius: 1, boxShadow: 2, ...paperStyle }}>
{asGroup ? (
<List> <List>
{groups.map((group) => ( {groups.map((group) => (
<ProxyGroup key={group.name} group={group} /> <ProxyGroup key={group.name} group={group} />
))} ))}
</List> </List>
)} ) : (
// virtual list
{!groups.length && ( <Virtuoso
<List> style={{ height: "100%" }}
{Object.values(proxies).map((proxy) => ( totalCount={filterProxies.length}
itemContent={(index) => (
<ProxyItem <ProxyItem
key={proxy.name} groupName="GLOBAL"
proxy={proxy} proxy={filterProxies[index]}
selected={false} selected={filterProxies[index].name === curProxy}
onClick={onChangeProxy}
sx={{ py: 0, px: 2 }} sx={{ py: 0, px: 2 }}
/> />
))} )}
</List> />
)} )}
</Paper> </Paper>
</BasePage> </BasePage>

View File

@@ -1,9 +1,9 @@
import { Paper } from "@mui/material"; import { Paper } from "@mui/material";
import BasePage from "../components/base-page"; import Notice from "../components/base/base-notice";
import BasePage from "../components/base/base-page";
import SettingVerge from "../components/setting/setting-verge"; import SettingVerge from "../components/setting/setting-verge";
import SettingClash from "../components/setting/setting-clash"; import SettingClash from "../components/setting/setting-clash";
import SettingSystem from "../components/setting/setting-system"; import SettingSystem from "../components/setting/setting-system";
import Notice from "../components/notice";
const SettingPage = () => { const SettingPage = () => {
const onError = (error: any) => { const onError = (error: any) => {

View File

@@ -60,10 +60,24 @@ export async function getRules() {
return instance.get("/rules") as Promise<ApiType.RuleItem[]>; return instance.get("/rules") as Promise<ApiType.RuleItem[]>;
} }
/// Get Proxy delay
export async function getProxyDelay(
name: string,
url?: string
): Promise<{ delay: number }> {
const params = {
timeout: 3000,
url: url || "http://www.gstatic.com/generate_204",
};
const instance = await getAxios();
return instance.get(`/proxies/${encodeURIComponent(name)}/delay`, { params });
}
/// Update the Proxy Choose /// Update the Proxy Choose
export async function updateProxy(group: string, proxy: string) { export async function updateProxy(group: string, proxy: string) {
const instance = await getAxios(); const instance = await getAxios();
return instance.put(`/proxies/${group}`, { name: proxy }); return instance.put(`/proxies/${encodeURIComponent(group)}`, { name: proxy });
} }
/// Get the Proxy infomation /// Get the Proxy infomation

View File

@@ -9,6 +9,10 @@ export async function syncProfiles() {
return invoke<void>("sync_profiles"); return invoke<void>("sync_profiles");
} }
export async function newProfile(name: string, desc: string) {
return invoke<void>("new_profile", { name, desc });
}
export async function viewProfile(index: number) { export async function viewProfile(index: number) {
return invoke<void>("view_profile", { index }); return invoke<void>("view_profile", { index });
} }
@@ -59,3 +63,15 @@ export async function patchVergeConfig(payload: CmdType.VergeConfig) {
export async function getSystemProxy() { export async function getSystemProxy() {
return invoke<any>("get_sys_proxy"); return invoke<any>("get_sys_proxy");
} }
export async function killSidecars() {
return invoke<any>("kill_sidecars");
}
export async function openAppDir() {
return invoke<void>("open_app_dir");
}
export async function openLogsDir() {
return invoke<void>("open_logs_dir");
}

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

@@ -0,0 +1,37 @@
import { getProxyDelay } from "./api";
const hashKey = (name: string, group: string) => `${group ?? ""}::${name}`;
class DelayManager {
private cache = new Map<string, [number, number]>();
setDelay(name: string, group: string, delay: number) {
this.cache.set(hashKey(name, group), [Date.now(), delay]);
}
getDelay(name: string, group: string) {
if (!name) return -1;
const result = this.cache.get(hashKey(name, group));
if (result && Date.now() - result[0] <= 18e5) {
return result[1];
}
return -1;
}
async checkDelay(name: string, group: string) {
let delay = -1;
try {
const result = await getProxyDelay(name);
delay = result.delay;
} catch {
delay = 1e6; // error
}
this.setDelay(name, group, delay);
return delay;
}
}
export default new DelayManager();

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

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

View File

@@ -87,6 +87,7 @@ export namespace CmdType {
export interface ProfileItem { export interface ProfileItem {
name?: string; name?: string;
desc?: string;
file?: string; file?: string;
mode?: string; mode?: string;
url?: string; url?: string;
@@ -111,7 +112,11 @@ export namespace CmdType {
export interface VergeConfig { export interface VergeConfig {
theme_mode?: "light" | "dark"; theme_mode?: "light" | "dark";
theme_blur?: boolean; theme_blur?: boolean;
traffic_graph?: boolean;
enable_tun_mode?: boolean;
enable_auto_launch?: boolean; enable_auto_launch?: boolean;
enable_system_proxy?: boolean; enable_system_proxy?: boolean;
enable_proxy_guard?: boolean;
system_proxy_bypass?: string;
} }
} }

View File

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

3870
yarn.lock

File diff suppressed because it is too large Load Diff