Compare commits
21 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
13e1ddbccd | ||
|
|
327b9a1757 | ||
|
|
18c48db7f7 | ||
|
|
b6543bd87f | ||
|
|
9ad8f71d7c | ||
|
|
e369311fc2 | ||
|
|
72ff261fe3 | ||
|
|
774c6f7e05 | ||
|
|
771af6ae08 | ||
|
|
b3cd207444 | ||
|
|
03f9fa4bc2 | ||
|
|
e32bfd9aab | ||
|
|
7e47f8f893 | ||
|
|
cb816e9653 | ||
|
|
6b3e7cbc08 | ||
|
|
db4993ae9b | ||
|
|
4dc3cf6c6b | ||
|
|
2b84bbf3a8 | ||
|
|
26ef4c9961 | ||
|
|
4f56c38599 | ||
|
|
240f4dcfb1 |
40
.github/workflows/release.yml
vendored
40
.github/workflows/release.yml
vendored
@@ -13,38 +13,42 @@ jobs:
|
|||||||
platform: [windows-latest]
|
platform: [windows-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:
|
||||||
|
|||||||
10
package.json
10
package.json
@@ -1,16 +1,17 @@
|
|||||||
{
|
{
|
||||||
"name": "clash-verge",
|
"name": "clash-verge",
|
||||||
"version": "0.0.4",
|
"version": "0.0.5",
|
||||||
"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",
|
||||||
"prepare": "husky install",
|
"check": "node scripts/check.mjs",
|
||||||
"predev": "node scripts/pre-dev.mjs",
|
"publish": "node scripts/publish.mjs",
|
||||||
"postversion": "node scripts/post-version.mjs"
|
"prepare": "husky install"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@emotion/react": "^11.7.0",
|
"@emotion/react": "^11.7.0",
|
||||||
@@ -29,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
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
import fs from "fs-extra";
|
|
||||||
import { createRequire } from "module";
|
|
||||||
import { execSync } from "child_process";
|
|
||||||
|
|
||||||
const require = createRequire(import.meta.url);
|
|
||||||
|
|
||||||
// update the tauri conf version
|
|
||||||
async function resolveVersion() {
|
|
||||||
const { version } = require("../package.json");
|
|
||||||
const tauri = require("../src-tauri/tauri.conf.json");
|
|
||||||
|
|
||||||
tauri.package.version = version;
|
|
||||||
|
|
||||||
await fs.writeFile(
|
|
||||||
"./src-tauri/tauri.conf.json",
|
|
||||||
JSON.stringify(tauri, undefined, 2)
|
|
||||||
);
|
|
||||||
execSync("git add ./src-tauri/tauri.conf.json");
|
|
||||||
execSync(`git commit -m v${version} --no-verify`);
|
|
||||||
execSync(`git push`);
|
|
||||||
execSync(`git push origin v${version}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
resolveVersion();
|
|
||||||
41
scripts/publish.mjs
Normal file
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();
|
||||||
1183
src-tauri/Cargo.lock
generated
1183
src-tauri/Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -18,7 +18,9 @@ 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"] }
|
||||||
|
|
||||||
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"
|
||||||
|
|||||||
238
src-tauri/src/cmds.rs
Normal file
238
src-tauri/src/cmds.rs
Normal file
@@ -0,0 +1,238 @@
|
|||||||
|
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::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),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// todo: need to check
|
||||||
|
/// delete profile item
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn delete_profile(index: usize, profiles: State<'_, ProfilesState>) -> Result<(), String> {
|
||||||
|
match profiles.0.lock() {
|
||||||
|
Ok(mut profiles) => profiles.delete_item(index),
|
||||||
|
Err(_) => Err("can not get profiles lock".into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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>) {
|
||||||
|
let mut clash_arc = clash_state.0.lock().unwrap();
|
||||||
|
if let Err(err) = clash_arc.restart_sidecar() {
|
||||||
|
log::error!("{}", 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)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// set the system proxy
|
||||||
|
/// Tips: only support windows now
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn set_sys_proxy(enable: bool, verge_state: State<'_, VergeState>) -> Result<(), String> {
|
||||||
|
let mut verge = verge_state.0.lock().unwrap();
|
||||||
|
|
||||||
|
if let Some(mut sysproxy) = verge.cur_sysproxy.take() {
|
||||||
|
sysproxy.enable = enable;
|
||||||
|
if sysproxy.set_sys().is_err() {
|
||||||
|
log::error!("failed to set system proxy");
|
||||||
|
}
|
||||||
|
verge.cur_sysproxy = Some(sysproxy);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// get the system proxy
|
||||||
|
/// Tips: only support windows now
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn get_sys_proxy() -> Result<SysProxyConfig, String> {
|
||||||
|
match SysProxyConfig::get_sys() {
|
||||||
|
Ok(value) => Ok(value),
|
||||||
|
Err(err) => Err(err.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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();
|
||||||
|
|
||||||
|
if payload.theme_mode.is_some() {
|
||||||
|
verge.config.theme_mode = payload.theme_mode;
|
||||||
|
}
|
||||||
|
|
||||||
|
if payload.enable_self_startup.is_some() {
|
||||||
|
verge.config.enable_self_startup = payload.enable_self_startup;
|
||||||
|
}
|
||||||
|
|
||||||
|
if payload.enable_system_proxy.is_some() {
|
||||||
|
verge.config.enable_system_proxy = payload.enable_system_proxy;
|
||||||
|
}
|
||||||
|
|
||||||
|
if payload.system_proxy_bypass.is_some() {
|
||||||
|
verge.config.system_proxy_bypass = payload.system_proxy_bypass;
|
||||||
|
}
|
||||||
|
|
||||||
|
verge.config.save_file()
|
||||||
|
}
|
||||||
@@ -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
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
311
src-tauri/src/core/profiles.rs
Normal file
311
src-tauri/src/core/profiles.rs
Normal file
@@ -0,0 +1,311 @@
|
|||||||
|
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<(), 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);
|
||||||
|
|
||||||
|
if current == index {
|
||||||
|
current = 0;
|
||||||
|
} else if current > index {
|
||||||
|
current = current - 1;
|
||||||
|
}
|
||||||
|
self.current = Some(current);
|
||||||
|
self.save_file()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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())),
|
||||||
|
}
|
||||||
|
}
|
||||||
93
src-tauri/src/core/verge.rs
Normal file
93
src-tauri/src/core/verge.rs
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
use crate::utils::{config, dirs, sysopt::SysProxyConfig};
|
||||||
|
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>,
|
||||||
|
}
|
||||||
|
|
||||||
|
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"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Verge {
|
||||||
|
pub config: VergeConfig,
|
||||||
|
|
||||||
|
pub old_sysproxy: Option<SysProxyConfig>,
|
||||||
|
|
||||||
|
pub cur_sysproxy: Option<SysProxyConfig>,
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,
|
||||||
};
|
};
|
||||||
@@ -26,14 +23,14 @@ 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", "显示应用"))
|
||||||
|
.add_item(CustomMenuItem::new("restart_clash", "重启clash"))
|
||||||
.add_native_item(SystemTrayMenuItem::Separator)
|
.add_native_item(SystemTrayMenuItem::Separator)
|
||||||
.add_item(CustomMenuItem::new("quit", "退出").accelerator("CmdOrControl+Q"));
|
.add_item(CustomMenuItem::new("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,13 @@ 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_arc = clash_state.0.lock().unwrap();
|
||||||
|
if let Err(err) = clash_arc.restart_sidecar() {
|
||||||
|
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 +62,21 @@ fn main() -> std::io::Result<()> {
|
|||||||
_ => {}
|
_ => {}
|
||||||
})
|
})
|
||||||
.invoke_handler(tauri::generate_handler![
|
.invoke_handler(tauri::generate_handler![
|
||||||
cmds::some::restart_sidecar,
|
cmds::restart_sidecar,
|
||||||
cmds::some::set_sys_proxy,
|
cmds::set_sys_proxy,
|
||||||
cmds::some::get_sys_proxy,
|
cmds::get_sys_proxy,
|
||||||
cmds::some::get_clash_info,
|
cmds::get_cur_proxy,
|
||||||
cmds::some::patch_clash_config,
|
cmds::get_clash_info,
|
||||||
cmds::some::get_verge_config,
|
cmds::patch_clash_config,
|
||||||
cmds::some::patch_verge_config,
|
cmds::get_verge_config,
|
||||||
cmds::profile::import_profile,
|
cmds::patch_verge_config,
|
||||||
cmds::profile::update_profile,
|
cmds::import_profile,
|
||||||
cmds::profile::get_profiles,
|
cmds::update_profile,
|
||||||
cmds::profile::set_profiles,
|
cmds::delete_profile,
|
||||||
cmds::profile::put_profiles,
|
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")
|
||||||
|
|||||||
11
src-tauri/src/states.rs
Normal file
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,8 +1,5 @@
|
|||||||
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;
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
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};
|
||||||
|
|
||||||
/// handle something when start app
|
/// handle something when start app
|
||||||
@@ -10,71 +10,31 @@ pub fn resolve_setup(app: &App) {
|
|||||||
// 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.init_sysproxy(clash.info.port.clone());
|
||||||
let mut some_arc = some_state.0.lock().unwrap();
|
|
||||||
*some_arc = original;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 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_arc = verge_state.0.lock().unwrap();
|
||||||
return;
|
|
||||||
}
|
verge_arc.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;
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::io;
|
use std::io;
|
||||||
|
|
||||||
|
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>";
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Serialize, Clone)]
|
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||||
pub struct SysProxyConfig {
|
pub struct SysProxyConfig {
|
||||||
pub enable: bool,
|
pub enable: bool,
|
||||||
@@ -18,16 +20,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;
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Get the windows system proxy config
|
/// Get the windows system proxy config
|
||||||
pub fn get_proxy_config() -> io::Result<SysProxyConfig> {
|
#[cfg(target_os = "windows")]
|
||||||
|
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 +48,38 @@ mod win {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[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")]
|
// #[cfg(target_os = "macos")]
|
||||||
mod macos {
|
// mod macos {
|
||||||
use super::*;
|
// use super::*;
|
||||||
|
|
||||||
pub fn get_proxy_config() -> io::Result<SysProxyConfig> {
|
// pub fn get_proxy_config() -> io::Result<SysProxyConfig> {
|
||||||
Ok(SysProxyConfig {
|
// Ok(SysProxyConfig {
|
||||||
enable: false,
|
// enable: false,
|
||||||
server: "server".into(),
|
// server: "server".into(),
|
||||||
bypass: "bypass".into(),
|
// bypass: "bypass".into(),
|
||||||
})
|
// })
|
||||||
}
|
// }
|
||||||
|
|
||||||
pub fn set_proxy_config(config: &SysProxyConfig) -> io::Result<()> {
|
// pub fn set_proxy_config(config: &SysProxyConfig) -> io::Result<()> {
|
||||||
Ok(())
|
// Ok(())
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
|
||||||
pub use win::*;
|
|
||||||
|
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
pub use macos::*;
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"package": {
|
"package": {
|
||||||
"productName": "clash-verge",
|
"productName": "clash-verge",
|
||||||
"version": "0.0.4"
|
"version": "0.0.5"
|
||||||
},
|
},
|
||||||
"build": {
|
"build": {
|
||||||
"distDir": "../dist",
|
"distDir": "../dist",
|
||||||
|
|||||||
@@ -16,8 +16,9 @@
|
|||||||
position: relative;
|
position: relative;
|
||||||
flex: 1 1 75%;
|
flex: 1 1 75%;
|
||||||
height: 100vh;
|
height: 100vh;
|
||||||
overflow: overlay;
|
overflow: auto;
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
|
scrollbar-gutter: "stable";
|
||||||
}
|
}
|
||||||
|
|
||||||
&__logo {
|
&__logo {
|
||||||
|
|||||||
@@ -22,8 +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, setProfiles } from "../services/cmds";
|
import { getProfiles, patchProfile } from "../services/cmds";
|
||||||
import noop from "../utils/noop";
|
|
||||||
|
|
||||||
interface ItemProps {
|
interface ItemProps {
|
||||||
proxy: ApiType.ProxyItem;
|
proxy: ApiType.ProxyItem;
|
||||||
@@ -105,7 +104,7 @@ const ProxyGroup = ({ group }: Props) => {
|
|||||||
profile.selected[index] = { name: group.name, now: name };
|
profile.selected[index] = { name: group.name, now: name };
|
||||||
}
|
}
|
||||||
|
|
||||||
setProfiles(profiles.current!, profile).catch(console.error);
|
patchProfile(profiles.current!, profile).catch(console.error);
|
||||||
} catch {
|
} catch {
|
||||||
setNow(oldValue);
|
setNow(oldValue);
|
||||||
// Todo
|
// Todo
|
||||||
|
|||||||
@@ -42,7 +42,9 @@ const SettingClash = ({ onError }: Props) => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<List>
|
<List>
|
||||||
<ListSubheader>Clash设置</ListSubheader>
|
<ListSubheader sx={{ background: "transparent" }}>
|
||||||
|
Clash设置
|
||||||
|
</ListSubheader>
|
||||||
|
|
||||||
<SettingItem>
|
<SettingItem>
|
||||||
<ListItemText primary="局域网连接" />
|
<ListItemText primary="局域网连接" />
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ const SettingVerge = ({ onError }: Props) => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<List>
|
<List>
|
||||||
<ListSubheader>通用设置</ListSubheader>
|
<ListSubheader sx={{ background: "transparent" }}>通用设置</ListSubheader>
|
||||||
|
|
||||||
<SettingItem>
|
<SettingItem>
|
||||||
<ListItemText primary="外观主题" />
|
<ListItemText primary="外观主题" />
|
||||||
|
|||||||
@@ -3,8 +3,8 @@ import useSWR, { useSWRConfig } from "swr";
|
|||||||
import { Box, Button, Grid, TextField, Typography } from "@mui/material";
|
import { Box, Button, Grid, TextField, Typography } from "@mui/material";
|
||||||
import {
|
import {
|
||||||
getProfiles,
|
getProfiles,
|
||||||
putProfiles,
|
selectProfile,
|
||||||
setProfiles,
|
patchProfile,
|
||||||
importProfile,
|
importProfile,
|
||||||
} from "../services/cmds";
|
} from "../services/cmds";
|
||||||
import { getProxies, updateProxy } from "../services/api";
|
import { getProxies, updateProxy } from "../services/api";
|
||||||
@@ -22,6 +22,7 @@ const ProfilePage = () => {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (profiles.current == null) return;
|
if (profiles.current == null) return;
|
||||||
|
if (!profiles.items) profiles.items = [];
|
||||||
|
|
||||||
const profile = profiles.items![profiles.current];
|
const profile = profiles.items![profiles.current];
|
||||||
if (!profile) return;
|
if (!profile) return;
|
||||||
@@ -51,7 +52,7 @@ const ProfilePage = () => {
|
|||||||
name,
|
name,
|
||||||
now,
|
now,
|
||||||
}));
|
}));
|
||||||
setProfiles(profiles.current!, profile).catch(console.error);
|
patchProfile(profiles.current!, profile).catch(console.error);
|
||||||
// update proxies cache
|
// update proxies cache
|
||||||
if (hasChange) mutate("getProxies", getProxies());
|
if (hasChange) mutate("getProxies", getProxies());
|
||||||
});
|
});
|
||||||
@@ -65,7 +66,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.");
|
||||||
@@ -76,9 +77,10 @@ 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);
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -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,6 +1,37 @@
|
|||||||
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 getProfiles() {
|
||||||
|
return invoke<CmdType.ProfilesConfig>("get_profiles");
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function syncProfiles() {
|
||||||
|
return invoke<void>("sync_profiles");
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function importProfile(url: string) {
|
||||||
|
return invoke<void>("import_profile", { url });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateProfile(index: number) {
|
||||||
|
return invoke<void>("update_profile", { index });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteProfile(index: number) {
|
||||||
|
return invoke<void>("delete_profile", { index });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function patchProfile(
|
||||||
|
index: number,
|
||||||
|
profile: CmdType.ProfileItem
|
||||||
|
) {
|
||||||
|
return invoke<void>("patch_profile", { index, profile });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function selectProfile(index: number) {
|
||||||
|
return invoke<void>("select_profile", { index });
|
||||||
|
}
|
||||||
|
|
||||||
export async function restartSidecar() {
|
export async function restartSidecar() {
|
||||||
return invoke<void>("restart_sidecar");
|
return invoke<void>("restart_sidecar");
|
||||||
}
|
}
|
||||||
@@ -13,26 +44,6 @@ export async function patchClashConfig(payload: Partial<ApiType.ConfigData>) {
|
|||||||
return invoke<void>("patch_clash_config", { payload });
|
return invoke<void>("patch_clash_config", { payload });
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function importProfile(url: string) {
|
|
||||||
return invoke<void>("import_profile", { url });
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function updateProfile(index: number) {
|
|
||||||
return invoke<void>("update_profile", { index });
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getProfiles() {
|
|
||||||
return (await invoke<CmdType.ProfilesConfig>("get_profiles")) ?? {};
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function setProfiles(index: number, profile: CmdType.ProfileItem) {
|
|
||||||
return invoke<void>("set_profiles", { index, profile });
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function putProfiles(current: number) {
|
|
||||||
return invoke<void>("put_profiles", { current });
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function setSysProxy(enable: boolean) {
|
export async function setSysProxy(enable: boolean) {
|
||||||
return invoke<void>("set_sys_proxy", { enable });
|
return invoke<void>("set_sys_proxy", { enable });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 {
|
||||||
|
|||||||
@@ -559,6 +559,13 @@
|
|||||||
"@types/node" "*"
|
"@types/node" "*"
|
||||||
"@types/responselike" "*"
|
"@types/responselike" "*"
|
||||||
|
|
||||||
|
"@types/fs-extra@^9.0.13":
|
||||||
|
version "9.0.13"
|
||||||
|
resolved "https://registry.yarnpkg.com/@types/fs-extra/-/fs-extra-9.0.13.tgz#7594fbae04fe7f1918ce8b3d213f74ff44ac1f45"
|
||||||
|
integrity sha512-nEnwB++1u5lVDM2UI4c1+5R+FYaKfaAzS4OococimjVm3nQw3TuzH5UNsocrcTBbhnerblyHj4A49qXbIiZdpA==
|
||||||
|
dependencies:
|
||||||
|
"@types/node" "*"
|
||||||
|
|
||||||
"@types/http-cache-semantics@*":
|
"@types/http-cache-semantics@*":
|
||||||
version "4.0.1"
|
version "4.0.1"
|
||||||
resolved "https://registry.yarnpkg.com/@types/http-cache-semantics/-/http-cache-semantics-4.0.1.tgz#0ea7b61496902b95890dc4c3a116b60cb8dae812"
|
resolved "https://registry.yarnpkg.com/@types/http-cache-semantics/-/http-cache-semantics-4.0.1.tgz#0ea7b61496902b95890dc4c3a116b60cb8dae812"
|
||||||
|
|||||||
Reference in New Issue
Block a user