Compare commits
153 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1ad3ddef94 | ||
|
|
97ec5eabf7 | ||
|
|
e12e3a3f2d | ||
|
|
4ff625f23b | ||
|
|
e38dcd85ac | ||
|
|
0245baf1b6 | ||
|
|
10b55c043c | ||
|
|
457655b416 | ||
|
|
7e4506c860 | ||
|
|
794d376348 | ||
|
|
c60578f5b5 | ||
|
|
3a9a392a77 | ||
|
|
a13d4698be | ||
|
|
c046a1993e | ||
|
|
f709117cc4 | ||
|
|
30dd298fca | ||
|
|
0ff8bb8090 | ||
|
|
74bbd3c3a2 | ||
|
|
2e82eaf59a | ||
|
|
7f1df1f1bd | ||
|
|
3c79238a44 | ||
|
|
0aa2565df3 | ||
|
|
22b11db16e | ||
|
|
d0e678b5e9 | ||
|
|
e7bba968b3 | ||
|
|
4934a24293 | ||
|
|
ccb68bcda9 | ||
|
|
66bf4ba3ad | ||
|
|
78a0cfd052 | ||
|
|
8548373742 | ||
|
|
2dfd725ee0 | ||
|
|
5b779b4f14 | ||
|
|
fc48aa7155 | ||
|
|
6193a842f4 | ||
|
|
eb86b471fe | ||
|
|
2b52584547 | ||
|
|
6e3cc57f48 | ||
|
|
f2c04621a5 | ||
|
|
3ed6938d4a | ||
|
|
99fec25ed5 | ||
|
|
73758ad1fd | ||
|
|
c53fe0ed1f | ||
|
|
6082c2bcac | ||
|
|
069abed784 | ||
|
|
7d8fa4d78a | ||
|
|
76081f8d89 | ||
|
|
5ef4285558 | ||
|
|
aa7df4282e | ||
|
|
0ef1d5d0de | ||
|
|
cceb4bb81f | ||
|
|
f0f45e007d | ||
|
|
6a8ffe1642 | ||
|
|
3a73868c10 | ||
|
|
ab1b5897a6 | ||
|
|
f94734a5c8 | ||
|
|
61b86c9584 | ||
|
|
1ac1d6e903 | ||
|
|
b6c58f74c0 | ||
|
|
c88e99d87c | ||
|
|
8d7ab9d05e | ||
|
|
47155a4a29 | ||
|
|
d0b87fd7c3 | ||
|
|
d49fd37656 | ||
|
|
0bd29d71be | ||
|
|
4b5b62c8ae | ||
|
|
65fb2ca2d5 | ||
|
|
0d5bfc0997 | ||
|
|
4f02c373c2 | ||
|
|
209a5b1207 | ||
|
|
95349eacab | ||
|
|
82ba604b99 | ||
|
|
46a8dec655 | ||
|
|
b5af234524 | ||
|
|
b5c41750f7 | ||
|
|
6083824eec | ||
|
|
40977785c3 | ||
|
|
5eddf4f1aa | ||
|
|
99a8e25411 | ||
|
|
08587d8f2f | ||
|
|
3480d50f61 | ||
|
|
43af55252d | ||
|
|
9c43b31fc0 | ||
|
|
9ec7184aa1 | ||
|
|
4e2cb30db7 | ||
|
|
9ca83d3291 | ||
|
|
6b2172d873 | ||
|
|
1a5d9f7dad | ||
|
|
a8425862f0 | ||
|
|
a3a3db6abb | ||
|
|
d6c3bc57c0 | ||
|
|
59c09f90f9 | ||
|
|
d982b83e14 | ||
|
|
cc0e930d34 | ||
|
|
3c3d77fbea | ||
|
|
da7453fdbf | ||
|
|
5fcd25506e | ||
|
|
4979a472de | ||
|
|
4e8d4f4591 | ||
|
|
0f5d2b15e0 | ||
|
|
7fc9631434 | ||
|
|
df5953dd7b | ||
|
|
8f5b2b4a0e | ||
|
|
43c63ffa70 | ||
|
|
6779bc7459 | ||
|
|
664be2d0ba | ||
|
|
6113898b69 | ||
|
|
79aad6b5c2 | ||
|
|
6da7757d36 | ||
|
|
dbb3cb8cc8 | ||
|
|
579f36a1dd | ||
|
|
72c2b306cf | ||
|
|
c2673cd396 | ||
|
|
8eb152816a | ||
|
|
a0bc8a21a5 | ||
|
|
08e4d72758 | ||
|
|
66340a27fa | ||
|
|
83fe9835b6 | ||
|
|
4c1a50a3ca | ||
|
|
fe44a7b3bc | ||
|
|
e86d192db7 | ||
|
|
ea8f1c52f9 | ||
|
|
a4c1573c45 | ||
|
|
182bf49ad0 | ||
|
|
13e1ddbccd | ||
|
|
327b9a1757 | ||
|
|
18c48db7f7 | ||
|
|
b6543bd87f | ||
|
|
9ad8f71d7c | ||
|
|
e369311fc2 | ||
|
|
72ff261fe3 | ||
|
|
774c6f7e05 | ||
|
|
771af6ae08 | ||
|
|
b3cd207444 | ||
|
|
03f9fa4bc2 | ||
|
|
e32bfd9aab | ||
|
|
7e47f8f893 | ||
|
|
cb816e9653 | ||
|
|
6b3e7cbc08 | ||
|
|
db4993ae9b | ||
|
|
4dc3cf6c6b | ||
|
|
2b84bbf3a8 | ||
|
|
26ef4c9961 | ||
|
|
4f56c38599 | ||
|
|
240f4dcfb1 | ||
|
|
ac6abd81c9 | ||
|
|
14bda4f3a5 | ||
|
|
61b9670b45 | ||
|
|
01e8db317e | ||
|
|
92fc09493e | ||
|
|
d927209db7 | ||
|
|
e94007b21f | ||
|
|
18750f275a | ||
|
|
d686a853f4 |
100
.github/workflows/ci.yml
vendored
Normal file
@@ -0,0 +1,100 @@
|
||||
name: CI
|
||||
|
||||
on: [push]
|
||||
|
||||
env:
|
||||
CARGO_INCREMENTAL: 0
|
||||
RUST_BACKTRACE: short
|
||||
|
||||
jobs:
|
||||
release:
|
||||
strategy:
|
||||
matrix:
|
||||
os: [windows-latest, macos-11]
|
||||
runs-on: ${{ matrix.os }}
|
||||
if: |
|
||||
startsWith(github.repository, 'zzzgydi') &&
|
||||
startsWith(github.ref, 'refs/tags/v')
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Install Rust
|
||||
uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: stable
|
||||
profile: minimal
|
||||
override: true
|
||||
|
||||
- name: Rust Cache
|
||||
uses: Swatinem/rust-cache@ce325b60658c1b38465c06cc965b79baf32c1e72
|
||||
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: 14
|
||||
|
||||
- name: Get yarn cache dir path
|
||||
id: yarn-cache-dir-path
|
||||
run: echo "::set-output name=dir::$(yarn cache dir)"
|
||||
|
||||
- name: Yarn Cache
|
||||
uses: actions/cache@v2
|
||||
id: yarn-cache
|
||||
with:
|
||||
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
|
||||
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-yarn-
|
||||
|
||||
- name: Yarn install and check
|
||||
run: |
|
||||
yarn install --network-timeout 1000000
|
||||
yarn run check
|
||||
|
||||
- name: Tauri build
|
||||
uses: tauri-apps/tauri-action@v0
|
||||
# enable cache even though failed
|
||||
continue-on-error: true
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
|
||||
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
|
||||
with:
|
||||
tagName: v__VERSION__
|
||||
releaseName: "Clash Verge v__VERSION__"
|
||||
releaseBody: "Clash Verge now supports Windows and macos(intel)."
|
||||
releaseDraft: false
|
||||
prerelease: true
|
||||
|
||||
release-update:
|
||||
needs: release
|
||||
runs-on: macos-11
|
||||
if: |
|
||||
startsWith(github.repository, 'zzzgydi') &&
|
||||
startsWith(github.ref, 'refs/tags/v')
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Get yarn cache dir path
|
||||
id: yarn-cache-dir-path
|
||||
run: echo "::set-output name=dir::$(yarn cache dir)"
|
||||
|
||||
- name: Yarn Cache
|
||||
uses: actions/cache@v2
|
||||
id: yarn-cache
|
||||
with:
|
||||
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
|
||||
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-yarn-
|
||||
|
||||
- name: Yarn install
|
||||
run: yarn
|
||||
|
||||
- name: Release update.json
|
||||
run: yarn run release
|
||||
continue-on-error: true
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
55
.github/workflows/release.yml
vendored
@@ -1,55 +0,0 @@
|
||||
name: Release Project
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- v*
|
||||
|
||||
jobs:
|
||||
build-tauri:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
platform: [windows-latest]
|
||||
runs-on: ${{ matrix.platform }}
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: setup node
|
||||
uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: 14
|
||||
- name: install Rust stable
|
||||
uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: stable
|
||||
- name: Get yarn cache directory path
|
||||
id: yarn-cache-dir-path
|
||||
run: echo "::set-output name=dir::$(yarn cache dir)"
|
||||
- uses: actions/cache@v2
|
||||
id: yarn-cache
|
||||
with:
|
||||
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
|
||||
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-yarn-
|
||||
- uses: actions/cache@v2
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/bin/
|
||||
~/.cargo/registry/index/
|
||||
~/.cargo/registry/cache/
|
||||
~/.cargo/git/db/
|
||||
src-tauri/target/
|
||||
src-tauri/WixTools/
|
||||
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
|
||||
- name: install app dependencies and build it
|
||||
run: yarn && yarn run predev
|
||||
- uses: tauri-apps/tauri-action@v0
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
tagName: v__VERSION__
|
||||
releaseName: "Clash Verge v__VERSION__"
|
||||
releaseBody: "This is a release."
|
||||
releaseDraft: true
|
||||
prerelease: false
|
||||
3
.gitignore
vendored
@@ -3,5 +3,4 @@ node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
package-lock.json
|
||||
yarn.lock
|
||||
update.json
|
||||
|
||||
21
README.md
@@ -26,7 +26,7 @@ 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).
|
||||
|
||||
```shell
|
||||
yarn run predev
|
||||
yarn run check
|
||||
```
|
||||
|
||||
Then run
|
||||
@@ -42,8 +42,12 @@ yarn dev
|
||||
## Screenshots
|
||||
|
||||
<div align="center">
|
||||
<img src="./docs/demo1.png" alt="demo1" width="42%" />
|
||||
<img src="./docs/demo2.png" alt="demo2" width="42%" />
|
||||
<img src="./docs/demo1.png" alt="demo1" width="32%" />
|
||||
<img src="./docs/demo2.png" alt="demo2" width="32%" />
|
||||
<img src="./docs/demo3.png" alt="demo3" width="32%" />
|
||||
<img src="./docs/demo4.png" alt="demo4" width="32%" />
|
||||
<img src="./docs/demo5.png" alt="demo5" width="32%" />
|
||||
<img src="./docs/demo6.png" alt="demo6" width="32%" />
|
||||
</div>
|
||||
|
||||
## Disclaimer
|
||||
@@ -54,6 +58,15 @@ This is a learning project for Rust practice.
|
||||
|
||||
PR welcome!
|
||||
|
||||
## Acknowledgement
|
||||
|
||||
Clash Verge was based on or inspired by these projects and so on:
|
||||
|
||||
- [tauri-apps/tauri](https://github.com/tauri-apps/tauri): Build smaller, faster, and more secure desktop applications with a web frontend.
|
||||
- [Dreamacro/clash](https://github.com/Dreamacro/clash): A rule-based tunnel in Go.
|
||||
- [Fndroid/clash_for_windows_pkg](https://github.com/Fndroid/clash_for_windows_pkg): A Windows/macOS GUI based on Clash.
|
||||
- [vitejs/vite](https://github.com/vitejs/vite): Next generation frontend tooling. It's fast!
|
||||
|
||||
## License
|
||||
|
||||
GPL-3.0 License
|
||||
GPL-3.0 License. See [License here](./LICENSE) for details.
|
||||
|
||||
BIN
docs/demo1.png
|
Before Width: | Height: | Size: 52 KiB After Width: | Height: | Size: 21 KiB |
BIN
docs/demo2.png
|
Before Width: | Height: | Size: 73 KiB After Width: | Height: | Size: 20 KiB |
BIN
docs/demo3.png
Normal file
|
After Width: | Height: | Size: 25 KiB |
BIN
docs/demo4.png
Normal file
|
After Width: | Height: | Size: 18 KiB |
BIN
docs/demo5.png
Normal file
|
After Width: | Height: | Size: 19 KiB |
BIN
docs/demo6.png
Normal file
|
After Width: | Height: | Size: 25 KiB |
43
package.json
@@ -1,44 +1,51 @@
|
||||
{
|
||||
"name": "clash-verge",
|
||||
"version": "0.0.1",
|
||||
"version": "0.0.16",
|
||||
"license": "GPL-3.0",
|
||||
"scripts": {
|
||||
"dev": "cargo tauri dev",
|
||||
"build": "cargo tauri build",
|
||||
"tauri": "tauri",
|
||||
"web:dev": "vite",
|
||||
"web:build": "tsc && vite build",
|
||||
"web:serve": "vite preview",
|
||||
"predev": "node scripts/pre-dev.mjs",
|
||||
"check": "node scripts/check.mjs",
|
||||
"publish": "node scripts/publish.mjs",
|
||||
"release": "node scripts/release.mjs",
|
||||
"prepare": "husky install"
|
||||
},
|
||||
"dependencies": {
|
||||
"@emotion/react": "^11.7.0",
|
||||
"@emotion/styled": "^11.6.0",
|
||||
"@mui/icons-material": "^5.2.1",
|
||||
"@mui/material": "^5.2.3",
|
||||
"@tauri-apps/api": "^1.0.0-beta.8",
|
||||
"axios": "^0.24.0",
|
||||
"@mui/icons-material": "^5.4.1",
|
||||
"@mui/material": "^5.4.1",
|
||||
"@tauri-apps/api": "^1.0.0-rc.1",
|
||||
"ahooks": "^3.1.9",
|
||||
"axios": "^0.26.0",
|
||||
"dayjs": "^1.10.7",
|
||||
"react": "^17.0.0",
|
||||
"react-dom": "^17.0.0",
|
||||
"react-router-dom": "^6.0.2",
|
||||
"react-virtuoso": "^2.3.1",
|
||||
"recoil": "^0.5.2",
|
||||
"swr": "^1.1.2-beta.0"
|
||||
"react": "^17.0.2",
|
||||
"react-dom": "^17.0.2",
|
||||
"react-router-dom": "^6.2.1",
|
||||
"react-virtuoso": "^2.7.0",
|
||||
"recoil": "^0.6.1",
|
||||
"swr": "^1.2.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tauri-apps/cli": "^1.0.0-beta.10",
|
||||
"@actions/github": "^5.0.0",
|
||||
"@tauri-apps/cli": "^1.0.0-rc.5",
|
||||
"@types/fs-extra": "^9.0.13",
|
||||
"@types/js-cookie": "^3.0.1",
|
||||
"@types/react": "^17.0.0",
|
||||
"@types/react-dom": "^17.0.0",
|
||||
"@vitejs/plugin-react": "^1.1.1",
|
||||
"@vitejs/plugin-react": "^1.2.0",
|
||||
"adm-zip": "^0.5.9",
|
||||
"fs-extra": "^10.0.0",
|
||||
"husky": "^7.0.0",
|
||||
"node-fetch": "^3.1.0",
|
||||
"node-fetch": "^3.2.0",
|
||||
"pretty-quick": "^3.1.3",
|
||||
"sass": "^1.44.0",
|
||||
"typescript": "^4.5.2",
|
||||
"vite": "^2.7.1"
|
||||
"sass": "^1.49.7",
|
||||
"typescript": "^4.5.5",
|
||||
"vite": "^2.8.0"
|
||||
},
|
||||
"prettier": {
|
||||
"tabWidth": 2,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import fs from "fs-extra";
|
||||
import zlib from "zlib";
|
||||
import path from "path";
|
||||
import AdmZip from "adm-zip";
|
||||
import fetch from "node-fetch";
|
||||
@@ -8,7 +9,7 @@ const cwd = process.cwd();
|
||||
|
||||
const CLASH_URL_PREFIX =
|
||||
"https://github.com/Dreamacro/clash/releases/download/premium/";
|
||||
const CLASH_LATEST_DATE = "2021.12.07";
|
||||
const CLASH_LATEST_DATE = "2022.01.27";
|
||||
|
||||
/**
|
||||
* get the correct clash release infomation
|
||||
@@ -16,15 +17,17 @@ const CLASH_LATEST_DATE = "2021.12.07";
|
||||
function resolveClash() {
|
||||
const { platform, arch } = process;
|
||||
|
||||
let name = "";
|
||||
|
||||
// todo
|
||||
if (platform === "win32" && arch === "x64") {
|
||||
name = `clash-windows-386`;
|
||||
}
|
||||
const map = {
|
||||
"win32-x64": "clash-windows-386",
|
||||
"darwin-x64": "clash-darwin-amd64",
|
||||
"darwin-arm64": "clash-darwin-arm64",
|
||||
};
|
||||
|
||||
const name = map[`${platform}-${arch}`];
|
||||
|
||||
if (!name) {
|
||||
throw new Error("todo");
|
||||
throw new Error(`unsupport platform "${platform}-${arch}"`);
|
||||
}
|
||||
|
||||
const isWin = platform === "win32";
|
||||
@@ -47,7 +50,7 @@ async function resolveSidecar() {
|
||||
const sidecarFile = `clash-${host}${ext}`;
|
||||
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;
|
||||
|
||||
// download sidecar
|
||||
@@ -56,18 +59,31 @@ async function resolveSidecar() {
|
||||
const tempZip = path.join(tempDir, binInfo.zipfile);
|
||||
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);
|
||||
|
||||
// Todo: support gz
|
||||
const zip = new AdmZip(tempZip);
|
||||
zip.getEntries().forEach((entry) => {
|
||||
console.log("[INFO]: entry name", entry.entryName);
|
||||
});
|
||||
zip.extractAllTo(tempDir, true);
|
||||
|
||||
// save as sidecar
|
||||
await fs.rename(tempExe, sidecarPath);
|
||||
if (binInfo.zip === "zip") {
|
||||
const zip = new AdmZip(tempZip);
|
||||
zip.getEntries().forEach((entry) => {
|
||||
console.log("[INFO]: entry name", entry.entryName);
|
||||
});
|
||||
zip.extractAllTo(tempDir, true);
|
||||
// save as sidecar
|
||||
await fs.rename(tempExe, sidecarPath);
|
||||
console.log(`[INFO]: unzip finished`);
|
||||
} else {
|
||||
// gz
|
||||
const readStream = fs.createReadStream(tempZip);
|
||||
const writeStream = fs.createWriteStream(sidecarPath);
|
||||
readStream
|
||||
.pipe(zlib.createGunzip())
|
||||
.pipe(writeStream)
|
||||
.on("finish", () => {
|
||||
console.log(`[INFO]: gunzip finished`);
|
||||
execSync(`chmod 755 ${sidecarPath}`);
|
||||
console.log(`[INFO]: chmod binary finished`);
|
||||
});
|
||||
}
|
||||
|
||||
// delete temp dir
|
||||
await fs.remove(tempDir);
|
||||
@@ -80,8 +96,10 @@ async function resolveMmdb() {
|
||||
const url =
|
||||
"https://github.com/Dreamacro/maxmind-geoip/releases/latest/download/Country.mmdb";
|
||||
|
||||
const resPath = path.join(cwd, "src-tauri", "resources", "Country.mmdb");
|
||||
const resDir = path.join(cwd, "src-tauri", "resources");
|
||||
const resPath = path.join(resDir, "Country.mmdb");
|
||||
if (await fs.pathExists(resPath)) return;
|
||||
await fs.mkdirp(resDir);
|
||||
await downloadFile(url, resPath);
|
||||
}
|
||||
|
||||
@@ -97,8 +115,10 @@ async function downloadFile(url, path) {
|
||||
});
|
||||
const buffer = await response.arrayBuffer();
|
||||
await fs.writeFile(path, new Uint8Array(buffer));
|
||||
|
||||
console.log(`[INFO]: download finished "${url}"`);
|
||||
}
|
||||
|
||||
/// main
|
||||
resolveSidecar();
|
||||
resolveMmdb();
|
||||
resolveSidecar().catch(console.error);
|
||||
resolveMmdb().catch(console.error);
|
||||
47
scripts/publish.mjs
Normal file
@@ -0,0 +1,47 @@
|
||||
import fs from "fs-extra";
|
||||
import { createRequire } from "module";
|
||||
import { execSync } from "child_process";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
|
||||
async function resolvePublish() {
|
||||
const flag = process.argv[2] ?? "patch";
|
||||
const packageJson = require("../package.json");
|
||||
const tauriJson = require("../src-tauri/tauri.conf.json");
|
||||
|
||||
let [a, b, c] = packageJson.version.split(".").map(Number);
|
||||
|
||||
if (flag === "major") {
|
||||
a += 1;
|
||||
b = 0;
|
||||
c = 0;
|
||||
} else if (flag === "minor") {
|
||||
b += 1;
|
||||
c = 0;
|
||||
} else if (flag === "patch") {
|
||||
c += 1;
|
||||
} else throw new Error(`invalid flag "${flag}"`);
|
||||
|
||||
const nextVersion = `${a}.${b}.${c}`;
|
||||
packageJson.version = nextVersion;
|
||||
tauriJson.package.version = nextVersion;
|
||||
|
||||
await fs.writeFile(
|
||||
"./package.json",
|
||||
JSON.stringify(packageJson, undefined, 2)
|
||||
);
|
||||
await fs.writeFile(
|
||||
"./src-tauri/tauri.conf.json",
|
||||
JSON.stringify(tauriJson, undefined, 2)
|
||||
);
|
||||
|
||||
execSync("git add ./package.json");
|
||||
execSync("git add ./src-tauri/tauri.conf.json");
|
||||
execSync(`git commit -m "v${nextVersion}"`);
|
||||
execSync(`git tag -a v${nextVersion} -m "v${nextVersion}"`);
|
||||
execSync(`git push`);
|
||||
execSync(`git push origin v${nextVersion}`);
|
||||
console.log(`Publish Successfully...`);
|
||||
}
|
||||
|
||||
resolvePublish();
|
||||
68
scripts/release.mjs
Normal file
@@ -0,0 +1,68 @@
|
||||
import { createRequire } from "module";
|
||||
import { getOctokit, context } from "@actions/github";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
|
||||
/// generate update.json
|
||||
/// upload to update tag's release asset
|
||||
async function resolveRelease() {
|
||||
if (process.env.GITHUB_TOKEN === undefined) {
|
||||
throw new Error("GITHUB_TOKEN is required");
|
||||
}
|
||||
|
||||
const packageJson = require("../package.json");
|
||||
|
||||
const { version } = packageJson;
|
||||
const urlPrefix = "https://github.com/zzzgydi/clash-verge/releases/download";
|
||||
const updateData = {
|
||||
name: `v${version}`,
|
||||
notes: `Version ${version} is available now!!!`,
|
||||
pub_date: new Date().toISOString(),
|
||||
platforms: {
|
||||
win64: {
|
||||
signature: "",
|
||||
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 github = getOctokit(process.env.GITHUB_TOKEN);
|
||||
|
||||
const { data: release } = await github.rest.repos.getReleaseByTag({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
tag: "updater",
|
||||
});
|
||||
const { data: assets } = await github.rest.repos.listReleaseAssets({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
release_id: release.id,
|
||||
});
|
||||
|
||||
for (let asset of assets) {
|
||||
if (asset.name === "update.json") {
|
||||
await github.rest.repos.deleteReleaseAsset({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
asset_id: asset.id,
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
await github.rest.repos.uploadReleaseAsset({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
release_id: release.id,
|
||||
name: "update.json",
|
||||
data: JSON.stringify(updateData, null, 2),
|
||||
});
|
||||
}
|
||||
|
||||
resolveRelease();
|
||||
1827
src-tauri/Cargo.lock
generated
@@ -1,16 +1,16 @@
|
||||
[package]
|
||||
name = "app"
|
||||
name = "clash-verge"
|
||||
version = "0.1.0"
|
||||
description = "clash verge"
|
||||
authors = ["zzzgydi"]
|
||||
license = "GPL-3.0"
|
||||
repository = ""
|
||||
default-run = "app"
|
||||
repository = "https://github.com/zzzgydi/clash-verge.git"
|
||||
default-run = "clash-verge"
|
||||
edition = "2021"
|
||||
build = "build.rs"
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "1.0.0-beta.4" }
|
||||
tauri-build = { version = "1.0.0-rc.3", features = [] }
|
||||
|
||||
[dependencies]
|
||||
dirs = "4.0.0"
|
||||
@@ -18,12 +18,17 @@ chrono = "0.4.19"
|
||||
serde_json = "1.0"
|
||||
serde_yaml = "0.8"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
tauri = { version = "1.0.0-beta.8", features = ["api-all", "system-tray"] }
|
||||
tauri = { version = "1.0.0-rc.3", features = ["shell-all", "system-tray", "updater", "window-all"] }
|
||||
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"] }
|
||||
|
||||
reqwest = { version = "0.11", features = ["json"] }
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
log = "0.4.14"
|
||||
log4rs = "1.0.0"
|
||||
warp = "0.3"
|
||||
which = "4.2.2"
|
||||
auto-launch = "0.2"
|
||||
port_scanner = "0.1.5"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
# Default Config For Clash Core
|
||||
|
||||
mixed-port: 7890
|
||||
log-level: info
|
||||
allow-lan: false
|
||||
external-controller: 127.0.0.1:9090
|
||||
secret: ""
|
||||
@@ -1,3 +0,0 @@
|
||||
# Profiles Config for Clash Verge
|
||||
|
||||
current: 0
|
||||
@@ -1,6 +0,0 @@
|
||||
# Defaulf Config For Clash Verge
|
||||
|
||||
theme_mode: light
|
||||
enable_self_startup: false
|
||||
enable_system_proxy: false
|
||||
system_proxy_bypass: localhost;127.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;192.168.*;<local>
|
||||
307
src-tauri/src/cmds.rs
Normal file
@@ -0,0 +1,307 @@
|
||||
use crate::{
|
||||
core::{ClashInfo, ProfileItem, Profiles, VergeConfig},
|
||||
states::{ClashState, ProfilesState, VergeState},
|
||||
utils::{dirs::app_home_dir, fetch::fetch_profile, sysopt::SysProxyConfig},
|
||||
};
|
||||
use serde_yaml::Mapping;
|
||||
use std::process::Command;
|
||||
use tauri::{api, State};
|
||||
|
||||
/// get all profiles from `profiles.yaml`
|
||||
/// do not acquire the lock of ProfileLock
|
||||
#[tauri::command]
|
||||
pub fn get_profiles(profiles_state: State<'_, ProfilesState>) -> Result<Profiles, String> {
|
||||
match profiles_state.0.lock() {
|
||||
Ok(profiles) => Ok(profiles.clone()),
|
||||
Err(_) => Err("failed to get profiles lock".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// synchronize data irregularly
|
||||
#[tauri::command]
|
||||
pub fn sync_profiles(profiles_state: State<'_, ProfilesState>) -> Result<(), String> {
|
||||
match profiles_state.0.lock() {
|
||||
Ok(mut profiles) => profiles.sync_file(),
|
||||
Err(_) => Err("failed to get profiles lock".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// import the profile from url
|
||||
/// and save to `profiles.yaml`
|
||||
#[tauri::command]
|
||||
pub async fn import_profile(
|
||||
url: String,
|
||||
with_proxy: bool,
|
||||
profiles_state: State<'_, ProfilesState>,
|
||||
) -> Result<(), String> {
|
||||
let result = fetch_profile(&url, with_proxy).await?;
|
||||
let mut profiles = profiles_state.0.lock().unwrap();
|
||||
profiles.import_from_url(url, result)
|
||||
}
|
||||
|
||||
/// 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
|
||||
#[tauri::command]
|
||||
pub async fn update_profile(
|
||||
index: usize,
|
||||
with_proxy: bool,
|
||||
clash_state: State<'_, ClashState>,
|
||||
profiles_state: State<'_, ProfilesState>,
|
||||
) -> Result<(), String> {
|
||||
// maybe we can get the url from the web app directly
|
||||
let url = match profiles_state.0.lock() {
|
||||
Ok(mut profile) => {
|
||||
let items = profile.items.take().unwrap_or(vec![]);
|
||||
if index >= items.len() {
|
||||
return Err("the index out of bound".into());
|
||||
}
|
||||
let url = match &items[index].url {
|
||||
Some(u) => u.clone(),
|
||||
None => return Err("failed to update profile for `invalid url`".into()),
|
||||
};
|
||||
profile.items = Some(items);
|
||||
url
|
||||
}
|
||||
Err(_) => return Err("failed to get profiles lock".into()),
|
||||
};
|
||||
|
||||
let result = fetch_profile(&url, with_proxy).await?;
|
||||
|
||||
match profiles_state.0.lock() {
|
||||
Ok(mut profiles) => {
|
||||
profiles.update_item(index, result)?;
|
||||
|
||||
// reactivate the profile
|
||||
let current = profiles.current.clone().unwrap_or(0);
|
||||
if current == index {
|
||||
let clash = clash_state.0.lock().unwrap();
|
||||
profiles.activate(&clash)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
Err(_) => Err("failed to get profiles lock".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// change the current profile
|
||||
#[tauri::command]
|
||||
pub fn select_profile(
|
||||
index: usize,
|
||||
clash_state: State<'_, ClashState>,
|
||||
profiles_state: State<'_, ProfilesState>,
|
||||
) -> Result<(), String> {
|
||||
let mut profiles = profiles_state.0.lock().unwrap();
|
||||
|
||||
match profiles.put_current(index) {
|
||||
Ok(()) => {
|
||||
let clash = clash_state.0.lock().unwrap();
|
||||
profiles.activate(&clash)
|
||||
}
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
/// delete profile item
|
||||
#[tauri::command]
|
||||
pub fn delete_profile(
|
||||
index: usize,
|
||||
clash_state: State<'_, ClashState>,
|
||||
profiles_state: State<'_, ProfilesState>,
|
||||
) -> Result<(), String> {
|
||||
let mut profiles = profiles_state.0.lock().unwrap();
|
||||
match profiles.delete_item(index) {
|
||||
Ok(change) => match change {
|
||||
true => {
|
||||
let clash = clash_state.0.lock().unwrap();
|
||||
profiles.activate(&clash)
|
||||
}
|
||||
false => Ok(()),
|
||||
},
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
/// patch the profile config
|
||||
#[tauri::command]
|
||||
pub fn patch_profile(
|
||||
index: usize,
|
||||
profile: ProfileItem,
|
||||
profiles_state: State<'_, ProfilesState>,
|
||||
) -> Result<(), String> {
|
||||
match profiles_state.0.lock() {
|
||||
Ok(mut profiles) => profiles.patch_item(index, profile),
|
||||
Err(_) => Err("can not get profiles lock".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// run vscode command to edit the profile
|
||||
#[tauri::command]
|
||||
pub fn view_profile(index: usize, profiles_state: State<'_, ProfilesState>) -> Result<(), String> {
|
||||
let mut profiles = profiles_state.0.lock().unwrap();
|
||||
let items = profiles.items.take().unwrap_or(vec![]);
|
||||
|
||||
if index >= items.len() {
|
||||
profiles.items = Some(items);
|
||||
return Err("the index out of bound".into());
|
||||
}
|
||||
|
||||
let file = items[index].file.clone().unwrap_or("".into());
|
||||
profiles.items = Some(items);
|
||||
|
||||
let path = app_home_dir().join("profiles").join(file);
|
||||
if !path.exists() {
|
||||
return Err("the file not found".into());
|
||||
}
|
||||
|
||||
// use vscode first
|
||||
if let Ok(code) = which::which("code") {
|
||||
return match Command::new(code).arg(path).spawn() {
|
||||
Ok(_) => Ok(()),
|
||||
Err(_) => Err("failed to open file by VScode".into()),
|
||||
};
|
||||
}
|
||||
|
||||
match open_command().arg(path).spawn() {
|
||||
Ok(_) => Ok(()),
|
||||
Err(_) => Err("failed to open file by `open`".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// restart the sidecar
|
||||
#[tauri::command]
|
||||
pub fn restart_sidecar(
|
||||
clash_state: State<'_, ClashState>,
|
||||
profiles_state: State<'_, ProfilesState>,
|
||||
) -> Result<(), String> {
|
||||
let mut clash = clash_state.0.lock().unwrap();
|
||||
let mut profiles = profiles_state.0.lock().unwrap();
|
||||
|
||||
match clash.restart_sidecar(&mut profiles) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(err) => {
|
||||
log::error!("{}", err);
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// get the clash core info from the state
|
||||
/// the caller can also get the infomation by clash's api
|
||||
#[tauri::command]
|
||||
pub fn get_clash_info(clash_state: State<'_, ClashState>) -> Result<ClashInfo, String> {
|
||||
match clash_state.0.lock() {
|
||||
Ok(clash) => Ok(clash.info.clone()),
|
||||
Err(_) => Err("failed to get clash lock".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// update the clash core config
|
||||
/// after putting the change to the clash core
|
||||
/// then we should save the latest config
|
||||
#[tauri::command]
|
||||
pub fn patch_clash_config(
|
||||
payload: Mapping,
|
||||
clash_state: State<'_, ClashState>,
|
||||
verge_state: State<'_, VergeState>,
|
||||
profiles_state: State<'_, ProfilesState>,
|
||||
) -> Result<(), String> {
|
||||
let mut clash = clash_state.0.lock().unwrap();
|
||||
let mut verge = verge_state.0.lock().unwrap();
|
||||
let mut profiles = profiles_state.0.lock().unwrap();
|
||||
clash.patch_config(payload, &mut verge, &mut profiles)
|
||||
}
|
||||
|
||||
/// get the system proxy
|
||||
#[tauri::command]
|
||||
pub fn get_sys_proxy() -> Result<SysProxyConfig, String> {
|
||||
match SysProxyConfig::get_sys() {
|
||||
Ok(value) => Ok(value),
|
||||
Err(err) => Err(err.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// get the current proxy config
|
||||
/// which may not the same as system proxy
|
||||
#[tauri::command]
|
||||
pub fn get_cur_proxy(verge_state: State<'_, VergeState>) -> Result<Option<SysProxyConfig>, String> {
|
||||
match verge_state.0.lock() {
|
||||
Ok(verge) => Ok(verge.cur_sysproxy.clone()),
|
||||
Err(_) => Err("failed to get verge lock".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// get the verge config
|
||||
#[tauri::command]
|
||||
pub fn get_verge_config(verge_state: State<'_, VergeState>) -> Result<VergeConfig, String> {
|
||||
let verge = verge_state.0.lock().unwrap();
|
||||
let mut config = verge.config.clone();
|
||||
|
||||
if config.system_proxy_bypass.is_none() && verge.cur_sysproxy.is_some() {
|
||||
config.system_proxy_bypass = Some(verge.cur_sysproxy.clone().unwrap().bypass)
|
||||
}
|
||||
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
/// patch the verge config
|
||||
/// this command only save the config and not responsible for other things
|
||||
#[tauri::command]
|
||||
pub fn patch_verge_config(
|
||||
payload: VergeConfig,
|
||||
verge_state: State<'_, VergeState>,
|
||||
) -> Result<(), String> {
|
||||
let mut verge = verge_state.0.lock().unwrap();
|
||||
verge.patch_config(payload)
|
||||
}
|
||||
|
||||
/// 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();
|
||||
|
||||
match open_command().arg(app_dir).spawn() {
|
||||
Ok(_) => Ok(()),
|
||||
Err(_) => Err("failed to open logs dir".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// open logs dir
|
||||
#[tauri::command]
|
||||
pub fn open_logs_dir() -> Result<(), String> {
|
||||
let log_dir = app_home_dir().join("logs");
|
||||
|
||||
match open_command().arg(log_dir).spawn() {
|
||||
Ok(_) => Ok(()),
|
||||
Err(_) => Err("failed to open logs dir".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// get open/explorer command
|
||||
fn open_command() -> Command {
|
||||
let open = if cfg!(target_os = "windows") {
|
||||
"explorer"
|
||||
} else {
|
||||
"open"
|
||||
};
|
||||
Command::new(open)
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
pub mod profile;
|
||||
pub mod some;
|
||||
@@ -1,190 +0,0 @@
|
||||
use crate::{
|
||||
config::{ProfileItem, ProfilesConfig},
|
||||
events::state::{ClashInfoState, ProfileLock},
|
||||
utils::{
|
||||
app_home_dir,
|
||||
clash::put_clash_profile,
|
||||
config::{read_profiles, save_profiles},
|
||||
fetch::fetch_profile,
|
||||
},
|
||||
};
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use tauri::State;
|
||||
|
||||
/// Import the profile from url
|
||||
/// and save to `profiles.yaml`
|
||||
#[tauri::command]
|
||||
pub async fn import_profile(url: String, lock: State<'_, ProfileLock>) -> Result<(), String> {
|
||||
let result = match fetch_profile(&url).await {
|
||||
Some(r) => r,
|
||||
None => {
|
||||
log::error!("failed to fetch profile from `{}`", url);
|
||||
return Err(format!("failed to fetch profile from `{}`", url));
|
||||
}
|
||||
};
|
||||
|
||||
// get lock
|
||||
if lock.0.lock().is_err() {
|
||||
return Err(format!("can not get file lock"));
|
||||
}
|
||||
|
||||
// save the profile file
|
||||
let path = app_home_dir().join("profiles").join(&result.file);
|
||||
let file_data = result.data.as_bytes();
|
||||
File::create(path).unwrap().write(file_data).unwrap();
|
||||
|
||||
// update `profiles.yaml`
|
||||
let mut profiles = read_profiles();
|
||||
let mut items = profiles.items.unwrap_or(vec![]);
|
||||
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs();
|
||||
|
||||
items.push(ProfileItem {
|
||||
name: Some(result.name),
|
||||
file: Some(result.file),
|
||||
mode: Some(format!("rule")),
|
||||
url: Some(url),
|
||||
selected: Some(vec![]),
|
||||
extra: Some(result.extra),
|
||||
updated: Some(now as usize),
|
||||
});
|
||||
profiles.items = Some(items);
|
||||
save_profiles(&profiles)
|
||||
}
|
||||
|
||||
/// Update the profile
|
||||
/// and save to `profiles.yaml`
|
||||
/// http request firstly
|
||||
/// then acquire the lock of `profiles.yaml`
|
||||
#[tauri::command]
|
||||
pub async fn update_profile(index: usize, lock: State<'_, ProfileLock>) -> Result<(), String> {
|
||||
// get lock
|
||||
if lock.0.lock().is_err() {
|
||||
return Err(format!("can not get file lock"));
|
||||
}
|
||||
|
||||
// update `profiles.yaml`
|
||||
let mut profiles = read_profiles();
|
||||
let mut items = profiles.items.unwrap_or(vec![]);
|
||||
|
||||
if index >= items.len() {
|
||||
return Err(format!("the index out of bound"));
|
||||
}
|
||||
|
||||
let url = match &items[index].url {
|
||||
Some(u) => u,
|
||||
None => return Err(format!("invalid url")),
|
||||
};
|
||||
|
||||
let result = match fetch_profile(&url).await {
|
||||
Some(r) => r,
|
||||
None => {
|
||||
log::error!("failed to fetch profile from `{}`", url);
|
||||
return Err(format!("failed to fetch profile from `{}`", url));
|
||||
}
|
||||
};
|
||||
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs() as usize;
|
||||
|
||||
// update file
|
||||
let file_path = &items[index].file.as_ref().unwrap();
|
||||
let file_path = app_home_dir().join("profiles").join(file_path);
|
||||
let file_data = result.data.as_bytes();
|
||||
File::create(file_path).unwrap().write(file_data).unwrap();
|
||||
|
||||
items[index].name = Some(result.name);
|
||||
items[index].extra = Some(result.extra);
|
||||
items[index].updated = Some(now);
|
||||
profiles.items = Some(items);
|
||||
save_profiles(&profiles)
|
||||
}
|
||||
|
||||
/// get all profiles from `profiles.yaml`
|
||||
/// do not acquire the lock of ProfileLock
|
||||
#[tauri::command]
|
||||
pub fn get_profiles() -> Result<ProfilesConfig, String> {
|
||||
Ok(read_profiles())
|
||||
}
|
||||
|
||||
/// patch the profile config
|
||||
#[tauri::command]
|
||||
pub fn set_profiles(
|
||||
index: usize,
|
||||
profile: ProfileItem,
|
||||
lock: State<'_, ProfileLock>,
|
||||
) -> Result<(), String> {
|
||||
// get lock
|
||||
if lock.0.lock().is_err() {
|
||||
return Err(format!("can not get file lock"));
|
||||
}
|
||||
|
||||
let mut profiles = read_profiles();
|
||||
let mut items = profiles.items.unwrap_or(vec![]);
|
||||
|
||||
if index >= items.len() {
|
||||
return Err(format!("the index out of bound"));
|
||||
}
|
||||
|
||||
if profile.name.is_some() {
|
||||
items[index].name = profile.name;
|
||||
}
|
||||
if profile.file.is_some() {
|
||||
items[index].file = profile.file;
|
||||
}
|
||||
if profile.mode.is_some() {
|
||||
items[index].mode = profile.mode;
|
||||
}
|
||||
if profile.url.is_some() {
|
||||
items[index].url = profile.url;
|
||||
}
|
||||
if profile.selected.is_some() {
|
||||
items[index].selected = profile.selected;
|
||||
}
|
||||
if profile.extra.is_some() {
|
||||
items[index].extra = profile.extra;
|
||||
}
|
||||
|
||||
profiles.items = Some(items);
|
||||
save_profiles(&profiles)
|
||||
}
|
||||
|
||||
/// change the current profile
|
||||
#[tauri::command]
|
||||
pub async fn put_profiles(
|
||||
current: usize,
|
||||
lock: State<'_, ProfileLock>,
|
||||
clash_info: State<'_, ClashInfoState>,
|
||||
) -> Result<(), String> {
|
||||
if lock.0.lock().is_err() {
|
||||
return Err(format!("can not get file lock"));
|
||||
}
|
||||
|
||||
let clash_info = match clash_info.0.lock() {
|
||||
Ok(arc) => arc.clone(),
|
||||
_ => return Err(format!("can not get clash info")),
|
||||
};
|
||||
|
||||
let mut profiles = read_profiles();
|
||||
let items_len = match &profiles.items {
|
||||
Some(list) => list.len(),
|
||||
None => 0,
|
||||
};
|
||||
|
||||
if current >= items_len {
|
||||
return Err(format!("the index out of bound"));
|
||||
}
|
||||
|
||||
profiles.current = Some(current);
|
||||
match save_profiles(&profiles) {
|
||||
Ok(_) => put_clash_profile(&clash_info).await,
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
@@ -1,154 +0,0 @@
|
||||
use crate::{
|
||||
config::VergeConfig,
|
||||
events::{
|
||||
emit::ClashInfoPayload,
|
||||
state::{ClashInfoState, VergeConfLock},
|
||||
},
|
||||
utils::{
|
||||
clash::run_clash_bin,
|
||||
config::{read_clash, save_clash, save_verge},
|
||||
sysopt::{get_proxy_config, set_proxy_config, SysProxyConfig, DEFAULT_BYPASS},
|
||||
},
|
||||
};
|
||||
use serde_yaml::Mapping;
|
||||
use tauri::{api::process::kill_children, AppHandle, State};
|
||||
|
||||
/// restart the sidecar
|
||||
#[tauri::command]
|
||||
pub fn restart_sidecar(app_handle: AppHandle, clash_info: State<'_, ClashInfoState>) {
|
||||
kill_children();
|
||||
let payload = run_clash_bin(&app_handle);
|
||||
|
||||
if let Ok(mut arc) = clash_info.0.lock() {
|
||||
*arc = payload;
|
||||
}
|
||||
}
|
||||
|
||||
/// get the clash core info from the state
|
||||
/// the caller can also get the infomation by clash's api
|
||||
#[tauri::command]
|
||||
pub fn get_clash_info(clash_info: State<'_, ClashInfoState>) -> Result<ClashInfoPayload, String> {
|
||||
match clash_info.0.lock() {
|
||||
Ok(arc) => Ok(arc.clone()),
|
||||
Err(_) => Err(format!("can not get clash info")),
|
||||
}
|
||||
}
|
||||
|
||||
/// update the clash core config
|
||||
/// after putting the change to the clash core
|
||||
/// then we should save the latest config
|
||||
#[tauri::command]
|
||||
pub fn patch_clash_config(payload: Mapping) -> Result<(), String> {
|
||||
let mut config = read_clash();
|
||||
for (key, value) in payload.iter() {
|
||||
if config.contains_key(key) {
|
||||
config[key] = value.clone();
|
||||
} else {
|
||||
config.insert(key.clone(), value.clone());
|
||||
}
|
||||
}
|
||||
save_clash(&config)
|
||||
}
|
||||
|
||||
/// set the system proxy
|
||||
/// Tips: only support windows now
|
||||
#[tauri::command]
|
||||
pub fn set_sys_proxy(
|
||||
enable: bool,
|
||||
clash_info: State<'_, ClashInfoState>,
|
||||
verge_lock: State<'_, VergeConfLock>,
|
||||
) -> Result<(), String> {
|
||||
let clash_info = match clash_info.0.lock() {
|
||||
Ok(arc) => arc.clone(),
|
||||
_ => return Err(format!("can not get clash info")),
|
||||
};
|
||||
|
||||
let verge_info = match verge_lock.0.lock() {
|
||||
Ok(arc) => arc.clone(),
|
||||
_ => return Err(format!("can not get verge info")),
|
||||
};
|
||||
|
||||
let port = match clash_info.controller {
|
||||
Some(ctrl) => ctrl.port,
|
||||
None => None,
|
||||
};
|
||||
|
||||
if port.is_none() {
|
||||
return Err(format!("can not get clash core's port"));
|
||||
}
|
||||
|
||||
let config = if enable {
|
||||
let server = format!("127.0.0.1:{}", port.unwrap());
|
||||
let bypass = verge_info
|
||||
.system_proxy_bypass
|
||||
.unwrap_or(String::from(DEFAULT_BYPASS));
|
||||
SysProxyConfig {
|
||||
enable,
|
||||
server,
|
||||
bypass,
|
||||
}
|
||||
} else {
|
||||
SysProxyConfig {
|
||||
enable,
|
||||
server: String::from(""),
|
||||
bypass: String::from(""),
|
||||
}
|
||||
};
|
||||
|
||||
match set_proxy_config(&config) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(_) => Err(format!("can not set proxy")),
|
||||
}
|
||||
}
|
||||
|
||||
/// get the system proxy
|
||||
/// Tips: only support windows now
|
||||
#[tauri::command]
|
||||
pub fn get_sys_proxy() -> Result<SysProxyConfig, String> {
|
||||
match get_proxy_config() {
|
||||
Ok(value) => Ok(value),
|
||||
Err(err) => Err(err.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// get the verge config
|
||||
#[tauri::command]
|
||||
pub fn get_verge_config(verge_lock: State<'_, VergeConfLock>) -> Result<VergeConfig, String> {
|
||||
match verge_lock.0.lock() {
|
||||
Ok(arc) => Ok(arc.clone()),
|
||||
Err(_) => Err(format!("can not get the lock")),
|
||||
}
|
||||
}
|
||||
|
||||
/// patch the verge config
|
||||
/// this command only save the config and not responsible for other things
|
||||
#[tauri::command]
|
||||
pub async fn patch_verge_config(
|
||||
payload: VergeConfig,
|
||||
verge_lock: State<'_, VergeConfLock>,
|
||||
) -> Result<(), String> {
|
||||
let mut verge = match verge_lock.0.lock() {
|
||||
Ok(v) => v,
|
||||
Err(_) => return Err(format!("can not get the lock")),
|
||||
};
|
||||
|
||||
if payload.theme_mode.is_some() {
|
||||
verge.theme_mode = payload.theme_mode;
|
||||
}
|
||||
|
||||
// todo
|
||||
if payload.enable_self_startup.is_some() {
|
||||
verge.enable_self_startup = payload.enable_self_startup;
|
||||
}
|
||||
|
||||
// todo
|
||||
if payload.enable_system_proxy.is_some() {
|
||||
verge.enable_system_proxy = payload.enable_system_proxy;
|
||||
}
|
||||
|
||||
if payload.system_proxy_bypass.is_some() {
|
||||
verge.system_proxy_bypass = payload.system_proxy_bypass;
|
||||
}
|
||||
|
||||
save_verge(&verge)
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// ### `config.yaml` schema
|
||||
/// here should contain all configuration options.
|
||||
/// See: https://github.com/Dreamacro/clash/wiki/configuration for details
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct ClashConfig {
|
||||
pub port: Option<u32>,
|
||||
|
||||
/// alias to `mixed-port`
|
||||
pub mixed_port: Option<u32>,
|
||||
|
||||
/// alias to `allow-lan`
|
||||
pub allow_lan: Option<bool>,
|
||||
|
||||
/// alias to `external-controller`
|
||||
pub external_ctrl: Option<String>,
|
||||
|
||||
pub secret: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct ClashController {
|
||||
/// clash core port
|
||||
pub port: Option<String>,
|
||||
|
||||
/// same as `external-controller`
|
||||
pub server: Option<String>,
|
||||
pub secret: Option<String>,
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Define the `profiles.yaml` schema
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct ProfilesConfig {
|
||||
/// current profile's name
|
||||
pub current: Option<usize>,
|
||||
|
||||
/// profile list
|
||||
pub items: Option<Vec<ProfileItem>>,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct ProfileItem {
|
||||
/// profile name
|
||||
pub name: Option<String>,
|
||||
/// profile file
|
||||
pub file: Option<String>,
|
||||
/// current mode
|
||||
pub mode: Option<String>,
|
||||
/// source url
|
||||
pub url: Option<String>,
|
||||
/// selected infomation
|
||||
pub selected: Option<Vec<ProfileSelected>>,
|
||||
/// user info
|
||||
pub extra: Option<ProfileExtra>,
|
||||
/// updated time
|
||||
pub updated: Option<usize>,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct ProfileSelected {
|
||||
pub name: Option<String>,
|
||||
pub now: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Copy, Deserialize, Serialize)]
|
||||
pub struct ProfileExtra {
|
||||
pub upload: usize,
|
||||
pub download: usize,
|
||||
pub total: usize,
|
||||
pub expire: usize,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
/// the result from url
|
||||
pub struct ProfileResponse {
|
||||
pub name: String,
|
||||
pub file: String,
|
||||
pub data: String,
|
||||
pub extra: ProfileExtra,
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// ### `verge.yaml` schema
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct VergeConfig {
|
||||
/// `light` or `dark`
|
||||
pub theme_mode: Option<String>,
|
||||
|
||||
/// can the app auto startup
|
||||
pub enable_self_startup: Option<bool>,
|
||||
|
||||
/// set system proxy
|
||||
pub enable_system_proxy: Option<bool>,
|
||||
|
||||
/// set system proxy bypass
|
||||
pub system_proxy_bypass: Option<String>,
|
||||
}
|
||||
220
src-tauri/src/core/clash.rs
Normal file
@@ -0,0 +1,220 @@
|
||||
use super::{Profiles, Verge};
|
||||
use crate::utils::{config, dirs};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_yaml::{Mapping, Value};
|
||||
use tauri::api::process::{Command, CommandChild, CommandEvent};
|
||||
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct ClashInfo {
|
||||
/// clash sidecar status
|
||||
pub status: String,
|
||||
|
||||
/// clash core port
|
||||
pub port: Option<String>,
|
||||
|
||||
/// same as `external-controller`
|
||||
pub server: Option<String>,
|
||||
|
||||
/// clash secret
|
||||
pub secret: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Clash {
|
||||
/// maintain the clash config
|
||||
pub config: Mapping,
|
||||
|
||||
/// some info
|
||||
pub info: ClashInfo,
|
||||
|
||||
/// clash sidecar
|
||||
pub sidecar: Option<CommandChild>,
|
||||
}
|
||||
|
||||
static CLASH_CONFIG: &str = "config.yaml";
|
||||
|
||||
// todo: be able to change config field
|
||||
impl Clash {
|
||||
pub fn new() -> Clash {
|
||||
let config = Clash::get_config();
|
||||
let info = Clash::get_info(&config);
|
||||
|
||||
Clash {
|
||||
config,
|
||||
info,
|
||||
sidecar: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// parse the clash's config.yaml
|
||||
/// get some information
|
||||
fn get_info(clash_config: &Mapping) -> ClashInfo {
|
||||
let key_port_1 = Value::String("port".to_string());
|
||||
let key_port_2 = Value::String("mixed-port".to_string());
|
||||
let key_server = Value::String("external-controller".to_string());
|
||||
let key_secret = Value::String("secret".to_string());
|
||||
|
||||
let port = match clash_config.get(&key_port_1) {
|
||||
Some(value) => match value {
|
||||
Value::String(val_str) => Some(val_str.clone()),
|
||||
Value::Number(val_num) => Some(val_num.to_string()),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
let port = match port {
|
||||
Some(_) => port,
|
||||
None => match clash_config.get(&key_port_2) {
|
||||
Some(value) => match value {
|
||||
Value::String(val_str) => Some(val_str.clone()),
|
||||
Value::Number(val_num) => Some(val_num.to_string()),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
},
|
||||
};
|
||||
|
||||
let server = match clash_config.get(&key_server) {
|
||||
Some(value) => match value {
|
||||
Value::String(val_str) => Some(val_str.clone()),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
let secret = match clash_config.get(&key_secret) {
|
||||
Some(value) => match value {
|
||||
Value::String(val_str) => Some(val_str.clone()),
|
||||
Value::Bool(val_bool) => Some(val_bool.to_string()),
|
||||
Value::Number(val_num) => Some(val_num.to_string()),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
|
||||
ClashInfo {
|
||||
status: "init".into(),
|
||||
port,
|
||||
server,
|
||||
secret,
|
||||
}
|
||||
}
|
||||
|
||||
/// run clash sidecar
|
||||
pub fn run_sidecar(&mut self) -> Result<(), String> {
|
||||
let app_dir = dirs::app_home_dir();
|
||||
let app_dir = app_dir.as_os_str().to_str().unwrap();
|
||||
|
||||
match Command::new_sidecar("clash") {
|
||||
Ok(cmd) => match cmd.args(["-d", app_dir]).spawn() {
|
||||
Ok((mut rx, cmd_child)) => {
|
||||
self.sidecar = Some(cmd_child);
|
||||
|
||||
// clash log
|
||||
tauri::async_runtime::spawn(async move {
|
||||
while let Some(event) = rx.recv().await {
|
||||
match event {
|
||||
CommandEvent::Stdout(line) => log::info!("[stdout]: {}", line),
|
||||
CommandEvent::Stderr(err) => log::error!("[stderr]: {}", err),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
Err(err) => Err(err.to_string()),
|
||||
},
|
||||
Err(err) => Err(err.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// drop clash sidecar
|
||||
pub fn drop_sidecar(&mut self) -> Result<(), String> {
|
||||
if let Some(sidecar) = self.sidecar.take() {
|
||||
if let Err(err) = sidecar.kill() {
|
||||
return Err(format!("failed to drop clash for \"{}\"", err));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// restart clash sidecar
|
||||
/// should reactivate profile after restart
|
||||
pub fn restart_sidecar(&mut self, profiles: &mut Profiles) -> Result<(), String> {
|
||||
self.update_config();
|
||||
self.drop_sidecar()?;
|
||||
self.run_sidecar()?;
|
||||
profiles.activate(&self)
|
||||
}
|
||||
|
||||
/// update the clash info
|
||||
pub fn update_config(&mut self) {
|
||||
self.config = Clash::get_config();
|
||||
self.info = Clash::get_info(&self.config);
|
||||
}
|
||||
|
||||
/// get clash config
|
||||
fn get_config() -> Mapping {
|
||||
config::read_yaml::<Mapping>(dirs::app_home_dir().join(CLASH_CONFIG))
|
||||
}
|
||||
|
||||
/// save the clash config
|
||||
fn save_config(&self) -> Result<(), String> {
|
||||
config::save_yaml(
|
||||
dirs::app_home_dir().join(CLASH_CONFIG),
|
||||
&self.config,
|
||||
Some("# Default Config For Clash Core\n\n"),
|
||||
)
|
||||
}
|
||||
|
||||
/// patch update the clash config
|
||||
pub fn patch_config(
|
||||
&mut self,
|
||||
patch: Mapping,
|
||||
verge: &mut Verge,
|
||||
profiles: &mut Profiles,
|
||||
) -> Result<(), String> {
|
||||
for (key, value) in patch.iter() {
|
||||
let value = value.clone();
|
||||
let key_str = key.as_str().clone().unwrap_or("");
|
||||
|
||||
// restart the clash
|
||||
if key_str == "mixed-port" {
|
||||
self.restart_sidecar(profiles)?;
|
||||
|
||||
let port = if value.is_number() {
|
||||
match value.as_i64().clone() {
|
||||
Some(num) => Some(format!("{num}")),
|
||||
None => None,
|
||||
}
|
||||
} else {
|
||||
match value.as_str().clone() {
|
||||
Some(num) => Some(num.into()),
|
||||
None => None,
|
||||
}
|
||||
};
|
||||
verge.init_sysproxy(port);
|
||||
}
|
||||
|
||||
if self.config.contains_key(key) {
|
||||
self.config[key] = value;
|
||||
} else {
|
||||
self.config.insert(key.clone(), value);
|
||||
}
|
||||
}
|
||||
self.save_config()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Clash {
|
||||
fn default() -> Self {
|
||||
Clash::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Clash {
|
||||
fn drop(&mut self) {
|
||||
if let Err(err) = self.drop_sidecar() {
|
||||
log::error!("{}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
399
src-tauri/src/core/profiles.rs
Normal file
@@ -0,0 +1,399 @@
|
||||
use super::{Clash, ClashInfo};
|
||||
use crate::utils::{config, dirs, tmpl};
|
||||
use reqwest::header::HeaderMap;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_yaml::{Mapping, Value};
|
||||
use std::collections::HashMap;
|
||||
use std::env::temp_dir;
|
||||
use std::fs::{remove_file, File};
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
/// Define the `profiles.yaml` schema
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct Profiles {
|
||||
/// current profile's name
|
||||
pub current: Option<usize>,
|
||||
|
||||
/// profile list
|
||||
pub items: Option<Vec<ProfileItem>>,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct ProfileItem {
|
||||
/// profile name
|
||||
pub name: Option<String>,
|
||||
/// profile description
|
||||
pub desc: Option<String>,
|
||||
/// profile file
|
||||
pub file: Option<String>,
|
||||
/// current mode
|
||||
pub mode: Option<String>,
|
||||
/// source url
|
||||
pub url: Option<String>,
|
||||
/// selected infomation
|
||||
pub selected: Option<Vec<ProfileSelected>>,
|
||||
/// user info
|
||||
pub extra: Option<ProfileExtra>,
|
||||
/// updated time
|
||||
pub updated: Option<usize>,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct ProfileSelected {
|
||||
pub name: Option<String>,
|
||||
pub now: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Copy, Deserialize, Serialize)]
|
||||
pub struct ProfileExtra {
|
||||
pub upload: usize,
|
||||
pub download: usize,
|
||||
pub total: usize,
|
||||
pub expire: usize,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
/// the result from url
|
||||
pub struct ProfileResponse {
|
||||
pub name: String,
|
||||
pub file: String,
|
||||
pub data: String,
|
||||
pub extra: Option<ProfileExtra>,
|
||||
}
|
||||
|
||||
static PROFILE_YAML: &str = "profiles.yaml";
|
||||
static PROFILE_TEMP: &str = "clash-verge-runtime.yaml";
|
||||
|
||||
impl Profiles {
|
||||
/// read the config from the file
|
||||
pub fn read_file() -> Self {
|
||||
config::read_yaml::<Profiles>(dirs::app_home_dir().join(PROFILE_YAML))
|
||||
}
|
||||
|
||||
/// save the config to the file
|
||||
pub fn save_file(&self) -> Result<(), String> {
|
||||
config::save_yaml(
|
||||
dirs::app_home_dir().join(PROFILE_YAML),
|
||||
self,
|
||||
Some("# Profiles Config for Clash Verge\n\n"),
|
||||
)
|
||||
}
|
||||
|
||||
/// sync the config between file and memory
|
||||
pub fn sync_file(&mut self) -> Result<(), String> {
|
||||
let data = config::read_yaml::<Self>(dirs::app_home_dir().join(PROFILE_YAML));
|
||||
if data.current.is_none() {
|
||||
Err("failed to read profiles.yaml".into())
|
||||
} else {
|
||||
self.current = data.current;
|
||||
self.items = data.items;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// import the new profile from the url
|
||||
/// and update the config file
|
||||
pub fn import_from_url(&mut self, url: String, result: ProfileResponse) -> Result<(), String> {
|
||||
// save the profile file
|
||||
let path = dirs::app_home_dir().join("profiles").join(&result.file);
|
||||
let file_data = result.data.as_bytes();
|
||||
File::create(path).unwrap().write(file_data).unwrap();
|
||||
|
||||
// update `profiles.yaml`
|
||||
let data = Profiles::read_file();
|
||||
let mut items = data.items.unwrap_or(vec![]);
|
||||
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs();
|
||||
|
||||
items.push(ProfileItem {
|
||||
name: Some(result.name),
|
||||
desc: Some("imported url".into()),
|
||||
file: Some(result.file),
|
||||
mode: Some(format!("rule")),
|
||||
url: Some(url),
|
||||
selected: Some(vec![]),
|
||||
extra: result.extra,
|
||||
updated: Some(now as usize),
|
||||
});
|
||||
|
||||
self.items = Some(items);
|
||||
if data.current.is_none() {
|
||||
self.current = Some(0);
|
||||
}
|
||||
|
||||
self.save_file()
|
||||
}
|
||||
|
||||
/// set the current and save to file
|
||||
pub fn put_current(&mut self, index: usize) -> Result<(), String> {
|
||||
let items = self.items.take().unwrap_or(vec![]);
|
||||
|
||||
if index >= items.len() {
|
||||
return Err("the index out of bound".into());
|
||||
}
|
||||
|
||||
self.items = Some(items);
|
||||
self.current = Some(index);
|
||||
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
|
||||
/// and save to config file
|
||||
/// only support the url item
|
||||
pub fn update_item(&mut self, index: usize, result: ProfileResponse) -> Result<(), String> {
|
||||
let mut items = self.items.take().unwrap_or(vec![]);
|
||||
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs() as usize;
|
||||
|
||||
// update file
|
||||
let file_path = &items[index].file.as_ref().unwrap();
|
||||
let file_path = dirs::app_home_dir().join("profiles").join(file_path);
|
||||
let file_data = result.data.as_bytes();
|
||||
File::create(file_path).unwrap().write(file_data).unwrap();
|
||||
|
||||
items[index].name = Some(result.name);
|
||||
items[index].extra = result.extra;
|
||||
items[index].updated = Some(now);
|
||||
|
||||
self.items = Some(items);
|
||||
self.save_file()
|
||||
}
|
||||
|
||||
/// patch item
|
||||
pub fn patch_item(&mut self, index: usize, profile: ProfileItem) -> Result<(), String> {
|
||||
let mut items = self.items.take().unwrap_or(vec![]);
|
||||
if index >= items.len() {
|
||||
return Err("index out of bound".into());
|
||||
}
|
||||
|
||||
if profile.name.is_some() {
|
||||
items[index].name = profile.name;
|
||||
}
|
||||
if profile.file.is_some() {
|
||||
items[index].file = profile.file;
|
||||
}
|
||||
if profile.mode.is_some() {
|
||||
items[index].mode = profile.mode;
|
||||
}
|
||||
if profile.url.is_some() {
|
||||
items[index].url = profile.url;
|
||||
}
|
||||
if profile.selected.is_some() {
|
||||
items[index].selected = profile.selected;
|
||||
}
|
||||
if profile.extra.is_some() {
|
||||
items[index].extra = profile.extra;
|
||||
}
|
||||
|
||||
self.items = Some(items);
|
||||
self.save_file()
|
||||
}
|
||||
|
||||
/// delete the item
|
||||
pub fn delete_item(&mut self, index: usize) -> Result<bool, String> {
|
||||
let mut current = self.current.clone().unwrap_or(0);
|
||||
let mut items = self.items.clone().unwrap_or(vec![]);
|
||||
|
||||
if index >= items.len() {
|
||||
return Err("index out of bound".into());
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
if current == index {
|
||||
current = 0;
|
||||
should_change = true;
|
||||
} else if current > index {
|
||||
current = current - 1;
|
||||
}
|
||||
|
||||
self.current = Some(current);
|
||||
self.items = Some(items);
|
||||
|
||||
match self.save_file() {
|
||||
Ok(_) => Ok(should_change),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
/// activate current profile
|
||||
pub fn activate(&self, clash: &Clash) -> Result<(), String> {
|
||||
let current = self.current.unwrap_or(0);
|
||||
match self.items.clone() {
|
||||
Some(items) => {
|
||||
if current >= items.len() {
|
||||
return Err("the index out of bound".into());
|
||||
}
|
||||
|
||||
let profile = items[current].clone();
|
||||
let clash_config = clash.config.clone();
|
||||
let clash_info = clash.info.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let mut count = 5; // retry times
|
||||
let mut err = String::from("");
|
||||
while count > 0 {
|
||||
match activate_profile(&profile, &clash_config, &clash_info).await {
|
||||
Ok(_) => return,
|
||||
Err(e) => err = e,
|
||||
}
|
||||
count -= 1;
|
||||
}
|
||||
log::error!("failed to activate for `{}`", err);
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
None => Err("empty profiles".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// put the profile to clash
|
||||
pub async fn activate_profile(
|
||||
profile_item: &ProfileItem,
|
||||
clash_config: &Mapping,
|
||||
clash_info: &ClashInfo,
|
||||
) -> Result<(), String> {
|
||||
// temp profile's path
|
||||
let temp_path = temp_dir().join(PROFILE_TEMP);
|
||||
|
||||
// generate temp profile
|
||||
{
|
||||
let file_name = match profile_item.file.clone() {
|
||||
Some(file_name) => file_name,
|
||||
None => return Err("profile item should have `file` field".into()),
|
||||
};
|
||||
|
||||
let file_path = dirs::app_home_dir().join("profiles").join(file_name);
|
||||
if !file_path.exists() {
|
||||
return Err(format!(
|
||||
"profile `{}` not exists",
|
||||
file_path.as_os_str().to_str().unwrap()
|
||||
));
|
||||
}
|
||||
|
||||
// begin to generate the new profile config
|
||||
let def_config = config::read_yaml::<Mapping>(file_path.clone());
|
||||
let mut new_config = Mapping::new();
|
||||
|
||||
// Only the following fields are allowed:
|
||||
// proxies/proxy-providers/proxy-groups/rule-providers/rules
|
||||
let valid_keys = vec![
|
||||
"proxies",
|
||||
"proxy-providers",
|
||||
"proxy-groups",
|
||||
"rule-providers",
|
||||
"rules",
|
||||
];
|
||||
valid_keys.iter().for_each(|key| {
|
||||
let key = Value::String(key.to_string());
|
||||
if def_config.contains_key(&key) {
|
||||
let value = def_config[&key].clone();
|
||||
new_config.insert(key, value);
|
||||
}
|
||||
});
|
||||
|
||||
// add some of the clash `config.yaml` config to it
|
||||
let valid_keys = vec![
|
||||
"mixed-port",
|
||||
"log-level",
|
||||
"allow-lan",
|
||||
"external-controller",
|
||||
"secret",
|
||||
"mode",
|
||||
"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(
|
||||
temp_path.clone(),
|
||||
&new_config,
|
||||
Some("# Clash Verge Temp File"),
|
||||
)?
|
||||
};
|
||||
|
||||
let server = format!("http://{}/configs", clash_info.server.clone().unwrap());
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("Content-Type", "application/json".parse().unwrap());
|
||||
|
||||
if let Some(secret) = clash_info.secret.clone() {
|
||||
headers.insert(
|
||||
"Authorization",
|
||||
format!("Bearer {}", secret).parse().unwrap(),
|
||||
);
|
||||
}
|
||||
|
||||
let mut data = HashMap::new();
|
||||
data.insert("path", temp_path.as_os_str().to_str().unwrap());
|
||||
|
||||
let client = match reqwest::ClientBuilder::new().no_proxy().build() {
|
||||
Ok(c) => c,
|
||||
Err(_) => return Err("failed to create http::put".into()),
|
||||
};
|
||||
match client.put(server).headers(headers).json(&data).send().await {
|
||||
Ok(_) => Ok(()),
|
||||
Err(err) => Err(format!("request failed `{}`", err.to_string())),
|
||||
}
|
||||
}
|
||||
337
src-tauri/src/core/verge.rs
Normal file
@@ -0,0 +1,337 @@
|
||||
use crate::{
|
||||
core::Clash,
|
||||
utils::{config, dirs, sysopt::SysProxyConfig},
|
||||
};
|
||||
use auto_launch::{AutoLaunch, AutoLaunchBuilder};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::Arc;
|
||||
use tauri::{api::path::resource_dir, async_runtime::Mutex};
|
||||
|
||||
/// ### `verge.yaml` schema
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct VergeConfig {
|
||||
/// `light` or `dark`
|
||||
pub theme_mode: Option<String>,
|
||||
|
||||
/// enable blur mode
|
||||
/// maybe be able to set the alpha
|
||||
pub theme_blur: Option<bool>,
|
||||
|
||||
/// enable traffic graph default is true
|
||||
pub traffic_graph: Option<bool>,
|
||||
|
||||
/// can the app auto startup
|
||||
pub enable_auto_launch: Option<bool>,
|
||||
|
||||
/// set system proxy
|
||||
pub enable_system_proxy: Option<bool>,
|
||||
|
||||
/// enable proxy guard
|
||||
pub enable_proxy_guard: Option<bool>,
|
||||
|
||||
/// set system proxy bypass
|
||||
pub system_proxy_bypass: Option<String>,
|
||||
|
||||
/// proxy guard duration
|
||||
pub proxy_guard_duration: Option<u64>,
|
||||
}
|
||||
|
||||
static VERGE_CONFIG: &str = "verge.yaml";
|
||||
|
||||
impl VergeConfig {
|
||||
pub fn new() -> Self {
|
||||
config::read_yaml::<VergeConfig>(dirs::app_home_dir().join(VERGE_CONFIG))
|
||||
}
|
||||
|
||||
/// Save Verge App Config
|
||||
pub fn save_file(&self) -> Result<(), String> {
|
||||
config::save_yaml(
|
||||
dirs::app_home_dir().join(VERGE_CONFIG),
|
||||
self,
|
||||
Some("# The Config for Clash Verge App\n\n"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Verge App abilities
|
||||
#[derive(Debug)]
|
||||
pub struct Verge {
|
||||
pub config: VergeConfig,
|
||||
|
||||
pub old_sysproxy: Option<SysProxyConfig>,
|
||||
|
||||
pub cur_sysproxy: Option<SysProxyConfig>,
|
||||
|
||||
pub auto_launch: Option<AutoLaunch>,
|
||||
|
||||
/// record whether the guard async is running or not
|
||||
guard_state: Arc<Mutex<bool>>,
|
||||
}
|
||||
|
||||
impl Default for Verge {
|
||||
fn default() -> Self {
|
||||
Verge::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Verge {
|
||||
pub fn new() -> Self {
|
||||
Verge {
|
||||
config: VergeConfig::new(),
|
||||
old_sysproxy: None,
|
||||
cur_sysproxy: None,
|
||||
auto_launch: None,
|
||||
guard_state: Arc::new(Mutex::new(false)),
|
||||
}
|
||||
}
|
||||
|
||||
/// init the sysproxy
|
||||
pub fn init_sysproxy(&mut self, port: Option<String>) {
|
||||
if let Some(port) = port {
|
||||
let enable = self.config.enable_system_proxy.clone().unwrap_or(false);
|
||||
|
||||
self.old_sysproxy = match SysProxyConfig::get_sys() {
|
||||
Ok(proxy) => Some(proxy),
|
||||
Err(_) => None,
|
||||
};
|
||||
|
||||
let bypass = self.config.system_proxy_bypass.clone();
|
||||
let sysproxy = SysProxyConfig::new(enable, port, bypass);
|
||||
|
||||
if enable {
|
||||
if sysproxy.set_sys().is_err() {
|
||||
log::error!("failed to set system proxy");
|
||||
}
|
||||
}
|
||||
|
||||
self.cur_sysproxy = Some(sysproxy);
|
||||
}
|
||||
|
||||
// launchs the system proxy guard
|
||||
Verge::guard_proxy(self.guard_state.clone());
|
||||
}
|
||||
|
||||
/// reset the sysproxy
|
||||
pub fn reset_sysproxy(&mut self) {
|
||||
if let Some(sysproxy) = self.old_sysproxy.take() {
|
||||
match sysproxy.set_sys() {
|
||||
Ok(_) => self.cur_sysproxy = None,
|
||||
Err(_) => log::error!("failed to reset proxy for"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// init the auto launch
|
||||
pub fn init_launch(&mut self, package_info: &tauri::PackageInfo) {
|
||||
let app_name = "clash-verge";
|
||||
let app_path = get_app_path(app_name);
|
||||
let app_path = resource_dir(package_info, &tauri::Env::default())
|
||||
.unwrap()
|
||||
.join(app_path);
|
||||
let app_path = app_path.as_os_str().to_str().unwrap();
|
||||
|
||||
let auto = AutoLaunchBuilder::new()
|
||||
.set_app_name(app_name)
|
||||
.set_app_path(app_path)
|
||||
.build();
|
||||
|
||||
self.auto_launch = Some(auto);
|
||||
}
|
||||
|
||||
/// sync the startup when run the app
|
||||
pub fn sync_launch(&self) -> Result<(), String> {
|
||||
let enable = self.config.enable_auto_launch.clone().unwrap_or(false);
|
||||
if !enable {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if self.auto_launch.is_none() {
|
||||
return Err("should init the auto launch first".into());
|
||||
}
|
||||
|
||||
let auto_launch = self.auto_launch.clone().unwrap();
|
||||
|
||||
let is_enabled = auto_launch.is_enabled().unwrap_or(false);
|
||||
if !is_enabled {
|
||||
if let Err(_) = auto_launch.enable() {
|
||||
return Err("failed to enable auto-launch".into());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// update the startup
|
||||
fn update_launch(&mut self, enable: bool) -> Result<(), String> {
|
||||
let conf_enable = self.config.enable_auto_launch.clone().unwrap_or(false);
|
||||
|
||||
if enable == conf_enable {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let auto_launch = self.auto_launch.clone().unwrap();
|
||||
|
||||
let result = match enable {
|
||||
true => auto_launch.enable(),
|
||||
false => auto_launch.disable(),
|
||||
};
|
||||
|
||||
match result {
|
||||
Ok(_) => Ok(()),
|
||||
Err(err) => {
|
||||
log::error!("{err}");
|
||||
Err("failed to set system startup info".into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// patch verge config
|
||||
/// There should be only one update at a time here
|
||||
/// so call the save_file at the end is savely
|
||||
pub fn patch_config(&mut self, patch: VergeConfig) -> Result<(), String> {
|
||||
// only change it
|
||||
if patch.theme_mode.is_some() {
|
||||
self.config.theme_mode = patch.theme_mode;
|
||||
}
|
||||
if patch.theme_blur.is_some() {
|
||||
self.config.theme_blur = patch.theme_blur;
|
||||
}
|
||||
if patch.traffic_graph.is_some() {
|
||||
self.config.traffic_graph = patch.traffic_graph;
|
||||
}
|
||||
|
||||
// should update system startup
|
||||
if patch.enable_auto_launch.is_some() {
|
||||
let enable = patch.enable_auto_launch.unwrap();
|
||||
self.update_launch(enable)?;
|
||||
self.config.enable_auto_launch = Some(enable);
|
||||
}
|
||||
|
||||
// should update system proxy
|
||||
if patch.enable_system_proxy.is_some() {
|
||||
let enable = patch.enable_system_proxy.unwrap();
|
||||
|
||||
if let Some(mut sysproxy) = self.cur_sysproxy.take() {
|
||||
sysproxy.enable = enable;
|
||||
if sysproxy.set_sys().is_err() {
|
||||
self.cur_sysproxy = Some(sysproxy);
|
||||
|
||||
log::error!("failed to set system proxy");
|
||||
return Err("failed to set system proxy".into());
|
||||
}
|
||||
self.cur_sysproxy = Some(sysproxy);
|
||||
}
|
||||
self.config.enable_system_proxy = Some(enable);
|
||||
}
|
||||
|
||||
// should update system proxy too
|
||||
if patch.system_proxy_bypass.is_some() {
|
||||
let bypass = patch.system_proxy_bypass.unwrap();
|
||||
|
||||
if let Some(mut sysproxy) = self.cur_sysproxy.take() {
|
||||
if sysproxy.enable {
|
||||
sysproxy.bypass = bypass.clone();
|
||||
|
||||
if sysproxy.set_sys().is_err() {
|
||||
self.cur_sysproxy = Some(sysproxy);
|
||||
|
||||
log::error!("failed to set system proxy");
|
||||
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());
|
||||
}
|
||||
|
||||
self.config.save_file()
|
||||
}
|
||||
}
|
||||
|
||||
impl Verge {
|
||||
/// launch a system proxy guard
|
||||
/// read config from file directly
|
||||
pub fn guard_proxy(guard_state: Arc<Mutex<bool>>) {
|
||||
use tokio::time::{sleep, Duration};
|
||||
|
||||
tauri::async_runtime::spawn(async move {
|
||||
// if it is running, exit
|
||||
let mut state = guard_state.lock().await;
|
||||
if *state {
|
||||
return;
|
||||
}
|
||||
*state = true;
|
||||
std::mem::drop(state);
|
||||
|
||||
// default duration is 10s
|
||||
let mut wait_secs = 10u64;
|
||||
|
||||
loop {
|
||||
sleep(Duration::from_secs(wait_secs)).await;
|
||||
|
||||
log::debug!("[Guard]: heartbeat detection");
|
||||
|
||||
let verge = Verge::new();
|
||||
|
||||
let enable_proxy = verge.config.enable_system_proxy.unwrap_or(false);
|
||||
let enable_guard = verge.config.enable_proxy_guard.unwrap_or(false);
|
||||
let guard_duration = verge.config.proxy_guard_duration.unwrap_or(10);
|
||||
|
||||
// update duration
|
||||
wait_secs = guard_duration;
|
||||
|
||||
// stop loop
|
||||
if !enable_guard || !enable_proxy {
|
||||
break;
|
||||
}
|
||||
|
||||
log::info!("[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;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Get the target app_path
|
||||
fn get_app_path(app_name: &str) -> String {
|
||||
#[cfg(target_os = "linux")]
|
||||
let ext = "";
|
||||
#[cfg(target_os = "macos")]
|
||||
let ext = "";
|
||||
#[cfg(target_os = "windows")]
|
||||
let ext = ".exe";
|
||||
String::from(app_name) + ext
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tauri::{AppHandle, Manager};
|
||||
|
||||
use crate::config::ClashController;
|
||||
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct ClashInfoPayload {
|
||||
/// value between `success` and `error`
|
||||
pub status: String,
|
||||
|
||||
/// the clash core's external controller infomation
|
||||
pub controller: Option<ClashController>,
|
||||
|
||||
/// some message
|
||||
pub message: Option<String>,
|
||||
}
|
||||
|
||||
/// emit `clash_runtime` to the main windows
|
||||
pub fn clash_start(app_handle: &AppHandle, payload: &ClashInfoPayload) {
|
||||
match app_handle.get_window("main") {
|
||||
Some(main_win) => {
|
||||
main_win.emit("clash_start", payload).unwrap();
|
||||
}
|
||||
_ => {}
|
||||
};
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
pub mod emit;
|
||||
pub mod state;
|
||||
@@ -1,16 +0,0 @@
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use super::emit::ClashInfoPayload;
|
||||
use crate::{config::VergeConfig, utils::sysopt::SysProxyConfig};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct ClashInfoState(pub Arc<Mutex<ClashInfoPayload>>);
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct ProfileLock(pub Mutex<bool>);
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct VergeConfLock(pub Arc<Mutex<VergeConfig>>);
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct SomthingState(pub Arc<Mutex<Option<SysProxyConfig>>>);
|
||||
@@ -3,17 +3,12 @@
|
||||
windows_subsystem = "windows"
|
||||
)]
|
||||
|
||||
extern crate tauri;
|
||||
|
||||
mod cmds;
|
||||
mod config;
|
||||
mod events;
|
||||
mod core;
|
||||
mod states;
|
||||
mod utils;
|
||||
|
||||
use crate::{
|
||||
events::state,
|
||||
utils::{resolve, server},
|
||||
};
|
||||
use crate::utils::{resolve, server};
|
||||
use tauri::{
|
||||
api, CustomMenuItem, Manager, SystemTray, SystemTrayEvent, SystemTrayMenu, SystemTrayMenuItem,
|
||||
};
|
||||
@@ -25,64 +20,89 @@ fn main() -> std::io::Result<()> {
|
||||
}
|
||||
|
||||
let menu = SystemTrayMenu::new()
|
||||
.add_item(CustomMenuItem::new("open_window", "显示应用"))
|
||||
.add_item(CustomMenuItem::new("open_window", "Show"))
|
||||
.add_item(CustomMenuItem::new("restart_clash", "Restart Clash"))
|
||||
.add_native_item(SystemTrayMenuItem::Separator)
|
||||
.add_item(CustomMenuItem::new("quit", "退出").accelerator("CmdOrControl+Q"));
|
||||
.add_item(CustomMenuItem::new("quit", "Quit").accelerator("CmdOrControl+Q"));
|
||||
|
||||
tauri::Builder::default()
|
||||
.manage(state::VergeConfLock::default())
|
||||
.manage(state::ClashInfoState::default())
|
||||
.manage(state::SomthingState::default())
|
||||
.manage(state::ProfileLock::default())
|
||||
.manage(states::VergeState::default())
|
||||
.manage(states::ClashState::default())
|
||||
.manage(states::ProfilesState::default())
|
||||
.setup(|app| Ok(resolve::resolve_setup(app)))
|
||||
.system_tray(SystemTray::new().with_menu(menu))
|
||||
.on_system_tray_event(move |app_handle, event| match event {
|
||||
SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() {
|
||||
"open_window" => {
|
||||
let window = app_handle.get_window("main").unwrap();
|
||||
window.unminimize().unwrap();
|
||||
window.show().unwrap();
|
||||
window.set_focus().unwrap();
|
||||
}
|
||||
"restart_clash" => {
|
||||
let clash_state = app_handle.state::<states::ClashState>();
|
||||
let profiles_state = app_handle.state::<states::ProfilesState>();
|
||||
let mut clash = clash_state.0.lock().unwrap();
|
||||
let mut profiles = profiles_state.0.lock().unwrap();
|
||||
match clash.restart_sidecar(&mut profiles) {
|
||||
Ok(_) => {
|
||||
let window = app_handle.get_window("main").unwrap();
|
||||
window.emit("restart_clash", "yes").unwrap();
|
||||
}
|
||||
Err(err) => log::error!("{}", err),
|
||||
}
|
||||
}
|
||||
"quit" => {
|
||||
api::process::kill_children();
|
||||
resolve::resolve_reset(app_handle);
|
||||
app_handle.exit(0);
|
||||
api::process::kill_children();
|
||||
std::process::exit(0);
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
SystemTrayEvent::LeftClick { .. } => {
|
||||
let window = app_handle.get_window("main").unwrap();
|
||||
window.show().unwrap();
|
||||
window.set_focus().unwrap();
|
||||
if cfg![target_os = "windows"] {
|
||||
let window = app_handle.get_window("main").unwrap();
|
||||
window.unminimize().unwrap();
|
||||
window.show().unwrap();
|
||||
window.set_focus().unwrap();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
cmds::some::restart_sidecar,
|
||||
cmds::some::set_sys_proxy,
|
||||
cmds::some::get_sys_proxy,
|
||||
cmds::some::get_clash_info,
|
||||
cmds::some::patch_clash_config,
|
||||
cmds::some::get_verge_config,
|
||||
cmds::some::patch_verge_config,
|
||||
cmds::profile::import_profile,
|
||||
cmds::profile::update_profile,
|
||||
cmds::profile::get_profiles,
|
||||
cmds::profile::set_profiles,
|
||||
cmds::profile::put_profiles,
|
||||
// common
|
||||
cmds::restart_sidecar,
|
||||
cmds::get_sys_proxy,
|
||||
cmds::get_cur_proxy,
|
||||
cmds::kill_sidecars,
|
||||
cmds::open_app_dir,
|
||||
cmds::open_logs_dir,
|
||||
// clash
|
||||
cmds::get_clash_info,
|
||||
cmds::patch_clash_config,
|
||||
// verge
|
||||
cmds::get_verge_config,
|
||||
cmds::patch_verge_config,
|
||||
// profile
|
||||
cmds::new_profile,
|
||||
cmds::view_profile,
|
||||
cmds::patch_profile,
|
||||
cmds::import_profile,
|
||||
cmds::update_profile,
|
||||
cmds::delete_profile,
|
||||
cmds::select_profile,
|
||||
cmds::get_profiles,
|
||||
cmds::sync_profiles,
|
||||
])
|
||||
.build(tauri::generate_context!())
|
||||
.expect("error while running tauri application")
|
||||
.run(|app_handle, e| match e {
|
||||
tauri::Event::CloseRequested { label, api, .. } => {
|
||||
tauri::RunEvent::CloseRequested { label, api, .. } => {
|
||||
let app_handle = app_handle.clone();
|
||||
api.prevent_close();
|
||||
app_handle.get_window(&label).unwrap().hide().unwrap();
|
||||
}
|
||||
tauri::Event::ExitRequested { api, .. } => {
|
||||
api.prevent_exit();
|
||||
}
|
||||
tauri::Event::Exit => {
|
||||
tauri::RunEvent::ExitRequested { .. } => {
|
||||
resolve::resolve_reset(app_handle);
|
||||
api::process::kill_children();
|
||||
}
|
||||
|
||||
11
src-tauri/src/states.rs
Normal file
@@ -0,0 +1,11 @@
|
||||
use crate::core::{Clash, Profiles, Verge};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct ProfilesState(pub Arc<Mutex<Profiles>>);
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct ClashState(pub Arc<Mutex<Clash>>);
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct VergeState(pub Arc<Mutex<Verge>>);
|
||||
@@ -1,150 +0,0 @@
|
||||
extern crate log;
|
||||
|
||||
use crate::{
|
||||
events::emit::{clash_start, ClashInfoPayload},
|
||||
utils::{
|
||||
app_home_dir,
|
||||
config::{read_clash_controller, read_profiles, read_yaml, save_yaml},
|
||||
},
|
||||
};
|
||||
use reqwest::header::HeaderMap;
|
||||
use serde_yaml::{Mapping, Value};
|
||||
use std::{collections::HashMap, env::temp_dir};
|
||||
use tauri::{
|
||||
api::process::{Command, CommandEvent},
|
||||
AppHandle,
|
||||
};
|
||||
|
||||
/// Run the clash bin
|
||||
pub fn run_clash_bin(app_handle: &AppHandle) -> ClashInfoPayload {
|
||||
let app_dir = app_home_dir();
|
||||
let app_dir = app_dir.as_os_str().to_str().unwrap();
|
||||
|
||||
let mut payload = ClashInfoPayload {
|
||||
status: "success".to_string(),
|
||||
controller: None,
|
||||
message: None,
|
||||
};
|
||||
|
||||
let result = match Command::new_sidecar("clash") {
|
||||
Ok(cmd) => match cmd.args(["-d", app_dir]).spawn() {
|
||||
Ok(res) => Ok(res),
|
||||
Err(err) => Err(err.to_string()),
|
||||
},
|
||||
Err(err) => Err(err.to_string()),
|
||||
};
|
||||
|
||||
match result {
|
||||
Ok((mut rx, _)) => {
|
||||
log::info!("Successfully execute clash sidecar");
|
||||
payload.controller = Some(read_clash_controller());
|
||||
|
||||
tauri::async_runtime::spawn(async move {
|
||||
while let Some(event) = rx.recv().await {
|
||||
match event {
|
||||
CommandEvent::Stdout(line) => log::info!("{}", line),
|
||||
CommandEvent::Stderr(err) => log::error!("{}", err),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
Err(err) => {
|
||||
log::error!("Failed to execute clash sidecar for \"{}\"", err);
|
||||
payload.status = "error".to_string();
|
||||
payload.message = Some(err.to_string());
|
||||
}
|
||||
};
|
||||
|
||||
clash_start(app_handle, &payload);
|
||||
payload
|
||||
}
|
||||
|
||||
/// Update the clash profile firstly
|
||||
pub async fn put_clash_profile(payload: &ClashInfoPayload) -> Result<(), String> {
|
||||
let profile = {
|
||||
let profiles = read_profiles();
|
||||
let current = profiles.current.unwrap_or(0) as usize;
|
||||
match profiles.items {
|
||||
Some(items) => {
|
||||
if items.len() == 0 {
|
||||
return Err("can not read profiles".to_string());
|
||||
}
|
||||
let idx = if current < items.len() { current } else { 0 };
|
||||
items[idx].clone()
|
||||
}
|
||||
None => {
|
||||
return Err("can not read profiles".to_string());
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// temp profile's path
|
||||
let temp_path = temp_dir().join("clash-verge-runtime.yaml");
|
||||
|
||||
// generate temp profile
|
||||
{
|
||||
let file_name = match profile.file {
|
||||
Some(file_name) => file_name.clone(),
|
||||
None => {
|
||||
return Err(format!("profile item should have `file` field"));
|
||||
}
|
||||
};
|
||||
|
||||
let file_path = app_home_dir().join("profiles").join(file_name);
|
||||
if !file_path.exists() {
|
||||
return Err(format!("profile `{:?}` not exists", file_path));
|
||||
}
|
||||
|
||||
// Only the following fields are allowed:
|
||||
// proxies/proxy-providers/proxy-groups/rule-providers/rules
|
||||
let config = read_yaml::<Mapping>(file_path.clone());
|
||||
let mut new_config = Mapping::new();
|
||||
vec![
|
||||
"proxies",
|
||||
"proxy-providers",
|
||||
"proxy-groups",
|
||||
"rule-providers",
|
||||
"rules",
|
||||
]
|
||||
.iter()
|
||||
.map(|item| Value::String(item.to_string()))
|
||||
.for_each(|key| {
|
||||
if config.contains_key(&key) {
|
||||
let value = config[&key].clone();
|
||||
new_config.insert(key, value);
|
||||
}
|
||||
});
|
||||
|
||||
match save_yaml(
|
||||
temp_path.clone(),
|
||||
&new_config,
|
||||
Some("# Clash Verge Temp File"),
|
||||
) {
|
||||
Err(err) => return Err(err),
|
||||
_ => {}
|
||||
};
|
||||
}
|
||||
|
||||
let ctrl = payload.controller.clone().unwrap();
|
||||
let server = format!("http://{}/configs", ctrl.server.unwrap());
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("Content-Type", "application/json".parse().unwrap());
|
||||
|
||||
if let Some(secret) = ctrl.secret {
|
||||
headers.insert(
|
||||
"Authorization",
|
||||
format!("Bearer {}", secret).parse().unwrap(),
|
||||
);
|
||||
}
|
||||
|
||||
let mut data = HashMap::new();
|
||||
data.insert("path", temp_path.as_os_str().to_str().unwrap());
|
||||
|
||||
let client = reqwest::Client::new();
|
||||
match client.put(server).headers(headers).json(&data).send().await {
|
||||
Ok(_) => Ok(()),
|
||||
Err(err) => Err(format!("request failed `{}`", err.to_string())),
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,4 @@
|
||||
use crate::{
|
||||
config::{ClashController, ProfilesConfig, VergeConfig},
|
||||
utils::app_home_dir,
|
||||
};
|
||||
use serde::{de::DeserializeOwned, Serialize};
|
||||
use serde_yaml::{Mapping, Value};
|
||||
use std::{fs, path::PathBuf};
|
||||
|
||||
/// read data from yaml as struct T
|
||||
@@ -19,114 +14,19 @@ pub fn save_yaml<T: Serialize>(
|
||||
data: &T,
|
||||
prefix: Option<&str>,
|
||||
) -> Result<(), String> {
|
||||
if let Ok(data_str) = serde_yaml::to_string(data) {
|
||||
let yaml_str = if prefix.is_some() {
|
||||
prefix.unwrap().to_string() + &data_str
|
||||
} else {
|
||||
data_str
|
||||
};
|
||||
match serde_yaml::to_string(data) {
|
||||
Ok(data_str) => {
|
||||
let yaml_str = match prefix {
|
||||
Some(prefix) => format!("{}{}", prefix, data_str),
|
||||
None => data_str,
|
||||
};
|
||||
|
||||
if fs::write(path.clone(), yaml_str.as_bytes()).is_err() {
|
||||
Err(format!("can not save file `{:?}`", path))
|
||||
} else {
|
||||
Ok(())
|
||||
let path_str = path.as_os_str().to_string_lossy().to_string();
|
||||
match fs::write(path, yaml_str.as_bytes()) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(_) => Err(format!("can not save file `{}`", path_str)),
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Err(String::from("can not convert the data to yaml"))
|
||||
Err(_) => Err("can not convert the data to yaml".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get Clash Core Config `config.yaml`
|
||||
pub fn read_clash() -> Mapping {
|
||||
read_yaml::<Mapping>(app_home_dir().join("config.yaml"))
|
||||
}
|
||||
|
||||
/// Save the clash core Config `config.yaml`
|
||||
pub fn save_clash(config: &Mapping) -> Result<(), String> {
|
||||
save_yaml(
|
||||
app_home_dir().join("config.yaml"),
|
||||
config,
|
||||
Some("# Default Config For Clash Core\n\n"),
|
||||
)
|
||||
}
|
||||
|
||||
/// Get infomation of the clash's `external-controller` and `secret`
|
||||
pub fn read_clash_controller() -> ClashController {
|
||||
let config = read_clash();
|
||||
|
||||
let key_port_1 = Value::String("port".to_string());
|
||||
let key_port_2 = Value::String("mixed-port".to_string());
|
||||
let key_server = Value::String("external-controller".to_string());
|
||||
let key_secret = Value::String("secret".to_string());
|
||||
|
||||
let port = match config.get(&key_port_1) {
|
||||
Some(value) => match value {
|
||||
Value::String(val_str) => Some(val_str.clone()),
|
||||
Value::Number(val_num) => Some(val_num.to_string()),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
let port = match port {
|
||||
Some(_) => port,
|
||||
None => match config.get(&key_port_2) {
|
||||
Some(value) => match value {
|
||||
Value::String(val_str) => Some(val_str.clone()),
|
||||
Value::Number(val_num) => Some(val_num.to_string()),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
},
|
||||
};
|
||||
|
||||
let server = match config.get(&key_server) {
|
||||
Some(value) => match value {
|
||||
Value::String(val_str) => Some(val_str.clone()),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
let secret = match config.get(&key_secret) {
|
||||
Some(value) => match value {
|
||||
Value::String(val_str) => Some(val_str.clone()),
|
||||
Value::Bool(val_bool) => Some(val_bool.to_string()),
|
||||
Value::Number(val_num) => Some(val_num.to_string()),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
|
||||
ClashController {
|
||||
port,
|
||||
server,
|
||||
secret,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get Profiles Config
|
||||
pub fn read_profiles() -> ProfilesConfig {
|
||||
read_yaml::<ProfilesConfig>(app_home_dir().join("profiles.yaml"))
|
||||
}
|
||||
|
||||
/// Save Verge App Config
|
||||
pub fn save_profiles(profiles: &ProfilesConfig) -> Result<(), String> {
|
||||
save_yaml(
|
||||
app_home_dir().join("profiles.yaml"),
|
||||
profiles,
|
||||
Some("# Profiles Config for Clash Verge\n\n"),
|
||||
)
|
||||
}
|
||||
|
||||
/// Get the `verge.yaml`
|
||||
pub fn read_verge() -> VergeConfig {
|
||||
read_yaml::<VergeConfig>(app_home_dir().join("verge.yaml"))
|
||||
}
|
||||
|
||||
/// Save Verge App Config
|
||||
pub fn save_verge(verge: &VergeConfig) -> Result<(), String> {
|
||||
save_yaml(
|
||||
app_home_dir().join("verge.yaml"),
|
||||
verge,
|
||||
Some("# The Config for Clash Verge App\n\n"),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
use tauri::{
|
||||
api::path::{home_dir, resource_dir},
|
||||
PackageInfo,
|
||||
Env, PackageInfo,
|
||||
};
|
||||
|
||||
/// get the verge app home dir
|
||||
@@ -14,5 +14,7 @@ pub fn app_home_dir() -> PathBuf {
|
||||
|
||||
/// get the resources dir
|
||||
pub fn app_resources_dir(package_info: &PackageInfo) -> PathBuf {
|
||||
resource_dir(package_info).unwrap().join("resources")
|
||||
resource_dir(package_info, &Env::default())
|
||||
.unwrap()
|
||||
.join("resources")
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::config::{ProfileExtra, ProfileResponse};
|
||||
use crate::core::{ProfileExtra, ProfileResponse};
|
||||
use std::{
|
||||
str::FromStr,
|
||||
time::{SystemTime, UNIX_EPOCH},
|
||||
@@ -22,57 +22,63 @@ fn parse_string<T: FromStr>(target: &str, key: &str) -> Option<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// fetch and parse the profile
|
||||
pub async fn fetch_profile(url: &str) -> Option<ProfileResponse> {
|
||||
let resp = match reqwest::get(url).await {
|
||||
Ok(res) => res,
|
||||
Err(_) => return None,
|
||||
/// fetch and parse the profile url
|
||||
/// 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 client = match with_proxy {
|
||||
true => builder.build(),
|
||||
false => builder.no_proxy().build(),
|
||||
};
|
||||
|
||||
let resp = match client.unwrap().get(url).send().await {
|
||||
Ok(res) => res,
|
||||
Err(_) => return Err("failed to create https client".into()),
|
||||
};
|
||||
|
||||
let header = resp.headers();
|
||||
|
||||
// parse the Subscription Userinfo
|
||||
let extra = {
|
||||
let sub_info = match header.get("Subscription-Userinfo") {
|
||||
Some(value) => value.to_str().unwrap_or(""),
|
||||
None => "",
|
||||
};
|
||||
let extra = match header.get("Subscription-Userinfo") {
|
||||
Some(value) => {
|
||||
let sub_info = value.to_str().unwrap_or("");
|
||||
|
||||
ProfileExtra {
|
||||
upload: parse_string(sub_info, "upload=").unwrap_or(0),
|
||||
download: parse_string(sub_info, "download=").unwrap_or(0),
|
||||
total: parse_string(sub_info, "total=").unwrap_or(0),
|
||||
expire: parse_string(sub_info, "expire=").unwrap_or(0),
|
||||
Some(ProfileExtra {
|
||||
upload: parse_string(sub_info, "upload=").unwrap_or(0),
|
||||
download: parse_string(sub_info, "download=").unwrap_or(0),
|
||||
total: parse_string(sub_info, "total=").unwrap_or(0),
|
||||
expire: parse_string(sub_info, "expire=").unwrap_or(0),
|
||||
})
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
|
||||
// parse the `name` and `file`
|
||||
let (name, file) = {
|
||||
let file = {
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs();
|
||||
let file = format!("{}.yaml", now);
|
||||
let name = header.get("Content-Disposition").unwrap().to_str().unwrap();
|
||||
let name = parse_string::<String>(name, "filename=");
|
||||
format!("{}.yaml", now)
|
||||
};
|
||||
|
||||
match name {
|
||||
Some(f) => (f, file),
|
||||
None => (file.clone(), file),
|
||||
let name = match header.get("Content-Disposition") {
|
||||
Some(name) => {
|
||||
let name = name.to_str().unwrap();
|
||||
parse_string::<String>(name, "filename=").unwrap_or(file.clone())
|
||||
}
|
||||
None => file.clone(),
|
||||
};
|
||||
|
||||
// get the data
|
||||
let data = match resp.text_with_charset("utf-8").await {
|
||||
Ok(d) => d,
|
||||
Err(_) => return None,
|
||||
};
|
||||
|
||||
Some(ProfileResponse {
|
||||
file,
|
||||
name,
|
||||
data,
|
||||
extra,
|
||||
})
|
||||
match resp.text_with_charset("utf-8").await {
|
||||
Ok(data) => Ok(ProfileResponse {
|
||||
file,
|
||||
name,
|
||||
data,
|
||||
extra,
|
||||
}),
|
||||
Err(_) => Err("failed to parse the response data".into()),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
extern crate serde_yaml;
|
||||
|
||||
use crate::utils::{dirs, tmpl};
|
||||
use chrono::Local;
|
||||
use log::LevelFilter;
|
||||
use log4rs::append::console::ConsoleAppender;
|
||||
@@ -11,8 +12,6 @@ use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use tauri::PackageInfo;
|
||||
|
||||
use crate::utils::{app_home_dir, app_resources_dir};
|
||||
|
||||
/// initialize this instance's log file
|
||||
fn init_log(log_dir: &PathBuf) {
|
||||
let local_time = Local::now().format("%Y-%m-%d-%H%M%S").to_string();
|
||||
@@ -42,54 +41,32 @@ fn init_log(log_dir: &PathBuf) {
|
||||
}
|
||||
|
||||
/// Initialize all the files from resources
|
||||
fn init_config_file(app_dir: &PathBuf, res_dir: &PathBuf) {
|
||||
fn init_config(app_dir: &PathBuf) -> std::io::Result<()> {
|
||||
// target path
|
||||
let clash_path = app_dir.join("config.yaml");
|
||||
let verge_path = app_dir.join("verge.yaml");
|
||||
let profile_path = app_dir.join("profiles.yaml");
|
||||
let mmdb_path = app_dir.join("Country.mmdb");
|
||||
|
||||
// template path
|
||||
let clash_tmpl = res_dir.join("config_tmp.yaml");
|
||||
let verge_tmpl = res_dir.join("verge_tmp.yaml");
|
||||
let profiles_tmpl = res_dir.join("profiles_tmp.yaml");
|
||||
let mmdb_tmpl = res_dir.join("Country.mmdb");
|
||||
|
||||
if !clash_path.exists() {
|
||||
if clash_tmpl.exists() {
|
||||
fs::copy(clash_tmpl, clash_path).unwrap();
|
||||
} else {
|
||||
// make sure that the config.yaml not null
|
||||
let content = b"\
|
||||
mixed-port: 7890\n\
|
||||
log-level: info\n\
|
||||
allow-lan: false\n\
|
||||
external-controller: 127.0.0.1:9090\n\
|
||||
secret: \"\"\n";
|
||||
File::create(clash_path).unwrap().write(content).unwrap();
|
||||
}
|
||||
File::create(clash_path)?.write(tmpl::CLASH_CONFIG)?;
|
||||
}
|
||||
|
||||
// only copy it
|
||||
if !verge_path.exists() && verge_tmpl.exists() {
|
||||
fs::copy(verge_tmpl, verge_path).unwrap();
|
||||
if !verge_path.exists() {
|
||||
File::create(verge_path)?.write(tmpl::VERGE_CONFIG)?;
|
||||
}
|
||||
if !profile_path.exists() && profiles_tmpl.exists() {
|
||||
fs::copy(profiles_tmpl, profile_path).unwrap();
|
||||
}
|
||||
if !mmdb_path.exists() && mmdb_tmpl.exists() {
|
||||
fs::copy(mmdb_tmpl, mmdb_path).unwrap();
|
||||
if !profile_path.exists() {
|
||||
File::create(profile_path)?.write(tmpl::PROFILES_CONFIG)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// initialize app
|
||||
pub fn init_app(package_info: &PackageInfo) {
|
||||
// create app dir
|
||||
let app_dir = app_home_dir();
|
||||
let app_dir = dirs::app_home_dir();
|
||||
let log_dir = app_dir.join("logs");
|
||||
let profiles_dir = app_dir.join("profiles");
|
||||
|
||||
let res_dir = app_resources_dir(package_info);
|
||||
let res_dir = dirs::app_resources_dir(package_info);
|
||||
|
||||
if !app_dir.exists() {
|
||||
fs::create_dir(&app_dir).unwrap();
|
||||
@@ -102,5 +79,14 @@ pub fn init_app(package_info: &PackageInfo) {
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
mod dirs;
|
||||
pub use self::dirs::*;
|
||||
|
||||
pub mod clash;
|
||||
pub mod config;
|
||||
pub mod dirs;
|
||||
pub mod fetch;
|
||||
pub mod init;
|
||||
pub mod resolve;
|
||||
pub mod server;
|
||||
pub mod sysopt;
|
||||
pub mod tmpl;
|
||||
|
||||
@@ -1,80 +1,77 @@
|
||||
use super::{clash, config, init, server, sysopt};
|
||||
use crate::events::state;
|
||||
use super::{init, server};
|
||||
use crate::{core::Profiles, states};
|
||||
use tauri::{App, AppHandle, Manager};
|
||||
|
||||
/// handle something when start app
|
||||
pub fn resolve_setup(app: &App) {
|
||||
resolve_window(app);
|
||||
|
||||
// setup a simple http server for singleton
|
||||
server::embed_server(&app.handle());
|
||||
|
||||
// init app config
|
||||
init::init_app(app.package_info());
|
||||
|
||||
// run clash sidecar
|
||||
let info = clash::run_clash_bin(&app.handle());
|
||||
// init states
|
||||
let clash_state = app.state::<states::ClashState>();
|
||||
let verge_state = app.state::<states::VergeState>();
|
||||
let profiles_state = app.state::<states::ProfilesState>();
|
||||
|
||||
// update the profile
|
||||
let info_ = info.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
if let Err(err) = clash::put_clash_profile(&info_).await {
|
||||
log::error!("failed to put config for `{}`", err);
|
||||
};
|
||||
});
|
||||
let mut clash = clash_state.0.lock().unwrap();
|
||||
let mut verge = verge_state.0.lock().unwrap();
|
||||
let mut profiles = profiles_state.0.lock().unwrap();
|
||||
|
||||
// resolve the verge config - enable system proxy
|
||||
let mut original: Option<sysopt::SysProxyConfig> = None;
|
||||
let verge = config::read_verge();
|
||||
let enable = verge.enable_system_proxy.unwrap_or(false);
|
||||
|
||||
if enable && info.controller.is_some() {
|
||||
if let Ok(original_conf) = sysopt::get_proxy_config() {
|
||||
original = Some(original_conf)
|
||||
};
|
||||
let ctl = info.controller.clone().unwrap();
|
||||
if ctl.port.is_some() {
|
||||
let server = format!("127.0.0.1:{}", ctl.port.unwrap());
|
||||
let bypass = verge
|
||||
.system_proxy_bypass
|
||||
.clone()
|
||||
.unwrap_or(String::from(sysopt::DEFAULT_BYPASS));
|
||||
let config = sysopt::SysProxyConfig {
|
||||
enable,
|
||||
server,
|
||||
bypass,
|
||||
};
|
||||
if let Err(err) = sysopt::set_proxy_config(&config) {
|
||||
log::error!("can not set system proxy for `{}`", err);
|
||||
}
|
||||
}
|
||||
if let Err(err) = clash.run_sidecar() {
|
||||
log::error!("{}", err);
|
||||
}
|
||||
// update state
|
||||
let verge_state = app.state::<state::VergeConfLock>();
|
||||
let mut verge_arc = verge_state.0.lock().unwrap();
|
||||
*verge_arc = verge;
|
||||
|
||||
let clash_state = app.state::<state::ClashInfoState>();
|
||||
let mut clash_arc = clash_state.0.lock().unwrap();
|
||||
*clash_arc = info;
|
||||
*profiles = Profiles::read_file();
|
||||
if let Err(err) = profiles.activate(&clash) {
|
||||
log::error!("{}", err);
|
||||
}
|
||||
|
||||
let some_state = app.state::<state::SomthingState>();
|
||||
let mut some_arc = some_state.0.lock().unwrap();
|
||||
*some_arc = original;
|
||||
verge.init_sysproxy(clash.info.port.clone());
|
||||
verge.init_launch(app.package_info());
|
||||
if let Err(err) = verge.sync_launch() {
|
||||
log::error!("{}", err);
|
||||
}
|
||||
}
|
||||
|
||||
/// reset system proxy
|
||||
pub fn resolve_reset(app_handle: &AppHandle) {
|
||||
let state = app_handle.try_state::<state::SomthingState>();
|
||||
if state.is_none() {
|
||||
return;
|
||||
}
|
||||
match state.unwrap().0.lock() {
|
||||
Ok(arc) => {
|
||||
if arc.is_some() {
|
||||
if let Err(err) = sysopt::set_proxy_config(arc.as_ref().unwrap()) {
|
||||
log::error!("failed to reset proxy for `{}`", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
};
|
||||
let verge_state = app_handle.state::<states::VergeState>();
|
||||
let mut verge = verge_state.0.lock().unwrap();
|
||||
|
||||
verge.reset_sysproxy();
|
||||
}
|
||||
|
||||
/// customize the window theme
|
||||
fn resolve_window(app: &App) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,13 +24,13 @@ pub fn check_singleton() -> Result<(), ()> {
|
||||
pub fn embed_server(app: &AppHandle) {
|
||||
let window = app.get_window("main").unwrap();
|
||||
|
||||
let commands = warp::path!("commands" / "visible").map(move || {
|
||||
window.show().unwrap();
|
||||
window.set_focus().unwrap();
|
||||
return format!("ok");
|
||||
});
|
||||
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let commands = warp::path!("commands" / "visible").map(move || {
|
||||
window.show().unwrap();
|
||||
window.set_focus().unwrap();
|
||||
return format!("ok");
|
||||
});
|
||||
|
||||
warp::serve(commands)
|
||||
.bind(([127, 0, 0, 1], SERVER_PORT))
|
||||
.await;
|
||||
|
||||
182
src-tauri/src/utils/sysopt.rs
Normal file → Executable file
@@ -1,6 +1,14 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::io;
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
static DEFAULT_BYPASS: &str = "localhost;127.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;192.168.*;<local>";
|
||||
#[cfg(target_os = "macos")]
|
||||
static DEFAULT_BYPASS: &str =
|
||||
"192.168.0.0/16\n10.0.0.0/8\n172.16.0.0/12\n127.0.0.1\nlocalhost\n*.local\ntimestamp.apple.com\n";
|
||||
#[cfg(target_os = "macos")]
|
||||
static MACOS_SERVICE: &str = "Wi-Fi";
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||
pub struct SysProxyConfig {
|
||||
pub enable: bool,
|
||||
@@ -18,16 +26,21 @@ impl Default for SysProxyConfig {
|
||||
}
|
||||
}
|
||||
|
||||
pub static DEFAULT_BYPASS: &str = "localhost;127.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;192.168.*;<local>";
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
mod win {
|
||||
use super::*;
|
||||
use winreg::enums::*;
|
||||
use winreg::RegKey;
|
||||
impl SysProxyConfig {
|
||||
pub fn new(enable: bool, port: String, bypass: Option<String>) -> Self {
|
||||
SysProxyConfig {
|
||||
enable,
|
||||
server: format!("127.0.0.1:{}", port),
|
||||
bypass: bypass.unwrap_or(DEFAULT_BYPASS.into()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
/// Get the windows system proxy config
|
||||
pub fn get_proxy_config() -> io::Result<SysProxyConfig> {
|
||||
pub fn get_sys() -> io::Result<Self> {
|
||||
use winreg::enums::*;
|
||||
use winreg::RegKey;
|
||||
|
||||
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
|
||||
let cur_var = hkcu.open_subkey_with_flags(
|
||||
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",
|
||||
@@ -41,43 +54,158 @@ mod win {
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
/// Get the macos system proxy config
|
||||
pub fn get_sys() -> io::Result<Self> {
|
||||
use std::process::Command;
|
||||
|
||||
let http = macproxy::get_proxy(&["-getwebproxy", MACOS_SERVICE])?;
|
||||
let https = macproxy::get_proxy(&["-getsecurewebproxy", MACOS_SERVICE])?;
|
||||
let sock = macproxy::get_proxy(&["-getsocksfirewallproxy", MACOS_SERVICE])?;
|
||||
|
||||
let mut enable = false;
|
||||
let mut server = "".into();
|
||||
|
||||
if sock.0 == "Yes" {
|
||||
enable = true;
|
||||
server = sock.1;
|
||||
}
|
||||
if https.0 == "Yes" {
|
||||
enable = true;
|
||||
server = https.1;
|
||||
}
|
||||
if http.0 == "Yes" || !enable {
|
||||
enable = http.0 == "Yes";
|
||||
server = http.1;
|
||||
}
|
||||
|
||||
let bypass_output = Command::new("networksetup")
|
||||
.args(["-getproxybypassdomains", MACOS_SERVICE])
|
||||
.output()?;
|
||||
let bypass = std::str::from_utf8(&bypass_output.stdout).unwrap_or(DEFAULT_BYPASS);
|
||||
|
||||
Ok(SysProxyConfig {
|
||||
enable,
|
||||
server,
|
||||
bypass: bypass.into(),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
/// Set the windows system proxy config
|
||||
pub fn set_proxy_config(config: &SysProxyConfig) -> io::Result<()> {
|
||||
pub fn set_sys(&self) -> io::Result<()> {
|
||||
use winreg::enums::*;
|
||||
use winreg::RegKey;
|
||||
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
|
||||
let cur_var = hkcu.open_subkey_with_flags(
|
||||
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",
|
||||
KEY_SET_VALUE,
|
||||
)?;
|
||||
|
||||
let enable: u32 = if config.enable { 1u32 } else { 0u32 };
|
||||
let enable: u32 = if self.enable { 1u32 } else { 0u32 };
|
||||
|
||||
cur_var.set_value("ProxyEnable", &enable)?;
|
||||
cur_var.set_value("ProxyServer", &config.server)?;
|
||||
cur_var.set_value("ProxyOverride", &config.bypass)?;
|
||||
cur_var.set_value("ProxyServer", &self.server)?;
|
||||
cur_var.set_value("ProxyOverride", &self.bypass)
|
||||
}
|
||||
|
||||
Ok(())
|
||||
#[cfg(target_os = "macos")]
|
||||
/// Set the macos system proxy config
|
||||
pub fn set_sys(&self) -> io::Result<()> {
|
||||
let enable = self.enable;
|
||||
let server = self.server.as_str();
|
||||
macproxy::set_proxy("-setwebproxy", MACOS_SERVICE, enable, server)?;
|
||||
macproxy::set_proxy("-setsecurewebproxy", MACOS_SERVICE, enable, server)?;
|
||||
macproxy::set_proxy("-setsocksfirewallproxy", MACOS_SERVICE, enable, server)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos {
|
||||
mod macproxy {
|
||||
use super::*;
|
||||
use std::process::Command;
|
||||
|
||||
pub fn get_proxy_config() -> io::Result<SysProxyConfig> {
|
||||
Ok(SysProxyConfig {
|
||||
enable: false,
|
||||
server: "server".into(),
|
||||
bypass: "bypass".into(),
|
||||
})
|
||||
/// use networksetup
|
||||
/// get the target proxy config
|
||||
pub(super) fn get_proxy(args: &[&str; 2]) -> io::Result<(String, String)> {
|
||||
let output = Command::new("networksetup").args(args).output()?;
|
||||
match std::str::from_utf8(&output.stdout) {
|
||||
Ok(stdout) => {
|
||||
let enable = parse(stdout, "Enabled:");
|
||||
let server = parse(stdout, "Server:");
|
||||
let port = parse(stdout, "Port:");
|
||||
let server = format!("{}:{}", server, port);
|
||||
Ok((enable.into(), server))
|
||||
}
|
||||
Err(_) => Err(io::Error::from_raw_os_error(1)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_proxy_config(config: &SysProxyConfig) -> io::Result<()> {
|
||||
/// use networksetup
|
||||
/// set the target proxy config
|
||||
pub(super) fn set_proxy(
|
||||
target: &str, // like: -setwebproxy
|
||||
device: &str,
|
||||
enable: bool,
|
||||
server: &str,
|
||||
) -> io::Result<()> {
|
||||
let mut split = server.split(":");
|
||||
let domain = split.next();
|
||||
let port = split.next();
|
||||
|
||||
// can not parse the field
|
||||
if domain.is_none() || port.is_none() {
|
||||
return Err(io::Error::from_raw_os_error(1));
|
||||
}
|
||||
|
||||
let args = vec![target, device, domain.unwrap(), port.unwrap()];
|
||||
Command::new("networksetup").args(&args).status()?;
|
||||
|
||||
let target_state = String::from(target) + "state";
|
||||
let enable = if enable { "on" } else { "off" };
|
||||
let args = vec![target_state.as_str(), device, enable];
|
||||
Command::new("networksetup").args(&args).status()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// parse the networksetup output
|
||||
pub(super) fn parse<'a>(target: &'a str, key: &'a str) -> &'a str {
|
||||
match target.find(key) {
|
||||
Some(idx) => {
|
||||
let idx = idx + key.len();
|
||||
let value = &target[idx..];
|
||||
let value = match value.find("\n") {
|
||||
Some(end) => &value[..end],
|
||||
None => value,
|
||||
};
|
||||
value.trim()
|
||||
}
|
||||
None => "",
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get() {
|
||||
use std::process::Command;
|
||||
|
||||
let output = Command::new("networksetup")
|
||||
.args(["-getwebproxy", "Wi-Fi"])
|
||||
.output();
|
||||
|
||||
let output = output.unwrap();
|
||||
let stdout = std::str::from_utf8(&output.stdout).unwrap();
|
||||
let enable = parse(stdout, "Enabled:");
|
||||
let server = parse(stdout, "Server:");
|
||||
let port = parse(stdout, "Port:");
|
||||
|
||||
println!("enable: {}, server: {}, port: {}", enable, server, port);
|
||||
|
||||
dbg!(SysProxyConfig::get_sys().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_set() {
|
||||
let sysproxy = SysProxyConfig::new(true, "7890".into(), None);
|
||||
dbg!(sysproxy.set_sys().unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
pub use win::*;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub use macos::*;
|
||||
|
||||
42
src-tauri/src/utils/tmpl.rs
Normal 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
|
||||
";
|
||||
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"package": {
|
||||
"productName": "clash-verge",
|
||||
"version": "0.0.1"
|
||||
"version": "0.0.16"
|
||||
},
|
||||
"build": {
|
||||
"distDir": "../dist",
|
||||
"devPath": "http://localhost:3000/proxy",
|
||||
"devPath": "http://localhost:3000/",
|
||||
"beforeDevCommand": "yarn run web:dev",
|
||||
"beforeBuildCommand": "yarn run web:build"
|
||||
},
|
||||
@@ -50,10 +50,20 @@
|
||||
}
|
||||
},
|
||||
"updater": {
|
||||
"active": false
|
||||
"active": true,
|
||||
"endpoints": [
|
||||
"https://github.com/zzzgydi/clash-verge/releases/download/updater/update.json"
|
||||
],
|
||||
"dialog": false,
|
||||
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDExNUFBNTBBN0FDNEFBRTUKUldUbHFzUjZDcVZhRVRJM25NS3NkSFlFVElxUkNZMzZ6bHUwRVJjb2F3alJXVzRaeDdSaTA2YWYK"
|
||||
},
|
||||
"allowlist": {
|
||||
"all": true
|
||||
"shell": {
|
||||
"all": true
|
||||
},
|
||||
"window": {
|
||||
"all": true
|
||||
}
|
||||
},
|
||||
"windows": [
|
||||
{
|
||||
@@ -62,8 +72,8 @@
|
||||
"height": 600,
|
||||
"resizable": true,
|
||||
"fullscreen": false,
|
||||
"decorations": true,
|
||||
"transparent": false,
|
||||
"decorations": false,
|
||||
"transparent": true,
|
||||
"minWidth": 600,
|
||||
"minHeight": 520
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ body {
|
||||
"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
|
||||
sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
:root {
|
||||
@@ -28,3 +29,4 @@ body {
|
||||
}
|
||||
|
||||
@import "./layout.scss";
|
||||
@import "./page.scss";
|
||||
|
||||
@@ -1,45 +1,87 @@
|
||||
.layout {
|
||||
width: 100%;
|
||||
height: 100vh;
|
||||
display: flex;
|
||||
overflow: hidden;
|
||||
|
||||
&__sidebar {
|
||||
position: relative;
|
||||
&__left {
|
||||
flex: 1 0 25%;
|
||||
height: 100vh;
|
||||
display: flex;
|
||||
height: 100%;
|
||||
max-width: 225px;
|
||||
min-width: 125px;
|
||||
overflow: hidden auto;
|
||||
padding: 8px 0;
|
||||
flex-direction: column;
|
||||
box-sizing: border-box;
|
||||
user-select: none;
|
||||
overflow: hidden;
|
||||
|
||||
.the-logo {
|
||||
position: relative;
|
||||
flex: 0 1 180px;
|
||||
width: 100%;
|
||||
max-width: 168px;
|
||||
max-height: 168px;
|
||||
margin: 0 auto;
|
||||
padding: 0 8px;
|
||||
text-align: center;
|
||||
box-sizing: border-box;
|
||||
|
||||
img {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.the-newbtn {
|
||||
position: absolute;
|
||||
right: 20px;
|
||||
bottom: 12px;
|
||||
transform: scale(0.8);
|
||||
}
|
||||
}
|
||||
|
||||
.the-menu {
|
||||
flex: 1 1 75%;
|
||||
overflow-y: auto;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.the-traffic {
|
||||
flex: 0 0 60px;
|
||||
|
||||
> div {
|
||||
margin: 0 auto;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&__content {
|
||||
&__right {
|
||||
position: relative;
|
||||
flex: 1 1 75%;
|
||||
height: 100vh;
|
||||
overflow: overlay;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
height: 100%;
|
||||
|
||||
&__logo {
|
||||
width: 100%;
|
||||
height: auto;
|
||||
max-width: 180px;
|
||||
max-height: 180px;
|
||||
margin: 0 auto;
|
||||
padding: 8px 8px 0;
|
||||
user-select: none;
|
||||
text-align: center;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.the-bar {
|
||||
position: absolute;
|
||||
top: 2px;
|
||||
right: 8px;
|
||||
height: 36px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
box-sizing: border-box;
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
&__traffic {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 8px;
|
||||
|
||||
> div {
|
||||
margin: 0 auto;
|
||||
.the-content {
|
||||
position: absolute;
|
||||
top: 30px;
|
||||
left: 0;
|
||||
right: 2px;
|
||||
bottom: 10px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.macos.layout {
|
||||
.layout__right .the-content {
|
||||
top: 0;
|
||||
}
|
||||
}
|
||||
|
||||
35
src/assets/styles/page.scss
Normal file
@@ -0,0 +1,35 @@
|
||||
.base-page {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
> header {
|
||||
flex: 0 0 58px;
|
||||
width: 90%;
|
||||
max-width: 850px;
|
||||
margin: 0 auto;
|
||||
padding-right: 4px;
|
||||
box-sizing: border-box;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
> section {
|
||||
position: relative;
|
||||
flex: 1 1 100%;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow: auto;
|
||||
padding: 8px 0;
|
||||
box-sizing: border-box;
|
||||
scrollbar-gutter: stable;
|
||||
|
||||
.base-content {
|
||||
width: 90%;
|
||||
max-width: 850px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
}
|
||||
}
|
||||
92
src/components/base/base-notice.tsx
Normal file
@@ -0,0 +1,92 @@
|
||||
import ReactDOM from "react-dom";
|
||||
import { ReactNode, useState } from "react";
|
||||
import { Box, IconButton, Slide, Snackbar, Typography } from "@mui/material";
|
||||
import { Close, CheckCircleRounded, ErrorRounded } from "@mui/icons-material";
|
||||
|
||||
interface InnerProps {
|
||||
type: string;
|
||||
duration?: number;
|
||||
message: ReactNode;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
const NoticeInner = (props: InnerProps) => {
|
||||
const { type, message, duration = 2000, onClose } = props;
|
||||
const [visible, setVisible] = useState(true);
|
||||
|
||||
const onBtnClose = () => {
|
||||
setVisible(false);
|
||||
onClose();
|
||||
};
|
||||
const onAutoClose = (_e: any, reason: string) => {
|
||||
if (reason !== "clickaway") onBtnClose();
|
||||
};
|
||||
|
||||
const msgElement =
|
||||
type === "info" ? (
|
||||
message
|
||||
) : (
|
||||
<Box sx={{ display: "flex", alignItems: "center" }}>
|
||||
{type === "error" && <ErrorRounded color="error" />}
|
||||
{type === "success" && <CheckCircleRounded color="success" />}
|
||||
|
||||
<Typography
|
||||
sx={{ ml: 1, wordWrap: "break-word", wordBreak: "break-all" }}
|
||||
>
|
||||
{message}
|
||||
</Typography>
|
||||
</Box>
|
||||
);
|
||||
|
||||
return (
|
||||
<Snackbar
|
||||
open={visible}
|
||||
anchorOrigin={{ vertical: "top", horizontal: "right" }}
|
||||
autoHideDuration={duration}
|
||||
onClose={onAutoClose}
|
||||
message={msgElement}
|
||||
sx={{ maxWidth: 360 }}
|
||||
TransitionComponent={(p) => <Slide {...p} direction="left" />}
|
||||
transitionDuration={200}
|
||||
action={
|
||||
<IconButton size="small" color="inherit" onClick={onBtnClose}>
|
||||
<Close fontSize="inherit" />
|
||||
</IconButton>
|
||||
}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
interface NoticeInstance {
|
||||
(props: Omit<InnerProps, "onClose">): void;
|
||||
|
||||
info(message: ReactNode, duration?: number): void;
|
||||
error(message: ReactNode, duration?: number): void;
|
||||
success(message: ReactNode, duration?: number): void;
|
||||
}
|
||||
|
||||
let parent: HTMLDivElement = null!;
|
||||
|
||||
// @ts-ignore
|
||||
const Notice: NoticeInstance = (props) => {
|
||||
if (!parent) {
|
||||
parent = document.createElement("div");
|
||||
document.body.appendChild(parent);
|
||||
}
|
||||
|
||||
const container = document.createElement("div");
|
||||
parent.appendChild(container);
|
||||
|
||||
const onUnmount = () => {
|
||||
const result = ReactDOM.unmountComponentAtNode(container);
|
||||
if (result && parent) parent.removeChild(container);
|
||||
};
|
||||
|
||||
ReactDOM.render(<NoticeInner {...props} onClose={onUnmount} />, container);
|
||||
};
|
||||
|
||||
(["info", "error", "success"] as const).forEach((type) => {
|
||||
Notice[type] = (message, duration) => Notice({ type, message, duration });
|
||||
});
|
||||
|
||||
export default Notice;
|
||||
32
src/components/base/base-page.tsx
Normal file
@@ -0,0 +1,32 @@
|
||||
import { Typography } from "@mui/material";
|
||||
import React from "react";
|
||||
|
||||
interface Props {
|
||||
title?: React.ReactNode; // the page title
|
||||
header?: React.ReactNode; // something behind title
|
||||
contentStyle?: React.CSSProperties;
|
||||
}
|
||||
|
||||
const BasePage: React.FC<Props> = (props) => {
|
||||
const { title, header, contentStyle, children } = props;
|
||||
|
||||
return (
|
||||
<div className="base-page" data-windrag>
|
||||
<header data-windrag style={{ userSelect: "none" }}>
|
||||
<Typography variant="h4" component="h1" data-windrag>
|
||||
{title}
|
||||
</Typography>
|
||||
|
||||
{header}
|
||||
</header>
|
||||
|
||||
<section>
|
||||
<div className="base-content" style={contentStyle} data-windrag>
|
||||
{children}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default BasePage;
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ApiType } from "../services/types";
|
||||
import { ApiType } from "../../services/types";
|
||||
|
||||
interface Props {
|
||||
value: ApiType.ConnectionsItem;
|
||||
41
src/components/layout/layout-control.tsx
Normal file
@@ -0,0 +1,41 @@
|
||||
import { Button } from "@mui/material";
|
||||
import { appWindow } from "@tauri-apps/api/window";
|
||||
import {
|
||||
CloseRounded,
|
||||
CropSquareRounded,
|
||||
HorizontalRuleRounded,
|
||||
} from "@mui/icons-material";
|
||||
|
||||
const LayoutControl = () => {
|
||||
const minWidth = 40;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
size="small"
|
||||
sx={{ minWidth, svg: { transform: "scale(0.9)" } }}
|
||||
onClick={() => appWindow.minimize()}
|
||||
>
|
||||
<HorizontalRuleRounded fontSize="small" />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
size="small"
|
||||
sx={{ minWidth, svg: { transform: "scale(0.9)" } }}
|
||||
onClick={() => appWindow.toggleMaximize()}
|
||||
>
|
||||
<CropSquareRounded fontSize="small" />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
size="small"
|
||||
sx={{ minWidth, svg: { transform: "scale(1.05)" } }}
|
||||
onClick={() => appWindow.hide()}
|
||||
>
|
||||
<CloseRounded fontSize="small" />
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default LayoutControl;
|
||||
@@ -1,12 +1,23 @@
|
||||
import useSWR from "swr";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useRecoilValue } from "recoil";
|
||||
import { Box, Typography } from "@mui/material";
|
||||
import { ArrowDownward, ArrowUpward } from "@mui/icons-material";
|
||||
import { getInfomation } from "../services/api";
|
||||
import { ApiType } from "../services/types";
|
||||
import parseTraffic from "../utils/parse-traffic";
|
||||
import { ApiType } from "../../services/types";
|
||||
import { getInfomation } from "../../services/api";
|
||||
import { getVergeConfig } from "../../services/cmds";
|
||||
import { atomClashPort } from "../../states/setting";
|
||||
import parseTraffic from "../../utils/parse-traffic";
|
||||
import useTrafficGraph from "./use-traffic-graph";
|
||||
|
||||
const Traffic = () => {
|
||||
const LayoutTraffic = () => {
|
||||
const portValue = useRecoilValue(atomClashPort);
|
||||
const [traffic, setTraffic] = useState({ up: 0, down: 0 });
|
||||
const { canvasRef, appendData, toggleStyle } = useTrafficGraph();
|
||||
|
||||
// whether hide traffic graph
|
||||
const { data } = useSWR("getVergeConfig", getVergeConfig);
|
||||
const trafficGraph = data?.traffic_graph ?? true;
|
||||
|
||||
useEffect(() => {
|
||||
let ws: WebSocket | null = null;
|
||||
@@ -16,12 +27,14 @@ const Traffic = () => {
|
||||
ws = new WebSocket(`ws://${server}/traffic?token=${secret}`);
|
||||
|
||||
ws.addEventListener("message", (event) => {
|
||||
setTraffic(JSON.parse(event.data) as ApiType.TrafficItem);
|
||||
const data = JSON.parse(event.data) as ApiType.TrafficItem;
|
||||
appendData(data);
|
||||
setTraffic(data);
|
||||
});
|
||||
});
|
||||
|
||||
return () => ws?.close();
|
||||
}, []);
|
||||
}, [portValue]);
|
||||
|
||||
const [up, upUnit] = parseTraffic(traffic.up);
|
||||
const [down, downUnit] = parseTraffic(traffic.down);
|
||||
@@ -41,7 +54,14 @@ const Traffic = () => {
|
||||
};
|
||||
|
||||
return (
|
||||
<Box width="110px">
|
||||
<Box width="110px" position="relative" onClick={toggleStyle}>
|
||||
{trafficGraph && (
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
style={{ width: "100%", height: 60, marginBottom: 6 }}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Box mb={1.5} display="flex" alignItems="center" whiteSpace="nowrap">
|
||||
<ArrowUpward
|
||||
fontSize="small"
|
||||
@@ -63,4 +83,4 @@ const Traffic = () => {
|
||||
);
|
||||
};
|
||||
|
||||
export default Traffic;
|
||||
export default LayoutTraffic;
|
||||
40
src/components/layout/update-button.tsx
Normal file
@@ -0,0 +1,40 @@
|
||||
import useSWR from "swr";
|
||||
import { useState } from "react";
|
||||
import { Button } from "@mui/material";
|
||||
import { checkUpdate } from "@tauri-apps/api/updater";
|
||||
import UpdateDialog from "./update-dialog";
|
||||
|
||||
interface Props {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const UpdateButton = (props: Props) => {
|
||||
const { className } = props;
|
||||
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const { data: updateInfo } = useSWR("checkUpdate", checkUpdate, {
|
||||
errorRetryCount: 2,
|
||||
revalidateIfStale: false,
|
||||
focusThrottleInterval: 36e5, // 1 hour
|
||||
});
|
||||
|
||||
if (!updateInfo?.shouldUpdate) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
color="error"
|
||||
variant="contained"
|
||||
size="small"
|
||||
className={className}
|
||||
onClick={() => setDialogOpen(true)}
|
||||
>
|
||||
New
|
||||
</Button>
|
||||
|
||||
<UpdateDialog open={dialogOpen} onClose={() => setDialogOpen(false)} />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default UpdateButton;
|
||||
68
src/components/layout/update-dialog.tsx
Normal file
@@ -0,0 +1,68 @@
|
||||
import useSWR from "swr";
|
||||
import { useState } from "react";
|
||||
import { checkUpdate, installUpdate } from "@tauri-apps/api/updater";
|
||||
import { relaunch } from "@tauri-apps/api/process";
|
||||
import {
|
||||
Button,
|
||||
Dialog,
|
||||
DialogActions,
|
||||
DialogContent,
|
||||
DialogContentText,
|
||||
DialogTitle,
|
||||
} from "@mui/material";
|
||||
import { killSidecars } from "../../services/cmds";
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
let uploadingState = false;
|
||||
|
||||
const UpdateDialog = (props: Props) => {
|
||||
const { open, onClose } = props;
|
||||
const { data: updateInfo } = useSWR("checkUpdate", checkUpdate, {
|
||||
errorRetryCount: 2,
|
||||
revalidateIfStale: false,
|
||||
focusThrottleInterval: 36e5, // 1 hour
|
||||
});
|
||||
const [uploading, setUploading] = useState(uploadingState);
|
||||
|
||||
const onUpdate = async () => {
|
||||
try {
|
||||
setUploading(true);
|
||||
uploadingState = true;
|
||||
await killSidecars();
|
||||
await installUpdate();
|
||||
await relaunch();
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
window.alert("Failed to upload, please try again.");
|
||||
} finally {
|
||||
setUploading(true);
|
||||
uploadingState = true;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onClose={onClose}>
|
||||
<DialogTitle>New Version v{updateInfo?.manifest?.version}</DialogTitle>
|
||||
<DialogContent sx={{ minWidth: 360, maxWidth: 400, maxHeight: "50vh" }}>
|
||||
<DialogContentText>{updateInfo?.manifest?.body}</DialogContentText>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={onClose}>Cancel</Button>
|
||||
<Button
|
||||
variant="contained"
|
||||
autoFocus
|
||||
onClick={onUpdate}
|
||||
disabled={uploading}
|
||||
>
|
||||
Update
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default UpdateDialog;
|
||||
146
src/components/layout/use-traffic-graph.ts
Normal 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,
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { styled, Box } from "@mui/material";
|
||||
import { ApiType } from "../services/types";
|
||||
import { ApiType } from "../../services/types";
|
||||
|
||||
const Item = styled(Box)(({ theme }) => ({
|
||||
padding: "8px 0",
|
||||
@@ -1,177 +0,0 @@
|
||||
import React, { useState } from "react";
|
||||
import dayjs from "dayjs";
|
||||
import {
|
||||
alpha,
|
||||
Box,
|
||||
styled,
|
||||
Typography,
|
||||
LinearProgress,
|
||||
IconButton,
|
||||
keyframes,
|
||||
} from "@mui/material";
|
||||
import { useSWRConfig } from "swr";
|
||||
import { RefreshRounded } from "@mui/icons-material";
|
||||
import { CmdType } from "../services/types";
|
||||
import parseTraffic from "../utils/parse-traffic";
|
||||
import relativeTime from "dayjs/plugin/relativeTime";
|
||||
import { updateProfile } from "../services/cmds";
|
||||
|
||||
dayjs.extend(relativeTime);
|
||||
|
||||
const Wrapper = styled(Box)(({ theme }) => ({
|
||||
width: "100%",
|
||||
display: "block",
|
||||
cursor: "pointer",
|
||||
textAlign: "left",
|
||||
borderRadius: theme.shape.borderRadius,
|
||||
boxShadow: theme.shadows[2],
|
||||
padding: "8px 16px",
|
||||
boxSizing: "border-box",
|
||||
}));
|
||||
|
||||
const round = keyframes`
|
||||
from { transform: rotate(0deg); }
|
||||
to { transform: rotate(360deg); }
|
||||
`;
|
||||
|
||||
interface Props {
|
||||
index: number;
|
||||
selected: boolean;
|
||||
itemData: CmdType.ProfileItem;
|
||||
onClick: () => void;
|
||||
}
|
||||
|
||||
const ProfileItemComp: React.FC<Props> = (props) => {
|
||||
const { index, selected, itemData, onClick } = props;
|
||||
|
||||
const { mutate } = useSWRConfig();
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const { name = "Profile", extra, updated = 0 } = itemData;
|
||||
const { upload = 0, download = 0, total = 0 } = extra ?? {};
|
||||
const from = parseUrl(itemData.url);
|
||||
const expire = parseExpire(extra?.expire);
|
||||
const progress = Math.round(((download + upload) * 100) / (total + 0.1));
|
||||
const fromnow = updated > 0 ? dayjs(updated * 1000).fromNow() : "";
|
||||
|
||||
const onUpdate = async () => {
|
||||
if (loading) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
await updateProfile(index);
|
||||
mutate("getProfiles");
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Wrapper
|
||||
sx={({ palette }) => {
|
||||
const { mode, primary, text, grey } = palette;
|
||||
const isDark = mode === "dark";
|
||||
|
||||
if (selected) {
|
||||
const bgcolor = isDark
|
||||
? alpha(primary.main, 0.35)
|
||||
: alpha(primary.main, 0.15);
|
||||
|
||||
return {
|
||||
bgcolor,
|
||||
color: isDark ? alpha(text.secondary, 0.6) : text.secondary,
|
||||
"& h2": {
|
||||
color: isDark ? primary.light : primary.main,
|
||||
},
|
||||
};
|
||||
}
|
||||
const bgcolor = isDark
|
||||
? alpha(grey[700], 0.35)
|
||||
: palette.background.paper;
|
||||
return {
|
||||
bgcolor,
|
||||
color: isDark ? alpha(text.secondary, 0.6) : text.secondary,
|
||||
"& h2": {
|
||||
color: isDark ? text.primary : text.primary,
|
||||
},
|
||||
};
|
||||
}}
|
||||
onClick={onClick}
|
||||
>
|
||||
<Box display="flex" justifyContent="space-between">
|
||||
<Typography
|
||||
width="calc(100% - 40px)"
|
||||
variant="h6"
|
||||
component="h2"
|
||||
noWrap
|
||||
title={name}
|
||||
>
|
||||
{name}
|
||||
</Typography>
|
||||
|
||||
<IconButton
|
||||
sx={{
|
||||
width: 30,
|
||||
height: 30,
|
||||
animation: loading ? `1s linear infinite ${round}` : "none",
|
||||
}}
|
||||
color="inherit"
|
||||
disabled={loading}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onUpdate();
|
||||
}}
|
||||
>
|
||||
<RefreshRounded />
|
||||
</IconButton>
|
||||
</Box>
|
||||
|
||||
<Box display="flex" justifyContent="space-between" alignItems="center">
|
||||
<Typography noWrap title={`From: ${from}`}>
|
||||
{from}
|
||||
</Typography>
|
||||
|
||||
<Typography
|
||||
noWrap
|
||||
flex="1 0 auto"
|
||||
fontSize={14}
|
||||
textAlign="right"
|
||||
title="updated time"
|
||||
>
|
||||
{fromnow}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
my: 0.5,
|
||||
fontSize: 14,
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
}}
|
||||
>
|
||||
<span title="used / total">
|
||||
{parseTraffic(upload + download)} / {parseTraffic(total)}
|
||||
</span>
|
||||
<span title="expire time">{expire}</span>
|
||||
</Box>
|
||||
|
||||
<LinearProgress variant="determinate" value={progress} color="inherit" />
|
||||
</Wrapper>
|
||||
);
|
||||
};
|
||||
|
||||
function parseUrl(url?: string) {
|
||||
if (!url) return "";
|
||||
const regex = /https?:\/\/(.+?)\//;
|
||||
const result = url.match(regex);
|
||||
return result ? result[1] : "local file";
|
||||
}
|
||||
|
||||
function parseExpire(expire?: number) {
|
||||
if (!expire) return "-";
|
||||
return dayjs(expire * 1000).format("YYYY-MM-DD");
|
||||
}
|
||||
|
||||
export default ProfileItemComp;
|
||||
283
src/components/profile/profile-item.tsx
Normal file
@@ -0,0 +1,283 @@
|
||||
import React, { useRef, useState } from "react";
|
||||
import dayjs from "dayjs";
|
||||
import {
|
||||
alpha,
|
||||
Box,
|
||||
styled,
|
||||
Typography,
|
||||
LinearProgress,
|
||||
IconButton,
|
||||
keyframes,
|
||||
MenuItem,
|
||||
Menu,
|
||||
} from "@mui/material";
|
||||
import { useSWRConfig } from "swr";
|
||||
import { RefreshRounded } from "@mui/icons-material";
|
||||
import { CmdType } from "../../services/types";
|
||||
import { updateProfile, deleteProfile, viewProfile } from "../../services/cmds";
|
||||
import Notice from "../base/base-notice";
|
||||
import parseTraffic from "../../utils/parse-traffic";
|
||||
import relativeTime from "dayjs/plugin/relativeTime";
|
||||
|
||||
dayjs.extend(relativeTime);
|
||||
|
||||
const Wrapper = styled(Box)(({ theme }) => ({
|
||||
width: "100%",
|
||||
display: "block",
|
||||
cursor: "pointer",
|
||||
textAlign: "left",
|
||||
borderRadius: theme.shape.borderRadius,
|
||||
boxShadow: theme.shadows[2],
|
||||
padding: "8px 16px",
|
||||
boxSizing: "border-box",
|
||||
}));
|
||||
|
||||
const round = keyframes`
|
||||
from { transform: rotate(0deg); }
|
||||
to { transform: rotate(360deg); }
|
||||
`;
|
||||
|
||||
interface Props {
|
||||
index: number;
|
||||
selected: boolean;
|
||||
itemData: CmdType.ProfileItem;
|
||||
onSelect: (force: boolean) => void;
|
||||
}
|
||||
|
||||
const ProfileItem: React.FC<Props> = (props) => {
|
||||
const { index, selected, itemData, onSelect } = props;
|
||||
|
||||
const { mutate } = useSWRConfig();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [anchorEl, setAnchorEl] = useState<any>(null);
|
||||
const [position, setPosition] = useState({ left: 0, top: 0 });
|
||||
|
||||
const { name = "Profile", extra, updated = 0 } = itemData;
|
||||
const { upload = 0, download = 0, total = 0 } = extra ?? {};
|
||||
const from = parseUrl(itemData.url);
|
||||
const expire = parseExpire(extra?.expire);
|
||||
const progress = Math.round(((download + upload) * 100) / (total + 0.1));
|
||||
const fromnow = updated > 0 ? dayjs(updated * 1000).fromNow() : "";
|
||||
|
||||
// local file mode
|
||||
// remote file mode
|
||||
// subscription url mode
|
||||
const hasUrl = !!itemData.url;
|
||||
const hasExtra = !!extra; // only subscription url has extra info
|
||||
|
||||
const onView = async () => {
|
||||
setAnchorEl(null);
|
||||
try {
|
||||
await viewProfile(index);
|
||||
} catch (err: any) {
|
||||
Notice.error(err.toString());
|
||||
}
|
||||
};
|
||||
|
||||
const onForceSelect = () => {
|
||||
setAnchorEl(null);
|
||||
onSelect(true);
|
||||
};
|
||||
|
||||
const onUpdateWrapper = (withProxy: boolean) => async () => {
|
||||
setAnchorEl(null);
|
||||
if (loading) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
await updateProfile(index, withProxy);
|
||||
mutate("getProfiles");
|
||||
} catch (err: any) {
|
||||
Notice.error(err.toString());
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const deleteRef = useRef(false);
|
||||
const onDelete = async () => {
|
||||
setAnchorEl(null);
|
||||
if (deleteRef.current) return;
|
||||
deleteRef.current = true;
|
||||
try {
|
||||
await deleteProfile(index);
|
||||
mutate("getProfiles");
|
||||
} catch (err: any) {
|
||||
Notice.error(err.toString());
|
||||
} finally {
|
||||
deleteRef.current = false;
|
||||
}
|
||||
};
|
||||
|
||||
const handleContextMenu = (
|
||||
event: React.MouseEvent<HTMLDivElement, MouseEvent>
|
||||
) => {
|
||||
const { clientX, clientY } = event;
|
||||
setPosition({ top: clientY, left: clientX });
|
||||
setAnchorEl(event.currentTarget);
|
||||
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 (
|
||||
<>
|
||||
<Wrapper
|
||||
sx={({ palette }) => {
|
||||
const { mode, primary, text, grey } = palette;
|
||||
const key = `${mode}-${selected}`;
|
||||
|
||||
const bgcolor = {
|
||||
"light-true": alpha(primary.main, 0.15),
|
||||
"light-false": palette.background.paper,
|
||||
"dark-true": alpha(primary.main, 0.35),
|
||||
"dark-false": alpha(grey[700], 0.35),
|
||||
}[key]!;
|
||||
|
||||
const color = {
|
||||
"light-true": text.secondary,
|
||||
"light-false": text.secondary,
|
||||
"dark-true": alpha(text.secondary, 0.6),
|
||||
"dark-false": alpha(text.secondary, 0.6),
|
||||
}[key]!;
|
||||
|
||||
const h2color = {
|
||||
"light-true": primary.main,
|
||||
"light-false": text.primary,
|
||||
"dark-true": primary.light,
|
||||
"dark-false": text.primary,
|
||||
}[key]!;
|
||||
|
||||
return { bgcolor, color, "& h2": { color: h2color } };
|
||||
}}
|
||||
onClick={() => onSelect(false)}
|
||||
onContextMenu={handleContextMenu}
|
||||
>
|
||||
<Box display="flex" justifyContent="space-between">
|
||||
<Typography
|
||||
width="calc(100% - 40px)"
|
||||
variant="h6"
|
||||
component="h2"
|
||||
noWrap
|
||||
title={name}
|
||||
>
|
||||
{name}
|
||||
</Typography>
|
||||
|
||||
{/* only if has url can it be updated */}
|
||||
{hasUrl && (
|
||||
<IconButton
|
||||
sx={{
|
||||
width: 26,
|
||||
height: 26,
|
||||
animation: loading ? `1s linear infinite ${round}` : "none",
|
||||
}}
|
||||
color="inherit"
|
||||
disabled={loading}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onUpdateWrapper(false)();
|
||||
}}
|
||||
>
|
||||
<RefreshRounded />
|
||||
</IconButton>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
{/* the second line show url's info or description */}
|
||||
{hasUrl ? (
|
||||
<Box sx={boxStyle}>
|
||||
<Typography noWrap title={`From: ${from}`}>
|
||||
{from}
|
||||
</Typography>
|
||||
|
||||
<Typography
|
||||
noWrap
|
||||
flex="1 0 auto"
|
||||
fontSize={14}
|
||||
textAlign="right"
|
||||
title="updated time"
|
||||
>
|
||||
{fromnow}
|
||||
</Typography>
|
||||
</Box>
|
||||
) : (
|
||||
<Box sx={boxStyle}>
|
||||
<Typography noWrap title={itemData.desc}>
|
||||
{itemData.desc}
|
||||
</Typography>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{/* the third line show extra info or last updated time */}
|
||||
{hasExtra ? (
|
||||
<Box sx={{ ...boxStyle, fontSize: 14 }}>
|
||||
<span title="used / total">
|
||||
{parseTraffic(upload + download)} / {parseTraffic(total)}
|
||||
</span>
|
||||
<span title="expire time">{expire}</span>
|
||||
</Box>
|
||||
) : (
|
||||
<Box sx={{ ...boxStyle, fontSize: 14, justifyContent: "flex-end" }}>
|
||||
<span title="updated time">{parseExpire(updated)}</span>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
<LinearProgress
|
||||
variant="determinate"
|
||||
value={progress}
|
||||
color="inherit"
|
||||
/>
|
||||
</Wrapper>
|
||||
|
||||
<Menu
|
||||
open={!!anchorEl}
|
||||
anchorEl={anchorEl}
|
||||
onClose={() => setAnchorEl(null)}
|
||||
anchorPosition={position}
|
||||
anchorReference="anchorPosition"
|
||||
>
|
||||
{(hasUrl ? urlModeMenu : fileModeMenu).map((item) => (
|
||||
<MenuItem
|
||||
key={item.label}
|
||||
onClick={item.handler}
|
||||
sx={{ minWidth: 133 }}
|
||||
>
|
||||
{item.label}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Menu>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
function parseUrl(url?: string) {
|
||||
if (!url) return "";
|
||||
const regex = /https?:\/\/(.+?)\//;
|
||||
const result = url.match(regex);
|
||||
return result ? result[1] : "local file";
|
||||
}
|
||||
|
||||
function parseExpire(expire?: number) {
|
||||
if (!expire) return "-";
|
||||
return dayjs(expire * 1000).format("YYYY-MM-DD");
|
||||
}
|
||||
|
||||
export default ProfileItem;
|
||||
71
src/components/profile/profile-new.tsx
Normal 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;
|
||||
@@ -1,160 +0,0 @@
|
||||
import { useState } from "react";
|
||||
import { Virtuoso } from "react-virtuoso";
|
||||
import {
|
||||
alpha,
|
||||
Box,
|
||||
Collapse,
|
||||
Divider,
|
||||
IconButton,
|
||||
List,
|
||||
ListItem,
|
||||
ListItemButton,
|
||||
ListItemIcon,
|
||||
ListItemText,
|
||||
} from "@mui/material";
|
||||
import {
|
||||
SendRounded,
|
||||
ExpandLessRounded,
|
||||
ExpandMoreRounded,
|
||||
MyLocationRounded,
|
||||
NetworkCheckRounded,
|
||||
CheckCircleOutlineRounded,
|
||||
} from "@mui/icons-material";
|
||||
import { updateProxy } from "../services/api";
|
||||
import { ApiType } from "../services/types";
|
||||
|
||||
interface ItemProps {
|
||||
proxy: ApiType.ProxyItem;
|
||||
selected: boolean;
|
||||
onClick?: (name: string) => void;
|
||||
}
|
||||
|
||||
const Item = ({ proxy, selected, onClick }: ItemProps) => {
|
||||
return (
|
||||
<ListItem sx={{ py: 0, pl: 4 }}>
|
||||
<ListItemButton
|
||||
dense
|
||||
selected={selected}
|
||||
onClick={() => onClick?.(proxy.name)}
|
||||
sx={[
|
||||
{
|
||||
borderRadius: 1,
|
||||
},
|
||||
({ palette: { mode, primary } }) => {
|
||||
const bgcolor =
|
||||
mode === "light"
|
||||
? alpha(primary.main, 0.15)
|
||||
: alpha(primary.main, 0.35);
|
||||
const color = mode === "light" ? primary.main : primary.light;
|
||||
|
||||
return {
|
||||
"&.Mui-selected": { bgcolor },
|
||||
"&.Mui-selected .MuiListItemText-secondary": { color },
|
||||
};
|
||||
},
|
||||
]}
|
||||
>
|
||||
<ListItemText title={proxy.name} secondary={proxy.name} />
|
||||
<ListItemIcon
|
||||
sx={{ justifyContent: "flex-end", color: "primary.main" }}
|
||||
>
|
||||
{selected && <CheckCircleOutlineRounded sx={{ fontSize: 16 }} />}
|
||||
</ListItemIcon>
|
||||
</ListItemButton>
|
||||
</ListItem>
|
||||
);
|
||||
};
|
||||
|
||||
interface Props {
|
||||
group: ApiType.ProxyGroupItem;
|
||||
}
|
||||
|
||||
const ProxyGroup = ({ group }: Props) => {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [now, setNow] = useState(group.now);
|
||||
|
||||
const proxies = group.all ?? [];
|
||||
|
||||
const onUpdate = async (name: string) => {
|
||||
// can not call update
|
||||
if (group.type !== "Selector") {
|
||||
// Todo
|
||||
// error Tips
|
||||
return;
|
||||
}
|
||||
const oldValue = now;
|
||||
try {
|
||||
setNow(name);
|
||||
await updateProxy(group.name, name);
|
||||
} catch {
|
||||
setNow(oldValue);
|
||||
// Todo
|
||||
// error tips
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<ListItem button onClick={() => setOpen(!open)} dense>
|
||||
<ListItemText
|
||||
primary={group.name}
|
||||
secondary={
|
||||
<>
|
||||
<SendRounded color="primary" sx={{ mr: 1, fontSize: 14 }} />
|
||||
<span>{now}</span>
|
||||
</>
|
||||
}
|
||||
secondaryTypographyProps={{
|
||||
sx: { display: "flex", alignItems: "center" },
|
||||
}}
|
||||
/>
|
||||
|
||||
{open ? <ExpandLessRounded /> : <ExpandMoreRounded />}
|
||||
</ListItem>
|
||||
|
||||
<Collapse in={open} timeout="auto" unmountOnExit>
|
||||
<Box sx={{ pl: 4, pr: 3, my: 0.5 }}>
|
||||
<IconButton size="small" title="location">
|
||||
<MyLocationRounded />
|
||||
</IconButton>
|
||||
<IconButton size="small" title="check">
|
||||
<NetworkCheckRounded />
|
||||
</IconButton>
|
||||
</Box>
|
||||
|
||||
{proxies.length >= 10 ? (
|
||||
<Virtuoso
|
||||
style={{ height: "400px", marginBottom: "4px" }}
|
||||
totalCount={proxies.length}
|
||||
itemContent={(index) => (
|
||||
<Item
|
||||
proxy={proxies[index]}
|
||||
selected={proxies[index].name === now}
|
||||
onClick={onUpdate}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
<List
|
||||
component="div"
|
||||
disablePadding
|
||||
sx={{ maxHeight: "400px", overflow: "auto", mb: "4px" }}
|
||||
>
|
||||
{proxies.map((proxy) => (
|
||||
<Item
|
||||
key={proxy.name}
|
||||
proxy={proxy}
|
||||
selected={proxy.name === now}
|
||||
onClick={onUpdate}
|
||||
/>
|
||||
))}
|
||||
</List>
|
||||
)}
|
||||
|
||||
<Divider variant="middle" />
|
||||
</Collapse>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProxyGroup;
|
||||
182
src/components/proxy/proxy-group.tsx
Normal file
@@ -0,0 +1,182 @@
|
||||
import { useRef, useState } from "react";
|
||||
import { useSWRConfig } from "swr";
|
||||
import { Virtuoso } from "react-virtuoso";
|
||||
import {
|
||||
Box,
|
||||
Collapse,
|
||||
Divider,
|
||||
IconButton,
|
||||
List,
|
||||
ListItem,
|
||||
ListItemText,
|
||||
} from "@mui/material";
|
||||
import {
|
||||
SendRounded,
|
||||
ExpandLessRounded,
|
||||
ExpandMoreRounded,
|
||||
MyLocationRounded,
|
||||
NetworkCheckRounded,
|
||||
} from "@mui/icons-material";
|
||||
import { ApiType } from "../../services/types";
|
||||
import { updateProxy } from "../../services/api";
|
||||
import { getProfiles, patchProfile } from "../../services/cmds";
|
||||
import delayManager from "../../services/delay";
|
||||
import ProxyItem from "./proxy-item";
|
||||
|
||||
interface Props {
|
||||
group: ApiType.ProxyGroupItem;
|
||||
}
|
||||
|
||||
const ProxyGroup = ({ group }: Props) => {
|
||||
const { mutate } = useSWRConfig();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [now, setNow] = useState(group.now);
|
||||
|
||||
const virtuosoRef = useRef<any>();
|
||||
const proxies = group.all ?? [];
|
||||
|
||||
const selectLockRef = useRef(false);
|
||||
const onSelect = async (name: string) => {
|
||||
// Todo: support another proxy group type
|
||||
if (group.type !== "Selector") return;
|
||||
|
||||
if (selectLockRef.current) return;
|
||||
selectLockRef.current = true;
|
||||
|
||||
const oldValue = now;
|
||||
try {
|
||||
setNow(name);
|
||||
await updateProxy(group.name, name);
|
||||
} catch {
|
||||
setNow(oldValue);
|
||||
return; // do not update profile
|
||||
} finally {
|
||||
selectLockRef.current = false;
|
||||
}
|
||||
|
||||
try {
|
||||
const profiles = await getProfiles();
|
||||
const profile = profiles.items![profiles.current!]!;
|
||||
if (!profile) return;
|
||||
if (!profile.selected) profile.selected = [];
|
||||
|
||||
const index = profile.selected.findIndex(
|
||||
(item) => item.name === group.name
|
||||
);
|
||||
|
||||
if (index < 0) {
|
||||
profile.selected.push({ name: group.name, now: name });
|
||||
} else {
|
||||
profile.selected[index] = { name: group.name, now: name };
|
||||
}
|
||||
await patchProfile(profiles.current!, profile);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
};
|
||||
|
||||
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 (
|
||||
<>
|
||||
<ListItem button onClick={() => setOpen(!open)} dense>
|
||||
<ListItemText
|
||||
primary={group.name}
|
||||
secondary={
|
||||
<>
|
||||
<SendRounded color="primary" sx={{ mr: 1, fontSize: 14 }} />
|
||||
<span>{now}</span>
|
||||
</>
|
||||
}
|
||||
secondaryTypographyProps={{
|
||||
sx: { display: "flex", alignItems: "center" },
|
||||
}}
|
||||
/>
|
||||
|
||||
{open ? <ExpandLessRounded /> : <ExpandMoreRounded />}
|
||||
</ListItem>
|
||||
|
||||
<Collapse in={open} timeout="auto" unmountOnExit>
|
||||
<Box sx={{ pl: 4, pr: 3, my: 0.5 }}>
|
||||
<IconButton size="small" title="location" onClick={onLocation}>
|
||||
<MyLocationRounded />
|
||||
</IconButton>
|
||||
<IconButton size="small" title="check" onClick={onCheckAll}>
|
||||
<NetworkCheckRounded />
|
||||
</IconButton>
|
||||
</Box>
|
||||
|
||||
{proxies.length >= 10 ? (
|
||||
<Virtuoso
|
||||
ref={virtuosoRef}
|
||||
style={{ height: "320px", marginBottom: "4px" }}
|
||||
totalCount={proxies.length}
|
||||
itemContent={(index) => (
|
||||
<ProxyItem
|
||||
groupName={group.name}
|
||||
proxy={proxies[index]}
|
||||
selected={proxies[index].name === now}
|
||||
sx={{ py: 0, pl: 4 }}
|
||||
onClick={onSelect}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
<List
|
||||
component="div"
|
||||
disablePadding
|
||||
sx={{ maxHeight: "320px", overflow: "auto", mb: "4px" }}
|
||||
>
|
||||
{proxies.map((proxy) => (
|
||||
<ProxyItem
|
||||
key={proxy.name}
|
||||
groupName={group.name}
|
||||
proxy={proxy}
|
||||
selected={proxy.name === now}
|
||||
sx={{ py: 0, pl: 4 }}
|
||||
onClick={onSelect}
|
||||
/>
|
||||
))}
|
||||
</List>
|
||||
)}
|
||||
|
||||
<Divider variant="middle" />
|
||||
</Collapse>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProxyGroup;
|
||||
114
src/components/proxy/proxy-item.tsx
Normal 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;
|
||||
@@ -1,8 +0,0 @@
|
||||
import { ListItem, styled } from "@mui/material";
|
||||
|
||||
const SettingItem = styled(ListItem)(() => ({
|
||||
paddingTop: 5,
|
||||
paddingBottom: 5,
|
||||
}));
|
||||
|
||||
export default SettingItem;
|
||||
@@ -1,89 +0,0 @@
|
||||
import useSWR, { useSWRConfig } from "swr";
|
||||
import { List, ListItemText, ListSubheader, Switch } from "@mui/material";
|
||||
import {
|
||||
getVergeConfig,
|
||||
patchVergeConfig,
|
||||
setSysProxy,
|
||||
} from "../services/cmds";
|
||||
import { CmdType } from "../services/types";
|
||||
import GuardState from "./guard-state";
|
||||
import SettingItem from "./setting-item";
|
||||
import PaletteSwitch from "./palette-switch";
|
||||
|
||||
interface Props {
|
||||
onError?: (err: Error) => void;
|
||||
}
|
||||
|
||||
const SettingVerge = ({ onError }: Props) => {
|
||||
const { mutate } = useSWRConfig();
|
||||
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
|
||||
|
||||
const {
|
||||
theme_mode: mode = "light",
|
||||
enable_self_startup: startup = false,
|
||||
enable_system_proxy: proxy = false,
|
||||
} = vergeConfig ?? {};
|
||||
|
||||
const onSwitchFormat = (_e: any, value: boolean) => value;
|
||||
|
||||
const onChangeData = (patch: Partial<CmdType.VergeConfig>) => {
|
||||
mutate("getVergeConfig", { ...vergeConfig, ...patch }, false);
|
||||
};
|
||||
|
||||
return (
|
||||
<List>
|
||||
<ListSubheader>通用设置</ListSubheader>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText primary="外观主题" />
|
||||
<GuardState
|
||||
value={mode === "dark"}
|
||||
valueProps="checked"
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
onChange={(e) => onChangeData({ theme_mode: e ? "dark" : "light" })}
|
||||
onGuard={async (c) => {
|
||||
await patchVergeConfig({ theme_mode: c ? "dark" : "light" });
|
||||
}}
|
||||
>
|
||||
<PaletteSwitch edge="end" />
|
||||
</GuardState>
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText primary="开机自启" />
|
||||
<GuardState
|
||||
value={startup}
|
||||
valueProps="checked"
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
onChange={(e) => onChangeData({ enable_self_startup: e })}
|
||||
onGuard={async (e) => {
|
||||
await patchVergeConfig({ enable_self_startup: e });
|
||||
}}
|
||||
>
|
||||
<Switch edge="end" />
|
||||
</GuardState>
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText primary="设置系统代理" />
|
||||
<GuardState
|
||||
value={proxy}
|
||||
valueProps="checked"
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
onChange={(e) => onChangeData({ enable_system_proxy: e })}
|
||||
onGuard={async (e) => {
|
||||
await setSysProxy(e);
|
||||
await patchVergeConfig({ enable_system_proxy: e });
|
||||
}}
|
||||
>
|
||||
<Switch edge="end" />
|
||||
</GuardState>
|
||||
</SettingItem>
|
||||
</List>
|
||||
);
|
||||
};
|
||||
|
||||
export default SettingVerge;
|
||||
@@ -1,5 +1,5 @@
|
||||
import { cloneElement, isValidElement, ReactNode, useRef } from "react";
|
||||
import noop from "../utils/noop";
|
||||
import noop from "../../utils/noop";
|
||||
|
||||
interface Props<Value> {
|
||||
value?: Value;
|
||||
@@ -7,7 +7,7 @@ interface Props<Value> {
|
||||
onChangeProps?: string;
|
||||
onChange?: (value: Value) => void;
|
||||
onFormat?: (...args: any[]) => Value;
|
||||
onGuard?: (value: Value) => Promise<void>;
|
||||
onGuard?: (value: Value, oldValue: Value) => Promise<void>;
|
||||
onCatch?: (error: Error) => void;
|
||||
children: ReactNode;
|
||||
}
|
||||
@@ -41,7 +41,7 @@ function GuardState<T>(props: Props<T>) {
|
||||
const newValue = (onFormat as any)(...args);
|
||||
// 先在ui上响应操作
|
||||
onChange(newValue);
|
||||
await onGuard(newValue);
|
||||
await onGuard(newValue, oldValue!);
|
||||
} catch (err: any) {
|
||||
// 状态回退
|
||||
onChange(oldValue!);
|
||||
@@ -1,21 +1,25 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useDebounceFn } from "ahooks";
|
||||
import { useSetRecoilState } from "recoil";
|
||||
import useSWR, { useSWRConfig } from "swr";
|
||||
import {
|
||||
List,
|
||||
ListItemText,
|
||||
ListSubheader,
|
||||
TextField,
|
||||
Switch,
|
||||
Select,
|
||||
MenuItem,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import { getClashConfig, updateConfigs } from "../services/api";
|
||||
import { patchClashConfig } from "../services/cmds";
|
||||
import { ApiType } from "../services/types";
|
||||
import { ApiType } from "../../services/types";
|
||||
import { atomClashPort } from "../../states/setting";
|
||||
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 SettingItem from "./setting-item";
|
||||
|
||||
interface Props {
|
||||
onError?: (err: Error) => void;
|
||||
onError: (err: Error) => void;
|
||||
}
|
||||
|
||||
const SettingClash = ({ onError }: Props) => {
|
||||
@@ -26,26 +30,57 @@ const SettingClash = ({ onError }: Props) => {
|
||||
ipv6 = false,
|
||||
"allow-lan": allowLan = false,
|
||||
"log-level": logLevel = "silent",
|
||||
"mixed-port": mixedPort = 7890,
|
||||
"mixed-port": thePort = 0,
|
||||
} = clashConfig ?? {};
|
||||
|
||||
const onSwitchFormat = (_e: any, value: boolean) => value;
|
||||
const setPort = useSetRecoilState(atomClashPort);
|
||||
const [mixedPort, setMixedPort] = useState(thePort);
|
||||
|
||||
useEffect(() => setMixedPort(thePort), [thePort]);
|
||||
|
||||
const onSwitchFormat = (_e: any, value: boolean) => value;
|
||||
const onChangeData = (patch: Partial<ApiType.ConfigData>) => {
|
||||
mutate("getClashConfig", { ...clashConfig, ...patch }, false);
|
||||
};
|
||||
|
||||
const onUpdateData = async (patch: Partial<ApiType.ConfigData>) => {
|
||||
await updateConfigs(patch);
|
||||
await patchClashConfig(patch);
|
||||
};
|
||||
|
||||
return (
|
||||
<List>
|
||||
<ListSubheader>Clash设置</ListSubheader>
|
||||
// restart clash when port is changed
|
||||
const { run: onUpdatePort } = useDebounceFn(
|
||||
async (port: number) => {
|
||||
try {
|
||||
if (port < 1000) {
|
||||
throw new Error("The port should not < 1000");
|
||||
}
|
||||
if (port > 65536) {
|
||||
throw new Error("The port should not > 65536");
|
||||
}
|
||||
await patchClashConfig({ "mixed-port": port });
|
||||
onChangeData({ "mixed-port": port });
|
||||
setPort(port);
|
||||
Notice.success("Change Clash port successfully!");
|
||||
} catch (err: any) {
|
||||
setMixedPort(thePort); // back to old port value
|
||||
Notice.error(err.message ?? err.toString());
|
||||
}
|
||||
},
|
||||
{ wait: 1000 }
|
||||
);
|
||||
|
||||
// get clash core version
|
||||
const [clashVer, setClashVer] = useState("");
|
||||
useEffect(() => {
|
||||
getVersion().then(({ premium, version }) => {
|
||||
setClashVer(premium ? `${version} Premium` : version);
|
||||
});
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<SettingList title="Clash Setting">
|
||||
<SettingItem>
|
||||
<ListItemText primary="局域网连接" />
|
||||
<ListItemText primary="Allow Lan" />
|
||||
<GuardState
|
||||
value={allowLan}
|
||||
valueProps="checked"
|
||||
@@ -73,7 +108,7 @@ const SettingClash = ({ onError }: Props) => {
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText primary="日志等级" />
|
||||
<ListItemText primary="Log Level" />
|
||||
<GuardState
|
||||
value={logLevel}
|
||||
onCatch={onError}
|
||||
@@ -92,15 +127,22 @@ const SettingClash = ({ onError }: Props) => {
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText primary="混合代理端口" />
|
||||
<TextField
|
||||
size="small"
|
||||
<ListItemText primary="Mixed Port" />
|
||||
<GuardState
|
||||
value={mixedPort!}
|
||||
sx={{ width: 120 }}
|
||||
disabled
|
||||
/>
|
||||
onFormat={(e: any) => +e.target.value?.replace(/\D+/, "")}
|
||||
onChange={setMixedPort}
|
||||
onGuard={onUpdatePort}
|
||||
>
|
||||
<TextField autoComplete="off" size="small" sx={{ width: 120 }} />
|
||||
</GuardState>
|
||||
</SettingItem>
|
||||
</List>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText primary="Clash core" />
|
||||
<Typography sx={{ py: 1 }}>{clashVer}</Typography>
|
||||
</SettingItem>
|
||||
</SettingList>
|
||||
);
|
||||
};
|
||||
|
||||
103
src/components/setting/setting-system.tsx
Normal file
@@ -0,0 +1,103 @@
|
||||
import useSWR, { useSWRConfig } from "swr";
|
||||
import { Box, ListItemText, Switch, TextField } from "@mui/material";
|
||||
import { getVergeConfig, patchVergeConfig } from "../../services/cmds";
|
||||
import { SettingList, SettingItem } from "./setting";
|
||||
import { CmdType } from "../../services/types";
|
||||
import GuardState from "./guard-state";
|
||||
import SysproxyTooltip from "./sysproxy-tooltip";
|
||||
|
||||
interface Props {
|
||||
onError?: (err: Error) => void;
|
||||
}
|
||||
|
||||
const SettingSystem = ({ onError }: Props) => {
|
||||
const { mutate } = useSWRConfig();
|
||||
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
|
||||
|
||||
const {
|
||||
enable_auto_launch = false,
|
||||
enable_system_proxy = false,
|
||||
system_proxy_bypass = "",
|
||||
enable_proxy_guard = false,
|
||||
} = vergeConfig ?? {};
|
||||
|
||||
const onSwitchFormat = (_e: any, value: boolean) => value;
|
||||
const onChangeData = (patch: Partial<CmdType.VergeConfig>) => {
|
||||
mutate("getVergeConfig", { ...vergeConfig, ...patch }, false);
|
||||
};
|
||||
|
||||
return (
|
||||
<SettingList title="System Setting">
|
||||
<SettingItem>
|
||||
<ListItemText primary="Auto Launch" />
|
||||
<GuardState
|
||||
value={enable_auto_launch}
|
||||
valueProps="checked"
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
onChange={(e) => onChangeData({ enable_auto_launch: e })}
|
||||
onGuard={(e) => patchVergeConfig({ enable_auto_launch: e })}
|
||||
>
|
||||
<Switch edge="end" />
|
||||
</GuardState>
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText
|
||||
primary={
|
||||
<Box sx={{ display: "flex", alignItems: "center" }}>
|
||||
System Proxy
|
||||
<SysproxyTooltip />
|
||||
</Box>
|
||||
}
|
||||
/>
|
||||
<GuardState
|
||||
value={enable_system_proxy}
|
||||
valueProps="checked"
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
onChange={(e) => onChangeData({ enable_system_proxy: e })}
|
||||
onGuard={async (e) => {
|
||||
await patchVergeConfig({ enable_system_proxy: e });
|
||||
mutate("getVergeConfig"); // update bypass value
|
||||
}}
|
||||
>
|
||||
<Switch edge="end" />
|
||||
</GuardState>
|
||||
</SettingItem>
|
||||
|
||||
{enable_system_proxy && (
|
||||
<SettingItem>
|
||||
<ListItemText primary="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 })}
|
||||
>
|
||||
<TextField autoComplete="off" size="small" sx={{ width: 120 }} />
|
||||
</GuardState>
|
||||
</SettingItem>
|
||||
)}
|
||||
</SettingList>
|
||||
);
|
||||
};
|
||||
|
||||
export default SettingSystem;
|
||||
100
src/components/setting/setting-verge.tsx
Normal file
@@ -0,0 +1,100 @@
|
||||
import useSWR, { useSWRConfig } from "swr";
|
||||
import { IconButton, ListItemText, Switch, Typography } from "@mui/material";
|
||||
import {
|
||||
getVergeConfig,
|
||||
openAppDir,
|
||||
openLogsDir,
|
||||
patchVergeConfig,
|
||||
} from "../../services/cmds";
|
||||
import { ArrowForward } from "@mui/icons-material";
|
||||
import { SettingList, SettingItem } from "./setting";
|
||||
import { CmdType } from "../../services/types";
|
||||
import { version } from "../../../package.json";
|
||||
import PaletteSwitch from "./palette-switch";
|
||||
import GuardState from "./guard-state";
|
||||
|
||||
interface Props {
|
||||
onError?: (err: Error) => void;
|
||||
}
|
||||
|
||||
const SettingVerge = ({ onError }: Props) => {
|
||||
const { mutate } = useSWRConfig();
|
||||
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
|
||||
|
||||
const { theme_mode = "light", theme_blur = false, traffic_graph } =
|
||||
vergeConfig ?? {};
|
||||
|
||||
const onSwitchFormat = (_e: any, value: boolean) => value;
|
||||
const onChangeData = (patch: Partial<CmdType.VergeConfig>) => {
|
||||
mutate("getVergeConfig", { ...vergeConfig, ...patch }, false);
|
||||
};
|
||||
|
||||
return (
|
||||
<SettingList title="Verge Setting">
|
||||
<SettingItem>
|
||||
<ListItemText primary="Theme Mode" />
|
||||
<GuardState
|
||||
value={theme_mode === "dark"}
|
||||
valueProps="checked"
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
onChange={(e) => onChangeData({ theme_mode: e ? "dark" : "light" })}
|
||||
onGuard={(e) =>
|
||||
patchVergeConfig({ theme_mode: e ? "dark" : "light" })
|
||||
}
|
||||
>
|
||||
<PaletteSwitch edge="end" />
|
||||
</GuardState>
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText primary="Theme Blur" />
|
||||
<GuardState
|
||||
value={theme_blur}
|
||||
valueProps="checked"
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
onChange={(e) => onChangeData({ theme_blur: e })}
|
||||
onGuard={(e) => patchVergeConfig({ theme_blur: e })}
|
||||
>
|
||||
<Switch edge="end" />
|
||||
</GuardState>
|
||||
</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>
|
||||
<ListItemText primary="Version" />
|
||||
<Typography sx={{ py: "6px" }}>v{version}</Typography>
|
||||
</SettingItem>
|
||||
</SettingList>
|
||||
);
|
||||
};
|
||||
|
||||
export default SettingVerge;
|
||||
17
src/components/setting/setting.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
import React from "react";
|
||||
import { List, ListItem, ListSubheader, styled } from "@mui/material";
|
||||
|
||||
export const SettingItem = styled(ListItem)(() => ({
|
||||
paddingTop: 5,
|
||||
paddingBottom: 5,
|
||||
}));
|
||||
|
||||
export const SettingList: React.FC<{ title: string }> = (props) => (
|
||||
<List>
|
||||
<ListSubheader sx={{ background: "transparent" }} disableSticky>
|
||||
{props.title}
|
||||
</ListSubheader>
|
||||
|
||||
{props.children}
|
||||
</List>
|
||||
);
|
||||
52
src/components/setting/sysproxy-tooltip.tsx
Normal file
@@ -0,0 +1,52 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { InfoRounded } from "@mui/icons-material";
|
||||
import { ClickAwayListener, Tooltip } from "@mui/material";
|
||||
import { getSystemProxy } from "../../services/cmds";
|
||||
|
||||
const SysproxyTooltip = () => {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [info, setInfo] = useState<any>({});
|
||||
|
||||
const onShow = async () => {
|
||||
const data = await getSystemProxy();
|
||||
setInfo(data ?? {});
|
||||
setOpen(true);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const timer = setTimeout(() => setOpen(false), 2000);
|
||||
return () => clearTimeout(timer);
|
||||
}, [open]);
|
||||
|
||||
// todo: add error info
|
||||
const showTitle = (
|
||||
<div>
|
||||
<div>Enable: {(!!info.enable).toString()}</div>
|
||||
<div>Server: {info.server}</div>
|
||||
<div>Bypass: {info.bypass}</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<ClickAwayListener onClickAway={() => setOpen(false)}>
|
||||
<Tooltip
|
||||
PopperProps={{
|
||||
disablePortal: true,
|
||||
}}
|
||||
onClose={() => setOpen(false)}
|
||||
open={open}
|
||||
disableFocusListener
|
||||
disableHoverListener
|
||||
disableTouchListener
|
||||
placement="top"
|
||||
title={showTitle}
|
||||
arrow
|
||||
>
|
||||
<InfoRounded fontSize="small" onClick={onShow} />
|
||||
</Tooltip>
|
||||
</ClickAwayListener>
|
||||
);
|
||||
};
|
||||
|
||||
export default SysproxyTooltip;
|
||||
@@ -1,99 +1,90 @@
|
||||
import useSWR, { SWRConfig, useSWRConfig } from "swr";
|
||||
import { useEffect, useMemo } from "react";
|
||||
import useSWR, { SWRConfig } from "swr";
|
||||
import { Route, Routes } from "react-router-dom";
|
||||
import { useRecoilState } from "recoil";
|
||||
import { createTheme, List, Paper, ThemeProvider } from "@mui/material";
|
||||
import { atomPaletteMode } from "../states/setting";
|
||||
import { alpha, createTheme, List, Paper, ThemeProvider } from "@mui/material";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { appWindow } from "@tauri-apps/api/window";
|
||||
import { routers } from "./_routers";
|
||||
import { getAxios } from "../services/api";
|
||||
import { getVergeConfig } from "../services/cmds";
|
||||
import LogoSvg from "../assets/image/logo.svg";
|
||||
import LogPage from "./log";
|
||||
import HomePage from "./home";
|
||||
import ProfilePage from "./profile";
|
||||
import ProxyPage from "./proxy";
|
||||
import SettingPage from "./setting";
|
||||
import ConnectionsPage from "./connections";
|
||||
import LayoutItem from "../components/layout-item";
|
||||
import Traffic from "../components/traffic";
|
||||
import LayoutItem from "../components/layout/layout-item";
|
||||
import LayoutControl from "../components/layout/layout-control";
|
||||
import LayoutTraffic from "../components/layout/layout-traffic";
|
||||
import UpdateButton from "../components/layout/update-button";
|
||||
|
||||
const routers = [
|
||||
{
|
||||
label: "代理",
|
||||
link: "/proxy",
|
||||
},
|
||||
{
|
||||
label: "配置",
|
||||
link: "/profile",
|
||||
},
|
||||
{
|
||||
label: "连接",
|
||||
link: "/connections",
|
||||
},
|
||||
{
|
||||
label: "日志",
|
||||
link: "/log",
|
||||
},
|
||||
{
|
||||
label: "设置",
|
||||
link: "/setting",
|
||||
},
|
||||
];
|
||||
const isMacos = navigator.userAgent.includes("Mac OS X");
|
||||
|
||||
const Layout = () => {
|
||||
const [mode, setMode] = useRecoilState(atomPaletteMode);
|
||||
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
|
||||
const { mutate } = useSWRConfig();
|
||||
const { data } = useSWR("getVergeConfig", getVergeConfig);
|
||||
|
||||
const blur = !!data?.theme_blur;
|
||||
const mode = data?.theme_mode ?? "light";
|
||||
|
||||
useEffect(() => {
|
||||
setMode(vergeConfig?.theme_mode ?? "light");
|
||||
}, [vergeConfig?.theme_mode]);
|
||||
window.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Escape") appWindow.hide();
|
||||
});
|
||||
|
||||
listen("restart_clash", async () => {
|
||||
// the clash info may be updated
|
||||
await getAxios(true);
|
||||
// make sure that the clash is ok
|
||||
setTimeout(() => mutate("getProxies"), 1000);
|
||||
setTimeout(() => mutate("getProxies"), 2000);
|
||||
mutate("getClashConfig");
|
||||
});
|
||||
}, []);
|
||||
|
||||
const theme = useMemo(() => {
|
||||
if (mode === "light") {
|
||||
document.documentElement.style.background = "#f5f5f5";
|
||||
document.documentElement.style.setProperty(
|
||||
"--selection-color",
|
||||
"#f5f5f5"
|
||||
);
|
||||
} else {
|
||||
document.documentElement.style.background = "#000";
|
||||
document.documentElement.style.setProperty(
|
||||
"--selection-color",
|
||||
"#d5d5d5"
|
||||
);
|
||||
}
|
||||
// const background = mode === "light" ? "#f5f5f5" : "#000";
|
||||
const selectColor = mode === "light" ? "#f5f5f5" : "#d5d5d5";
|
||||
|
||||
const rootEle = document.documentElement;
|
||||
rootEle.style.background = "transparent";
|
||||
rootEle.style.setProperty("--selection-color", selectColor);
|
||||
|
||||
return createTheme({
|
||||
breakpoints: {
|
||||
values: {
|
||||
xs: 0,
|
||||
sm: 650,
|
||||
md: 900,
|
||||
lg: 1200,
|
||||
xl: 1536,
|
||||
},
|
||||
values: { xs: 0, sm: 650, md: 900, lg: 1200, xl: 1536 },
|
||||
},
|
||||
palette: {
|
||||
mode,
|
||||
primary: {
|
||||
main: "#5b5c9d",
|
||||
},
|
||||
text: {
|
||||
primary: "#637381",
|
||||
secondary: "#909399",
|
||||
},
|
||||
primary: { main: "#5b5c9d" },
|
||||
text: { primary: "#637381", secondary: "#909399" },
|
||||
},
|
||||
});
|
||||
}, [mode]);
|
||||
|
||||
const onDragging = (e: any) => {
|
||||
if (e?.target?.dataset?.windrag) {
|
||||
appWindow.startDragging();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<SWRConfig value={{}}>
|
||||
<ThemeProvider theme={theme}>
|
||||
<Paper square elevation={0} className="layout">
|
||||
<div className="layout__sidebar">
|
||||
<div className="layout__logo">
|
||||
<img src={LogoSvg} width="100%" alt="" />
|
||||
<Paper
|
||||
square
|
||||
elevation={0}
|
||||
className={`${isMacos ? "macos " : ""}layout`}
|
||||
onPointerDown={onDragging}
|
||||
sx={[
|
||||
(theme) => ({
|
||||
bgcolor: alpha(theme.palette.background.paper, blur ? 0.85 : 1),
|
||||
}),
|
||||
]}
|
||||
>
|
||||
<div className="layout__left" data-windrag>
|
||||
<div className="the-logo" data-windrag>
|
||||
<img src={LogoSvg} alt="" data-windrag />
|
||||
|
||||
<UpdateButton className="the-newbtn" />
|
||||
</div>
|
||||
|
||||
<List sx={{ userSelect: "none" }}>
|
||||
<List className="the-menu" data-windrag>
|
||||
{routers.map((router) => (
|
||||
<LayoutItem key={router.label} to={router.link}>
|
||||
{router.label}
|
||||
@@ -101,20 +92,25 @@ const Layout = () => {
|
||||
))}
|
||||
</List>
|
||||
|
||||
<div className="layout__traffic">
|
||||
<Traffic />
|
||||
<div className="the-traffic" data-windrag>
|
||||
<LayoutTraffic />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="layout__content">
|
||||
<Routes>
|
||||
<Route path="/" element={<HomePage />} />
|
||||
<Route path="/proxy" element={<ProxyPage />} />
|
||||
<Route path="/profile" element={<ProfilePage />} />
|
||||
<Route path="/log" element={<LogPage />} />
|
||||
<Route path="/connections" element={<ConnectionsPage />} />
|
||||
<Route path="/setting" element={<SettingPage />} />
|
||||
</Routes>
|
||||
<div className="layout__right" data-windrag>
|
||||
{!isMacos && (
|
||||
<div className="the-bar">
|
||||
<LayoutControl />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="the-content">
|
||||
<Routes>
|
||||
{routers.map(({ label, link, ele: Ele }) => (
|
||||
<Route key={label} path={link} element={<Ele />} />
|
||||
))}
|
||||
</Routes>
|
||||
</div>
|
||||
</div>
|
||||
</Paper>
|
||||
</ThemeProvider>
|
||||
|
||||
33
src/pages/_routers.tsx
Normal file
@@ -0,0 +1,33 @@
|
||||
import LogsPage from "./logs";
|
||||
import ProxiesPage from "./proxies";
|
||||
import ProfilesPage from "./profiles";
|
||||
import SettingsPage from "./settings";
|
||||
import ConnectionsPage from "./connections";
|
||||
|
||||
export const routers = [
|
||||
{
|
||||
label: "Proxies",
|
||||
link: "/",
|
||||
ele: ProxiesPage,
|
||||
},
|
||||
{
|
||||
label: "Profiles",
|
||||
link: "/profile",
|
||||
ele: ProfilesPage,
|
||||
},
|
||||
{
|
||||
label: "Connections",
|
||||
link: "/connections",
|
||||
ele: ConnectionsPage,
|
||||
},
|
||||
{
|
||||
label: "Logs",
|
||||
link: "/logs",
|
||||
ele: LogsPage,
|
||||
},
|
||||
{
|
||||
label: "Settings",
|
||||
link: "/settings",
|
||||
ele: SettingsPage,
|
||||
},
|
||||
];
|
||||
@@ -1,9 +1,10 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Box, Paper, Typography } from "@mui/material";
|
||||
import { Paper } from "@mui/material";
|
||||
import { Virtuoso } from "react-virtuoso";
|
||||
import { getInfomation } from "../services/api";
|
||||
import { ApiType } from "../services/types";
|
||||
import ConnectionItem from "../components/connection-item";
|
||||
import { getInfomation } from "../services/api";
|
||||
import BasePage from "../components/base/base-page";
|
||||
import ConnectionItem from "../components/connection/connection-item";
|
||||
|
||||
const ConnectionsPage = () => {
|
||||
const initConn = { uploadTotal: 0, downloadTotal: 0, connections: [] };
|
||||
@@ -26,25 +27,14 @@ const ConnectionsPage = () => {
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
width: 0.9,
|
||||
maxWidth: "850px",
|
||||
height: "100%",
|
||||
mx: "auto",
|
||||
}}
|
||||
>
|
||||
<Typography variant="h4" component="h1" sx={{ py: 2 }}>
|
||||
Connections
|
||||
</Typography>
|
||||
|
||||
<Paper sx={{ boxShadow: 2, height: "calc(100% - 100px)" }}>
|
||||
<BasePage title="Connections" contentStyle={{ height: "100%" }}>
|
||||
<Paper sx={{ boxShadow: 2, height: "100%" }}>
|
||||
<Virtuoso
|
||||
data={conn.connections}
|
||||
itemContent={(index, item) => <ConnectionItem value={item} />}
|
||||
/>
|
||||
</Paper>
|
||||
</Box>
|
||||
</BasePage>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
import { Typography } from "@mui/material";
|
||||
|
||||
const HomePage = () => {
|
||||
return (
|
||||
<Typography variant="h1" textAlign="center" mt={10}>
|
||||
Hello Clash!
|
||||
</Typography>
|
||||
);
|
||||
};
|
||||
|
||||
export default HomePage;
|
||||
@@ -1,10 +1,11 @@
|
||||
import dayjs from "dayjs";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Box, Button, Paper, Typography } from "@mui/material";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Button, Paper } from "@mui/material";
|
||||
import { Virtuoso } from "react-virtuoso";
|
||||
import { ApiType } from "../services/types";
|
||||
import { getInfomation } from "../services/api";
|
||||
import LogItem from "../components/log-item";
|
||||
import BasePage from "../components/base/base-page";
|
||||
import LogItem from "../components/log/log-item";
|
||||
|
||||
let logCache: ApiType.LogItem[] = [];
|
||||
|
||||
@@ -28,33 +29,27 @@ const LogPage = () => {
|
||||
return () => ws?.close();
|
||||
}, []);
|
||||
|
||||
const onClear = () => {
|
||||
setLogData([]);
|
||||
logCache = [];
|
||||
};
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
position: "relative",
|
||||
width: 0.9,
|
||||
maxWidth: "850px",
|
||||
height: "100%",
|
||||
mx: "auto",
|
||||
}}
|
||||
<BasePage
|
||||
title="Logs"
|
||||
contentStyle={{ height: "100%" }}
|
||||
header={
|
||||
<Button
|
||||
size="small"
|
||||
sx={{ mt: 1 }}
|
||||
variant="contained"
|
||||
onClick={onClear}
|
||||
>
|
||||
Clear
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<Typography variant="h4" component="h1" sx={{ py: 2 }}>
|
||||
Logs
|
||||
</Typography>
|
||||
|
||||
<Button
|
||||
size="small"
|
||||
variant="contained"
|
||||
sx={{ position: "absolute", top: 22, right: 0 }}
|
||||
onClick={() => {
|
||||
setLogData([]);
|
||||
logCache = [];
|
||||
}}
|
||||
>
|
||||
Clear
|
||||
</Button>
|
||||
|
||||
<Paper sx={{ boxShadow: 2, height: "calc(100% - 100px)" }}>
|
||||
<Paper sx={{ boxShadow: 2, height: "100%" }}>
|
||||
<Virtuoso
|
||||
initialTopMostItemIndex={999}
|
||||
data={logData}
|
||||
@@ -62,7 +57,7 @@ const LogPage = () => {
|
||||
followOutput={"smooth"}
|
||||
/>
|
||||
</Paper>
|
||||
</Box>
|
||||
</BasePage>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,96 +0,0 @@
|
||||
import { useRef, useState } from "react";
|
||||
import useSWR, { useSWRConfig } from "swr";
|
||||
import { Box, Button, Grid, TextField, Typography } from "@mui/material";
|
||||
import { getProfiles, importProfile, putProfiles } from "../services/cmds";
|
||||
import { getProxies } from "../services/api";
|
||||
import ProfileItemComp from "../components/profile-item";
|
||||
import useNotice from "../utils/use-notice";
|
||||
import noop from "../utils/noop";
|
||||
|
||||
const ProfilePage = () => {
|
||||
const [url, setUrl] = useState("");
|
||||
const [disabled, setDisabled] = useState(false);
|
||||
const [notice, noticeElement] = useNotice();
|
||||
|
||||
const { mutate } = useSWRConfig();
|
||||
const { data: profiles = {} } = useSWR("getProfiles", getProfiles);
|
||||
|
||||
const onImport = async () => {
|
||||
if (!url) return;
|
||||
setUrl("");
|
||||
setDisabled(true);
|
||||
|
||||
try {
|
||||
await importProfile(url);
|
||||
mutate("getProfiles", getProfiles());
|
||||
if (!profiles.items?.length) putProfiles(0).catch(noop);
|
||||
notice.success("Successfully import profile.");
|
||||
} catch {
|
||||
notice.error("Failed to import profile.");
|
||||
} finally {
|
||||
setDisabled(false);
|
||||
}
|
||||
};
|
||||
|
||||
const lockRef = useRef(false);
|
||||
const onProfileChange = (index: number) => {
|
||||
if (lockRef.current) return;
|
||||
lockRef.current = true;
|
||||
putProfiles(index)
|
||||
.then(() => {
|
||||
mutate("getProfiles", { ...profiles, current: index }, true);
|
||||
mutate("getProxies", getProxies());
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error(err);
|
||||
})
|
||||
.finally(() => {
|
||||
lockRef.current = false;
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Box sx={{ width: 0.9, maxWidth: "850px", mx: "auto", mb: 2 }}>
|
||||
<Typography variant="h4" component="h1" sx={{ py: 2, mb: 1 }}>
|
||||
Profiles
|
||||
</Typography>
|
||||
|
||||
<Box sx={{ display: "flex", mb: 3 }}>
|
||||
<TextField
|
||||
id="profile_url"
|
||||
name="profile_url"
|
||||
label="Profile URL"
|
||||
size="small"
|
||||
fullWidth
|
||||
value={url}
|
||||
onChange={(e) => setUrl(e.target.value)}
|
||||
sx={{ mr: 4 }}
|
||||
/>
|
||||
<Button
|
||||
disabled={!url || disabled}
|
||||
variant="contained"
|
||||
onClick={onImport}
|
||||
>
|
||||
Import
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
<Grid container spacing={3}>
|
||||
{profiles?.items?.map((item, idx) => (
|
||||
<Grid item xs={12} sm={6} key={item.file}>
|
||||
<ProfileItemComp
|
||||
index={idx}
|
||||
selected={profiles.current === idx}
|
||||
itemData={item}
|
||||
onClick={() => onProfileChange(idx)}
|
||||
/>
|
||||
</Grid>
|
||||
))}
|
||||
</Grid>
|
||||
|
||||
{noticeElement}
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProfilePage;
|
||||
164
src/pages/profiles.tsx
Normal file
@@ -0,0 +1,164 @@
|
||||
import useSWR, { useSWRConfig } from "swr";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Box, Button, Grid, TextField } from "@mui/material";
|
||||
import {
|
||||
getProfiles,
|
||||
selectProfile,
|
||||
patchProfile,
|
||||
importProfile,
|
||||
newProfile,
|
||||
} from "../services/cmds";
|
||||
import { getProxies, updateProxy } from "../services/api";
|
||||
import noop from "../utils/noop";
|
||||
import Notice from "../components/base/base-notice";
|
||||
import BasePage from "../components/base/base-page";
|
||||
import ProfileItem from "../components/profile/profile-item";
|
||||
import ProfileNew from "../components/profile/profile-new";
|
||||
|
||||
const ProfilePage = () => {
|
||||
const [url, setUrl] = useState("");
|
||||
const [disabled, setDisabled] = useState(false);
|
||||
|
||||
const { mutate } = useSWRConfig();
|
||||
const { data: profiles = {} } = useSWR("getProfiles", getProfiles);
|
||||
|
||||
useEffect(() => {
|
||||
if (profiles.current == null) return;
|
||||
if (!profiles.items) profiles.items = [];
|
||||
|
||||
const current = profiles.current;
|
||||
const profile = profiles.items![current];
|
||||
if (!profile) return;
|
||||
|
||||
setTimeout(async () => {
|
||||
const proxiesData = await getProxies();
|
||||
mutate("getProxies", proxiesData);
|
||||
|
||||
// init selected array
|
||||
const { selected = [] } = profile;
|
||||
const selectedMap = Object.fromEntries(
|
||||
selected.map((each) => [each.name!, each.now!])
|
||||
);
|
||||
|
||||
// todo: enhance error handle
|
||||
let hasChange = false;
|
||||
proxiesData.groups.forEach((group) => {
|
||||
const { name, now } = group;
|
||||
|
||||
if (!now || selectedMap[name] === now) return;
|
||||
if (selectedMap[name] == null) {
|
||||
selectedMap[name] = now!;
|
||||
} else {
|
||||
hasChange = true;
|
||||
updateProxy(name, selectedMap[name]);
|
||||
}
|
||||
});
|
||||
// update profile selected list
|
||||
profile.selected = Object.entries(selectedMap).map(([name, now]) => ({
|
||||
name,
|
||||
now,
|
||||
}));
|
||||
patchProfile(current!, profile).catch(console.error);
|
||||
// update proxies cache
|
||||
if (hasChange) mutate("getProxies", getProxies());
|
||||
}, 100);
|
||||
}, [profiles]);
|
||||
|
||||
const onImport = async () => {
|
||||
if (!url) return;
|
||||
setUrl("");
|
||||
setDisabled(true);
|
||||
|
||||
try {
|
||||
await importProfile(url);
|
||||
mutate("getProfiles", getProfiles());
|
||||
if (!profiles.items?.length) selectProfile(0).catch(noop);
|
||||
Notice.success("Successfully import profile.");
|
||||
} catch {
|
||||
Notice.error("Failed to import profile.");
|
||||
} finally {
|
||||
setDisabled(false);
|
||||
}
|
||||
};
|
||||
|
||||
const lockRef = useRef(false);
|
||||
const onSelect = async (index: number, force: boolean) => {
|
||||
if (lockRef.current) return;
|
||||
if (!force && index === profiles.current) return;
|
||||
lockRef.current = true;
|
||||
try {
|
||||
await selectProfile(index);
|
||||
mutate("getProfiles", { ...profiles, current: index }, true);
|
||||
} catch (err: any) {
|
||||
err && Notice.error(err.toString());
|
||||
} finally {
|
||||
lockRef.current = false;
|
||||
}
|
||||
};
|
||||
|
||||
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 (
|
||||
<BasePage title="Profiles">
|
||||
<Box sx={{ display: "flex", mb: 3 }}>
|
||||
<TextField
|
||||
id="profile_url"
|
||||
name="profile_url"
|
||||
label="Profile URL"
|
||||
size="small"
|
||||
fullWidth
|
||||
value={url}
|
||||
onChange={(e) => setUrl(e.target.value)}
|
||||
sx={{ mr: 1 }}
|
||||
/>
|
||||
<Button
|
||||
disabled={!url || disabled}
|
||||
variant="contained"
|
||||
onClick={onImport}
|
||||
sx={{ mr: 1 }}
|
||||
>
|
||||
Import
|
||||
</Button>
|
||||
<Button variant="contained" onClick={() => setDialogOpen(true)}>
|
||||
New
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
<Grid container spacing={3}>
|
||||
{profiles?.items?.map((item, idx) => (
|
||||
<Grid item xs={12} sm={6} key={item.file}>
|
||||
<ProfileItem
|
||||
index={idx}
|
||||
selected={profiles.current === idx}
|
||||
itemData={item}
|
||||
onSelect={(f) => onSelect(idx, f)}
|
||||
/>
|
||||
</Grid>
|
||||
))}
|
||||
</Grid>
|
||||
|
||||
<ProfileNew
|
||||
open={dialogOpen}
|
||||
onClose={() => setDialogOpen(false)}
|
||||
onSubmit={onNew}
|
||||
/>
|
||||
</BasePage>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProfilePage;
|
||||
131
src/pages/proxies.tsx
Normal file
@@ -0,0 +1,131 @@
|
||||
import useSWR, { useSWRConfig } from "swr";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
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 BasePage from "../components/base/base-page";
|
||||
import ProxyItem from "../components/proxy/proxy-item";
|
||||
import ProxyGroup from "../components/proxy/proxy-group";
|
||||
|
||||
const ProxyPage = () => {
|
||||
const { mutate } = useSWRConfig();
|
||||
const { data: proxiesData } = useSWR("getProxies", getProxies);
|
||||
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(() => {
|
||||
if (
|
||||
(curMode === "rule" && !groups.length) ||
|
||||
(curMode === "global" && filterProxies.length < 4)
|
||||
) {
|
||||
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 (
|
||||
<BasePage
|
||||
contentStyle={pageStyle}
|
||||
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>
|
||||
{groups.map((group) => (
|
||||
<ProxyGroup key={group.name} group={group} />
|
||||
))}
|
||||
</List>
|
||||
) : (
|
||||
// virtual list
|
||||
<Virtuoso
|
||||
style={{ height: "100%" }}
|
||||
totalCount={filterProxies.length}
|
||||
itemContent={(index) => (
|
||||
<ProxyItem
|
||||
groupName="GLOBAL"
|
||||
proxy={filterProxies[index]}
|
||||
selected={filterProxies[index].name === curProxy}
|
||||
onClick={onChangeProxy}
|
||||
sx={{ py: 0, px: 2 }}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</Paper>
|
||||
</BasePage>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProxyPage;
|
||||
@@ -1,29 +0,0 @@
|
||||
import useSWR from "swr";
|
||||
import { Box, List, Paper, Typography } from "@mui/material";
|
||||
import { getProxies } from "../services/api";
|
||||
import ProxyGroup from "../components/proxy-group";
|
||||
|
||||
const ProxyPage = () => {
|
||||
const { data } = useSWR("getProxies", getProxies);
|
||||
const { groups = [] } = data ?? {};
|
||||
|
||||
return (
|
||||
<Box sx={{ width: 0.9, maxWidth: "850px", mx: "auto", mb: 2 }}>
|
||||
<Typography variant="h4" component="h1" sx={{ py: 2 }}>
|
||||
Proxy Groups
|
||||
</Typography>
|
||||
|
||||
{groups.length > 0 && (
|
||||
<Paper sx={{ borderRadius: 1, boxShadow: 2 }}>
|
||||
<List>
|
||||
{groups.map((group) => (
|
||||
<ProxyGroup key={group.name} group={group} />
|
||||
))}
|
||||
</List>
|
||||
</Paper>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProxyPage;
|
||||
@@ -1,23 +0,0 @@
|
||||
import { Box, Paper, Typography } from "@mui/material";
|
||||
import SettingVerge from "../components/setting-verge";
|
||||
import SettingClash from "../components/setting-clash";
|
||||
|
||||
const SettingPage = () => {
|
||||
return (
|
||||
<Box sx={{ width: 0.9, maxWidth: 850, mx: "auto", mb: 2 }}>
|
||||
<Typography variant="h4" component="h1" sx={{ py: 2 }}>
|
||||
Setting
|
||||
</Typography>
|
||||
|
||||
<Paper sx={{ borderRadius: 1, boxShadow: 2 }}>
|
||||
<SettingVerge />
|
||||
</Paper>
|
||||
|
||||
<Paper sx={{ borderRadius: 1, boxShadow: 2, mt: 3 }}>
|
||||
<SettingClash />
|
||||
</Paper>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export default SettingPage;
|
||||
30
src/pages/settings.tsx
Normal file
@@ -0,0 +1,30 @@
|
||||
import { Paper } from "@mui/material";
|
||||
import Notice from "../components/base/base-notice";
|
||||
import BasePage from "../components/base/base-page";
|
||||
import SettingVerge from "../components/setting/setting-verge";
|
||||
import SettingClash from "../components/setting/setting-clash";
|
||||
import SettingSystem from "../components/setting/setting-system";
|
||||
|
||||
const SettingPage = () => {
|
||||
const onError = (error: any) => {
|
||||
error && Notice.error(error.toString());
|
||||
};
|
||||
|
||||
return (
|
||||
<BasePage title="Settings">
|
||||
<Paper sx={{ borderRadius: 1, boxShadow: 2, mb: 3 }}>
|
||||
<SettingClash onError={onError} />
|
||||
</Paper>
|
||||
|
||||
<Paper sx={{ borderRadius: 1, boxShadow: 2, mb: 3 }}>
|
||||
<SettingSystem onError={onError} />
|
||||
</Paper>
|
||||
|
||||
<Paper sx={{ borderRadius: 1, boxShadow: 2 }}>
|
||||
<SettingVerge onError={onError} />
|
||||
</Paper>
|
||||
</BasePage>
|
||||
);
|
||||
};
|
||||
|
||||
export default SettingPage;
|
||||
@@ -7,14 +7,15 @@ let server = "";
|
||||
let secret = "";
|
||||
|
||||
/// initialize some infomation
|
||||
export async function getAxios() {
|
||||
if (axiosIns) return axiosIns;
|
||||
/// enable force update axiosIns
|
||||
export async function getAxios(force: boolean = false) {
|
||||
if (axiosIns && !force) return axiosIns;
|
||||
|
||||
try {
|
||||
const info = await getClashInfo();
|
||||
|
||||
if (info?.controller?.server) server = info?.controller?.server;
|
||||
if (info?.controller?.secret) secret = info?.controller?.secret;
|
||||
if (info?.server) server = info?.server;
|
||||
if (info?.secret) secret = info?.secret;
|
||||
} catch {}
|
||||
|
||||
axiosIns = axios.create({
|
||||
@@ -29,7 +30,7 @@ export async function getAxios() {
|
||||
export async function getInfomation() {
|
||||
if (server) return { server, secret };
|
||||
const info = await getClashInfo();
|
||||
return info?.controller!;
|
||||
return info!;
|
||||
}
|
||||
|
||||
/// Get Version
|
||||
@@ -59,10 +60,24 @@ export async function getRules() {
|
||||
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
|
||||
export async function updateProxy(group: string, proxy: string) {
|
||||
const instance = await getAxios();
|
||||
return instance.put(`/proxies/${group}`, { name: proxy });
|
||||
return instance.put(`/proxies/${encodeURIComponent(group)}`, { name: proxy });
|
||||
}
|
||||
|
||||
/// Get the Proxy infomation
|
||||
|
||||
@@ -1,6 +1,45 @@
|
||||
import { invoke } from "@tauri-apps/api/tauri";
|
||||
import { ApiType, CmdType } from "./types";
|
||||
|
||||
export async function getProfiles() {
|
||||
return invoke<CmdType.ProfilesConfig>("get_profiles");
|
||||
}
|
||||
|
||||
export async function syncProfiles() {
|
||||
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) {
|
||||
return invoke<void>("view_profile", { index });
|
||||
}
|
||||
|
||||
export async function importProfile(url: string) {
|
||||
return invoke<void>("import_profile", { url, withProxy: true });
|
||||
}
|
||||
|
||||
export async function updateProfile(index: number, withProxy: boolean) {
|
||||
return invoke<void>("update_profile", { index, withProxy });
|
||||
}
|
||||
|
||||
export async function deleteProfile(index: number) {
|
||||
return invoke<void>("delete_profile", { index });
|
||||
}
|
||||
|
||||
export async function patchProfile(
|
||||
index: number,
|
||||
profile: CmdType.ProfileItem
|
||||
) {
|
||||
return invoke<void>("patch_profile", { index, profile });
|
||||
}
|
||||
|
||||
export async function selectProfile(index: number) {
|
||||
return invoke<void>("select_profile", { index });
|
||||
}
|
||||
|
||||
export async function restartSidecar() {
|
||||
return invoke<void>("restart_sidecar");
|
||||
}
|
||||
@@ -13,33 +52,6 @@ export async function patchClashConfig(payload: Partial<ApiType.ConfigData>) {
|
||||
return invoke<void>("patch_clash_config", { payload });
|
||||
}
|
||||
|
||||
export async function importProfile(url: string) {
|
||||
return invoke<void>("import_profile", { url });
|
||||
}
|
||||
|
||||
export async function updateProfile(index: number) {
|
||||
return invoke<void>("update_profile", { index });
|
||||
}
|
||||
|
||||
export async function getProfiles() {
|
||||
return (await invoke<CmdType.ProfilesConfig>("get_profiles")) ?? {};
|
||||
}
|
||||
|
||||
export async function setProfiles(
|
||||
current: number,
|
||||
profile: CmdType.ProfileItem
|
||||
) {
|
||||
return invoke<void>("set_profiles", { current, profile });
|
||||
}
|
||||
|
||||
export async function putProfiles(current: number) {
|
||||
return invoke<void>("put_profiles", { current });
|
||||
}
|
||||
|
||||
export async function setSysProxy(enable: boolean) {
|
||||
return invoke<void>("set_sys_proxy", { enable });
|
||||
}
|
||||
|
||||
export async function getVergeConfig() {
|
||||
return invoke<CmdType.VergeConfig>("get_verge_config");
|
||||
}
|
||||
@@ -47,3 +59,19 @@ export async function getVergeConfig() {
|
||||
export async function patchVergeConfig(payload: CmdType.VergeConfig) {
|
||||
return invoke<void>("patch_verge_config", { payload });
|
||||
}
|
||||
|
||||
export async function getSystemProxy() {
|
||||
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
@@ -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();
|
||||
@@ -80,12 +80,14 @@ export namespace ApiType {
|
||||
export namespace CmdType {
|
||||
export interface ClashInfo {
|
||||
status: string;
|
||||
controller?: { server?: string; secret?: string };
|
||||
message?: string;
|
||||
port?: string;
|
||||
server?: string;
|
||||
secret?: string;
|
||||
}
|
||||
|
||||
export interface ProfileItem {
|
||||
name?: string;
|
||||
desc?: string;
|
||||
file?: string;
|
||||
mode?: string;
|
||||
url?: string;
|
||||
@@ -109,7 +111,11 @@ export namespace CmdType {
|
||||
|
||||
export interface VergeConfig {
|
||||
theme_mode?: "light" | "dark";
|
||||
enable_self_startup?: boolean;
|
||||
theme_blur?: boolean;
|
||||
traffic_graph?: boolean;
|
||||
enable_auto_launch?: boolean;
|
||||
enable_system_proxy?: boolean;
|
||||
enable_proxy_guard?: boolean;
|
||||
system_proxy_bypass?: string;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { atom } from "recoil";
|
||||
|
||||
export const atomPaletteMode = atom<"light" | "dark">({
|
||||
key: "atomPaletteMode",
|
||||
default: "light",
|
||||
export const atomClashPort = atom<number>({
|
||||
key: "atomClashPort",
|
||||
default: 0,
|
||||
});
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { Box, IconButton, Slide, Snackbar } from "@mui/material";
|
||||
import { Close, CheckCircleRounded, ErrorRounded } from "@mui/icons-material";
|
||||
|
||||
interface NoticeInstance {
|
||||
info: (msg: string) => void;
|
||||
error: (msg: string) => void;
|
||||
success: (msg: string) => void;
|
||||
}
|
||||
|
||||
const useNotice = () => {
|
||||
const [message, setMessage] = useState("");
|
||||
const [level, setLevel] = useState<"info" | "error" | "success">("info");
|
||||
|
||||
const handleClose = (_e: any, reason: string) => {
|
||||
if (reason !== "clickaway") setMessage("");
|
||||
};
|
||||
|
||||
const msgElement =
|
||||
level === "info" ? (
|
||||
message
|
||||
) : (
|
||||
<Box sx={{ display: "flex", alignItems: "center" }}>
|
||||
{level === "error" && <ErrorRounded color="error" />}
|
||||
{level === "success" && <CheckCircleRounded color="success" />}
|
||||
<span style={{ marginLeft: 4 }}>{message}</span>
|
||||
</Box>
|
||||
);
|
||||
|
||||
const element = useMemo(
|
||||
() => (
|
||||
<Snackbar
|
||||
open={!!message}
|
||||
anchorOrigin={{ vertical: "top", horizontal: "right" }}
|
||||
autoHideDuration={3000}
|
||||
onClose={handleClose}
|
||||
message={msgElement}
|
||||
sx={{ maxWidth: 360 }}
|
||||
TransitionComponent={(p) => <Slide {...p} direction="left" />}
|
||||
transitionDuration={200}
|
||||
action={
|
||||
<IconButton
|
||||
size="small"
|
||||
color="inherit"
|
||||
onClick={() => setMessage("")}
|
||||
>
|
||||
<Close fontSize="small" />
|
||||
</IconButton>
|
||||
}
|
||||
/>
|
||||
),
|
||||
[message]
|
||||
);
|
||||
|
||||
const instance = (Object.fromEntries(
|
||||
(["info", "error", "success"] as const).map((item) => [
|
||||
item,
|
||||
(msg: string) => {
|
||||
setLevel(item);
|
||||
setMessage(msg);
|
||||
},
|
||||
])
|
||||
) as unknown) as NoticeInstance;
|
||||
|
||||
return [instance, element] as const;
|
||||
};
|
||||
|
||||
export default useNotice;
|
||||