22 Commits

Author SHA1 Message Date
GyDi
46ef348f0d v0.0.17 2022-02-22 02:08:31 +08:00
GyDi
1a55cca8af fix: reconnect websocket when restart clash 2022-02-22 02:05:22 +08:00
GyDi
81ee989f1f chore: enhance publish ci 2022-02-22 01:56:06 +08:00
GyDi
c9c06f8a3d fix: wrong exe path 2022-02-21 22:33:37 +08:00
GyDi
72127979c3 chore: use tauri cli 2022-02-21 22:31:00 +08:00
GyDi
1ad3ddef94 v0.0.16 2022-02-21 01:33:11 +08:00
GyDi
97ec5eabf7 feat: change window style 2022-02-20 23:46:13 +08:00
GyDi
e12e3a3f2d feat: fill verge template 2022-02-20 20:12:55 +08:00
GyDi
4ff625f23b feat: enable customize guard duration 2022-02-20 20:11:39 +08:00
GyDi
e38dcd85ac feat: system proxy guard 2022-02-20 18:53:21 +08:00
GyDi
0245baf1b6 feat: enable show or hide traffic graph 2022-02-19 18:14:40 +08:00
GyDi
10b55c043c fix: patch verge config 2022-02-19 17:32:23 +08:00
GyDi
457655b416 feat: traffic line graph 2022-02-19 17:02:24 +08:00
GyDi
7e4506c860 chore: update deps 2022-02-19 00:34:09 +08:00
GyDi
794d376348 feat: adjust profile item ui 2022-02-19 00:23:47 +08:00
GyDi
c60578f5b5 feat: adjust fetch profile url 2022-02-19 00:09:36 +08:00
GyDi
3a9a392a77 feat: inline config file template 2022-02-18 23:57:13 +08:00
GyDi
a13d4698be chore: update check script 2022-02-18 23:49:39 +08:00
GyDi
c046a1993e fix: fetch profile panic 2022-02-17 13:44:26 +08:00
GyDi
f709117cc4 feat: kill sidecars when update app 2022-02-17 02:10:25 +08:00
GyDi
30dd298fca feat: delete file 2022-02-17 01:58:12 +08:00
GyDi
0ff8bb8090 feat: lock some async functions 2022-02-17 01:42:25 +08:00
34 changed files with 1059 additions and 774 deletions

View File

