Compare commits
55 Commits
updater-al
...
v0.0.9
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 |
48
.github/workflows/release.yml
vendored
@@ -10,46 +10,50 @@ jobs:
|
|||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
platform: [windows-latest]
|
platform: [windows-latest, macos-latest]
|
||||||
runs-on: ${{ matrix.platform }}
|
runs-on: ${{ matrix.platform }}
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- name: Checkout repository
|
||||||
- name: setup node
|
uses: actions/checkout@v2
|
||||||
|
|
||||||
|
- name: Install Node
|
||||||
uses: actions/setup-node@v1
|
uses: actions/setup-node@v1
|
||||||
with:
|
with:
|
||||||
node-version: 14
|
node-version: 14
|
||||||
- name: install Rust stable
|
|
||||||
|
- name: Install Rust
|
||||||
uses: actions-rs/toolchain@v1
|
uses: actions-rs/toolchain@v1
|
||||||
with:
|
with:
|
||||||
toolchain: stable
|
toolchain: stable
|
||||||
- name: Get yarn cache directory path
|
profile: minimal
|
||||||
|
override: true
|
||||||
|
|
||||||
|
- name: Get yarn cache dir path
|
||||||
id: yarn-cache-dir-path
|
id: yarn-cache-dir-path
|
||||||
run: echo "::set-output name=dir::$(yarn cache dir)"
|
run: echo "::set-output name=dir::$(yarn cache dir)"
|
||||||
- uses: actions/cache@v2
|
|
||||||
|
- name: Yarn Cache
|
||||||
|
uses: actions/cache@v2
|
||||||
id: yarn-cache
|
id: yarn-cache
|
||||||
with:
|
with:
|
||||||
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
|
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
|
||||||
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
|
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
|
||||||
restore-keys: |
|
restore-keys: |
|
||||||
${{ runner.os }}-yarn-
|
${{ runner.os }}-yarn-
|
||||||
- uses: actions/cache@v2
|
|
||||||
with:
|
- name: Rust Cache
|
||||||
path: |
|
uses: Swatinem/rust-cache@ce325b60658c1b38465c06cc965b79baf32c1e72
|
||||||
~/.cargo/bin/
|
|
||||||
~/.cargo/registry/index/
|
- name: Yarn install and check
|
||||||
~/.cargo/registry/cache/
|
run: yarn && yarn run check
|
||||||
~/.cargo/git/db/
|
|
||||||
src-tauri/target/
|
- name: Tauri build
|
||||||
src-tauri/WixTools/
|
uses: tauri-apps/tauri-action@v0
|
||||||
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:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
with:
|
with:
|
||||||
tagName: v__VERSION__
|
tagName: v__VERSION__
|
||||||
releaseName: "Clash Verge v__VERSION__"
|
releaseName: "Clash Verge v__VERSION__"
|
||||||
releaseBody: "This is a release."
|
releaseBody: "Clash Verge now supports Windows and macos(intel)."
|
||||||
releaseDraft: true
|
releaseDraft: false
|
||||||
prerelease: false
|
prerelease: true
|
||||||
|
|||||||
3
.gitignore
vendored
@@ -3,5 +3,4 @@ node_modules
|
|||||||
dist
|
dist
|
||||||
dist-ssr
|
dist-ssr
|
||||||
*.local
|
*.local
|
||||||
package-lock.json
|
update.json
|
||||||
yarn.lock
|
|
||||||
|
|||||||
10
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).
|
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
|
```shell
|
||||||
yarn run predev
|
yarn run check
|
||||||
```
|
```
|
||||||
|
|
||||||
Then run
|
Then run
|
||||||
@@ -42,8 +42,12 @@ yarn dev
|
|||||||
## Screenshots
|
## Screenshots
|
||||||
|
|
||||||
<div align="center">
|
<div align="center">
|
||||||
<img src="./docs/demo1.png" alt="demo1" width="42%" />
|
<img src="./docs/demo1.png" alt="demo1" width="32%" />
|
||||||
<img src="./docs/demo2.png" alt="demo2" width="42%" />
|
<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>
|
</div>
|
||||||
|
|
||||||
## Disclaimer
|
## Disclaimer
|
||||||
|
|||||||
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 |
@@ -1,14 +1,16 @@
|
|||||||
{
|
{
|
||||||
"name": "clash-verge",
|
"name": "clash-verge",
|
||||||
"version": "0.0.1",
|
"version": "0.0.9",
|
||||||
"license": "GPL-3.0",
|
"license": "GPL-3.0",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "cargo tauri dev",
|
"dev": "cargo tauri dev",
|
||||||
"build": "cargo tauri build",
|
"build": "cargo tauri build",
|
||||||
|
"tauri": "tauri",
|
||||||
"web:dev": "vite",
|
"web:dev": "vite",
|
||||||
"web:build": "tsc && vite build",
|
"web:build": "tsc && vite build",
|
||||||
"web:serve": "vite preview",
|
"web:serve": "vite preview",
|
||||||
"predev": "node scripts/pre-dev.mjs",
|
"check": "node scripts/check.mjs",
|
||||||
|
"publish": "node scripts/publish.mjs",
|
||||||
"prepare": "husky install"
|
"prepare": "husky install"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
@@ -28,6 +30,7 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@tauri-apps/cli": "^1.0.0-beta.10",
|
"@tauri-apps/cli": "^1.0.0-beta.10",
|
||||||
|
"@types/fs-extra": "^9.0.13",
|
||||||
"@types/react": "^17.0.0",
|
"@types/react": "^17.0.0",
|
||||||
"@types/react-dom": "^17.0.0",
|
"@types/react-dom": "^17.0.0",
|
||||||
"@vitejs/plugin-react": "^1.1.1",
|
"@vitejs/plugin-react": "^1.1.1",
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import fs from "fs-extra";
|
import fs from "fs-extra";
|
||||||
|
import zlib from "zlib";
|
||||||
import path from "path";
|
import path from "path";
|
||||||
import AdmZip from "adm-zip";
|
import AdmZip from "adm-zip";
|
||||||
import fetch from "node-fetch";
|
import fetch from "node-fetch";
|
||||||
@@ -8,7 +9,7 @@ const cwd = process.cwd();
|
|||||||
|
|
||||||
const CLASH_URL_PREFIX =
|
const CLASH_URL_PREFIX =
|
||||||
"https://github.com/Dreamacro/clash/releases/download/premium/";
|
"https://github.com/Dreamacro/clash/releases/download/premium/";
|
||||||
const CLASH_LATEST_DATE = "2021.12.07";
|
const CLASH_LATEST_DATE = "2022.01.03";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* get the correct clash release infomation
|
* get the correct clash release infomation
|
||||||
@@ -16,15 +17,17 @@ const CLASH_LATEST_DATE = "2021.12.07";
|
|||||||
function resolveClash() {
|
function resolveClash() {
|
||||||
const { platform, arch } = process;
|
const { platform, arch } = process;
|
||||||
|
|
||||||
let name = "";
|
|
||||||
|
|
||||||
// todo
|
// todo
|
||||||
if (platform === "win32" && arch === "x64") {
|
const map = {
|
||||||
name = `clash-windows-386`;
|
"win32-x64": "clash-windows-386",
|
||||||
}
|
"darwin-x64": "clash-darwin-amd64",
|
||||||
|
"darwin-arm64": "clash-darwin-arm64",
|
||||||
|
};
|
||||||
|
|
||||||
|
const name = map[`${platform}-${arch}`];
|
||||||
|
|
||||||
if (!name) {
|
if (!name) {
|
||||||
throw new Error("todo");
|
throw new Error(`unsupport platform "${platform}-${arch}"`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const isWin = platform === "win32";
|
const isWin = platform === "win32";
|
||||||
@@ -59,15 +62,28 @@ async function resolveSidecar() {
|
|||||||
if (!(await fs.pathExists(tempDir))) await fs.mkdir(tempDir);
|
if (!(await fs.pathExists(tempDir))) await fs.mkdir(tempDir);
|
||||||
if (!(await fs.pathExists(tempZip))) await downloadFile(binInfo.url, tempZip);
|
if (!(await fs.pathExists(tempZip))) await downloadFile(binInfo.url, tempZip);
|
||||||
|
|
||||||
// Todo: support gz
|
if (binInfo.zip === "zip") {
|
||||||
const zip = new AdmZip(tempZip);
|
const zip = new AdmZip(tempZip);
|
||||||
zip.getEntries().forEach((entry) => {
|
zip.getEntries().forEach((entry) => {
|
||||||
console.log("[INFO]: entry name", entry.entryName);
|
console.log("[INFO]: entry name", entry.entryName);
|
||||||
});
|
});
|
||||||
zip.extractAllTo(tempDir, true);
|
zip.extractAllTo(tempDir, true);
|
||||||
|
// save as sidecar
|
||||||
// save as sidecar
|
await fs.rename(tempExe, sidecarPath);
|
||||||
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
|
// delete temp dir
|
||||||
await fs.remove(tempDir);
|
await fs.remove(tempDir);
|
||||||
@@ -97,6 +113,8 @@ async function downloadFile(url, path) {
|
|||||||
});
|
});
|
||||||
const buffer = await response.arrayBuffer();
|
const buffer = await response.arrayBuffer();
|
||||||
await fs.writeFile(path, new Uint8Array(buffer));
|
await fs.writeFile(path, new Uint8Array(buffer));
|
||||||
|
|
||||||
|
console.log(`[INFO]: download finished "${url}"`);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// main
|
/// main
|
||||||
41
scripts/publish.mjs
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
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;
|
||||||
|
else if (flag === "minor") b += 1;
|
||||||
|
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();
|
||||||
851
src-tauri/Cargo.lock
generated
@@ -4,7 +4,7 @@ version = "0.1.0"
|
|||||||
description = "clash verge"
|
description = "clash verge"
|
||||||
authors = ["zzzgydi"]
|
authors = ["zzzgydi"]
|
||||||
license = "GPL-3.0"
|
license = "GPL-3.0"
|
||||||
repository = ""
|
repository = "https://github.com/zzzgydi/clash-verge.git"
|
||||||
default-run = "app"
|
default-run = "app"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
build = "build.rs"
|
build = "build.rs"
|
||||||
@@ -18,7 +18,12 @@ chrono = "0.4.19"
|
|||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
serde_yaml = "0.8"
|
serde_yaml = "0.8"
|
||||||
serde = { version = "1.0", features = ["derive"] }
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
tauri = { version = "1.0.0-beta.8", features = ["api-all", "system-tray"] }
|
# tauri = { version = "1.0.0-beta.8", features = ["api-all", "system-tray"] }
|
||||||
|
# tauri = { git = "https://github.com/tauri-apps/tauri", rev = "5e0d59ec", features = ["api-all", "system-tray"] }
|
||||||
|
tauri = { git = "https://github.com/tauri-apps/tauri", branch = "next", features = ["api-all", "system-tray", "updater"] }
|
||||||
|
tauri-plugin-shadows = { git = "https://github.com/tauri-apps/tauri-plugin-shadows", features = ["tauri-impl"] }
|
||||||
|
tauri-plugin-vibrancy = { git = "https://github.com/tauri-apps/tauri-plugin-vibrancy", features = ["tauri-impl"] }
|
||||||
|
|
||||||
reqwest = { version = "0.11", features = ["json"] }
|
reqwest = { version = "0.11", features = ["json"] }
|
||||||
tokio = { version = "1", features = ["full"] }
|
tokio = { version = "1", features = ["full"] }
|
||||||
log = "0.4.14"
|
log = "0.4.14"
|
||||||
|
|||||||
255
src-tauri/src/cmds.rs
Normal file
@@ -0,0 +1,255 @@
|
|||||||
|
use crate::{
|
||||||
|
core::{ClashInfo, ProfileItem, ProfilesConfig, VergeConfig},
|
||||||
|
states::{ClashState, ProfilesState, VergeState},
|
||||||
|
utils::{
|
||||||
|
config::{read_clash, save_clash},
|
||||||
|
fetch::fetch_profile,
|
||||||
|
sysopt::SysProxyConfig,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
use serde_yaml::Mapping;
|
||||||
|
use tauri::{AppHandle, Manager, State};
|
||||||
|
|
||||||
|
/// get all profiles from `profiles.yaml`
|
||||||
|
/// do not acquire the lock of ProfileLock
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn get_profiles(profiles: State<'_, ProfilesState>) -> Result<ProfilesConfig, String> {
|
||||||
|
match profiles.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<'_, ProfilesState>) -> Result<(), String> {
|
||||||
|
match profiles.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, profiles: State<'_, ProfilesState>) -> Result<(), String> {
|
||||||
|
match fetch_profile(&url).await {
|
||||||
|
Some(result) => {
|
||||||
|
let mut profiles = profiles.0.lock().unwrap();
|
||||||
|
profiles.import_from_url(url, result)
|
||||||
|
}
|
||||||
|
None => Err(format!("failed to fetch profile from `{}`", url)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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,
|
||||||
|
clash: State<'_, ClashState>,
|
||||||
|
profiles: State<'_, ProfilesState>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
// maybe we can get the url from the web app directly
|
||||||
|
let url = match profiles.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()),
|
||||||
|
};
|
||||||
|
|
||||||
|
match fetch_profile(&url).await {
|
||||||
|
Some(result) => match profiles.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.0.lock().unwrap();
|
||||||
|
profiles.activate(clash.info.clone())
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(_) => Err("failed to get profiles lock".into()),
|
||||||
|
},
|
||||||
|
None => Err(format!("failed to fetch profile from `{}`", url)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// change the current profile
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn select_profile(
|
||||||
|
index: usize,
|
||||||
|
clash: State<'_, ClashState>,
|
||||||
|
profiles: State<'_, ProfilesState>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let mut profiles = profiles.0.lock().unwrap();
|
||||||
|
|
||||||
|
match profiles.put_current(index) {
|
||||||
|
Ok(()) => {
|
||||||
|
let clash = clash.0.lock().unwrap();
|
||||||
|
profiles.activate(clash.info.clone())
|
||||||
|
}
|
||||||
|
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.info.clone())
|
||||||
|
}
|
||||||
|
false => Ok(()),
|
||||||
|
},
|
||||||
|
Err(err) => Err(err),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// patch the profile config
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn patch_profile(
|
||||||
|
index: usize,
|
||||||
|
profile: ProfileItem,
|
||||||
|
profiles: State<'_, ProfilesState>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
match profiles.0.lock() {
|
||||||
|
Ok(mut profiles) => profiles.patch_item(index, profile),
|
||||||
|
Err(_) => Err("can not get profiles lock".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();
|
||||||
|
|
||||||
|
match clash.restart_sidecar() {
|
||||||
|
Ok(_) => {
|
||||||
|
let profiles = profiles_state.0.lock().unwrap();
|
||||||
|
match profiles.activate(clash.info.clone()) {
|
||||||
|
Ok(()) => Ok(()),
|
||||||
|
Err(err) => {
|
||||||
|
log::error!("{}", err);
|
||||||
|
Err(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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(arc) => Ok(arc.info.clone()),
|
||||||
|
Err(_) => Err("failed to get clash lock".into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// todo: need refactor
|
||||||
|
/// 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)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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> {
|
||||||
|
match verge_state.0.lock() {
|
||||||
|
Ok(arc) => Ok(arc.config.clone()),
|
||||||
|
Err(_) => Err("failed to get verge lock".into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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_state: State<'_, VergeState>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let mut verge = verge_state.0.lock().unwrap();
|
||||||
|
verge.patch_config(payload)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// start dragging window
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn win_drag(app_handle: AppHandle) {
|
||||||
|
let window = app_handle.get_window("main").unwrap();
|
||||||
|
window.start_dragging().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// hide the window
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn win_hide(app_handle: AppHandle) {
|
||||||
|
let window = app_handle.get_window("main").unwrap();
|
||||||
|
window.hide().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// mini the window
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn win_mini(app_handle: AppHandle) {
|
||||||
|
let window = app_handle.get_window("main").unwrap();
|
||||||
|
// todo: these methods still has bug on Windows
|
||||||
|
window.minimize().unwrap();
|
||||||
|
}
|
||||||
@@ -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>,
|
|
||||||
}
|
|
||||||
147
src-tauri/src/core/clash.rs
Normal file
@@ -0,0 +1,147 @@
|
|||||||
|
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 {
|
||||||
|
/// 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 clash_config = config::read_yaml::<Mapping>(dirs::app_home_dir().join(CLASH_CONFIG));
|
||||||
|
|
||||||
|
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,
|
||||||
|
};
|
||||||
|
|
||||||
|
Clash {
|
||||||
|
info: ClashInfo {
|
||||||
|
status: "init".into(),
|
||||||
|
port,
|
||||||
|
server,
|
||||||
|
secret,
|
||||||
|
},
|
||||||
|
sidecar: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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
|
||||||
|
pub fn restart_sidecar(&mut self) -> Result<(), String> {
|
||||||
|
self.drop_sidecar()?;
|
||||||
|
self.run_sidecar()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
320
src-tauri/src/core/profiles.rs
Normal file
@@ -0,0 +1,320 @@
|
|||||||
|
use crate::utils::{config, dirs};
|
||||||
|
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::File;
|
||||||
|
use std::io::Write;
|
||||||
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
use super::ClashInfo;
|
||||||
|
|
||||||
|
/// 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,
|
||||||
|
}
|
||||||
|
|
||||||
|
static PROFILE_YAML: &str = "profiles.yaml";
|
||||||
|
static PROFILE_TEMP: &str = "clash-verge-runtime.yaml";
|
||||||
|
|
||||||
|
impl ProfilesConfig {
|
||||||
|
/// read the config from the file
|
||||||
|
pub fn read_file() -> Self {
|
||||||
|
config::read_yaml::<ProfilesConfig>(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 = ProfilesConfig::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),
|
||||||
|
file: Some(result.file),
|
||||||
|
mode: Some(format!("rule")),
|
||||||
|
url: Some(url),
|
||||||
|
selected: Some(vec![]),
|
||||||
|
extra: Some(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()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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 = Some(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());
|
||||||
|
}
|
||||||
|
|
||||||
|
items.remove(index);
|
||||||
|
|
||||||
|
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_config: ClashInfo) -> 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();
|
||||||
|
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).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, 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));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only the following fields are allowed:
|
||||||
|
// proxies/proxy-providers/proxy-groups/rule-providers/rules
|
||||||
|
let config = 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);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
config::save_yaml(
|
||||||
|
temp_path.clone(),
|
||||||
|
&new_config,
|
||||||
|
Some("# Clash Verge Temp File"),
|
||||||
|
)?
|
||||||
|
};
|
||||||
|
|
||||||
|
let server = format!("http://{}/configs", info.server.clone().unwrap());
|
||||||
|
|
||||||
|
let mut headers = HeaderMap::new();
|
||||||
|
headers.insert("Content-Type", "application/json".parse().unwrap());
|
||||||
|
|
||||||
|
if let Some(secret) = 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 = reqwest::Client::new();
|
||||||
|
match client.put(server).headers(headers).json(&data).send().await {
|
||||||
|
Ok(_) => Ok(()),
|
||||||
|
Err(err) => Err(format!("request failed `{}`", err.to_string())),
|
||||||
|
}
|
||||||
|
}
|
||||||
197
src-tauri/src/core/verge.rs
Normal file
@@ -0,0 +1,197 @@
|
|||||||
|
use crate::utils::{config, dirs, startup, sysopt::SysProxyConfig};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use tauri::api::path::resource_dir;
|
||||||
|
|
||||||
|
/// ### `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>,
|
||||||
|
|
||||||
|
/// 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>,
|
||||||
|
}
|
||||||
|
|
||||||
|
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 exe_path: Option<PathBuf>,
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
exe_path: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// set the exe_path
|
||||||
|
pub fn set_exe_path(&mut self, package_info: &tauri::PackageInfo) {
|
||||||
|
let exe = if cfg!(target_os = "windows") {
|
||||||
|
"clash-verge.exe"
|
||||||
|
} else {
|
||||||
|
"clash-verge"
|
||||||
|
};
|
||||||
|
let path = resource_dir(package_info).unwrap().join(exe);
|
||||||
|
self.exe_path = Some(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// sync the startup when run the app
|
||||||
|
pub fn sync_startup(&self) -> Result<(), String> {
|
||||||
|
let enable = self.config.enable_self_startup.clone().unwrap_or(false);
|
||||||
|
|
||||||
|
if !enable {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if self.exe_path.is_none() {
|
||||||
|
return Err("should init the exe_path first".into());
|
||||||
|
}
|
||||||
|
|
||||||
|
let exe_path = self.exe_path.clone().unwrap();
|
||||||
|
match startup::get_startup(&exe_path) {
|
||||||
|
Ok(sys_enable) => {
|
||||||
|
if sys_enable || (!sys_enable && startup::set_startup(true, &exe_path).is_ok()) {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err("failed to sync startup".into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(_) => Err("failed to get system startup info".into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// update the startup
|
||||||
|
fn update_startup(&mut self, enable: bool) -> Result<(), String> {
|
||||||
|
let conf_enable = self.config.enable_self_startup.clone().unwrap_or(false);
|
||||||
|
|
||||||
|
if enable == conf_enable {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if self.exe_path.is_none() {
|
||||||
|
return Err("should init the exe_path first".into());
|
||||||
|
}
|
||||||
|
let exe_path = self.exe_path.clone().unwrap();
|
||||||
|
match startup::set_startup(enable, &exe_path) {
|
||||||
|
Ok(_) => Ok(()),
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// should update system startup
|
||||||
|
if patch.enable_self_startup.is_some() {
|
||||||
|
let enable = patch.enable_self_startup.unwrap();
|
||||||
|
self.update_startup(enable)?;
|
||||||
|
self.config.enable_self_startup = 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() {
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
// todo
|
||||||
|
// should update system proxt too
|
||||||
|
if patch.system_proxy_bypass.is_some() {
|
||||||
|
self.config.system_proxy_bypass = patch.system_proxy_bypass;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.config.save_file()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use tauri::{AppHandle, Manager};
|
|
||||||
|
|
||||||
use crate::config::ClashController;
|
|
||||||
|
|
||||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
|
||||||
pub struct ClashInfoPayload {
|
|
||||||
/// value between `success` and `error`
|
|
||||||
pub status: String,
|
|
||||||
|
|
||||||
/// the clash core's external controller infomation
|
|
||||||
pub controller: Option<ClashController>,
|
|
||||||
|
|
||||||
/// some message
|
|
||||||
pub message: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// emit `clash_runtime` to the main windows
|
|
||||||
pub fn clash_start(app_handle: &AppHandle, payload: &ClashInfoPayload) {
|
|
||||||
match app_handle.get_window("main") {
|
|
||||||
Some(main_win) => {
|
|
||||||
main_win.emit("clash_start", payload).unwrap();
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
pub mod emit;
|
|
||||||
pub mod state;
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
use std::sync::{Arc, Mutex};
|
|
||||||
|
|
||||||
use super::emit::ClashInfoPayload;
|
|
||||||
use crate::{config::VergeConfig, utils::sysopt::SysProxyConfig};
|
|
||||||
|
|
||||||
#[derive(Default)]
|
|
||||||
pub struct ClashInfoState(pub Arc<Mutex<ClashInfoPayload>>);
|
|
||||||
|
|
||||||
#[derive(Default)]
|
|
||||||
pub struct ProfileLock(pub Mutex<bool>);
|
|
||||||
|
|
||||||
#[derive(Default)]
|
|
||||||
pub struct VergeConfLock(pub Arc<Mutex<VergeConfig>>);
|
|
||||||
|
|
||||||
#[derive(Default)]
|
|
||||||
pub struct SomthingState(pub Arc<Mutex<Option<SysProxyConfig>>>);
|
|
||||||
@@ -6,14 +6,11 @@
|
|||||||
extern crate tauri;
|
extern crate tauri;
|
||||||
|
|
||||||
mod cmds;
|
mod cmds;
|
||||||
mod config;
|
mod core;
|
||||||
mod events;
|
mod states;
|
||||||
mod utils;
|
mod utils;
|
||||||
|
|
||||||
use crate::{
|
use crate::utils::{resolve, server};
|
||||||
events::state,
|
|
||||||
utils::{resolve, server},
|
|
||||||
};
|
|
||||||
use tauri::{
|
use tauri::{
|
||||||
api, CustomMenuItem, Manager, SystemTray, SystemTrayEvent, SystemTrayMenu, SystemTrayMenuItem,
|
api, CustomMenuItem, Manager, SystemTray, SystemTrayEvent, SystemTrayMenu, SystemTrayMenuItem,
|
||||||
};
|
};
|
||||||
@@ -25,15 +22,15 @@ fn main() -> std::io::Result<()> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let menu = SystemTrayMenu::new()
|
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_native_item(SystemTrayMenuItem::Separator)
|
||||||
.add_item(CustomMenuItem::new("quit", "退出").accelerator("CmdOrControl+Q"));
|
.add_item(CustomMenuItem::new("quit", "Quit").accelerator("CmdOrControl+Q"));
|
||||||
|
|
||||||
tauri::Builder::default()
|
tauri::Builder::default()
|
||||||
.manage(state::VergeConfLock::default())
|
.manage(states::VergeState::default())
|
||||||
.manage(state::ClashInfoState::default())
|
.manage(states::ClashState::default())
|
||||||
.manage(state::SomthingState::default())
|
.manage(states::ProfilesState::default())
|
||||||
.manage(state::ProfileLock::default())
|
|
||||||
.setup(|app| Ok(resolve::resolve_setup(app)))
|
.setup(|app| Ok(resolve::resolve_setup(app)))
|
||||||
.system_tray(SystemTray::new().with_menu(menu))
|
.system_tray(SystemTray::new().with_menu(menu))
|
||||||
.on_system_tray_event(move |app_handle, event| match event {
|
.on_system_tray_event(move |app_handle, event| match event {
|
||||||
@@ -43,6 +40,20 @@ fn main() -> std::io::Result<()> {
|
|||||||
window.show().unwrap();
|
window.show().unwrap();
|
||||||
window.set_focus().unwrap();
|
window.set_focus().unwrap();
|
||||||
}
|
}
|
||||||
|
"restart_clash" => {
|
||||||
|
let clash_state = app_handle.state::<states::ClashState>();
|
||||||
|
let mut clash = clash_state.0.lock().unwrap();
|
||||||
|
match clash.restart_sidecar() {
|
||||||
|
Ok(_) => {
|
||||||
|
let profiles = app_handle.state::<states::ProfilesState>();
|
||||||
|
let profiles = profiles.0.lock().unwrap();
|
||||||
|
if let Err(err) = profiles.activate(clash.info.clone()) {
|
||||||
|
log::error!("{}", err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(err) => log::error!("{}", err),
|
||||||
|
}
|
||||||
|
}
|
||||||
"quit" => {
|
"quit" => {
|
||||||
api::process::kill_children();
|
api::process::kill_children();
|
||||||
resolve::resolve_reset(app_handle);
|
resolve::resolve_reset(app_handle);
|
||||||
@@ -58,18 +69,27 @@ fn main() -> std::io::Result<()> {
|
|||||||
_ => {}
|
_ => {}
|
||||||
})
|
})
|
||||||
.invoke_handler(tauri::generate_handler![
|
.invoke_handler(tauri::generate_handler![
|
||||||
cmds::some::restart_sidecar,
|
// common
|
||||||
cmds::some::set_sys_proxy,
|
cmds::restart_sidecar,
|
||||||
cmds::some::get_sys_proxy,
|
cmds::get_sys_proxy,
|
||||||
cmds::some::get_clash_info,
|
cmds::get_cur_proxy,
|
||||||
cmds::some::patch_clash_config,
|
cmds::win_drag,
|
||||||
cmds::some::get_verge_config,
|
cmds::win_hide,
|
||||||
cmds::some::patch_verge_config,
|
cmds::win_mini,
|
||||||
cmds::profile::import_profile,
|
// clash
|
||||||
cmds::profile::update_profile,
|
cmds::get_clash_info,
|
||||||
cmds::profile::get_profiles,
|
cmds::patch_clash_config,
|
||||||
cmds::profile::set_profiles,
|
// verge
|
||||||
cmds::profile::put_profiles,
|
cmds::get_verge_config,
|
||||||
|
cmds::patch_verge_config,
|
||||||
|
// profile
|
||||||
|
cmds::import_profile,
|
||||||
|
cmds::update_profile,
|
||||||
|
cmds::delete_profile,
|
||||||
|
cmds::select_profile,
|
||||||
|
cmds::patch_profile,
|
||||||
|
cmds::sync_profiles,
|
||||||
|
cmds::get_profiles,
|
||||||
])
|
])
|
||||||
.build(tauri::generate_context!())
|
.build(tauri::generate_context!())
|
||||||
.expect("error while running tauri application")
|
.expect("error while running tauri application")
|
||||||
@@ -79,10 +99,7 @@ fn main() -> std::io::Result<()> {
|
|||||||
api.prevent_close();
|
api.prevent_close();
|
||||||
app_handle.get_window(&label).unwrap().hide().unwrap();
|
app_handle.get_window(&label).unwrap().hide().unwrap();
|
||||||
}
|
}
|
||||||
tauri::Event::ExitRequested { api, .. } => {
|
tauri::Event::ExitRequested { .. } => {
|
||||||
api.prevent_exit();
|
|
||||||
}
|
|
||||||
tauri::Event::Exit => {
|
|
||||||
resolve::resolve_reset(app_handle);
|
resolve::resolve_reset(app_handle);
|
||||||
api::process::kill_children();
|
api::process::kill_children();
|
||||||
}
|
}
|
||||||
|
|||||||
11
src-tauri/src/states.rs
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
use crate::core::{Clash, ProfilesConfig, Verge};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct ProfilesState(pub Arc<Mutex<ProfilesConfig>>);
|
||||||
|
|
||||||
|
#[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,6 @@
|
|||||||
use crate::{
|
use crate::utils::dirs;
|
||||||
config::{ClashController, ProfilesConfig, VergeConfig},
|
|
||||||
utils::app_home_dir,
|
|
||||||
};
|
|
||||||
use serde::{de::DeserializeOwned, Serialize};
|
use serde::{de::DeserializeOwned, Serialize};
|
||||||
use serde_yaml::{Mapping, Value};
|
use serde_yaml::Mapping;
|
||||||
use std::{fs, path::PathBuf};
|
use std::{fs, path::PathBuf};
|
||||||
|
|
||||||
/// read data from yaml as struct T
|
/// read data from yaml as struct T
|
||||||
@@ -19,114 +16,33 @@ pub fn save_yaml<T: Serialize>(
|
|||||||
data: &T,
|
data: &T,
|
||||||
prefix: Option<&str>,
|
prefix: Option<&str>,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
if let Ok(data_str) = serde_yaml::to_string(data) {
|
match serde_yaml::to_string(data) {
|
||||||
let yaml_str = if prefix.is_some() {
|
Ok(data_str) => {
|
||||||
prefix.unwrap().to_string() + &data_str
|
let yaml_str = match prefix {
|
||||||
} else {
|
Some(prefix) => format!("{}{}", prefix, data_str),
|
||||||
data_str
|
None => data_str,
|
||||||
};
|
};
|
||||||
|
|
||||||
if fs::write(path.clone(), yaml_str.as_bytes()).is_err() {
|
let path_str = path.as_os_str().to_string_lossy().to_string();
|
||||||
Err(format!("can not save file `{:?}`", path))
|
match fs::write(path, yaml_str.as_bytes()) {
|
||||||
} else {
|
Ok(_) => Ok(()),
|
||||||
Ok(())
|
Err(_) => Err(format!("can not save file `{}`", path_str)),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
Err(_) => Err("can not convert the data to yaml".into()),
|
||||||
Err(String::from("can not convert the data to yaml"))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get Clash Core Config `config.yaml`
|
/// Get Clash Core Config `config.yaml`
|
||||||
pub fn read_clash() -> Mapping {
|
pub fn read_clash() -> Mapping {
|
||||||
read_yaml::<Mapping>(app_home_dir().join("config.yaml"))
|
read_yaml::<Mapping>(dirs::app_home_dir().join("config.yaml"))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Save the clash core Config `config.yaml`
|
/// Save the clash core Config `config.yaml`
|
||||||
pub fn save_clash(config: &Mapping) -> Result<(), String> {
|
pub fn save_clash(config: &Mapping) -> Result<(), String> {
|
||||||
save_yaml(
|
save_yaml(
|
||||||
app_home_dir().join("config.yaml"),
|
dirs::app_home_dir().join("config.yaml"),
|
||||||
config,
|
config,
|
||||||
Some("# Default Config For Clash Core\n\n"),
|
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,4 +1,4 @@
|
|||||||
use crate::config::{ProfileExtra, ProfileResponse};
|
use crate::core::{ProfileExtra, ProfileResponse};
|
||||||
use std::{
|
use std::{
|
||||||
str::FromStr,
|
str::FromStr,
|
||||||
time::{SystemTime, UNIX_EPOCH},
|
time::{SystemTime, UNIX_EPOCH},
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
extern crate serde_yaml;
|
extern crate serde_yaml;
|
||||||
|
|
||||||
|
use crate::utils::dirs;
|
||||||
use chrono::Local;
|
use chrono::Local;
|
||||||
use log::LevelFilter;
|
use log::LevelFilter;
|
||||||
use log4rs::append::console::ConsoleAppender;
|
use log4rs::append::console::ConsoleAppender;
|
||||||
@@ -11,8 +12,6 @@ use std::io::Write;
|
|||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use tauri::PackageInfo;
|
use tauri::PackageInfo;
|
||||||
|
|
||||||
use crate::utils::{app_home_dir, app_resources_dir};
|
|
||||||
|
|
||||||
/// initialize this instance's log file
|
/// initialize this instance's log file
|
||||||
fn init_log(log_dir: &PathBuf) {
|
fn init_log(log_dir: &PathBuf) {
|
||||||
let local_time = Local::now().format("%Y-%m-%d-%H%M%S").to_string();
|
let local_time = Local::now().format("%Y-%m-%d-%H%M%S").to_string();
|
||||||
@@ -85,11 +84,11 @@ fn init_config_file(app_dir: &PathBuf, res_dir: &PathBuf) {
|
|||||||
/// initialize app
|
/// initialize app
|
||||||
pub fn init_app(package_info: &PackageInfo) {
|
pub fn init_app(package_info: &PackageInfo) {
|
||||||
// create app dir
|
// create app dir
|
||||||
let app_dir = app_home_dir();
|
let app_dir = dirs::app_home_dir();
|
||||||
let log_dir = app_dir.join("logs");
|
let log_dir = app_dir.join("logs");
|
||||||
let profiles_dir = app_dir.join("profiles");
|
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() {
|
if !app_dir.exists() {
|
||||||
fs::create_dir(&app_dir).unwrap();
|
fs::create_dir(&app_dir).unwrap();
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
mod dirs;
|
|
||||||
pub use self::dirs::*;
|
|
||||||
|
|
||||||
pub mod clash;
|
|
||||||
pub mod config;
|
pub mod config;
|
||||||
|
pub mod dirs;
|
||||||
pub mod fetch;
|
pub mod fetch;
|
||||||
pub mod init;
|
pub mod init;
|
||||||
pub mod resolve;
|
pub mod resolve;
|
||||||
pub mod server;
|
pub mod server;
|
||||||
|
pub mod startup;
|
||||||
pub mod sysopt;
|
pub mod sysopt;
|
||||||
|
|||||||
@@ -1,80 +1,58 @@
|
|||||||
use super::{clash, config, init, server, sysopt};
|
use super::{init, server};
|
||||||
use crate::events::state;
|
use crate::{core::ProfilesConfig, states};
|
||||||
use tauri::{App, AppHandle, Manager};
|
use tauri::{App, AppHandle, Manager};
|
||||||
|
use tauri_plugin_shadows::Shadows;
|
||||||
|
|
||||||
/// handle something when start app
|
/// handle something when start app
|
||||||
pub fn resolve_setup(app: &App) {
|
pub fn resolve_setup(app: &App) {
|
||||||
|
// set shadow when window decorations
|
||||||
|
let window = app.get_window("main").unwrap();
|
||||||
|
window.set_shadow(true);
|
||||||
|
|
||||||
|
use tauri_plugin_vibrancy::Vibrancy;
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
window.apply_blur();
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
{
|
||||||
|
use tauri_plugin_vibrancy::MacOSVibrancy;
|
||||||
|
window.apply_vibrancy(MacOSVibrancy::AppearanceBased);
|
||||||
|
}
|
||||||
|
|
||||||
// setup a simple http server for singleton
|
// setup a simple http server for singleton
|
||||||
server::embed_server(&app.handle());
|
server::embed_server(&app.handle());
|
||||||
|
|
||||||
// init app config
|
// init app config
|
||||||
init::init_app(app.package_info());
|
init::init_app(app.package_info());
|
||||||
|
|
||||||
// run clash sidecar
|
// init states
|
||||||
let info = clash::run_clash_bin(&app.handle());
|
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 mut clash = clash_state.0.lock().unwrap();
|
||||||
let info_ = info.clone();
|
let mut verge = verge_state.0.lock().unwrap();
|
||||||
tauri::async_runtime::spawn(async move {
|
let mut profiles = profiles_state.0.lock().unwrap();
|
||||||
if let Err(err) = clash::put_clash_profile(&info_).await {
|
|
||||||
log::error!("failed to put config for `{}`", err);
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
// resolve the verge config - enable system proxy
|
if let Err(err) = clash.run_sidecar() {
|
||||||
let mut original: Option<sysopt::SysProxyConfig> = None;
|
log::error!("{}", err);
|
||||||
let verge = config::read_verge();
|
|
||||||
let enable = verge.enable_system_proxy.unwrap_or(false);
|
|
||||||
|
|
||||||
if enable && info.controller.is_some() {
|
|
||||||
if let Ok(original_conf) = sysopt::get_proxy_config() {
|
|
||||||
original = Some(original_conf)
|
|
||||||
};
|
|
||||||
let ctl = info.controller.clone().unwrap();
|
|
||||||
if ctl.port.is_some() {
|
|
||||||
let server = format!("127.0.0.1:{}", ctl.port.unwrap());
|
|
||||||
let bypass = verge
|
|
||||||
.system_proxy_bypass
|
|
||||||
.clone()
|
|
||||||
.unwrap_or(String::from(sysopt::DEFAULT_BYPASS));
|
|
||||||
let config = sysopt::SysProxyConfig {
|
|
||||||
enable,
|
|
||||||
server,
|
|
||||||
bypass,
|
|
||||||
};
|
|
||||||
if let Err(err) = sysopt::set_proxy_config(&config) {
|
|
||||||
log::error!("can not set system proxy for `{}`", err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
// update state
|
|
||||||
let verge_state = app.state::<state::VergeConfLock>();
|
|
||||||
let mut verge_arc = verge_state.0.lock().unwrap();
|
|
||||||
*verge_arc = verge;
|
|
||||||
|
|
||||||
let clash_state = app.state::<state::ClashInfoState>();
|
*profiles = ProfilesConfig::read_file();
|
||||||
let mut clash_arc = clash_state.0.lock().unwrap();
|
if let Err(err) = profiles.activate(clash.info.clone()) {
|
||||||
*clash_arc = info;
|
log::error!("{}", err);
|
||||||
|
}
|
||||||
|
|
||||||
let some_state = app.state::<state::SomthingState>();
|
verge.set_exe_path(app.package_info());
|
||||||
let mut some_arc = some_state.0.lock().unwrap();
|
verge.init_sysproxy(clash.info.port.clone());
|
||||||
*some_arc = original;
|
if let Err(err) = verge.sync_startup() {
|
||||||
|
log::error!("{}", err);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// reset system proxy
|
/// reset system proxy
|
||||||
pub fn resolve_reset(app_handle: &AppHandle) {
|
pub fn resolve_reset(app_handle: &AppHandle) {
|
||||||
let state = app_handle.try_state::<state::SomthingState>();
|
let verge_state = app_handle.state::<states::VergeState>();
|
||||||
if state.is_none() {
|
let mut verge = verge_state.0.lock().unwrap();
|
||||||
return;
|
|
||||||
}
|
verge.reset_sysproxy();
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,13 +24,13 @@ pub fn check_singleton() -> Result<(), ()> {
|
|||||||
pub fn embed_server(app: &AppHandle) {
|
pub fn embed_server(app: &AppHandle) {
|
||||||
let window = app.get_window("main").unwrap();
|
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 {
|
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)
|
warp::serve(commands)
|
||||||
.bind(([127, 0, 0, 1], SERVER_PORT))
|
.bind(([127, 0, 0, 1], SERVER_PORT))
|
||||||
.await;
|
.await;
|
||||||
|
|||||||
74
src-tauri/src/utils/startup.rs
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
use std::io;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
static APP_KEY: &str = "ClashVerge";
|
||||||
|
|
||||||
|
/// get the startup value
|
||||||
|
/// whether as same as the exe_path
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
pub fn get_startup(exe_path: &PathBuf) -> io::Result<bool> {
|
||||||
|
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\\Run",
|
||||||
|
KEY_READ,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
match cur_var.get_value::<String, _>(APP_KEY) {
|
||||||
|
Ok(path) => {
|
||||||
|
let exe_path = exe_path.clone();
|
||||||
|
let exe_path = exe_path.as_os_str().to_str().unwrap();
|
||||||
|
Ok(path == exe_path)
|
||||||
|
}
|
||||||
|
Err(_) => Ok(false),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// set the startup on windows
|
||||||
|
/// delete the reg key if disabled
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
pub fn set_startup(enable: bool, exe_path: &PathBuf) -> 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\\Run",
|
||||||
|
KEY_SET_VALUE,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
match enable {
|
||||||
|
true => {
|
||||||
|
let exe_path = exe_path.clone();
|
||||||
|
let exe_path = exe_path.as_os_str().to_str().unwrap();
|
||||||
|
cur_var.set_value::<&str, _>(APP_KEY, &exe_path)
|
||||||
|
}
|
||||||
|
false => cur_var.delete_value(APP_KEY),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// todo
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
pub fn get_startup(exe_path: &PathBuf) -> io::Result<bool> {
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// todo
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
pub fn set_startup(enable: bool, exe_path: &PathBuf) -> io::Result<()> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
#[test]
|
||||||
|
fn test() {
|
||||||
|
let path = PathBuf::from(r"D:\Software\Clash Verge\clash-verge.exe");
|
||||||
|
|
||||||
|
assert!(set_startup(true, &path).is_ok());
|
||||||
|
assert_eq!(get_startup(&path).unwrap(), true);
|
||||||
|
|
||||||
|
assert!(set_startup(false, &path).is_ok());
|
||||||
|
assert_eq!(get_startup(&path).unwrap(), false);
|
||||||
|
}
|
||||||
182
src-tauri/src/utils/sysopt.rs
Normal file → Executable file
@@ -1,6 +1,14 @@
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::io;
|
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)]
|
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||||
pub struct SysProxyConfig {
|
pub struct SysProxyConfig {
|
||||||
pub enable: bool,
|
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>";
|
impl SysProxyConfig {
|
||||||
|
pub fn new(enable: bool, port: String, bypass: Option<String>) -> Self {
|
||||||
#[cfg(target_os = "windows")]
|
SysProxyConfig {
|
||||||
mod win {
|
enable,
|
||||||
use super::*;
|
server: format!("127.0.0.1:{}", port),
|
||||||
use winreg::enums::*;
|
bypass: bypass.unwrap_or(DEFAULT_BYPASS.into()),
|
||||||
use winreg::RegKey;
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
/// Get the windows system proxy config
|
/// 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 hkcu = RegKey::predef(HKEY_CURRENT_USER);
|
||||||
let cur_var = hkcu.open_subkey_with_flags(
|
let cur_var = hkcu.open_subkey_with_flags(
|
||||||
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",
|
"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
|
/// 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 hkcu = RegKey::predef(HKEY_CURRENT_USER);
|
||||||
let cur_var = hkcu.open_subkey_with_flags(
|
let cur_var = hkcu.open_subkey_with_flags(
|
||||||
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",
|
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",
|
||||||
KEY_SET_VALUE,
|
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("ProxyEnable", &enable)?;
|
||||||
cur_var.set_value("ProxyServer", &config.server)?;
|
cur_var.set_value("ProxyServer", &self.server)?;
|
||||||
cur_var.set_value("ProxyOverride", &config.bypass)?;
|
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")]
|
#[cfg(target_os = "macos")]
|
||||||
mod macos {
|
mod macproxy {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use std::process::Command;
|
||||||
|
|
||||||
pub fn get_proxy_config() -> io::Result<SysProxyConfig> {
|
/// use networksetup
|
||||||
Ok(SysProxyConfig {
|
/// get the target proxy config
|
||||||
enable: false,
|
pub(super) fn get_proxy(args: &[&str; 2]) -> io::Result<(String, String)> {
|
||||||
server: "server".into(),
|
let output = Command::new("networksetup").args(args).output()?;
|
||||||
bypass: "bypass".into(),
|
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(())
|
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::*;
|
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
{
|
{
|
||||||
"package": {
|
"package": {
|
||||||
"productName": "clash-verge",
|
"productName": "clash-verge",
|
||||||
"version": "0.0.1"
|
"version": "0.0.9"
|
||||||
},
|
},
|
||||||
"build": {
|
"build": {
|
||||||
"distDir": "../dist",
|
"distDir": "../dist",
|
||||||
"devPath": "http://localhost:3000/proxy",
|
"devPath": "http://localhost:3000/",
|
||||||
"beforeDevCommand": "yarn run web:dev",
|
"beforeDevCommand": "yarn run web:dev",
|
||||||
"beforeBuildCommand": "yarn run web:build"
|
"beforeBuildCommand": "yarn run web:build"
|
||||||
},
|
},
|
||||||
@@ -50,7 +50,11 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"updater": {
|
"updater": {
|
||||||
"active": false
|
"active": true,
|
||||||
|
"endpoints": [
|
||||||
|
"https://github.com/zzzgydi/clash-verge/releases/download/updater/update.json"
|
||||||
|
],
|
||||||
|
"dialog": false
|
||||||
},
|
},
|
||||||
"allowlist": {
|
"allowlist": {
|
||||||
"all": true
|
"all": true
|
||||||
@@ -62,8 +66,8 @@
|
|||||||
"height": 600,
|
"height": 600,
|
||||||
"resizable": true,
|
"resizable": true,
|
||||||
"fullscreen": false,
|
"fullscreen": false,
|
||||||
"decorations": true,
|
"decorations": false,
|
||||||
"transparent": false,
|
"transparent": true,
|
||||||
"minWidth": 600,
|
"minWidth": 600,
|
||||||
"minHeight": 520
|
"minHeight": 520
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,45 +1,80 @@
|
|||||||
.layout {
|
.layout {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
|
height: 100vh;
|
||||||
display: flex;
|
display: flex;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
|
|
||||||
&__sidebar {
|
&__left {
|
||||||
position: relative;
|
|
||||||
flex: 1 0 25%;
|
flex: 1 0 25%;
|
||||||
height: 100vh;
|
display: flex;
|
||||||
|
height: 100%;
|
||||||
max-width: 225px;
|
max-width: 225px;
|
||||||
min-width: 125px;
|
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: 180px;
|
||||||
|
max-height: 180px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 0 8px;
|
||||||
|
text-align: center;
|
||||||
|
box-sizing: border-box;
|
||||||
|
|
||||||
|
.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;
|
position: relative;
|
||||||
flex: 1 1 75%;
|
flex: 1 1 75%;
|
||||||
height: 100vh;
|
height: 100%;
|
||||||
overflow: overlay;
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
padding: 2px 0;
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
}
|
|
||||||
|
|
||||||
&__logo {
|
.the-bar {
|
||||||
width: 100%;
|
flex: 0 0 30px;
|
||||||
height: auto;
|
width: 100%;
|
||||||
max-width: 180px;
|
height: 30px;
|
||||||
max-height: 180px;
|
padding: 0 16px;
|
||||||
margin: 0 auto;
|
display: flex;
|
||||||
padding: 8px 8px 0;
|
align-items: center;
|
||||||
user-select: none;
|
justify-content: flex-end;
|
||||||
text-align: center;
|
box-sizing: border-box;
|
||||||
box-sizing: border-box;
|
}
|
||||||
}
|
|
||||||
|
|
||||||
&__traffic {
|
.the-content {
|
||||||
position: absolute;
|
flex: 1 1 100%;
|
||||||
left: 0;
|
overflow: auto;
|
||||||
right: 0;
|
box-sizing: border-box;
|
||||||
bottom: 8px;
|
scrollbar-gutter: stable;
|
||||||
|
|
||||||
> div {
|
|
||||||
margin: 0 auto;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,13 +8,15 @@ import {
|
|||||||
LinearProgress,
|
LinearProgress,
|
||||||
IconButton,
|
IconButton,
|
||||||
keyframes,
|
keyframes,
|
||||||
|
MenuItem,
|
||||||
|
Menu,
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import { useSWRConfig } from "swr";
|
import { useSWRConfig } from "swr";
|
||||||
import { RefreshRounded } from "@mui/icons-material";
|
import { RefreshRounded } from "@mui/icons-material";
|
||||||
import { CmdType } from "../services/types";
|
import { CmdType } from "../services/types";
|
||||||
|
import { updateProfile, deleteProfile } from "../services/cmds";
|
||||||
import parseTraffic from "../utils/parse-traffic";
|
import parseTraffic from "../utils/parse-traffic";
|
||||||
import relativeTime from "dayjs/plugin/relativeTime";
|
import relativeTime from "dayjs/plugin/relativeTime";
|
||||||
import { updateProfile } from "../services/cmds";
|
|
||||||
|
|
||||||
dayjs.extend(relativeTime);
|
dayjs.extend(relativeTime);
|
||||||
|
|
||||||
@@ -46,6 +48,8 @@ const ProfileItemComp: React.FC<Props> = (props) => {
|
|||||||
|
|
||||||
const { mutate } = useSWRConfig();
|
const { mutate } = useSWRConfig();
|
||||||
const [loading, setLoading] = useState(false);
|
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 { name = "Profile", extra, updated = 0 } = itemData;
|
||||||
const { upload = 0, download = 0, total = 0 } = extra ?? {};
|
const { upload = 0, download = 0, total = 0 } = extra ?? {};
|
||||||
@@ -55,6 +59,7 @@ const ProfileItemComp: React.FC<Props> = (props) => {
|
|||||||
const fromnow = updated > 0 ? dayjs(updated * 1000).fromNow() : "";
|
const fromnow = updated > 0 ? dayjs(updated * 1000).fromNow() : "";
|
||||||
|
|
||||||
const onUpdate = async () => {
|
const onUpdate = async () => {
|
||||||
|
setAnchorEl(null);
|
||||||
if (loading) return;
|
if (loading) return;
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
@@ -67,98 +72,135 @@ const ProfileItemComp: React.FC<Props> = (props) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const onDelete = async () => {
|
||||||
|
setAnchorEl(null);
|
||||||
|
try {
|
||||||
|
await deleteProfile(index);
|
||||||
|
mutate("getProfiles");
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleContextMenu = (
|
||||||
|
event: React.MouseEvent<HTMLDivElement, MouseEvent>
|
||||||
|
) => {
|
||||||
|
const { clientX, clientY } = event;
|
||||||
|
setPosition({ top: clientY, left: clientX });
|
||||||
|
setAnchorEl(event.currentTarget);
|
||||||
|
event.preventDefault();
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Wrapper
|
<>
|
||||||
sx={({ palette }) => {
|
<Wrapper
|
||||||
const { mode, primary, text, grey } = palette;
|
sx={({ palette }) => {
|
||||||
const isDark = mode === "dark";
|
const { mode, primary, text, grey } = palette;
|
||||||
|
const key = `${mode}-${selected}`;
|
||||||
|
|
||||||
if (selected) {
|
const bgcolor = {
|
||||||
const bgcolor = isDark
|
"light-true": alpha(primary.main, 0.15),
|
||||||
? alpha(primary.main, 0.35)
|
"light-false": palette.background.paper,
|
||||||
: alpha(primary.main, 0.15);
|
"dark-true": alpha(primary.main, 0.35),
|
||||||
|
"dark-false": alpha(grey[700], 0.35),
|
||||||
|
}[key]!;
|
||||||
|
|
||||||
return {
|
const color = {
|
||||||
bgcolor,
|
"light-true": text.secondary,
|
||||||
color: isDark ? alpha(text.secondary, 0.6) : text.secondary,
|
"light-false": text.secondary,
|
||||||
"& h2": {
|
"dark-true": alpha(text.secondary, 0.6),
|
||||||
color: isDark ? primary.light : primary.main,
|
"dark-false": alpha(text.secondary, 0.6),
|
||||||
},
|
}[key]!;
|
||||||
};
|
|
||||||
}
|
|
||||||
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
|
const h2color = {
|
||||||
sx={{
|
"light-true": primary.main,
|
||||||
width: 30,
|
"light-false": text.primary,
|
||||||
height: 30,
|
"dark-true": primary.light,
|
||||||
animation: loading ? `1s linear infinite ${round}` : "none",
|
"dark-false": text.primary,
|
||||||
}}
|
}[key]!;
|
||||||
color="inherit"
|
|
||||||
disabled={loading}
|
|
||||||
onClick={(e) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
onUpdate();
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<RefreshRounded />
|
|
||||||
</IconButton>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Box display="flex" justifyContent="space-between" alignItems="center">
|
return { bgcolor, color, "& h2": { color: h2color } };
|
||||||
<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",
|
|
||||||
}}
|
}}
|
||||||
|
onClick={onClick}
|
||||||
|
onContextMenu={handleContextMenu}
|
||||||
>
|
>
|
||||||
<span title="used / total">
|
<Box display="flex" justifyContent="space-between">
|
||||||
{parseTraffic(upload + download)} / {parseTraffic(total)}
|
<Typography
|
||||||
</span>
|
width="calc(100% - 40px)"
|
||||||
<span title="expire time">{expire}</span>
|
variant="h6"
|
||||||
</Box>
|
component="h2"
|
||||||
|
noWrap
|
||||||
|
title={name}
|
||||||
|
>
|
||||||
|
{name}
|
||||||
|
</Typography>
|
||||||
|
|
||||||
<LinearProgress variant="determinate" value={progress} color="inherit" />
|
<IconButton
|
||||||
</Wrapper>
|
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>
|
||||||
|
|
||||||
|
<Menu
|
||||||
|
open={!!anchorEl}
|
||||||
|
anchorEl={anchorEl}
|
||||||
|
onClose={() => setAnchorEl(null)}
|
||||||
|
anchorPosition={position}
|
||||||
|
anchorReference="anchorPosition"
|
||||||
|
>
|
||||||
|
<MenuItem onClick={onUpdate}>Update</MenuItem>
|
||||||
|
<MenuItem onClick={onDelete}>Delete</MenuItem>
|
||||||
|
{/* <MenuItem>Update(proxy)</MenuItem> */}
|
||||||
|
</Menu>
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ import {
|
|||||||
} from "@mui/icons-material";
|
} from "@mui/icons-material";
|
||||||
import { updateProxy } from "../services/api";
|
import { updateProxy } from "../services/api";
|
||||||
import { ApiType } from "../services/types";
|
import { ApiType } from "../services/types";
|
||||||
|
import { getProfiles, patchProfile } from "../services/cmds";
|
||||||
|
|
||||||
interface ItemProps {
|
interface ItemProps {
|
||||||
proxy: ApiType.ProxyItem;
|
proxy: ApiType.ProxyItem;
|
||||||
@@ -86,6 +87,24 @@ const ProxyGroup = ({ group }: Props) => {
|
|||||||
try {
|
try {
|
||||||
setNow(name);
|
setNow(name);
|
||||||
await updateProxy(group.name, name);
|
await updateProxy(group.name, name);
|
||||||
|
|
||||||
|
const profiles = await getProfiles().catch(console.error);
|
||||||
|
if (!profiles) return;
|
||||||
|
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 };
|
||||||
|
}
|
||||||
|
|
||||||
|
patchProfile(profiles.current!, profile).catch(console.error);
|
||||||
} catch {
|
} catch {
|
||||||
setNow(oldValue);
|
setNow(oldValue);
|
||||||
// Todo
|
// Todo
|
||||||
|
|||||||
@@ -42,10 +42,12 @@ const SettingClash = ({ onError }: Props) => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<List>
|
<List>
|
||||||
<ListSubheader>Clash设置</ListSubheader>
|
<ListSubheader sx={{ background: "transparent" }}>
|
||||||
|
Clash Setting
|
||||||
|
</ListSubheader>
|
||||||
|
|
||||||
<SettingItem>
|
<SettingItem>
|
||||||
<ListItemText primary="局域网连接" />
|
<ListItemText primary="Allow Lan" />
|
||||||
<GuardState
|
<GuardState
|
||||||
value={allowLan}
|
value={allowLan}
|
||||||
valueProps="checked"
|
valueProps="checked"
|
||||||
@@ -73,7 +75,7 @@ const SettingClash = ({ onError }: Props) => {
|
|||||||
</SettingItem>
|
</SettingItem>
|
||||||
|
|
||||||
<SettingItem>
|
<SettingItem>
|
||||||
<ListItemText primary="日志等级" />
|
<ListItemText primary="Log Level" />
|
||||||
<GuardState
|
<GuardState
|
||||||
value={logLevel}
|
value={logLevel}
|
||||||
onCatch={onError}
|
onCatch={onError}
|
||||||
@@ -92,7 +94,7 @@ const SettingClash = ({ onError }: Props) => {
|
|||||||
</SettingItem>
|
</SettingItem>
|
||||||
|
|
||||||
<SettingItem>
|
<SettingItem>
|
||||||
<ListItemText primary="混合代理端口" />
|
<ListItemText primary="Mixed Port" />
|
||||||
<TextField
|
<TextField
|
||||||
size="small"
|
size="small"
|
||||||
value={mixedPort!}
|
value={mixedPort!}
|
||||||
|
|||||||
@@ -1,14 +1,19 @@
|
|||||||
import useSWR, { useSWRConfig } from "swr";
|
import useSWR, { useSWRConfig } from "swr";
|
||||||
import { List, ListItemText, ListSubheader, Switch } from "@mui/material";
|
|
||||||
import {
|
import {
|
||||||
getVergeConfig,
|
Box,
|
||||||
patchVergeConfig,
|
List,
|
||||||
setSysProxy,
|
ListItemText,
|
||||||
} from "../services/cmds";
|
ListSubheader,
|
||||||
|
Switch,
|
||||||
|
Typography,
|
||||||
|
} from "@mui/material";
|
||||||
|
import { getVergeConfig, patchVergeConfig } from "../services/cmds";
|
||||||
import { CmdType } from "../services/types";
|
import { CmdType } from "../services/types";
|
||||||
|
import { version } from "../../package.json";
|
||||||
import GuardState from "./guard-state";
|
import GuardState from "./guard-state";
|
||||||
import SettingItem from "./setting-item";
|
import SettingItem from "./setting-item";
|
||||||
import PaletteSwitch from "./palette-switch";
|
import PaletteSwitch from "./palette-switch";
|
||||||
|
import SysproxyTooltip from "./sysproxy-tooltip";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
onError?: (err: Error) => void;
|
onError?: (err: Error) => void;
|
||||||
@@ -20,68 +25,91 @@ const SettingVerge = ({ onError }: Props) => {
|
|||||||
|
|
||||||
const {
|
const {
|
||||||
theme_mode: mode = "light",
|
theme_mode: mode = "light",
|
||||||
|
theme_blur: blur = false,
|
||||||
enable_self_startup: startup = false,
|
enable_self_startup: startup = false,
|
||||||
enable_system_proxy: proxy = false,
|
enable_system_proxy: proxy = false,
|
||||||
} = vergeConfig ?? {};
|
} = vergeConfig ?? {};
|
||||||
|
|
||||||
const onSwitchFormat = (_e: any, value: boolean) => value;
|
const onSwitchFormat = (_e: any, value: boolean) => value;
|
||||||
|
|
||||||
const onChangeData = (patch: Partial<CmdType.VergeConfig>) => {
|
const onChangeData = (patch: Partial<CmdType.VergeConfig>) => {
|
||||||
mutate("getVergeConfig", { ...vergeConfig, ...patch }, false);
|
mutate("getVergeConfig", { ...vergeConfig, ...patch }, false);
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<List>
|
<List>
|
||||||
<ListSubheader>通用设置</ListSubheader>
|
<ListSubheader sx={{ background: "transparent" }}>
|
||||||
|
Common Setting
|
||||||
|
</ListSubheader>
|
||||||
|
|
||||||
<SettingItem>
|
<SettingItem>
|
||||||
<ListItemText primary="外观主题" />
|
<ListItemText primary="Theme Mode" />
|
||||||
<GuardState
|
<GuardState
|
||||||
value={mode === "dark"}
|
value={mode === "dark"}
|
||||||
valueProps="checked"
|
valueProps="checked"
|
||||||
onCatch={onError}
|
onCatch={onError}
|
||||||
onFormat={onSwitchFormat}
|
onFormat={onSwitchFormat}
|
||||||
onChange={(e) => onChangeData({ theme_mode: e ? "dark" : "light" })}
|
onChange={(e) => onChangeData({ theme_mode: e ? "dark" : "light" })}
|
||||||
onGuard={async (c) => {
|
onGuard={(c) =>
|
||||||
await patchVergeConfig({ theme_mode: c ? "dark" : "light" });
|
patchVergeConfig({ theme_mode: c ? "dark" : "light" })
|
||||||
}}
|
}
|
||||||
>
|
>
|
||||||
<PaletteSwitch edge="end" />
|
<PaletteSwitch edge="end" />
|
||||||
</GuardState>
|
</GuardState>
|
||||||
</SettingItem>
|
</SettingItem>
|
||||||
|
|
||||||
<SettingItem>
|
<SettingItem>
|
||||||
<ListItemText primary="开机自启" />
|
<ListItemText primary="Theme Blur" />
|
||||||
<GuardState
|
<GuardState
|
||||||
value={startup}
|
value={blur}
|
||||||
valueProps="checked"
|
valueProps="checked"
|
||||||
onCatch={onError}
|
onCatch={onError}
|
||||||
onFormat={onSwitchFormat}
|
onFormat={onSwitchFormat}
|
||||||
onChange={(e) => onChangeData({ enable_self_startup: e })}
|
onChange={(e) => onChangeData({ theme_blur: e })}
|
||||||
onGuard={async (e) => {
|
onGuard={(e) => patchVergeConfig({ theme_blur: e })}
|
||||||
await patchVergeConfig({ enable_self_startup: e });
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
<Switch edge="end" />
|
<Switch edge="end" />
|
||||||
</GuardState>
|
</GuardState>
|
||||||
</SettingItem>
|
</SettingItem>
|
||||||
|
|
||||||
<SettingItem>
|
<SettingItem>
|
||||||
<ListItemText primary="设置系统代理" />
|
<ListItemText primary="Self Startup" />
|
||||||
|
<GuardState
|
||||||
|
value={startup}
|
||||||
|
valueProps="checked"
|
||||||
|
onCatch={onError}
|
||||||
|
onFormat={onSwitchFormat}
|
||||||
|
onChange={(e) => onChangeData({ enable_self_startup: e })}
|
||||||
|
onGuard={(e) => patchVergeConfig({ enable_self_startup: e })}
|
||||||
|
>
|
||||||
|
<Switch edge="end" />
|
||||||
|
</GuardState>
|
||||||
|
</SettingItem>
|
||||||
|
|
||||||
|
<SettingItem>
|
||||||
|
<ListItemText
|
||||||
|
primary={
|
||||||
|
<Box sx={{ display: "flex", alignItems: "center" }}>
|
||||||
|
System Proxy
|
||||||
|
<SysproxyTooltip />
|
||||||
|
</Box>
|
||||||
|
}
|
||||||
|
/>
|
||||||
<GuardState
|
<GuardState
|
||||||
value={proxy}
|
value={proxy}
|
||||||
valueProps="checked"
|
valueProps="checked"
|
||||||
onCatch={onError}
|
onCatch={onError}
|
||||||
onFormat={onSwitchFormat}
|
onFormat={onSwitchFormat}
|
||||||
onChange={(e) => onChangeData({ enable_system_proxy: e })}
|
onChange={(e) => onChangeData({ enable_system_proxy: e })}
|
||||||
onGuard={async (e) => {
|
onGuard={(e) => patchVergeConfig({ enable_system_proxy: e })}
|
||||||
await setSysProxy(e);
|
|
||||||
await patchVergeConfig({ enable_system_proxy: e });
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
<Switch edge="end" />
|
<Switch edge="end" />
|
||||||
</GuardState>
|
</GuardState>
|
||||||
</SettingItem>
|
</SettingItem>
|
||||||
|
|
||||||
|
<SettingItem>
|
||||||
|
<ListItemText primary="Version" />
|
||||||
|
<Typography sx={{ py: "6px" }}>v{version}</Typography>
|
||||||
|
</SettingItem>
|
||||||
</List>
|
</List>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
53
src/components/sysproxy-tooltip.tsx
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
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();
|
||||||
|
console.log(data);
|
||||||
|
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;
|
||||||
66
src/components/update-dialog.tsx
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
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";
|
||||||
|
|
||||||
|
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 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;
|
||||||
@@ -1,85 +1,91 @@
|
|||||||
import { useEffect, useMemo } from "react";
|
import { useEffect, useMemo, useState } from "react";
|
||||||
import useSWR, { SWRConfig } from "swr";
|
import useSWR, { SWRConfig } from "swr";
|
||||||
import { Route, Routes } from "react-router-dom";
|
import { Route, Routes } from "react-router-dom";
|
||||||
import { useRecoilState } from "recoil";
|
import { useRecoilState } from "recoil";
|
||||||
import { createTheme, List, Paper, ThemeProvider } from "@mui/material";
|
import {
|
||||||
import { atomPaletteMode } from "../states/setting";
|
alpha,
|
||||||
import { getVergeConfig } from "../services/cmds";
|
Button,
|
||||||
|
createTheme,
|
||||||
|
IconButton,
|
||||||
|
List,
|
||||||
|
Paper,
|
||||||
|
ThemeProvider,
|
||||||
|
} from "@mui/material";
|
||||||
|
import { HorizontalRuleRounded, CloseRounded } from "@mui/icons-material";
|
||||||
|
import { checkUpdate } from "@tauri-apps/api/updater";
|
||||||
|
import { atomPaletteMode, atomThemeBlur } from "../states/setting";
|
||||||
|
import { getVergeConfig, windowDrag, windowHide } from "../services/cmds";
|
||||||
import LogoSvg from "../assets/image/logo.svg";
|
import LogoSvg from "../assets/image/logo.svg";
|
||||||
import LogPage from "./log";
|
import LogPage from "./log";
|
||||||
import HomePage from "./home";
|
|
||||||
import ProfilePage from "./profile";
|
import ProfilePage from "./profile";
|
||||||
import ProxyPage from "./proxy";
|
import ProxyPage from "./proxy";
|
||||||
import SettingPage from "./setting";
|
import SettingPage from "./setting";
|
||||||
import ConnectionsPage from "./connections";
|
import ConnectionsPage from "./connections";
|
||||||
import LayoutItem from "../components/layout-item";
|
import LayoutItem from "../components/layout-item";
|
||||||
import Traffic from "../components/traffic";
|
import Traffic from "../components/traffic";
|
||||||
|
import UpdateDialog from "../components/update-dialog";
|
||||||
|
|
||||||
const routers = [
|
const routers = [
|
||||||
{
|
{
|
||||||
label: "代理",
|
label: "Proxy",
|
||||||
link: "/proxy",
|
link: "/",
|
||||||
|
ele: ProxyPage,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: "配置",
|
label: "Profile",
|
||||||
link: "/profile",
|
link: "/profile",
|
||||||
|
ele: ProfilePage,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: "连接",
|
label: "Connections",
|
||||||
link: "/connections",
|
link: "/connections",
|
||||||
|
ele: ConnectionsPage,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: "日志",
|
label: "Log",
|
||||||
link: "/log",
|
link: "/log",
|
||||||
|
ele: LogPage,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: "设置",
|
label: "Setting",
|
||||||
link: "/setting",
|
link: "/setting",
|
||||||
|
ele: SettingPage,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
const Layout = () => {
|
const Layout = () => {
|
||||||
const [mode, setMode] = useRecoilState(atomPaletteMode);
|
const [mode, setMode] = useRecoilState(atomPaletteMode);
|
||||||
|
const [blur, setBlur] = useRecoilState(atomThemeBlur);
|
||||||
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
|
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
|
||||||
|
const { data: updateInfo } = useSWR("checkUpdate", checkUpdate, {
|
||||||
|
errorRetryCount: 2,
|
||||||
|
revalidateIfStale: false,
|
||||||
|
focusThrottleInterval: 36e5, // 1 hour
|
||||||
|
});
|
||||||
|
const [dialogOpen, setDialogOpen] = useState(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setMode(vergeConfig?.theme_mode ?? "light");
|
if (!vergeConfig) return;
|
||||||
}, [vergeConfig?.theme_mode]);
|
setBlur(!!vergeConfig.theme_blur);
|
||||||
|
setMode(vergeConfig.theme_mode ?? "light");
|
||||||
|
}, [vergeConfig]);
|
||||||
|
|
||||||
const theme = useMemo(() => {
|
const theme = useMemo(() => {
|
||||||
if (mode === "light") {
|
// const background = mode === "light" ? "#f5f5f5" : "#000";
|
||||||
document.documentElement.style.background = "#f5f5f5";
|
const selectColor = mode === "light" ? "#f5f5f5" : "#d5d5d5";
|
||||||
document.documentElement.style.setProperty(
|
|
||||||
"--selection-color",
|
const rootEle = document.documentElement;
|
||||||
"#f5f5f5"
|
rootEle.style.background = "transparent";
|
||||||
);
|
rootEle.style.setProperty("--selection-color", selectColor);
|
||||||
} else {
|
|
||||||
document.documentElement.style.background = "#000";
|
|
||||||
document.documentElement.style.setProperty(
|
|
||||||
"--selection-color",
|
|
||||||
"#d5d5d5"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return createTheme({
|
return createTheme({
|
||||||
breakpoints: {
|
breakpoints: {
|
||||||
values: {
|
values: { xs: 0, sm: 650, md: 900, lg: 1200, xl: 1536 },
|
||||||
xs: 0,
|
|
||||||
sm: 650,
|
|
||||||
md: 900,
|
|
||||||
lg: 1200,
|
|
||||||
xl: 1536,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
palette: {
|
palette: {
|
||||||
mode,
|
mode,
|
||||||
primary: {
|
primary: { main: "#5b5c9d" },
|
||||||
main: "#5b5c9d",
|
text: { primary: "#637381", secondary: "#909399" },
|
||||||
},
|
|
||||||
text: {
|
|
||||||
primary: "#637381",
|
|
||||||
secondary: "#909399",
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}, [mode]);
|
}, [mode]);
|
||||||
@@ -87,13 +93,42 @@ const Layout = () => {
|
|||||||
return (
|
return (
|
||||||
<SWRConfig value={{}}>
|
<SWRConfig value={{}}>
|
||||||
<ThemeProvider theme={theme}>
|
<ThemeProvider theme={theme}>
|
||||||
<Paper square elevation={0} className="layout">
|
<Paper
|
||||||
<div className="layout__sidebar">
|
square
|
||||||
<div className="layout__logo">
|
elevation={0}
|
||||||
<img src={LogoSvg} width="100%" alt="" />
|
className="layout"
|
||||||
|
sx={[
|
||||||
|
(theme) => ({
|
||||||
|
bgcolor: alpha(theme.palette.background.paper, blur ? 0.85 : 1),
|
||||||
|
}),
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<div className="layout__left">
|
||||||
|
<div className="the-logo">
|
||||||
|
<img
|
||||||
|
src={LogoSvg}
|
||||||
|
width="100%"
|
||||||
|
alt=""
|
||||||
|
onPointerDown={(e) => {
|
||||||
|
windowDrag();
|
||||||
|
e.preventDefault();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{updateInfo?.shouldUpdate && (
|
||||||
|
<Button
|
||||||
|
color="error"
|
||||||
|
variant="contained"
|
||||||
|
size="small"
|
||||||
|
className="the-newbtn"
|
||||||
|
onClick={() => setDialogOpen(true)}
|
||||||
|
>
|
||||||
|
New
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<List sx={{ userSelect: "none" }}>
|
<List className="the-menu">
|
||||||
{routers.map((router) => (
|
{routers.map((router) => (
|
||||||
<LayoutItem key={router.label} to={router.link}>
|
<LayoutItem key={router.label} to={router.link}>
|
||||||
{router.label}
|
{router.label}
|
||||||
@@ -101,22 +136,38 @@ const Layout = () => {
|
|||||||
))}
|
))}
|
||||||
</List>
|
</List>
|
||||||
|
|
||||||
<div className="layout__traffic">
|
<div className="the-traffic">
|
||||||
<Traffic />
|
<Traffic />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="layout__content">
|
<div className="layout__right">
|
||||||
<Routes>
|
<div
|
||||||
<Route path="/" element={<HomePage />} />
|
className="the-bar"
|
||||||
<Route path="/proxy" element={<ProxyPage />} />
|
onPointerDown={(e) =>
|
||||||
<Route path="/profile" element={<ProfilePage />} />
|
e.target === e.currentTarget && windowDrag()
|
||||||
<Route path="/log" element={<LogPage />} />
|
}
|
||||||
<Route path="/connections" element={<ConnectionsPage />} />
|
>
|
||||||
<Route path="/setting" element={<SettingPage />} />
|
{/* todo: onClick = windowMini */}
|
||||||
</Routes>
|
<IconButton size="small" sx={{ mx: 1 }} onClick={windowHide}>
|
||||||
|
<HorizontalRuleRounded fontSize="inherit" />
|
||||||
|
</IconButton>
|
||||||
|
|
||||||
|
<IconButton size="small" onClick={windowHide}>
|
||||||
|
<CloseRounded fontSize="inherit" />
|
||||||
|
</IconButton>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="the-content">
|
||||||
|
<Routes>
|
||||||
|
{routers.map(({ label, link, ele: Ele }) => (
|
||||||
|
<Route key={label} path={link} element={<Ele />} />
|
||||||
|
))}
|
||||||
|
</Routes>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</Paper>
|
</Paper>
|
||||||
|
<UpdateDialog open={dialogOpen} onClose={() => setDialogOpen(false)} />
|
||||||
</ThemeProvider>
|
</ThemeProvider>
|
||||||
</SWRConfig>
|
</SWRConfig>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -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,8 +1,13 @@
|
|||||||
import { useRef, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
import useSWR, { useSWRConfig } from "swr";
|
import useSWR, { useSWRConfig } from "swr";
|
||||||
import { Box, Button, Grid, TextField, Typography } from "@mui/material";
|
import { Box, Button, Grid, TextField, Typography } from "@mui/material";
|
||||||
import { getProfiles, importProfile, putProfiles } from "../services/cmds";
|
import {
|
||||||
import { getProxies } from "../services/api";
|
getProfiles,
|
||||||
|
selectProfile,
|
||||||
|
patchProfile,
|
||||||
|
importProfile,
|
||||||
|
} from "../services/cmds";
|
||||||
|
import { getProxies, updateProxy } from "../services/api";
|
||||||
import ProfileItemComp from "../components/profile-item";
|
import ProfileItemComp from "../components/profile-item";
|
||||||
import useNotice from "../utils/use-notice";
|
import useNotice from "../utils/use-notice";
|
||||||
import noop from "../utils/noop";
|
import noop from "../utils/noop";
|
||||||
@@ -15,6 +20,48 @@ const ProfilePage = () => {
|
|||||||
const { mutate } = useSWRConfig();
|
const { mutate } = useSWRConfig();
|
||||||
const { data: profiles = {} } = useSWR("getProfiles", getProfiles);
|
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 () => {
|
const onImport = async () => {
|
||||||
if (!url) return;
|
if (!url) return;
|
||||||
setUrl("");
|
setUrl("");
|
||||||
@@ -23,7 +70,7 @@ const ProfilePage = () => {
|
|||||||
try {
|
try {
|
||||||
await importProfile(url);
|
await importProfile(url);
|
||||||
mutate("getProfiles", getProfiles());
|
mutate("getProfiles", getProfiles());
|
||||||
if (!profiles.items?.length) putProfiles(0).catch(noop);
|
if (!profiles.items?.length) selectProfile(0).catch(noop);
|
||||||
notice.success("Successfully import profile.");
|
notice.success("Successfully import profile.");
|
||||||
} catch {
|
} catch {
|
||||||
notice.error("Failed to import profile.");
|
notice.error("Failed to import profile.");
|
||||||
@@ -34,12 +81,12 @@ const ProfilePage = () => {
|
|||||||
|
|
||||||
const lockRef = useRef(false);
|
const lockRef = useRef(false);
|
||||||
const onProfileChange = (index: number) => {
|
const onProfileChange = (index: number) => {
|
||||||
|
if (index === profiles.current || lockRef.current) return;
|
||||||
if (lockRef.current) return;
|
if (lockRef.current) return;
|
||||||
lockRef.current = true;
|
lockRef.current = true;
|
||||||
putProfiles(index)
|
selectProfile(index)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
mutate("getProfiles", { ...profiles, current: index }, true);
|
mutate("getProfiles", { ...profiles, current: index }, true);
|
||||||
mutate("getProxies", getProxies());
|
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch((err) => {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
|
|||||||
@@ -1,11 +1,21 @@
|
|||||||
import useSWR from "swr";
|
import useSWR, { useSWRConfig } from "swr";
|
||||||
|
import { useEffect } from "react";
|
||||||
import { Box, List, Paper, Typography } from "@mui/material";
|
import { Box, List, Paper, Typography } from "@mui/material";
|
||||||
import { getProxies } from "../services/api";
|
import { getProxies } from "../services/api";
|
||||||
import ProxyGroup from "../components/proxy-group";
|
import ProxyGroup from "../components/proxy-group";
|
||||||
|
|
||||||
const ProxyPage = () => {
|
const ProxyPage = () => {
|
||||||
const { data } = useSWR("getProxies", getProxies);
|
const { mutate } = useSWRConfig();
|
||||||
const { groups = [] } = data ?? {};
|
const { data: proxiesData } = useSWR("getProxies", getProxies);
|
||||||
|
const { groups = [] } = proxiesData ?? {};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
// fix the empty proxies on the first sight
|
||||||
|
// this bud only show on the build version
|
||||||
|
// call twice to avoid something unknown or the delay of the clash startup
|
||||||
|
setTimeout(() => mutate("getProxies"), 250);
|
||||||
|
setTimeout(() => mutate("getProxies"), 1000);
|
||||||
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box sx={{ width: 0.9, maxWidth: "850px", mx: "auto", mb: 2 }}>
|
<Box sx={{ width: 0.9, maxWidth: "850px", mx: "auto", mb: 2 }}>
|
||||||
|
|||||||
@@ -13,8 +13,8 @@ export async function getAxios() {
|
|||||||
try {
|
try {
|
||||||
const info = await getClashInfo();
|
const info = await getClashInfo();
|
||||||
|
|
||||||
if (info?.controller?.server) server = info?.controller?.server;
|
if (info?.server) server = info?.server;
|
||||||
if (info?.controller?.secret) secret = info?.controller?.secret;
|
if (info?.secret) secret = info?.secret;
|
||||||
} catch {}
|
} catch {}
|
||||||
|
|
||||||
axiosIns = axios.create({
|
axiosIns = axios.create({
|
||||||
@@ -29,7 +29,7 @@ export async function getAxios() {
|
|||||||
export async function getInfomation() {
|
export async function getInfomation() {
|
||||||
if (server) return { server, secret };
|
if (server) return { server, secret };
|
||||||
const info = await getClashInfo();
|
const info = await getClashInfo();
|
||||||
return info?.controller!;
|
return info!;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get Version
|
/// Get Version
|
||||||
|
|||||||
@@ -1,16 +1,12 @@
|
|||||||
import { invoke } from "@tauri-apps/api/tauri";
|
import { invoke } from "@tauri-apps/api/tauri";
|
||||||
import { ApiType, CmdType } from "./types";
|
import { ApiType, CmdType } from "./types";
|
||||||
|
|
||||||
export async function restartSidecar() {
|
export async function getProfiles() {
|
||||||
return invoke<void>("restart_sidecar");
|
return invoke<CmdType.ProfilesConfig>("get_profiles");
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getClashInfo() {
|
export async function syncProfiles() {
|
||||||
return invoke<CmdType.ClashInfo | null>("get_clash_info");
|
return invoke<void>("sync_profiles");
|
||||||
}
|
|
||||||
|
|
||||||
export async function patchClashConfig(payload: Partial<ApiType.ConfigData>) {
|
|
||||||
return invoke<void>("patch_clash_config", { payload });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function importProfile(url: string) {
|
export async function importProfile(url: string) {
|
||||||
@@ -21,23 +17,43 @@ export async function updateProfile(index: number) {
|
|||||||
return invoke<void>("update_profile", { index });
|
return invoke<void>("update_profile", { index });
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getProfiles() {
|
export async function deleteProfile(index: number) {
|
||||||
return (await invoke<CmdType.ProfilesConfig>("get_profiles")) ?? {};
|
return invoke<void>("delete_profile", { index });
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function setProfiles(
|
export async function patchProfile(
|
||||||
current: number,
|
index: number,
|
||||||
profile: CmdType.ProfileItem
|
profile: CmdType.ProfileItem
|
||||||
) {
|
) {
|
||||||
return invoke<void>("set_profiles", { current, profile });
|
return invoke<void>("patch_profile", { index, profile });
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function putProfiles(current: number) {
|
export async function selectProfile(index: number) {
|
||||||
return invoke<void>("put_profiles", { current });
|
return invoke<void>("select_profile", { index });
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function setSysProxy(enable: boolean) {
|
export async function restartSidecar() {
|
||||||
return invoke<void>("set_sys_proxy", { enable });
|
return invoke<void>("restart_sidecar");
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function windowDrag() {
|
||||||
|
return invoke<void>("win_drag");
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function windowHide() {
|
||||||
|
return invoke<void>("win_hide");
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function windowMini() {
|
||||||
|
return invoke<void>("win_mini");
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getClashInfo() {
|
||||||
|
return invoke<CmdType.ClashInfo | null>("get_clash_info");
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function patchClashConfig(payload: Partial<ApiType.ConfigData>) {
|
||||||
|
return invoke<void>("patch_clash_config", { payload });
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getVergeConfig() {
|
export async function getVergeConfig() {
|
||||||
@@ -47,3 +63,7 @@ export async function getVergeConfig() {
|
|||||||
export async function patchVergeConfig(payload: CmdType.VergeConfig) {
|
export async function patchVergeConfig(payload: CmdType.VergeConfig) {
|
||||||
return invoke<void>("patch_verge_config", { payload });
|
return invoke<void>("patch_verge_config", { payload });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function getSystemProxy() {
|
||||||
|
return invoke<any>("get_sys_proxy");
|
||||||
|
}
|
||||||
|
|||||||
@@ -80,8 +80,9 @@ export namespace ApiType {
|
|||||||
export namespace CmdType {
|
export namespace CmdType {
|
||||||
export interface ClashInfo {
|
export interface ClashInfo {
|
||||||
status: string;
|
status: string;
|
||||||
controller?: { server?: string; secret?: string };
|
port?: string;
|
||||||
message?: string;
|
server?: string;
|
||||||
|
secret?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ProfileItem {
|
export interface ProfileItem {
|
||||||
@@ -109,6 +110,7 @@ export namespace CmdType {
|
|||||||
|
|
||||||
export interface VergeConfig {
|
export interface VergeConfig {
|
||||||
theme_mode?: "light" | "dark";
|
theme_mode?: "light" | "dark";
|
||||||
|
theme_blur?: boolean;
|
||||||
enable_self_startup?: boolean;
|
enable_self_startup?: boolean;
|
||||||
enable_system_proxy?: boolean;
|
enable_system_proxy?: boolean;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,3 +4,8 @@ export const atomPaletteMode = atom<"light" | "dark">({
|
|||||||
key: "atomPaletteMode",
|
key: "atomPaletteMode",
|
||||||
default: "light",
|
default: "light",
|
||||||
});
|
});
|
||||||
|
|
||||||
|
export const atomThemeBlur = atom<boolean>({
|
||||||
|
key: "atomThemeBlur",
|
||||||
|
default: false,
|
||||||
|
});
|
||||||
|
|||||||