@@ -1,4 +1,4 @@
name: CI name: Release CI
on: [push] on: [push]
@@ -53,7 +53,7 @@ jobs:
yarn run check yarn run check
- name: Tauri build - name: Tauri build
uses: tauri-apps/tauri-action@v0 uses: tauri-apps/tauri-action@b9ce5d7dc68082d21d30a60103b0ab8c5ddae3a1
# enable cache even though failed # enable cache even though failed
continue-on-error: true continue-on-error: true
env: env:
@@ -95,6 +95,5 @@ jobs:
- name: Release update.json - name: Release update.json
run: yarn run release run: yarn run release
continue-on-error: true
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -1,10 +1,10 @@
{ {
"name": "clash-verge", "name": "clash-verge",
"version": "0.0.15", "version": "0.0.17",
"license": "GPL-3.0", "license": "GPL-3.0",
"scripts": { "scripts": {
"dev": "cargo tauri dev", "dev": "tauri dev",
"build": "cargo tauri build", "build": "tauri build",
"tauri": "tauri", "tauri": "tauri",
"web:dev": "vite", "web:dev": "vite",
"web:build": "tsc && vite build", "web:build": "tsc && vite build",
@@ -32,7 +32,7 @@
}, },
"devDependencies": { "devDependencies": {
"@actions/github": "^5.0.0", "@actions/github": "^5.0.0",
"@tauri-apps/cli": "^1.0.0-rc.4", "@tauri-apps/cli": "^1.0.0-rc.5",
"@types/fs-extra": "^9.0.13", "@types/fs-extra": "^9.0.13",
"@types/js-cookie": "^3.0.1", "@types/js-cookie": "^3.0.1",
"@types/react": "^17.0.0", "@types/react": "^17.0.0",

View File

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

View File

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

48
src-tauri/Cargo.lock generated
View File

@@ -448,6 +448,7 @@ dependencies = [
"auto-launch", "auto-launch",
"chrono", "chrono",
"dirs", "dirs",
"dunce",
"log", "log",
"log4rs", "log4rs",
"port_scanner", "port_scanner",
@@ -868,6 +869,12 @@ dependencies = [
"dtoa", "dtoa",
] ]
[[package]]
name = "dunce"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "453440c271cf5577fd2a40e4942540cb7d0d2f85e27c8d07dd0023c925a67541"
[[package]] [[package]]
name = "easy-parallel" name = "easy-parallel"
version = "3.2.0" version = "3.2.0"
@@ -3510,10 +3517,11 @@ dependencies = [
[[package]] [[package]]
name = "tauri" name = "tauri"
version = "1.0.0-rc.2" version = "1.0.0-rc.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3571de0bcfd1f4f7599cbb3fe42f28ea9f52c3e89914ff04eaba68b5ee36bb51" checksum = "bb0c4a4ffd1f9b02cc3e974ce902f8132fb3d08ec6cce4ca193f97d921f5bce4"
dependencies = [ dependencies = [
"anyhow",
"attohttpc", "attohttpc",
"base64", "base64",
"bincode", "bincode",
@@ -3560,9 +3568,9 @@ dependencies = [
[[package]] [[package]]
name = "tauri-build" name = "tauri-build"
version = "1.0.0-rc.1" version = "1.0.0-rc.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a35ca6c70dce0dbe3441ab9e6d4ebae9a2315cfe8823662ac86cf517b22831e8" checksum = "855e47d8cfb2219fc14d2eed2c09bfb35f9ecd71a40ca2084aeeee2d23e0b60d"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"cargo_toml", "cargo_toml",
@@ -3573,9 +3581,9 @@ dependencies = [
[[package]] [[package]]
name = "tauri-codegen" name = "tauri-codegen"
version = "1.0.0-rc.1" version = "1.0.0-rc.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d06ecdbd6beaf7348259f82885742f013c0c96ac139445ec7c4b8050cd18349" checksum = "eef4656d174ba982198266da0c016573fe6c7c760e4290f05c8c384fe180007e"
dependencies = [ dependencies = [
"base64", "base64",
"blake3", "blake3",
@@ -3594,9 +3602,9 @@ dependencies = [
[[package]] [[package]]
name = "tauri-macros" name = "tauri-macros"
version = "1.0.0-rc.1" version = "1.0.0-rc.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba9ab86a4e81b31b227800c120b452dae137754e06d75b75c41c06cd06d301e2" checksum = "a0993f5a867e321d26200b2d6394cdf482bd6cc5a0e4691bcabf811544f51cd4"
dependencies = [ dependencies = [
"heck 0.4.0", "heck 0.4.0",
"proc-macro2", "proc-macro2",
@@ -3630,9 +3638,9 @@ dependencies = [
[[package]] [[package]]
name = "tauri-runtime" name = "tauri-runtime"
version = "0.3.1" version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c683b979ec4841b86048a282cd86afbc13b418a0f546904b27fad06e882ad5d7" checksum = "851cd65e2c9df4dd70a4f9e115fb2441ac89f1c80df79de0c15a448b4acd7768"
dependencies = [ dependencies = [
"gtk", "gtk",
"http", "http",
@@ -3649,9 +3657,9 @@ dependencies = [
[[package]] [[package]]
name = "tauri-runtime-wry" name = "tauri-runtime-wry"
version = "0.3.1" version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec025e7c906451fd7ff9e46d106a2e1b5b73e48013d13d52ffce614212b63fdc" checksum = "0184f95e065fb80afadf53f0a5f87a75af2da774d0524fe8cb2976fbec4a0bf2"
dependencies = [ dependencies = [
"gtk", "gtk",
"ico", "ico",
@@ -3667,9 +3675,9 @@ dependencies = [
[[package]] [[package]]
name = "tauri-utils" name = "tauri-utils"
version = "1.0.0-rc.1" version = "1.0.0-rc.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "abcbfec197c4cb959376607ac2fd99cecca02bd6d52b794bd882959501e34533" checksum = "0ad38ad698838886bf22ecb91c4b3d1ce178fdff7901ac7bff370103a4f51e59"
dependencies = [ dependencies = [
"ctor", "ctor",
"glob", "glob",
@@ -4309,9 +4317,9 @@ dependencies = [
[[package]] [[package]]
name = "webview2-com" name = "webview2-com"
version = "0.11.0" version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1975ce3573344c099935fe3903f1708dac69efe8539f1efee3ae54d8f9315fbb" checksum = "bb8e90ac2d9ce39cdb70017aaec641be09fbdd702b7b332b9896d053eb469524"
dependencies = [ dependencies = [
"webview2-com-macros", "webview2-com-macros",
"webview2-com-sys", "webview2-com-sys",
@@ -4332,9 +4340,9 @@ dependencies = [
[[package]] [[package]]
name = "webview2-com-sys" name = "webview2-com-sys"
version = "0.11.0" version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a746838a94b7391f707209a246e3436d81d1e71832126a65a897d3ee5511040" checksum = "92160310b3322397e4ff8a8285a7429d73a07a68fda44ee80879605b93e53f76"
dependencies = [ dependencies = [
"regex", "regex",
"serde", "serde",
@@ -4560,9 +4568,9 @@ dependencies = [
[[package]] [[package]]
name = "wry" name = "wry"
version = "0.13.1" version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "194b2750d8fe10fef189af5e2ca09e56cb8c5458a365d2b32842b024351f58c9" checksum = "620bfe8ed3cde9310f32a69ffc654dfd8dae4ac5a0e08d6fbf0205a996fc7f0f"
dependencies = [ dependencies = [
"cocoa", "cocoa",
"core-graphics", "core-graphics",

View File

@@ -10,15 +10,16 @@ edition = "2021"
build = "build.rs" build = "build.rs"
[build-dependencies] [build-dependencies]
tauri-build = { version = "1.0.0-rc.1", features = [] } tauri-build = { version = "1.0.0-rc.3", features = [] }
[dependencies] [dependencies]
dirs = "4.0.0" dirs = "4.0.0"
dunce = "1.0.2"
chrono = "0.4.19" chrono = "0.4.19"
serde_json = "1.0" serde_json = "1.0"
serde_yaml = "0.8" serde_yaml = "0.8"
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
tauri = { version = "1.0.0-rc.2", features = ["shell-all", "system-tray", "updater", "window-all"] } tauri = { version = "1.0.0-rc.3", features = ["shell-all", "system-tray", "updater", "window-all"] }
tauri-plugin-shadows = { git = "https://github.com/tauri-apps/tauri-plugin-shadows", features = ["tauri-impl"] } tauri-plugin-shadows = { git = "https://github.com/tauri-apps/tauri-plugin-shadows", features = ["tauri-impl"] }
tauri-plugin-vibrancy = { git = "https://github.com/tauri-apps/tauri-plugin-vibrancy", features = ["tauri-impl"] } tauri-plugin-vibrancy = { git = "https://github.com/tauri-apps/tauri-plugin-vibrancy", features = ["tauri-impl"] }

View File

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

View File

@@ -1,16 +0,0 @@
# Profile Template for clash verge
# the profile's name
name: New Profile
# the description of this profile(optional)
description:
# proxies defination (optional, the same as clash)
proxies:
# proxy-groups (optional, the same as clash)
proxy-groups:
# rules (optional, the same as clash)
rules:

View File

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

View File

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

View File

@@ -5,7 +5,7 @@ use crate::{
}; };
use serde_yaml::Mapping; use serde_yaml::Mapping;
use std::process::Command; use std::process::Command;
use tauri::State; use tauri::{api, State};
/// get all profiles from `profiles.yaml` /// get all profiles from `profiles.yaml`
/// do not acquire the lock of ProfileLock /// do not acquire the lock of ProfileLock
@@ -34,13 +34,9 @@ pub async fn import_profile(
with_proxy: bool, with_proxy: bool,
profiles_state: State<'_, ProfilesState>, profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> { ) -> Result<(), String> {
match fetch_profile(&url, with_proxy).await { let result = fetch_profile(&url, with_proxy).await?;
Some(result) => { let mut profiles = profiles_state.0.lock().unwrap();
let mut profiles = profiles_state.0.lock().unwrap(); profiles.import_from_url(url, result)
profiles.import_from_url(url, result)
}
None => Err(format!("failed to fetch profile from `{}`", url)),
}
} }
/// new a profile /// new a profile
@@ -82,23 +78,22 @@ pub async fn update_profile(
Err(_) => return Err("failed to get profiles lock".into()), Err(_) => return Err("failed to get profiles lock".into()),
}; };
match fetch_profile(&url, with_proxy).await { let result = fetch_profile(&url, with_proxy).await?;
Some(result) => match profiles_state.0.lock() {
Ok(mut profiles) => {
profiles.update_item(index, result)?;
// reactivate the profile match profiles_state.0.lock() {
let current = profiles.current.clone().unwrap_or(0); Ok(mut profiles) => {
if current == index { profiles.update_item(index, result)?;
let clash = clash_state.0.lock().unwrap();
profiles.activate(&clash) // reactivate the profile
} else { let current = profiles.current.clone().unwrap_or(0);
Ok(()) if current == index {
} let clash = clash_state.0.lock().unwrap();
profiles.activate(&clash)
} else {
Ok(())
} }
Err(_) => Err("failed to get profiles lock".into()), }
}, Err(_) => Err("failed to get profiles lock".into()),
None => Err(format!("failed to fetch profile from `{}`", url)),
} }
} }
@@ -265,7 +260,7 @@ pub fn get_verge_config(verge_state: State<'_, VergeState>) -> Result<VergeConfi
/// patch the verge config /// patch the verge config
/// this command only save the config and not responsible for other things /// this command only save the config and not responsible for other things
#[tauri::command] #[tauri::command]
pub async fn patch_verge_config( pub fn patch_verge_config(
payload: VergeConfig, payload: VergeConfig,
verge_state: State<'_, VergeState>, verge_state: State<'_, VergeState>,
) -> Result<(), String> { ) -> Result<(), String> {
@@ -273,6 +268,12 @@ pub async fn patch_verge_config(
verge.patch_config(payload) verge.patch_config(payload)
} }
/// kill all sidecars when update app
#[tauri::command]
pub fn kill_sidecars() {
api::process::kill_children();
}
/// open app config dir /// open app config dir
#[tauri::command] #[tauri::command]
pub fn open_app_dir() -> Result<(), String> { pub fn open_app_dir() -> Result<(), String> {

View File

@@ -1,11 +1,11 @@
use super::{Clash, ClashInfo}; use super::{Clash, ClashInfo};
use crate::utils::{config, dirs}; use crate::utils::{config, dirs, tmpl};
use reqwest::header::HeaderMap; use reqwest::header::HeaderMap;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_yaml::{Mapping, Value}; use serde_yaml::{Mapping, Value};
use std::collections::HashMap; use std::collections::HashMap;
use std::env::temp_dir; use std::env::temp_dir;
use std::fs::File; use std::fs::{remove_file, File};
use std::io::Write; use std::io::Write;
use std::path::PathBuf; use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH}; use std::time::{SystemTime, UNIX_EPOCH};
@@ -60,7 +60,7 @@ pub struct ProfileResponse {
pub name: String, pub name: String,
pub file: String, pub file: String,
pub data: String, pub data: String,
pub extra: ProfileExtra, pub extra: Option<ProfileExtra>,
} }
static PROFILE_YAML: &str = "profiles.yaml"; static PROFILE_YAML: &str = "profiles.yaml";
@@ -117,7 +117,7 @@ impl Profiles {
mode: Some(format!("rule")), mode: Some(format!("rule")),
url: Some(url), url: Some(url),
selected: Some(vec![]), selected: Some(vec![]),
extra: Some(result.extra), extra: result.extra,
updated: Some(now as usize), updated: Some(now as usize),
}); });
@@ -155,16 +155,7 @@ impl Profiles {
let file = format!("{}.yaml", now); let file = format!("{}.yaml", now);
let path = dirs::app_home_dir().join("profiles").join(&file); let path = dirs::app_home_dir().join("profiles").join(&file);
let file_data = b"# Profile Template for clash verge\n match File::create(&path).unwrap().write(tmpl::ITEM_CONFIG) {
# proxies defination (optional, the same as clash)
proxies:\n
# proxy-groups (optional, the same as clash)
proxy-groups:\n
# rules (optional, the same as clash)
rules:\n\n
";
match File::create(&path).unwrap().write(file_data) {
Ok(_) => { Ok(_) => {
items.push(ProfileItem { items.push(ProfileItem {
name: Some(name), name: Some(name),
@@ -203,7 +194,7 @@ rules:\n\n
File::create(file_path).unwrap().write(file_data).unwrap(); File::create(file_path).unwrap().write(file_data).unwrap();
items[index].name = Some(result.name); items[index].name = Some(result.name);
items[index].extra = Some(result.extra); items[index].extra = result.extra;
items[index].updated = Some(now); items[index].updated = Some(now);
self.items = Some(items); self.items = Some(items);
@@ -249,7 +240,18 @@ rules:\n\n
return Err("index out of bound".into()); return Err("index out of bound".into());
} }
items.remove(index); let mut rm_item = items.remove(index);
// delete the file
if let Some(file) = rm_item.file.take() {
let file_path = dirs::app_home_dir().join("profiles").join(file);
if file_path.exists() {
if let Err(err) = remove_file(file_path) {
log::error!("{err}");
}
}
}
let mut should_change = false; let mut should_change = false;

View File

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

View File

@@ -74,6 +74,7 @@ fn main() -> std::io::Result<()> {
cmds::restart_sidecar, cmds::restart_sidecar,
cmds::get_sys_proxy, cmds::get_sys_proxy,
cmds::get_cur_proxy, cmds::get_cur_proxy,
cmds::kill_sidecars,
cmds::open_app_dir, cmds::open_app_dir,
cmds::open_logs_dir, cmds::open_logs_dir,
// clash // clash

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,7 +1,7 @@
{ {
"package": { "package": {
"productName": "clash-verge", "productName": "clash-verge",
"version": "0.0.15" "version": "0.0.17"
}, },
"build": { "build": {
"distDir": "../dist", "distDir": "../dist",

View File

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

View File

@@ -20,8 +20,8 @@
position: relative; position: relative;
flex: 0 1 180px; flex: 0 1 180px;
width: 100%; width: 100%;
max-width: 180px; max-width: 168px;
max-height: 180px; max-height: 168px;
margin: 0 auto; margin: 0 auto;
padding: 0 8px; padding: 0 8px;
text-align: center; text-align: center;
@@ -79,3 +79,9 @@
} }
} }
} }
.macos.layout {
.layout__right .the-content {
top: 0;
}
}

View File

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

View File

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

View File

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

View File

@@ -59,8 +59,11 @@ const ProfileItem: React.FC<Props> = (props) => {
const progress = Math.round(((download + upload) * 100) / (total + 0.1)); const progress = Math.round(((download + upload) * 100) / (total + 0.1));
const fromnow = updated > 0 ? dayjs(updated * 1000).fromNow() : ""; const fromnow = updated > 0 ? dayjs(updated * 1000).fromNow() : "";
// url or file mode // local file mode
const isUrlMode = itemData.url && extra; // remote file mode
// subscription url mode
const hasUrl = !!itemData.url;
const hasExtra = !!extra; // only subscription url has extra info
const onView = async () => { const onView = async () => {
setAnchorEl(null); setAnchorEl(null);
@@ -178,7 +181,8 @@ const ProfileItem: React.FC<Props> = (props) => {
{name} {name}
</Typography> </Typography>
{isUrlMode && ( {/* only if has url can it be updated */}
{hasUrl && (
<IconButton <IconButton
sx={{ sx={{
width: 26, width: 26,
@@ -197,43 +201,43 @@ const ProfileItem: React.FC<Props> = (props) => {
)} )}
</Box> </Box>
{isUrlMode ? ( {/* the second line show url's info or description */}
<> {hasUrl ? (
<Box sx={boxStyle}> <Box sx={boxStyle}>
<Typography noWrap title={`From: ${from}`}> <Typography noWrap title={`From: ${from}`}>
{from} {from}
</Typography> </Typography>
<Typography <Typography
noWrap noWrap
flex="1 0 auto" flex="1 0 auto"
fontSize={14} fontSize={14}
textAlign="right" textAlign="right"
title="updated time" title="updated time"
> >
{fromnow} {fromnow}
</Typography> </Typography>
</Box> </Box>
<Box sx={{ ...boxStyle, fontSize: 14 }}>
<span title="used / total">
{parseTraffic(upload + download)} / {parseTraffic(total)}
</span>
<span title="expire time">{expire}</span>
</Box>
</>
) : ( ) : (
<> <Box sx={boxStyle}>
<Box sx={boxStyle}> <Typography noWrap title={itemData.desc}>
<Typography noWrap title={itemData.desc}> {itemData.desc}
{itemData.desc} </Typography>
</Typography> </Box>
</Box> )}
<Box sx={{ ...boxStyle, fontSize: 14, justifyContent: "flex-end" }}> {/* the third line show extra info or last updated time */}
<span title="updated time">{parseExpire(updated)}</span> {hasExtra ? (
</Box> <Box sx={{ ...boxStyle, fontSize: 14 }}>
</> <span title="used / total">
{parseTraffic(upload + download)} / {parseTraffic(total)}
</span>
<span title="expire time">{expire}</span>
</Box>
) : (
<Box sx={{ ...boxStyle, fontSize: 14, justifyContent: "flex-end" }}>
<span title="updated time">{parseExpire(updated)}</span>
</Box>
)} )}
<LinearProgress <LinearProgress
@@ -250,8 +254,12 @@ const ProfileItem: React.FC<Props> = (props) => {
anchorPosition={position} anchorPosition={position}
anchorReference="anchorPosition" anchorReference="anchorPosition"
> >
{(isUrlMode ? urlModeMenu : fileModeMenu).map((item) => ( {(hasUrl ? urlModeMenu : fileModeMenu).map((item) => (
<MenuItem key={item.label} onClick={item.handler}> <MenuItem
key={item.label}
onClick={item.handler}
sx={{ minWidth: 133 }}
>
{item.label} {item.label}
</MenuItem> </MenuItem>
))} ))}

View File

@@ -29,27 +29,33 @@ interface Props {
const ProxyGroup = ({ group }: Props) => { const ProxyGroup = ({ group }: Props) => {
const { mutate } = useSWRConfig(); const { mutate } = useSWRConfig();
const listRef = useRef<any>();
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [now, setNow] = useState(group.now); const [now, setNow] = useState(group.now);
const virtuosoRef = useRef<any>();
const proxies = group.all ?? []; const proxies = group.all ?? [];
const selectLockRef = useRef(false);
const onSelect = async (name: string) => { const onSelect = async (name: string) => {
// can not call update // Todo: support another proxy group type
if (group.type !== "Selector") { if (group.type !== "Selector") return;
// Todo
// error Tips if (selectLockRef.current) return;
return; selectLockRef.current = true;
}
const oldValue = now; const oldValue = now;
try { try {
setNow(name); setNow(name);
await updateProxy(group.name, name); await updateProxy(group.name, name);
} catch {
setNow(oldValue);
return; // do not update profile
} finally {
selectLockRef.current = false;
}
const profiles = await getProfiles().catch(console.error); try {
if (!profiles) return; const profiles = await getProfiles();
const profile = profiles.items![profiles.current!]!; const profile = profiles.items![profiles.current!]!;
if (!profile) return; if (!profile) return;
if (!profile.selected) profile.selected = []; if (!profile.selected) profile.selected = [];
@@ -63,12 +69,9 @@ const ProxyGroup = ({ group }: Props) => {
} else { } else {
profile.selected[index] = { name: group.name, now: name }; profile.selected[index] = { name: group.name, now: name };
} }
await patchProfile(profiles.current!, profile);
patchProfile(profiles.current!, profile).catch(console.error); } catch (err) {
} catch { console.error(err);
setNow(oldValue);
// Todo
// error tips
} }
}; };
@@ -76,7 +79,7 @@ const ProxyGroup = ({ group }: Props) => {
const index = proxies.findIndex((p) => p.name === now); const index = proxies.findIndex((p) => p.name === now);
if (index >= 0) { if (index >= 0) {
listRef.current?.scrollToIndex?.({ virtuosoRef.current?.scrollToIndex?.({
index, index,
align: "center", align: "center",
behavior: "smooth", behavior: "smooth",
@@ -84,12 +87,18 @@ const ProxyGroup = ({ group }: Props) => {
} }
}; };
const checkLockRef = useRef(false);
const onCheckAll = async () => { const onCheckAll = async () => {
let names = proxies.map((p) => p.name); if (checkLockRef.current) return;
checkLockRef.current = true;
// rerender quickly
if (proxies.length) setTimeout(() => mutate("getProxies"), 500);
let names = proxies.map((p) => p.name);
while (names.length) { while (names.length) {
const list = names.slice(0, 10); const list = names.slice(0, 8);
names = names.slice(10); names = names.slice(8);
await Promise.all( await Promise.all(
list.map((n) => delayManager.checkDelay(n, group.name)) list.map((n) => delayManager.checkDelay(n, group.name))
@@ -97,6 +106,8 @@ const ProxyGroup = ({ group }: Props) => {
mutate("getProxies"); mutate("getProxies");
} }
checkLockRef.current = false;
}; };
return ( return (
@@ -130,7 +141,7 @@ const ProxyGroup = ({ group }: Props) => {
{proxies.length >= 10 ? ( {proxies.length >= 10 ? (
<Virtuoso <Virtuoso
ref={listRef} ref={virtuosoRef}
style={{ height: "320px", marginBottom: "4px" }} style={{ height: "320px", marginBottom: "4px" }}
totalCount={proxies.length} totalCount={proxies.length}
itemContent={(index) => ( itemContent={(index) => (

View File

@@ -15,9 +15,10 @@ const SettingSystem = ({ onError }: Props) => {
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig); const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
const { const {
enable_auto_launch: startup = false, enable_auto_launch = false,
enable_system_proxy: proxy = false, enable_system_proxy = false,
system_proxy_bypass: bypass = "", system_proxy_bypass = "",
enable_proxy_guard = false,
} = vergeConfig ?? {}; } = vergeConfig ?? {};
const onSwitchFormat = (_e: any, value: boolean) => value; const onSwitchFormat = (_e: any, value: boolean) => value;
@@ -30,7 +31,7 @@ const SettingSystem = ({ onError }: Props) => {
<SettingItem> <SettingItem>
<ListItemText primary="Auto Launch" /> <ListItemText primary="Auto Launch" />
<GuardState <GuardState
value={startup} value={enable_auto_launch}
valueProps="checked" valueProps="checked"
onCatch={onError} onCatch={onError}
onFormat={onSwitchFormat} onFormat={onSwitchFormat}
@@ -51,7 +52,7 @@ const SettingSystem = ({ onError }: Props) => {
} }
/> />
<GuardState <GuardState
value={proxy} value={enable_system_proxy}
valueProps="checked" valueProps="checked"
onCatch={onError} onCatch={onError}
onFormat={onSwitchFormat} onFormat={onSwitchFormat}
@@ -65,11 +66,27 @@ const SettingSystem = ({ onError }: Props) => {
</GuardState> </GuardState>
</SettingItem> </SettingItem>
{proxy && ( {enable_system_proxy && (
<SettingItem>
<ListItemText primary="Proxy Guard" />
<GuardState
value={enable_proxy_guard}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_proxy_guard: e })}
onGuard={(e) => patchVergeConfig({ enable_proxy_guard: e })}
>
<Switch edge="end" />
</GuardState>
</SettingItem>
)}
{enable_system_proxy && (
<SettingItem> <SettingItem>
<ListItemText primary="Proxy Bypass" /> <ListItemText primary="Proxy Bypass" />
<GuardState <GuardState
value={bypass ?? ""} value={system_proxy_bypass ?? ""}
onCatch={onError} onCatch={onError}
onFormat={(e: any) => e.target.value} onFormat={(e: any) => e.target.value}
onChange={(e) => onChangeData({ system_proxy_bypass: e })} onChange={(e) => onChangeData({ system_proxy_bypass: e })}

View File

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

View File

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

View File

@@ -64,6 +64,10 @@ export async function getSystemProxy() {
return invoke<any>("get_sys_proxy"); return invoke<any>("get_sys_proxy");
} }
export async function killSidecars() {
return invoke<any>("kill_sidecars");
}
export async function openAppDir() { export async function openAppDir() {
return invoke<void>("open_app_dir"); return invoke<void>("open_app_dir");
} }

View File

@@ -112,8 +112,10 @@ export namespace CmdType {
export interface VergeConfig { export interface VergeConfig {
theme_mode?: "light" | "dark"; theme_mode?: "light" | "dark";
theme_blur?: boolean; theme_blur?: boolean;
traffic_graph?: boolean;
enable_auto_launch?: boolean; enable_auto_launch?: boolean;
enable_system_proxy?: boolean; enable_system_proxy?: boolean;
enable_proxy_guard?: boolean;
system_proxy_bypass?: string; system_proxy_bypass?: string;
} }
} }

View File

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

685
yarn.lock

File diff suppressed because it is too large Load Diff