Compare commits

...
68 Commits
Author SHA1 Message Date
GyDi 91c14211c6 chore: continue on error 2022-05-11 01:26:11 +08:00
GyDi 1ea07c458b chore: test linux 2022-05-11 00:52:20 +08:00
GyDi 591add6e0c chore: test ci 2022-05-11 00:31:19 +08:00
GyDi b99fff66df v1.0.1 2022-05-10 21:40:33 +08:00
GyDi f54ba05b00 chore: update log 2022-05-10 21:40:07 +08:00
GyDi 6596fb00c7 fix: win11 drag lag 2022-05-09 14:41:26 +08:00
GyDi df0b5a80dc chore: change default height 2022-05-09 14:01:46 +08:00
GyDi 8cdbb31dbe fix: rm unwrap 2022-05-09 14:01:14 +08:00
GyDi 0be4b1222d feat: reduce gpu usage when hidden 2022-05-07 14:43:52 +08:00
GyDi 18a6bfd73a feat: interval update from now field 2022-05-07 14:43:08 +08:00
GyDi 5e2271b237 feat: adjust theme 2022-05-06 14:04:39 +08:00
GyDi 798999d490 fix: edit profile info 2022-05-06 12:46:27 +08:00
GyDi 0e68c5e8bc feat: supports more remote headers close #81 2022-05-06 10:52:59 +08:00
GyDi 9694af82f4 feat: check the remote profile 2022-05-06 01:26:24 +08:00
GyDi 28a4386975 fix: change window default size 2022-05-06 01:15:15 +08:00
GyDi a238f7beba chore: update deps 2022-05-06 01:14:13 +08:00
GyDi 75ba16281b chore: change default user agent 2022-05-06 00:42:20 +08:00
GyDi ad65a278d4 chore: merge
feat: remove outdated config
2022-04-28 16:28:18 +08:00
tianyoulan a2320b3f8d feat: fix typo 2022-04-28 15:35:17 +08:00
tianyoulan ae12853ad0 feat: remove trailing comma 2022-04-28 15:05:10 +08:00
tianyoulan 68adf6dc2f feat: remove outdated config 2022-04-28 15:02:37 +08:00
GyDi f88989bd4b fix: change service installer and uninstaller 2022-04-27 15:46:44 +08:00
GyDi 77ef3847ce v1.0.0 2022-04-26 00:50:48 +08:00
GyDi b8291837fc chore: update log 2022-04-26 00:49:07 +08:00
GyDi 423a7f951a fix: adjust connection scroll 2022-04-26 00:37:28 +08:00
GyDi 557f5fe364 fix: adjust something 2022-04-25 20:00:11 +08:00
GyDi 5308970ad8 fix: adjust debounce wait time 2022-04-25 19:39:21 +08:00
GyDi 6b368953f4 feat: windows service mode ui 2022-04-25 16:12:04 +08:00
GyDi 2d0b63c29d feat: add some commands 2022-04-24 21:03:47 +08:00
GyDi 34e941c8cb feat: windows service mode 2022-04-24 21:00:17 +08:00
GyDi 76cf007fff chore: update check script 2022-04-24 15:35:30 +08:00
GyDi 321963be83 wip: windows service mode 2022-04-23 17:26:32 +08:00
GyDi c733bda6c3 test: windows service 2022-04-21 21:28:44 +08:00
GyDi e67b50b976 chore: adjust guard log 2022-04-21 19:51:20 +08:00
GyDi 9e3c080909 fix: adjust dns config 2022-04-21 19:50:22 +08:00
GyDi cb661aaebd feat: add update interval 2022-04-21 14:26:41 +08:00
GyDi 573571978c chore: adjust 2022-04-21 14:24:35 +08:00
GyDi dc492a2a0a chore: update clash version 2022-04-20 21:02:41 +08:00
GyDi e47747dd0e feat: refactor and supports cron tasks 2022-04-20 20:39:27 +08:00
GyDi 4de944b41e feat: supports cron update profiles 2022-04-20 20:37:16 +08:00
GyDi 5f7a1fa5cd refactor: verge 2022-04-20 11:17:54 +08:00
GyDi b8ad328cde refactor: wip 2022-04-20 01:44:47 +08:00
GyDi 3076fd19c1 refactor: mutex 2022-04-19 14:38:59 +08:00
GyDi fac437b8c1 fix: traffic graph adapt to different fps 2022-04-19 13:55:26 +08:00
GyDi 697c25015e refactor: wip 2022-04-19 01:41:20 +08:00
GyDi d83b404fc3 chore: check script proxy agent supports 2022-04-17 00:37:21 +08:00
GyDi ab7313cbc4 feat: optimize traffic graph quadratic curve 2022-04-16 22:32:44 +08:00
GyDi 1b8d70322b feat: optimize the animation of the traffic graph 2022-04-16 17:28:30 +08:00
GyDi 844ffab4ed fix: optimize clash launch 2022-04-15 01:29:25 +08:00
GyDi f5d0513d1f fix: reset after exit 2022-04-14 01:29:33 +08:00
GyDi 557abd4285 fix: adjust code 2022-04-14 01:29:02 +08:00
GyDi f4f1a0fbc6 v0.0.29 2022-04-13 01:30:08 +08:00
GyDi 74e10dc012 chore: update log 2022-04-13 01:29:48 +08:00
GyDi 359812b7ed chore: update dep 2022-04-13 01:21:49 +08:00
GyDi c2449e53c4 chore: rename green to portable 2022-04-13 01:17:40 +08:00
GyDi 1a91249da2 feat: system tray add tun mode 2022-04-13 01:09:51 +08:00
GyDi b9162f9576 fix: adjust log 2022-04-13 00:49:30 +08:00
GyDi f726e8a7b3 feat: supports change config dir 2022-04-12 23:09:32 +08:00
GyDi 2f284cfdc9 chore: update clash version 2022-04-12 23:04:19 +08:00
GyDi b74696adba feat: add default user agent 2022-04-12 01:05:51 +08:00
GyDi c8ccba0192 chore: rm console 2022-04-11 02:26:09 +08:00
GyDi 41b0e05f62 feat: connections page supports filter 2022-04-11 02:25:34 +08:00
GyDi 847d5f1b3b feat: log page supports filter 2022-04-11 01:46:33 +08:00
GyDi 0445f9dfc2 fix: check button hover style 2022-04-10 03:33:17 +08:00
GyDi 3001c780bd feat: optimize delay checker concurrency strategy 2022-04-10 02:58:48 +08:00
GyDi 68ad5e2320 feat: support sort proxy node and custom test url 2022-04-10 02:09:36 +08:00
GyDi b5e229b19c chore: update deps 2022-04-10 01:31:05 +08:00
GyDi 453d798fcf refactor: proxy head 2022-04-08 01:35:18 +08:00
59 changed files with 4383 additions and 2248 deletions
+2 -2
View File
@@ -61,7 +61,7 @@ jobs:
- name: Tauri build
uses: tauri-apps/tauri-action@0e558392ccadcb49bcc89e7df15a400e8f0c954d
# enable cache even though failed
# continue-on-error: true
continue-on-error: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
@@ -76,7 +76,7 @@ jobs:
- name: Green zip bundle
if: matrix.os == 'windows-latest'
run: |
yarn run green
yarn run portable
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+63
View File
@@ -0,0 +1,63 @@
name: Test CI
on: workflow_dispatch
env:
CARGO_INCREMENTAL: 0
RUST_BACKTRACE: short
jobs:
release:
strategy:
matrix:
os: [windows-latest, ubuntu-latest, macos-latest]
runs-on: ${{ matrix.os }}
if: startsWith(github.repository, 'zzzgydi')
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
profile: minimal
override: true
- name: Install Node
uses: actions/setup-node@v1
with:
node-version: 14
- name: Install Dependencies (ubuntu only)
if: matrix.os == 'ubuntu-latest'
run: |
sudo apt-get update
sudo apt-get install -y libgtk-3-dev webkit2gtk-4.0 libappindicator3-dev librsvg2-dev patchelf
- name: Get yarn cache dir path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- name: Yarn Cache
uses: actions/cache@v2
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: Yarn install and check
run: |
yarn install --network-timeout 1000000
yarn run check
- name: Tauri build
uses: tauri-apps/tauri-action@0e558392ccadcb49bcc89e7df15a400e8f0c954d
# enable cache even though failed
continue-on-error: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
+46
View File
@@ -1,3 +1,49 @@
## v1.0.1
### Features
- adjust default theme settings
- reduce gpu usage of traffic graph when hidden
- supports more remote profile response header setting
- check remote profile data format when imported
### Bug Fixes
- service mode install and start issue (Windows)
- fix launch panic (Some Windows)
---
## v1.0.0
### Features
- update clash core
- optimize traffic graph animation
- supports interval update profiles
- supports service mode (Windows)
### Bug Fixes
- reset system proxy when exit from dock (macOS)
- adjust clash dns config process strategy
---
## v0.0.29
### Features
- sort proxy node
- custom proxy test url
- logs page filter
- connections page filter
- default user agent for subscription
- system tray add tun mode toggle
- enable to change the config dir (Windows only)
---
## v0.0.28
### Features
+8 -7
View File
@@ -1,6 +1,6 @@
{
"name": "clash-verge",
"version": "0.0.28",
"version": "1.0.1",
"license": "GPL-3.0",
"scripts": {
"dev": "tauri dev",
@@ -10,17 +10,17 @@
"web:build": "tsc && vite build",
"web:serve": "vite preview",
"check": "node scripts/check.mjs",
"green": "node scripts/green.mjs",
"publish": "node scripts/publish.mjs",
"updater": "node scripts/updater.mjs",
"publish": "node scripts/publish.mjs",
"portable": "node scripts/portable.mjs",
"prepare": "husky install"
},
"dependencies": {
"@emotion/react": "^11.8.2",
"@emotion/styled": "^11.8.1",
"@mui/icons-material": "^5.5.1",
"@mui/material": "^5.5.3",
"@tauri-apps/api": "^1.0.0-rc.3",
"@mui/icons-material": "^5.6.2",
"@mui/material": "^5.6.4",
"@tauri-apps/api": "^1.0.0-rc.4",
"ahooks": "^3.2.0",
"axios": "^0.26.0",
"dayjs": "^1.11.0",
@@ -37,7 +37,7 @@
},
"devDependencies": {
"@actions/github": "^5.0.0",
"@tauri-apps/cli": "^1.0.0-rc.8",
"@tauri-apps/cli": "^1.0.0-rc.9",
"@types/fs-extra": "^9.0.13",
"@types/js-cookie": "^3.0.1",
"@types/lodash": "^4.14.180",
@@ -46,6 +46,7 @@
"@vitejs/plugin-react": "^1.2.0",
"adm-zip": "^0.5.9",
"fs-extra": "^10.0.0",
"https-proxy-agent": "^5.0.1",
"husky": "^7.0.0",
"node-fetch": "^3.2.0",
"pretty-quick": "^3.1.3",
+53 -5
View File
@@ -3,9 +3,12 @@ import zlib from "zlib";
import path from "path";
import AdmZip from "adm-zip";
import fetch from "node-fetch";
import proxyAgent from "https-proxy-agent";
import { execSync } from "child_process";
const cwd = process.cwd();
const TEMP_DIR = path.join(cwd, "node_modules/.verge");
const FORCE = process.argv.includes("--force");
/**
@@ -16,7 +19,7 @@ function resolveClash() {
const CLASH_URL_PREFIX =
"https://github.com/Dreamacro/clash/releases/download/premium/";
const CLASH_LATEST_DATE = "2022.03.21";
const CLASH_LATEST_DATE = "2022.04.17";
// todo
const map = {
@@ -57,7 +60,7 @@ async function resolveSidecar() {
// download sidecar
const binInfo = resolveClash();
const tempDir = path.join(cwd, "pre-dev-temp");
const tempDir = path.join(TEMP_DIR, "clash");
const tempZip = path.join(tempDir, binInfo.zipfile);
const tempExe = path.join(tempDir, binInfo.exefile);
@@ -103,7 +106,7 @@ async function resolveWintun() {
const url = "https://www.wintun.net/builds/wintun-0.14.1.zip";
const tempDir = path.join(cwd, "pre-dev-temp-1");
const tempDir = path.join(TEMP_DIR, "wintun");
const tempZip = path.join(tempDir, "wintun.zip");
const wintunPath = path.join(tempDir, "wintun/bin/amd64/wintun.dll");
@@ -125,14 +128,43 @@ async function resolveWintun() {
throw new Error(`path not found "${wintunPath}"`);
}
// move wintun.dll to resources
await fs.rename(wintunPath, targetPath);
// delete temp dir
await fs.remove(tempDir);
console.log(`[INFO]: resolve wintun.dll finished`);
}
/**
* only Windows
* get the clash-verge-service.exe
*/
async function resolveService() {
const { platform } = process;
if (platform !== "win32") return;
const resDir = path.join(cwd, "src-tauri/resources");
const repo =
"https://github.com/zzzgydi/clash-verge-service/releases/download/latest";
async function help(bin) {
const targetPath = path.join(resDir, bin);
if (!FORCE && (await fs.pathExists(targetPath))) return;
const url = `${repo}/${bin}`;
await downloadFile(url, targetPath);
}
await fs.mkdirp(resDir);
await help("clash-verge-service.exe");
await help("install-service.exe");
await help("uninstall-service.exe");
console.log(`[INFO]: resolve Service finished`);
}
/**
* get the Country.mmdb (not required)
*/
@@ -142,7 +174,9 @@ async function resolveMmdb() {
const resDir = path.join(cwd, "src-tauri", "resources");
const resPath = path.join(resDir, "Country.mmdb");
if (!FORCE && (await fs.pathExists(resPath))) return;
await fs.mkdirp(resDir);
await downloadFile(url, resPath);
}
@@ -153,7 +187,20 @@ async function resolveMmdb() {
async function downloadFile(url, path) {
console.log(`[INFO]: downloading from "${url}"`);
const options = {};
const httpProxy =
process.env.HTTP_PROXY ||
process.env.http_proxy ||
process.env.HTTPS_PROXY ||
process.env.https_proxy;
if (httpProxy) {
options.agent = proxyAgent(httpProxy);
}
const response = await fetch(url, {
...options,
method: "GET",
headers: { "Content-Type": "application/octet-stream" },
});
@@ -167,3 +214,4 @@ async function downloadFile(url, path) {
resolveSidecar().catch(console.error);
resolveWintun().catch(console.error);
resolveMmdb().catch(console.error);
resolveService().catch(console.error);
+4 -4
View File
@@ -6,7 +6,7 @@ import { getOctokit, context } from "@actions/github";
/// Script for ci
/// 打包绿色版/便携版 (only Windows)
async function resolveGreen() {
async function resolvePortable() {
if (process.platform !== "win32") return;
const releaseDir = "./src-tauri/target/release";
@@ -25,10 +25,10 @@ async function resolveGreen() {
const packageJson = require("../package.json");
const { version } = packageJson;
const zipFile = `Clash.Verge_${version}_x64_green.zip`;
const zipFile = `Clash.Verge_${version}_x64_portable.zip`;
zip.writeZip(zipFile);
console.log("[INFO]: create green zip successfully");
console.log("[INFO]: create portable zip successfully");
// push release assets
if (process.env.GITHUB_TOKEN === undefined) {
@@ -53,4 +53,4 @@ async function resolveGreen() {
});
}
resolveGreen().catch(console.error);
resolvePortable().catch(console.error);
+906 -361
View File
File diff suppressed because it is too large Load Diff
+9 -4
View File
@@ -10,7 +10,7 @@ edition = "2021"
build = "build.rs"
[build-dependencies]
tauri-build = { version = "1.0.0-rc.5", features = [] }
tauri-build = { version = "1.0.0-rc.7", features = [] }
[dependencies]
anyhow = "1.0"
@@ -21,8 +21,10 @@ nanoid = "0.4.0"
chrono = "0.4.19"
serde_json = "1.0"
serde_yaml = "0.8"
delay_timer = "0.11.1"
parking_lot = "0.12.0"
serde = { version = "1.0", features = ["derive"] }
tauri = { version = "1.0.0-rc.6", features = ["process-all", "shell-all", "system-tray", "updater", "window-all"] }
tauri = { version = "1.0.0-rc.8", features = ["process-all", "shell-all", "system-tray", "updater", "window-all"] }
window-shadows = { git = "https://github.com/tauri-apps/window-shadows" }
window-vibrancy = { git = "https://github.com/tauri-apps/window-vibrancy" }
@@ -36,11 +38,14 @@ auto-launch = "0.2"
port_scanner = "0.1.5"
[target.'cfg(windows)'.dependencies]
runas = "0.2.1"
deelevate = "0.2.0"
windows-sys = "0.36"
winreg = { version = "0.10", features = ["transactions"] }
[features]
default = [ "custom-protocol" ]
custom-protocol = [ "tauri/custom-protocol" ]
default = ["custom-protocol", "tauri/ayatana-tray"]
custom-protocol = ["tauri/custom-protocol"]
verge-dev = []
debug-yml = []
+157 -238
View File
@@ -1,26 +1,25 @@
use crate::{
core::{ClashInfo, PrfItem, PrfOption, Profiles, VergeConfig},
states::{ClashState, ProfilesState, VergeState},
utils::{dirs, sysopt::SysProxyConfig},
core::{ClashInfo, Core, PrfItem, PrfOption, Profiles, Verge},
utils::{dirs, help, sysopt::SysProxyConfig},
};
use crate::{ret_err, wrap_err};
use crate::{log_if_err, ret_err, wrap_err};
use anyhow::Result;
use serde_yaml::Mapping;
use std::process::Command;
use tauri::{api, Manager, State};
use tauri::{api, State};
type CmdResult<T = ()> = Result<T, String>;
/// get all profiles from `profiles.yaml`
#[tauri::command]
pub fn get_profiles<'a>(profiles_state: State<'_, ProfilesState>) -> Result<Profiles, String> {
let profiles = profiles_state.0.lock().unwrap();
pub fn get_profiles(core: State<'_, Core>) -> CmdResult<Profiles> {
let profiles = core.profiles.lock();
Ok(profiles.clone())
}
/// synchronize data irregularly
/// manually exec enhanced profile
#[tauri::command]
pub fn sync_profiles(profiles_state: State<'_, ProfilesState>) -> Result<(), String> {
let mut profiles = profiles_state.0.lock().unwrap();
wrap_err!(profiles.sync_file())
pub fn enhance_profiles(core: State<'_, Core>) -> CmdResult {
wrap_err!(core.activate_enhanced(false))
}
/// import the profile from url
@@ -29,11 +28,11 @@ pub fn sync_profiles(profiles_state: State<'_, ProfilesState>) -> Result<(), Str
pub async fn import_profile(
url: String,
option: Option<PrfOption>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
core: State<'_, Core>,
) -> CmdResult {
let item = wrap_err!(PrfItem::from_url(&url, None, None, option).await)?;
let mut profiles = profiles_state.0.lock().unwrap();
let mut profiles = core.profiles.lock();
wrap_err!(profiles.append_item(item))
}
@@ -44,11 +43,11 @@ pub async fn import_profile(
pub async fn create_profile(
item: PrfItem, // partial
file_data: Option<String>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
core: State<'_, Core>,
) -> CmdResult {
let item = wrap_err!(PrfItem::from(item, file_data).await)?;
let mut profiles = profiles_state.0.lock().unwrap();
let mut profiles = core.profiles.lock();
wrap_err!(profiles.append_item(item))
}
@@ -57,118 +56,53 @@ pub async fn create_profile(
pub async fn update_profile(
index: String,
option: Option<PrfOption>,
clash_state: State<'_, ClashState>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let (url, opt) = {
// must release the lock here
let profiles = profiles_state.0.lock().unwrap();
let item = wrap_err!(profiles.get_item(&index))?;
// check the profile type
if let Some(typ) = item.itype.as_ref() {
if *typ != "remote" {
ret_err!(format!("could not update the `{typ}` profile"));
}
}
if item.url.is_none() {
ret_err!("failed to get the item url");
}
(item.url.clone().unwrap(), item.option.clone())
};
let fetch_opt = PrfOption::merge(opt, option);
let item = wrap_err!(PrfItem::from_url(&url, None, None, fetch_opt).await)?;
let mut profiles = profiles_state.0.lock().unwrap();
wrap_err!(profiles.update_item(index.clone(), item))?;
// reactivate the profile
if Some(index) == profiles.get_current() {
let clash = clash_state.0.lock().unwrap();
wrap_err!(clash.activate_enhanced(&profiles, false, false))?;
}
Ok(())
core: State<'_, Core>,
) -> CmdResult {
wrap_err!(Core::update_profile_item(core.inner().clone(), index, option).await)
}
/// change the current profile
#[tauri::command]
pub fn select_profile(
index: String,
clash_state: State<'_, ClashState>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let mut profiles = profiles_state.0.lock().unwrap();
pub fn select_profile(index: String, core: State<'_, Core>) -> CmdResult {
let mut profiles = core.profiles.lock();
wrap_err!(profiles.put_current(index))?;
let clash = clash_state.0.lock().unwrap();
wrap_err!(clash.activate_enhanced(&profiles, false, false))
drop(profiles);
wrap_err!(core.activate_enhanced(false))
}
/// change the profile chain
#[tauri::command]
pub fn change_profile_chain(
chain: Option<Vec<String>>,
app_handle: tauri::AppHandle,
clash_state: State<'_, ClashState>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let mut clash = clash_state.0.lock().unwrap();
let mut profiles = profiles_state.0.lock().unwrap();
pub fn change_profile_chain(chain: Option<Vec<String>>, core: State<'_, Core>) -> CmdResult {
let mut profiles = core.profiles.lock();
profiles.put_chain(chain);
clash.set_window(app_handle.get_window("main"));
wrap_err!(clash.activate_enhanced(&profiles, false, false))
drop(profiles);
wrap_err!(core.activate_enhanced(false))
}
/// change the profile valid fields
#[tauri::command]
pub fn change_profile_valid(
valid: Option<Vec<String>>,
app_handle: tauri::AppHandle,
clash_state: State<'_, ClashState>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let mut clash = clash_state.0.lock().unwrap();
let mut profiles = profiles_state.0.lock().unwrap();
pub fn change_profile_valid(valid: Option<Vec<String>>, core: State<Core>) -> CmdResult {
let mut profiles = core.profiles.lock();
profiles.put_valid(valid);
clash.set_window(app_handle.get_window("main"));
wrap_err!(clash.activate_enhanced(&profiles, false, false))
}
drop(profiles);
/// manually exec enhanced profile
#[tauri::command]
pub fn enhance_profiles(
app_handle: tauri::AppHandle,
clash_state: State<'_, ClashState>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let mut clash = clash_state.0.lock().unwrap();
let profiles = profiles_state.0.lock().unwrap();
clash.set_window(app_handle.get_window("main"));
wrap_err!(clash.activate_enhanced(&profiles, false, false))
wrap_err!(core.activate_enhanced(false))
}
/// delete profile item
#[tauri::command]
pub fn delete_profile(
index: String,
clash_state: State<'_, ClashState>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let mut profiles = profiles_state.0.lock().unwrap();
pub fn delete_profile(index: String, core: State<'_, Core>) -> CmdResult {
let mut profiles = core.profiles.lock();
if wrap_err!(profiles.delete_item(index))? {
let clash = clash_state.0.lock().unwrap();
wrap_err!(clash.activate_enhanced(&profiles, false, false))?;
drop(profiles);
log_if_err!(core.activate_enhanced(false));
}
Ok(())
@@ -176,19 +110,20 @@ pub fn delete_profile(
/// patch the profile config
#[tauri::command]
pub fn patch_profile(
index: String,
profile: PrfItem,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let mut profiles = profiles_state.0.lock().unwrap();
wrap_err!(profiles.patch_item(index, profile))
pub fn patch_profile(index: String, profile: PrfItem, core: State<'_, Core>) -> CmdResult {
let mut profiles = core.profiles.lock();
wrap_err!(profiles.patch_item(index, profile))?;
drop(profiles);
// update cron task
let mut timer = core.timer.lock();
wrap_err!(timer.refresh())
}
/// run vscode command to edit the profile
#[tauri::command]
pub fn view_profile(index: String, profiles_state: State<'_, ProfilesState>) -> Result<(), String> {
let profiles = profiles_state.0.lock().unwrap();
pub fn view_profile(index: String, core: State<'_, Core>) -> CmdResult {
let profiles = core.profiles.lock();
let item = wrap_err!(profiles.get_item(&index))?;
let file = item.file.clone();
@@ -201,41 +136,14 @@ pub fn view_profile(index: String, profiles_state: State<'_, ProfilesState>) ->
ret_err!("the file not found");
}
// use vscode first
if let Ok(code) = which::which("code") {
#[cfg(target_os = "windows")]
{
use std::os::windows::process::CommandExt;
if let Err(err) = Command::new(code)
.creation_flags(0x08000000)
.arg(path)
.spawn()
{
log::error!("failed to open file by VScode for {err}");
return Err("failed to open file by VScode".into());
}
}
#[cfg(not(target_os = "windows"))]
if let Err(err) = Command::new(code).arg(path).spawn() {
log::error!("failed to open file by VScode for {err}");
return Err("failed to open file by VScode".into());
}
return Ok(());
}
wrap_err!(open::that(path))
wrap_err!(help::open_file(path))
}
/// read the profile item file data
#[tauri::command]
pub fn read_profile_file(
index: String,
profiles_state: State<'_, ProfilesState>,
) -> Result<String, String> {
let profiles = profiles_state.0.lock().unwrap();
pub fn read_profile_file(index: String, core: State<'_, Core>) -> CmdResult<String> {
let profiles = core.profiles.lock();
let item = wrap_err!(profiles.get_item(&index))?;
let data = wrap_err!(item.read_file())?;
@@ -247,34 +155,22 @@ pub fn read_profile_file(
pub fn save_profile_file(
index: String,
file_data: Option<String>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
core: State<'_, Core>,
) -> CmdResult {
if file_data.is_none() {
return Ok(());
}
let profiles = profiles_state.0.lock().unwrap();
let profiles = core.profiles.lock();
let item = wrap_err!(profiles.get_item(&index))?;
wrap_err!(item.save_file(file_data.unwrap()))
}
/// restart the sidecar
#[tauri::command]
pub fn restart_sidecar(
clash_state: State<'_, ClashState>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let mut clash = clash_state.0.lock().unwrap();
let mut profiles = profiles_state.0.lock().unwrap();
wrap_err!(clash.restart_sidecar(&mut profiles))
}
/// 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> {
let clash = clash_state.0.lock().unwrap();
pub fn get_clash_info(core: State<'_, Core>) -> CmdResult<ClashInfo> {
let clash = core.clash.lock();
Ok(clash.info.clone())
}
@@ -282,16 +178,38 @@ pub fn get_clash_info(clash_state: State<'_, ClashState>) -> Result<ClashInfo, S
/// after putting the change to the clash core
/// then we should save the latest config
#[tauri::command]
pub fn patch_clash_config(
payload: Mapping,
clash_state: State<'_, ClashState>,
verge_state: State<'_, VergeState>,
profiles_state: State<'_, ProfilesState>,
pub fn patch_clash_config(payload: Mapping, core: State<'_, Core>) -> CmdResult {
wrap_err!(core.patch_clash(payload))
}
/// get the verge config
#[tauri::command]
pub fn get_verge_config(core: State<'_, Core>) -> CmdResult<Verge> {
let verge = core.verge.lock();
Ok(verge.clone())
}
/// patch the verge config
/// this command only save the config and not responsible for other things
#[tauri::command]
pub fn patch_verge_config(
payload: Verge,
app_handle: tauri::AppHandle,
core: State<'_, Core>,
) -> Result<(), String> {
let mut clash = clash_state.0.lock().unwrap();
let mut verge = verge_state.0.lock().unwrap();
let mut profiles = profiles_state.0.lock().unwrap();
wrap_err!(clash.patch_config(payload, &mut verge, &mut profiles))
wrap_err!(core.patch_verge(payload, &app_handle))
}
/// restart the sidecar
#[tauri::command]
pub fn restart_sidecar(core: State<'_, Core>) -> CmdResult {
wrap_err!(core.restart_clash())
}
/// kill all sidecars when update app
#[tauri::command]
pub fn kill_sidecar() {
api::process::kill_children();
}
/// get the system proxy
@@ -303,73 +221,9 @@ pub fn get_sys_proxy() -> Result<SysProxyConfig, String> {
/// get the current proxy config
/// which may not the same as system proxy
#[tauri::command]
pub fn get_cur_proxy(verge_state: State<'_, VergeState>) -> Result<Option<SysProxyConfig>, String> {
let verge = verge_state.0.lock().unwrap();
Ok(verge.cur_sysproxy.clone())
}
/// get the verge config
#[tauri::command]
pub fn get_verge_config(verge_state: State<'_, VergeState>) -> Result<VergeConfig, String> {
let verge = verge_state.0.lock().unwrap();
let mut config = verge.config.clone();
if config.system_proxy_bypass.is_none() && verge.cur_sysproxy.is_some() {
config.system_proxy_bypass = Some(verge.cur_sysproxy.clone().unwrap().bypass)
}
Ok(config)
}
/// patch the verge config
/// this command only save the config and not responsible for other things
#[tauri::command]
pub fn patch_verge_config(
payload: VergeConfig,
app_handle: tauri::AppHandle,
clash_state: State<'_, ClashState>,
verge_state: State<'_, VergeState>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let tun_mode = payload.enable_tun_mode.clone();
let system_proxy = payload.enable_system_proxy.clone();
let mut verge = verge_state.0.lock().unwrap();
wrap_err!(verge.patch_config(payload))?;
// change system tray
if system_proxy.is_some() {
app_handle
.tray_handle()
.get_item("system_proxy")
.set_selected(system_proxy.unwrap())
.unwrap();
}
// change tun mode
if tun_mode.is_some() {
#[cfg(target_os = "windows")]
if *tun_mode.as_ref().unwrap() {
let wintun_dll = dirs::app_home_dir().join("wintun.dll");
if !wintun_dll.exists() {
log::error!("failed to enable TUN for missing `wintun.dll`");
return Err("failed to enable TUN for missing `wintun.dll`".into());
}
}
let clash = clash_state.0.lock().unwrap();
let profiles = profiles_state.0.lock().unwrap();
wrap_err!(clash.activate_enhanced(&profiles, false, false))?;
}
Ok(())
}
/// kill all sidecars when update app
#[tauri::command]
pub fn kill_sidecars() {
api::process::kill_children();
pub fn get_cur_proxy(core: State<'_, Core>) -> CmdResult<Option<SysProxyConfig>> {
let sysopt = core.sysopt.lock();
wrap_err!(sysopt.get_sysproxy())
}
/// open app config dir
@@ -385,3 +239,68 @@ pub fn open_logs_dir() -> Result<(), String> {
let log_dir = dirs::app_logs_dir();
wrap_err!(open::that(log_dir))
}
/// service mode
#[cfg(windows)]
pub mod service {
use super::*;
use crate::core::win_service::JsonResponse;
#[tauri::command]
pub async fn start_service() -> Result<(), String> {
wrap_err!(crate::core::Service::start_service().await)
}
#[tauri::command]
pub async fn stop_service() -> Result<(), String> {
wrap_err!(crate::core::Service::stop_service().await)
}
#[tauri::command]
pub async fn check_service() -> Result<JsonResponse, String> {
// no log
match crate::core::Service::check_service().await {
Ok(res) => Ok(res),
Err(err) => Err(err.to_string()),
}
}
#[tauri::command]
pub async fn install_service() -> Result<(), String> {
wrap_err!(crate::core::Service::install_service().await)
}
#[tauri::command]
pub async fn uninstall_service() -> Result<(), String> {
wrap_err!(crate::core::Service::uninstall_service().await)
}
}
#[cfg(not(windows))]
pub mod service {
use super::*;
#[tauri::command]
pub async fn start_service() -> Result<(), String> {
Ok(())
}
#[tauri::command]
pub async fn stop_service() -> Result<(), String> {
Ok(())
}
#[tauri::command]
pub async fn check_service() -> Result<(), String> {
Ok(())
}
#[tauri::command]
pub async fn install_service() -> Result<(), String> {
Ok(())
}
#[tauri::command]
pub async fn uninstall_service() -> Result<(), String> {
Ok(())
}
}
+80 -310
View File
@@ -1,14 +1,7 @@
use super::{PrfEnhancedResult, Profiles, Verge, VergeConfig};
use crate::log_if_err;
use crate::utils::{config, dirs, help};
use anyhow::{bail, Result};
use reqwest::header::HeaderMap;
use crate::utils::{config, dirs};
use anyhow::Result;
use serde::{Deserialize, Serialize};
use serde_yaml::{Mapping, Value};
use std::{collections::HashMap, time::Duration};
use tauri::api::process::{Command, CommandChild, CommandEvent};
use tauri::Window;
use tokio::time::sleep;
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct ClashInfo {
@@ -25,56 +18,16 @@ pub struct ClashInfo {
pub secret: Option<String>,
}
pub struct Clash {
/// maintain the clash config
pub config: Mapping,
/// some info
pub info: ClashInfo,
/// clash sidecar
pub sidecar: Option<CommandChild>,
/// save the main window
pub window: Option<Window>,
}
impl Clash {
pub fn new() -> Clash {
let config = Clash::read_config();
let info = Clash::get_info(&config);
Clash {
config,
info,
sidecar: None,
window: None,
}
}
/// get clash config
fn read_config() -> Mapping {
config::read_yaml::<Mapping>(dirs::clash_path())
}
/// save the clash config
fn save_config(&self) -> Result<()> {
config::save_yaml(
dirs::clash_path(),
&self.config,
Some("# Default Config For Clash Core\n\n"),
)
}
impl ClashInfo {
/// parse the clash's config.yaml
/// get some information
fn get_info(clash_config: &Mapping) -> ClashInfo {
let key_port_1 = Value::String("port".to_string());
let key_port_2 = Value::String("mixed-port".to_string());
let key_server = Value::String("external-controller".to_string());
let key_secret = Value::String("secret".to_string());
pub fn from(config: &Mapping) -> ClashInfo {
let key_port_1 = Value::from("port");
let key_port_2 = Value::from("mixed-port");
let key_server = Value::from("external-controller");
let key_secret = Value::from("secret");
let port = match clash_config.get(&key_port_1) {
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()),
@@ -84,7 +37,7 @@ impl Clash {
};
let port = match port {
Some(_) => port,
None => match clash_config.get(&key_port_2) {
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()),
@@ -94,25 +47,21 @@ impl Clash {
},
};
let server = match clash_config.get(&key_server) {
// `external-controller` could be
// "127.0.0.1:9090" or ":9090"
// "9090" or 9090 (clash do not support this)
let server = match config.get(&key_server) {
Some(value) => match value {
Value::String(val_str) => {
// `external-controller` could be
// "127.0.0.1:9090" or ":9090"
// Todo: maybe it could support single port
let server = val_str.clone();
let server = match server.starts_with(":") {
true => format!("127.0.0.1{server}"),
false => server,
};
Some(server)
}
Value::String(val_str) => match val_str.starts_with(":") {
true => Some(format!("127.0.0.1{val_str}")),
false => Some(val_str.clone()),
},
_ => None,
},
_ => None,
};
let secret = match clash_config.get(&key_secret) {
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()),
@@ -129,101 +78,71 @@ impl Clash {
secret,
}
}
}
/// save the main window
pub fn set_window(&mut self, win: Option<Window>) {
self.window = win;
pub struct Clash {
/// maintain the clash config
pub config: Mapping,
/// some info
pub info: ClashInfo,
}
impl Clash {
pub fn new() -> Clash {
let config = Clash::read_config();
let info = ClashInfo::from(&config);
Clash { config, info }
}
/// run clash sidecar
pub fn run_sidecar(&mut self) -> Result<()> {
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!("[clash]: {}", line),
CommandEvent::Stderr(err) => log::error!("[clash]: {}", err),
_ => {}
}
}
});
Ok(())
}
Err(err) => bail!(err.to_string()),
},
Err(err) => bail!(err.to_string()),
}
/// get clash config
pub fn read_config() -> Mapping {
config::read_yaml::<Mapping>(dirs::clash_path())
}
/// drop clash sidecar
pub fn drop_sidecar(&mut self) -> Result<()> {
if let Some(sidecar) = self.sidecar.take() {
sidecar.kill()?;
}
Ok(())
}
/// restart clash sidecar
/// should reactivate profile after restart
pub fn restart_sidecar(&mut self, profiles: &mut Profiles) -> Result<()> {
self.update_config();
self.drop_sidecar()?;
self.run_sidecar()?;
self.activate(profiles)?;
self.activate_enhanced(profiles, false, true)
}
/// update the clash info
pub fn update_config(&mut self) {
self.config = Clash::read_config();
self.info = Clash::get_info(&self.config);
/// save the clash config
pub fn save_config(&self) -> Result<()> {
config::save_yaml(
dirs::clash_path(),
&self.config,
Some("# Default Config For Clash Core\n\n"),
)
}
/// patch update the clash config
pub fn patch_config(
&mut self,
patch: Mapping,
verge: &mut Verge,
profiles: &mut Profiles,
) -> Result<()> {
let mix_port_key = Value::from("mixed-port");
let mut port = None;
/// if the port is changed then return true
pub fn patch_config(&mut self, patch: Mapping) -> Result<bool> {
let port_key = Value::from("mixed-port");
let server_key = Value::from("external-controller");
let secret_key = Value::from("secret");
let mut change_port = false;
let mut change_info = false;
for (key, value) in patch.into_iter() {
let value = value.clone();
// check whether the mix_port is changed
if key == mix_port_key {
if value.is_number() {
port = value.as_i64().as_ref().map(|n| n.to_string());
} else {
port = value.as_str().as_ref().map(|s| s.to_string());
}
if key == port_key {
change_port = true;
}
self.config.insert(key.clone(), value);
if key == port_key || key == server_key || key == secret_key {
change_info = true;
}
self.config.insert(key, value);
}
if change_info {
self.info = ClashInfo::from(&self.config);
}
self.save_config()?;
if let Some(port) = port {
self.restart_sidecar(profiles)?;
verge.init_sysproxy(Some(port));
}
Ok(())
Ok(change_port)
}
/// revise the `tun` and `dns` config
fn _tun_mode(mut config: Mapping, enable: bool) -> Mapping {
pub fn _tun_mode(mut config: Mapping, enable: bool) -> Mapping {
macro_rules! revise {
($map: expr, $key: expr, $val: expr) => {
let ret_key = Value::String($key.into());
@@ -260,18 +179,17 @@ impl Clash {
revise!(config, "tun", new_tun);
// dns config
let dns_val = config.get(&Value::from("dns"));
let mut new_dns = Mapping::new();
if dns_val.is_some() && dns_val.as_ref().unwrap().is_mapping() {
new_dns = dns_val.as_ref().unwrap().as_mapping().unwrap().clone();
}
// 借鉴cfw的默认配置
revise!(new_dns, "enable", enable);
if enable {
// dns config
let dns_val = config.get(&Value::from("dns"));
let mut new_dns = Mapping::new();
if dns_val.is_some() && dns_val.as_ref().unwrap().is_mapping() {
new_dns = dns_val.as_ref().unwrap().as_mapping().unwrap().clone();
}
revise!(new_dns, "enable", enable);
// 借鉴cfw的默认配置
append!(new_dns, "enhanced-mode", "fake-ip");
append!(
new_dns,
@@ -290,156 +208,16 @@ impl Clash {
"www.msftconnecttest.com"
]
);
revise!(config, "dns", new_dns);
}
revise!(config, "dns", new_dns);
config
}
/// activate the profile
/// generate a new profile to the temp_dir
/// then put the path to the clash core
fn _activate(info: ClashInfo, config: Mapping, window: Option<Window>) -> Result<()> {
let verge_config = VergeConfig::new();
let tun_enable = verge_config.enable_tun_mode.unwrap_or(false);
let config = Clash::_tun_mode(config, tun_enable);
let temp_path = dirs::profiles_temp_path();
config::save_yaml(temp_path.clone(), &config, Some("# Clash Verge Temp File"))?;
tauri::async_runtime::spawn(async move {
let server = info.server.unwrap();
let server = format!("http://{server}/configs");
let mut headers = HeaderMap::new();
headers.insert("Content-Type", "application/json".parse().unwrap());
if let Some(secret) = info.secret.as_ref() {
let secret = format!("Bearer {}", secret.clone()).parse().unwrap();
headers.insert("Authorization", secret);
}
let mut data = HashMap::new();
data.insert("path", temp_path.as_os_str().to_str().unwrap());
// retry 5 times
for _ in 0..5 {
match reqwest::ClientBuilder::new().no_proxy().build() {
Ok(client) => {
let builder = client.put(&server).headers(headers.clone()).json(&data);
match builder.send().await {
Ok(resp) => {
if resp.status() != 204 {
log::error!("failed to activate clash for status \"{}\"", resp.status());
}
// emit the window to update something
if let Some(window) = window {
window.emit("verge://refresh-clash-config", "yes").unwrap();
}
// do not retry
break;
}
Err(err) => log::error!("failed to activate for `{err}`"),
}
}
Err(err) => log::error!("failed to activate for `{err}`"),
}
sleep(Duration::from_millis(500)).await;
}
});
Ok(())
}
/// enhanced profiles mode
/// - (sync) refresh config if enhance chain is null
/// - (async) enhanced config
pub fn activate_enhanced(&self, profiles: &Profiles, delay: bool, skip: bool) -> Result<()> {
if self.window.is_none() {
bail!("failed to get the main window");
}
let event_name = help::get_uid("e");
let event_name = format!("enhanced-cb-{event_name}");
// generate the payload
let payload = profiles.gen_enhanced(event_name.clone())?;
let info = self.info.clone();
// do not run enhanced
if payload.chain.len() == 0 {
if skip {
return Ok(());
}
let mut config = self.config.clone();
let filter_data = Clash::strict_filter(payload.current);
for (key, value) in filter_data.into_iter() {
config.insert(key, value);
}
return Clash::_activate(info, config, self.window.clone());
}
let window = self.window.clone().unwrap();
let window_move = self.window.clone();
window.once(&event_name, move |event| {
if let Some(result) = event.payload() {
let result: PrfEnhancedResult = serde_json::from_str(result).unwrap();
if let Some(data) = result.data {
let mut config = Clash::read_config();
let filter_data = Clash::loose_filter(data); // loose filter
for (key, value) in filter_data.into_iter() {
config.insert(key, value);
}
log_if_err!(Clash::_activate(info, config, window_move));
log::info!("profile enhanced status {}", result.status);
}
result.error.map(|err| log::error!("{err}"));
}
});
tauri::async_runtime::spawn(async move {
// wait the window setup during resolve app
if delay {
sleep(Duration::from_secs(2)).await;
}
window.emit("script-handler", payload).unwrap();
});
Ok(())
}
/// activate the profile
/// auto activate enhanced profile
pub fn activate(&self, profiles: &Profiles) -> Result<()> {
let data = profiles.gen_activate()?;
let data = Clash::strict_filter(data);
let info = self.info.clone();
let mut config = self.config.clone();
for (key, value) in data.into_iter() {
config.insert(key, value);
}
Clash::_activate(info, config, self.window.clone())
}
/// only 5 default fields available (clash config fields)
/// convert to lowercase
fn strict_filter(config: Mapping) -> Mapping {
pub fn strict_filter(config: Mapping) -> Mapping {
// Only the following fields are allowed:
// proxies/proxy-providers/proxy-groups/rule-providers/rules
let valid_keys = vec![
@@ -470,7 +248,7 @@ impl Clash {
/// more clash config fields available
/// convert to lowercase
fn loose_filter(config: Mapping) -> Mapping {
pub fn loose_filter(config: Mapping) -> Mapping {
// all of these can not be revised by script or merge
// http/https/socks port should be under control
let not_allow = vec![
@@ -508,11 +286,3 @@ impl Default for Clash {
Clash::new()
}
}
impl Drop for Clash {
fn drop(&mut self) {
if let Err(err) = self.drop_sidecar() {
log::error!("{err}");
}
}
}
+66
View File
@@ -0,0 +1,66 @@
use super::prfitem::PrfItem;
use crate::utils::{config, dirs};
use serde::{Deserialize, Serialize};
use serde_yaml::Mapping;
use std::fs;
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct PrfEnhanced {
pub current: Mapping,
pub chain: Vec<PrfData>,
pub valid: Vec<String>,
pub callback: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct PrfEnhancedResult {
pub data: Option<Mapping>,
pub status: String,
pub error: Option<String>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct PrfData {
item: PrfItem,
#[serde(skip_serializing_if = "Option::is_none")]
merge: Option<Mapping>,
#[serde(skip_serializing_if = "Option::is_none")]
script: Option<String>,
}
impl PrfData {
pub fn from_item(item: &PrfItem) -> Option<PrfData> {
match item.itype.as_ref() {
Some(itype) => {
let file = item.file.clone()?;
let path = dirs::app_profiles_dir().join(file);
if !path.exists() {
return None;
}
match itype.as_str() {
"script" => Some(PrfData {
item: item.clone(),
script: Some(fs::read_to_string(path).unwrap_or("".into())),
merge: None,
}),
"merge" => Some(PrfData {
item: item.clone(),
merge: Some(config::read_yaml::<Mapping>(path)),
script: None,
}),
_ => None,
}
}
None => None,
}
}
}
+406
View File
@@ -1,7 +1,413 @@
use self::notice::Notice;
use self::sysopt::Sysopt;
use self::timer::Timer;
use crate::core::enhance::PrfEnhancedResult;
use crate::log_if_err;
use crate::utils::{dirs, help};
use anyhow::{bail, Result};
use parking_lot::Mutex;
use serde_yaml::Mapping;
use std::sync::Arc;
use std::time::Duration;
use tauri::{AppHandle, Manager, Window};
use tokio::time::sleep;
mod clash;
mod enhance;
mod notice;
mod prfitem;
mod profiles;
mod service;
mod sysopt;
mod timer;
mod verge;
pub use self::clash::*;
pub use self::prfitem::*;
pub use self::profiles::*;
pub use self::service::*;
pub use self::verge::*;
#[derive(Clone)]
pub struct Core {
pub clash: Arc<Mutex<Clash>>,
pub verge: Arc<Mutex<Verge>>,
pub profiles: Arc<Mutex<Profiles>>,
pub service: Arc<Mutex<Service>>,
pub sysopt: Arc<Mutex<Sysopt>>,
pub timer: Arc<Mutex<Timer>>,
pub window: Arc<Mutex<Option<Window>>>,
}
impl Core {
pub fn new() -> Core {
let clash = Clash::new();
let verge = Verge::new();
let profiles = Profiles::new();
let service = Service::new();
Core {
clash: Arc::new(Mutex::new(clash)),
verge: Arc::new(Mutex::new(verge)),
profiles: Arc::new(Mutex::new(profiles)),
service: Arc::new(Mutex::new(service)),
sysopt: Arc::new(Mutex::new(Sysopt::new())),
timer: Arc::new(Mutex::new(Timer::new())),
window: Arc::new(Mutex::new(None)),
}
}
/// initialize the core state
pub fn init(&self, app_handle: tauri::AppHandle) {
#[cfg(windows)]
{
let verge = self.verge.lock();
let enable = verge.enable_service_mode.clone();
let mut service = self.service.lock();
service.set_mode(enable.unwrap_or(false));
log_if_err!(service.start());
}
#[cfg(not(windows))]
{
let mut service = self.service.lock();
log_if_err!(service.start());
}
log_if_err!(self.activate());
let clash = self.clash.lock();
let verge = self.verge.lock();
let silent_start = verge.enable_silent_start.clone();
let auto_launch = verge.enable_auto_launch.clone();
// silent start
if silent_start.unwrap_or(false) {
let window = self.window.lock();
window.as_ref().map(|win| {
win.hide().unwrap();
});
}
let mut sysopt = self.sysopt.lock();
sysopt.init_sysproxy(clash.info.port.clone(), &verge);
drop(clash);
drop(verge);
log_if_err!(sysopt.init_launch(auto_launch));
log_if_err!(self.update_systray(&app_handle));
// wait the window setup during resolve app
let core = self.clone();
tauri::async_runtime::spawn(async move {
sleep(Duration::from_secs(2)).await;
log_if_err!(core.activate_enhanced(true));
});
// timer initialize
let mut timer = self.timer.lock();
timer.set_core(self.clone());
log_if_err!(timer.refresh());
}
/// save the window instance
pub fn set_win(&self, win: Option<Window>) {
let mut window = self.window.lock();
*window = win;
}
/// restart the clash sidecar
pub fn restart_clash(&self) -> Result<()> {
let mut service = self.service.lock();
service.restart()?;
drop(service);
self.activate()?;
self.activate_enhanced(true)
}
/// Patch Clash
/// handle the clash config changed
pub fn patch_clash(&self, patch: Mapping) -> Result<()> {
let (changed, port) = {
let mut clash = self.clash.lock();
(clash.patch_config(patch)?, clash.info.port.clone())
};
// todo: port check
if changed {
let mut service = self.service.lock();
service.restart()?;
drop(service);
self.activate()?;
self.activate_enhanced(true)?;
let mut sysopt = self.sysopt.lock();
let verge = self.verge.lock();
sysopt.init_sysproxy(port, &verge);
}
Ok(())
}
/// Patch Verge
pub fn patch_verge(&self, patch: Verge, app_handle: &AppHandle) -> Result<()> {
let tun_mode = patch.enable_tun_mode.clone();
let auto_launch = patch.enable_auto_launch.clone();
let system_proxy = patch.enable_system_proxy.clone();
let proxy_bypass = patch.system_proxy_bypass.clone();
let proxy_guard = patch.enable_proxy_guard.clone();
#[cfg(windows)]
{
let service_mode = patch.enable_service_mode.clone();
if service_mode.is_some() {
let service_mode = service_mode.unwrap();
let mut service = self.service.lock();
service.stop()?;
service.set_mode(service_mode);
service.start()?;
drop(service);
self.activate_enhanced(false)?;
}
}
if auto_launch.is_some() {
let mut sysopt = self.sysopt.lock();
sysopt.update_launch(auto_launch)?;
}
if system_proxy.is_some() || proxy_bypass.is_some() {
let mut sysopt = self.sysopt.lock();
sysopt.update_sysproxy(system_proxy.clone(), proxy_bypass)?;
sysopt.guard_proxy();
}
if proxy_guard.unwrap_or(false) {
let sysopt = self.sysopt.lock();
sysopt.guard_proxy();
}
#[cfg(target_os = "windows")]
if tun_mode.is_some() && *tun_mode.as_ref().unwrap_or(&false) {
let wintun_dll = dirs::app_home_dir().join("wintun.dll");
if !wintun_dll.exists() {
bail!("failed to enable TUN for missing `wintun.dll`");
}
}
// save the patch
let mut verge = self.verge.lock();
verge.patch_config(patch)?;
drop(verge);
if system_proxy.is_some() || tun_mode.is_some() {
self.update_systray(app_handle)?;
}
if tun_mode.is_some() {
self.activate_enhanced(false)?;
}
Ok(())
}
/// update the system tray state
pub fn update_systray(&self, app_handle: &AppHandle) -> Result<()> {
let verge = self.verge.lock();
let tray = app_handle.tray_handle();
let system_proxy = verge.enable_system_proxy.as_ref();
let tun_mode = verge.enable_tun_mode.as_ref();
tray
.get_item("system_proxy")
.set_selected(*system_proxy.unwrap_or(&false))?;
tray
.get_item("tun_mode")
.set_selected(*tun_mode.unwrap_or(&false))?;
// update verge config
let window = app_handle.get_window("main");
let notice = Notice::from(window);
notice.refresh_verge();
Ok(())
}
/// activate the profile
/// auto activate enhanced profile
pub fn activate(&self) -> Result<()> {
let data = {
let profiles = self.profiles.lock();
let data = profiles.gen_activate()?;
Clash::strict_filter(data)
};
let (mut config, info) = {
let clash = self.clash.lock();
let config = clash.config.clone();
let info = clash.info.clone();
(config, info)
};
for (key, value) in data.into_iter() {
config.insert(key, value);
}
let config = {
let verge = self.verge.lock();
let tun_mode = verge.enable_tun_mode.unwrap_or(false);
Clash::_tun_mode(config, tun_mode)
};
let notice = {
let window = self.window.lock();
Notice::from(window.clone())
};
let service = self.service.lock();
service.set_config(info, config, notice)
}
/// Enhanced
/// enhanced profiles mode
pub fn activate_enhanced(&self, skip: bool) -> Result<()> {
let window = self.window.lock();
if window.is_none() {
bail!("failed to get the main window");
}
let event_name = help::get_uid("e");
let event_name = format!("enhanced-cb-{event_name}");
// generate the payload
let payload = {
let profiles = self.profiles.lock();
profiles.gen_enhanced(event_name.clone())?
};
// do not run enhanced
if payload.chain.len() == 0 {
if skip {
return Ok(());
}
drop(window);
return self.activate();
}
let tun_mode = {
let verge = self.verge.lock();
verge.enable_tun_mode.unwrap_or(false)
};
let info = {
let clash = self.clash.lock();
clash.info.clone()
};
let notice = Notice::from(window.clone());
let service = self.service.clone();
let window = window.clone().unwrap();
window.once(&event_name, move |event| {
let result = event.payload();
if result.is_none() {
log::warn!("event payload result is none");
return;
}
let result = result.unwrap();
let result: PrfEnhancedResult = serde_json::from_str(result).unwrap();
if let Some(data) = result.data {
let mut config = Clash::read_config();
let filter_data = Clash::loose_filter(data); // loose filter
for (key, value) in filter_data.into_iter() {
config.insert(key, value);
}
let config = Clash::_tun_mode(config, tun_mode);
let service = service.lock();
log_if_err!(service.set_config(info, config, notice));
log::info!("profile enhanced status {}", result.status);
}
result.error.map(|err| log::error!("{err}"));
});
window.emit("script-handler", payload).unwrap();
Ok(())
}
}
impl Core {
/// Static function
/// update profile item
pub async fn update_profile_item(
core: Core,
uid: String,
option: Option<PrfOption>,
) -> Result<()> {
let (url, opt) = {
let profiles = core.profiles.lock();
let item = profiles.get_item(&uid)?;
if let Some(typ) = item.itype.as_ref() {
// maybe only valid for `local` profile
if *typ != "remote" {
// reactivate the config
if Some(uid) == profiles.get_current() {
drop(profiles);
return core.activate_enhanced(false);
}
return Ok(());
}
}
if item.url.is_none() {
bail!("failed to get the profile item url");
}
(item.url.clone().unwrap(), item.option.clone())
};
let merged_opt = PrfOption::merge(opt, option);
let item = PrfItem::from_url(&url, None, None, merged_opt).await?;
let mut profiles = core.profiles.lock();
profiles.update_item(uid.clone(), item)?;
// reactivate the profile
if Some(uid) == profiles.get_current() {
drop(profiles);
core.activate_enhanced(false)?;
}
Ok(())
}
}
+35
View File
@@ -0,0 +1,35 @@
use crate::log_if_err;
use tauri::Window;
#[derive(Debug, Default, Clone)]
pub struct Notice {
win: Option<Window>,
}
impl Notice {
pub fn from(win: Option<Window>) -> Notice {
Notice { win }
}
pub fn set_win(&mut self, win: Option<Window>) {
self.win = win;
}
pub fn refresh_clash(&self) {
if let Some(window) = self.win.as_ref() {
log_if_err!(window.emit("verge://refresh-clash-config", "yes"));
}
}
pub fn refresh_verge(&self) {
if let Some(window) = self.win.as_ref() {
log_if_err!(window.emit("verge://refresh-verge-config", "yes"));
}
}
pub fn refresh_profiles(&self) {
if let Some(window) = self.win.as_ref() {
log_if_err!(window.emit("verge://refresh-profiles-config", "yes"));
}
}
}
+336
View File
@@ -0,0 +1,336 @@
use crate::utils::{dirs, help, tmpl};
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use serde_yaml::Mapping;
use std::fs;
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PrfItem {
pub uid: Option<String>,
/// profile item type
/// enum value: remote | local | script | merge
#[serde(rename = "type")]
pub itype: Option<String>,
/// profile name
pub name: Option<String>,
/// profile file
pub file: Option<String>,
/// profile description
#[serde(skip_serializing_if = "Option::is_none")]
pub desc: Option<String>,
/// source url
#[serde(skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
/// selected infomation
#[serde(skip_serializing_if = "Option::is_none")]
pub selected: Option<Vec<PrfSelected>>,
/// subscription user info
#[serde(skip_serializing_if = "Option::is_none")]
pub extra: Option<PrfExtra>,
/// updated time
pub updated: Option<usize>,
/// some options of the item
#[serde(skip_serializing_if = "Option::is_none")]
pub option: Option<PrfOption>,
/// the file data
#[serde(skip)]
pub file_data: Option<String>,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct PrfSelected {
pub name: Option<String>,
pub now: Option<String>,
}
#[derive(Default, Debug, Clone, Copy, Deserialize, Serialize)]
pub struct PrfExtra {
pub upload: usize,
pub download: usize,
pub total: usize,
pub expire: usize,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct PrfOption {
/// for `remote` profile's http request
/// see issue #13
#[serde(skip_serializing_if = "Option::is_none")]
pub user_agent: Option<String>,
/// for `remote` profile
#[serde(skip_serializing_if = "Option::is_none")]
pub with_proxy: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub update_interval: Option<u64>,
}
impl PrfOption {
pub fn merge(one: Option<Self>, other: Option<Self>) -> Option<Self> {
if one.is_none() {
return other;
}
if one.is_some() && other.is_some() {
let mut one = one.unwrap();
let other = other.unwrap();
if let Some(val) = other.user_agent {
one.user_agent = Some(val);
}
if let Some(val) = other.with_proxy {
one.with_proxy = Some(val);
}
if let Some(val) = other.update_interval {
one.update_interval = Some(val);
}
return Some(one);
}
return one;
}
}
impl Default for PrfItem {
fn default() -> Self {
PrfItem {
uid: None,
itype: None,
name: None,
desc: None,
file: None,
url: None,
selected: None,
extra: None,
updated: None,
option: None,
file_data: None,
}
}
}
impl PrfItem {
/// From partial item
/// must contain `itype`
pub async fn from(item: PrfItem, file_data: Option<String>) -> Result<PrfItem> {
if item.itype.is_none() {
bail!("type should not be null");
}
match item.itype.unwrap().as_str() {
"remote" => {
if item.url.is_none() {
bail!("url should not be null");
}
let url = item.url.as_ref().unwrap().as_str();
let name = item.name;
let desc = item.desc;
PrfItem::from_url(url, name, desc, item.option).await
}
"local" => {
let name = item.name.unwrap_or("Local File".into());
let desc = item.desc.unwrap_or("".into());
PrfItem::from_local(name, desc, file_data)
}
"merge" => {
let name = item.name.unwrap_or("Merge".into());
let desc = item.desc.unwrap_or("".into());
PrfItem::from_merge(name, desc)
}
"script" => {
let name = item.name.unwrap_or("Script".into());
let desc = item.desc.unwrap_or("".into());
PrfItem::from_script(name, desc)
}
typ @ _ => bail!("invalid profile item type \"{typ}\""),
}
}
/// ## Local type
/// create a new item from name/desc
pub fn from_local(name: String, desc: String, file_data: Option<String>) -> Result<PrfItem> {
let uid = help::get_uid("l");
let file = format!("{uid}.yaml");
Ok(PrfItem {
uid: Some(uid),
itype: Some("local".into()),
name: Some(name),
desc: Some(desc),
file: Some(file),
url: None,
selected: None,
extra: None,
option: None,
updated: Some(help::get_now()),
file_data: Some(file_data.unwrap_or(tmpl::ITEM_LOCAL.into())),
})
}
/// ## Remote type
/// create a new item from url
pub async fn from_url(
url: &str,
name: Option<String>,
desc: Option<String>,
option: Option<PrfOption>,
) -> Result<PrfItem> {
let with_proxy = match option.as_ref() {
Some(opt) => opt.with_proxy.unwrap_or(false),
None => false,
};
let user_agent = match option.as_ref() {
Some(opt) => opt.user_agent.clone(),
None => None,
};
let mut builder = reqwest::ClientBuilder::new();
if !with_proxy {
builder = builder.no_proxy();
}
builder = builder.user_agent(user_agent.unwrap_or("clash-verge/v1.0.0".into()));
let resp = builder.build()?.get(url).send().await?;
let header = resp.headers();
// parse the Subscription Userinfo
let extra = match header.get("Subscription-Userinfo") {
Some(value) => {
let sub_info = value.to_str().unwrap_or("");
Some(PrfExtra {
upload: help::parse_str(sub_info, "upload=").unwrap_or(0),
download: help::parse_str(sub_info, "download=").unwrap_or(0),
total: help::parse_str(sub_info, "total=").unwrap_or(0),
expire: help::parse_str(sub_info, "expire=").unwrap_or(0),
})
}
None => None,
};
// parse the Content-Disposition
let filename = match header.get("Content-Disposition") {
Some(value) => {
let filename = value.to_str().unwrap_or("");
help::parse_str::<String>(filename, "filename=")
}
None => None,
};
// parse the profile-update-interval
let option = match header.get("profile-update-interval") {
Some(value) => match value.to_str().unwrap_or("").parse::<u64>() {
Ok(val) => Some(PrfOption {
update_interval: Some(val * 60), // hour -> min
..PrfOption::default()
}),
Err(_) => None,
},
None => None,
};
let uid = help::get_uid("r");
let file = format!("{uid}.yaml");
let name = name.unwrap_or(filename.unwrap_or("Remote File".into()));
let data = resp.text_with_charset("utf-8").await?;
// check the data whether the valid yaml format
if !serde_yaml::from_str::<Mapping>(&data).is_ok() {
bail!("the remote profile data is not valid yaml");
}
Ok(PrfItem {
uid: Some(uid),
itype: Some("remote".into()),
name: Some(name),
desc,
file: Some(file),
url: Some(url.into()),
selected: None,
extra,
option,
updated: Some(help::get_now()),
file_data: Some(data),
})
}
/// ## Merge type (enhance)
/// create the enhanced item by using `merge` rule
pub fn from_merge(name: String, desc: String) -> Result<PrfItem> {
let uid = help::get_uid("m");
let file = format!("{uid}.yaml");
Ok(PrfItem {
uid: Some(uid),
itype: Some("merge".into()),
name: Some(name),
desc: Some(desc),
file: Some(file),
url: None,
selected: None,
extra: None,
option: None,
updated: Some(help::get_now()),
file_data: Some(tmpl::ITEM_MERGE.into()),
})
}
/// ## Script type (enhance)
/// create the enhanced item by using javascript(browserjs)
pub fn from_script(name: String, desc: String) -> Result<PrfItem> {
let uid = help::get_uid("s");
let file = format!("{uid}.js"); // js ext
Ok(PrfItem {
uid: Some(uid),
itype: Some("script".into()),
name: Some(name),
desc: Some(desc),
file: Some(file),
url: None,
selected: None,
extra: None,
option: None,
updated: Some(help::get_now()),
file_data: Some(tmpl::ITEM_SCRIPT.into()),
})
}
/// get the file data
pub fn read_file(&self) -> Result<String> {
if self.file.is_none() {
bail!("could not find the file");
}
let file = self.file.clone().unwrap();
let path = dirs::app_profiles_dir().join(file);
fs::read_to_string(path).context("failed to read the file")
}
/// save the file data
pub fn save_file(&self, data: String) -> Result<()> {
if self.file.is_none() {
bail!("could not find the file");
}
let file = self.file.clone().unwrap();
let path = dirs::app_profiles_dir().join(file);
fs::write(path, data.as_bytes()).context("failed to save the file")
}
}
+21 -384
View File
@@ -1,308 +1,11 @@
use crate::utils::{config, dirs, help, tmpl};
use super::enhance::{PrfData, PrfEnhanced};
use super::prfitem::PrfItem;
use crate::utils::{config, dirs, help};
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use serde_yaml::Mapping;
use std::{fs, io::Write};
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PrfItem {
pub uid: Option<String>,
/// profile item type
/// enum value: remote | local | script | merge
#[serde(rename = "type")]
pub itype: Option<String>,
/// profile name
pub name: Option<String>,
/// profile description
#[serde(skip_serializing_if = "Option::is_none")]
pub desc: Option<String>,
/// profile file
pub file: Option<String>,
/// source url
#[serde(skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
/// selected infomation
#[serde(skip_serializing_if = "Option::is_none")]
pub selected: Option<Vec<PrfSelected>>,
/// subscription user info
#[serde(skip_serializing_if = "Option::is_none")]
pub extra: Option<PrfExtra>,
/// updated time
pub updated: Option<usize>,
/// some options of the item
#[serde(skip_serializing_if = "Option::is_none")]
pub option: Option<PrfOption>,
/// the file data
#[serde(skip)]
pub file_data: Option<String>,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct PrfSelected {
pub name: Option<String>,
pub now: Option<String>,
}
#[derive(Default, Debug, Clone, Copy, Deserialize, Serialize)]
pub struct PrfExtra {
pub upload: usize,
pub download: usize,
pub total: usize,
pub expire: usize,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct PrfOption {
/// for `remote` profile's http request
/// see issue #13
#[serde(skip_serializing_if = "Option::is_none")]
pub user_agent: Option<String>,
/// for `remote` profile
#[serde(skip_serializing_if = "Option::is_none")]
pub with_proxy: Option<bool>,
}
impl PrfOption {
pub fn merge(one: Option<Self>, other: Option<Self>) -> Option<Self> {
if one.is_some() && other.is_some() {
let mut one = one.unwrap();
let other = other.unwrap();
if let Some(val) = other.user_agent {
one.user_agent = Some(val);
}
if let Some(val) = other.with_proxy {
one.with_proxy = Some(val);
}
return Some(one);
}
if one.is_none() {
return other;
}
return one;
}
}
impl Default for PrfItem {
fn default() -> Self {
PrfItem {
uid: None,
itype: None,
name: None,
desc: None,
file: None,
url: None,
selected: None,
extra: None,
updated: None,
option: None,
file_data: None,
}
}
}
impl PrfItem {
/// From partial item
/// must contain `itype`
pub async fn from(item: PrfItem, file_data: Option<String>) -> Result<PrfItem> {
if item.itype.is_none() {
bail!("type should not be null");
}
match item.itype.unwrap().as_str() {
"remote" => {
if item.url.is_none() {
bail!("url should not be null");
}
let url = item.url.as_ref().unwrap().as_str();
let name = item.name;
let desc = item.desc;
PrfItem::from_url(url, name, desc, item.option).await
}
"local" => {
let name = item.name.unwrap_or("Local File".into());
let desc = item.desc.unwrap_or("".into());
PrfItem::from_local(name, desc, file_data)
}
"merge" => {
let name = item.name.unwrap_or("Merge".into());
let desc = item.desc.unwrap_or("".into());
PrfItem::from_merge(name, desc)
}
"script" => {
let name = item.name.unwrap_or("Script".into());
let desc = item.desc.unwrap_or("".into());
PrfItem::from_script(name, desc)
}
typ @ _ => bail!("invalid type \"{typ}\""),
}
}
/// ## Local type
/// create a new item from name/desc
pub fn from_local(name: String, desc: String, file_data: Option<String>) -> Result<PrfItem> {
let uid = help::get_uid("l");
let file = format!("{uid}.yaml");
Ok(PrfItem {
uid: Some(uid),
itype: Some("local".into()),
name: Some(name),
desc: Some(desc),
file: Some(file),
url: None,
selected: None,
extra: None,
option: None,
updated: Some(help::get_now()),
file_data: Some(file_data.unwrap_or(tmpl::ITEM_LOCAL.into())),
})
}
/// ## Remote type
/// create a new item from url
pub async fn from_url(
url: &str,
name: Option<String>,
desc: Option<String>,
option: Option<PrfOption>,
) -> Result<PrfItem> {
let with_proxy = match option.as_ref() {
Some(opt) => opt.with_proxy.unwrap_or(false),
None => false,
};
let user_agent = match option.as_ref() {
Some(opt) => opt.user_agent.clone(),
None => None,
};
let mut builder = reqwest::ClientBuilder::new();
if !with_proxy {
builder = builder.no_proxy();
}
if let Some(user_agent) = user_agent {
builder = builder.user_agent(user_agent);
}
let resp = builder.build()?.get(url).send().await?;
let header = resp.headers();
// parse the Subscription Userinfo
let extra = match header.get("Subscription-Userinfo") {
Some(value) => {
let sub_info = value.to_str().unwrap_or("");
Some(PrfExtra {
upload: help::parse_str(sub_info, "upload=").unwrap_or(0),
download: help::parse_str(sub_info, "download=").unwrap_or(0),
total: help::parse_str(sub_info, "total=").unwrap_or(0),
expire: help::parse_str(sub_info, "expire=").unwrap_or(0),
})
}
None => None,
};
let uid = help::get_uid("r");
let file = format!("{uid}.yaml");
let name = name.unwrap_or(uid.clone());
let data = resp.text_with_charset("utf-8").await?;
Ok(PrfItem {
uid: Some(uid),
itype: Some("remote".into()),
name: Some(name),
desc,
file: Some(file),
url: Some(url.into()),
selected: None,
extra,
option,
updated: Some(help::get_now()),
file_data: Some(data),
})
}
/// ## Merge type (enhance)
/// create the enhanced item by using `merge` rule
pub fn from_merge(name: String, desc: String) -> Result<PrfItem> {
let uid = help::get_uid("m");
let file = format!("{uid}.yaml");
Ok(PrfItem {
uid: Some(uid),
itype: Some("merge".into()),
name: Some(name),
desc: Some(desc),
file: Some(file),
url: None,
selected: None,
extra: None,
option: None,
updated: Some(help::get_now()),
file_data: Some(tmpl::ITEM_MERGE.into()),
})
}
/// ## Script type (enhance)
/// create the enhanced item by using javascript(browserjs)
pub fn from_script(name: String, desc: String) -> Result<PrfItem> {
let uid = help::get_uid("s");
let file = format!("{uid}.js"); // js ext
Ok(PrfItem {
uid: Some(uid),
itype: Some("script".into()),
name: Some(name),
desc: Some(desc),
file: Some(file),
url: None,
selected: None,
extra: None,
option: None,
updated: Some(help::get_now()),
file_data: Some(tmpl::ITEM_SCRIPT.into()),
})
}
/// get the file data
pub fn read_file(&self) -> Result<String> {
if self.file.is_none() {
bail!("could not find the file");
}
let file = self.file.clone().unwrap();
let path = dirs::app_profiles_dir().join(file);
fs::read_to_string(path).context("failed to read the file")
}
/// save the file data
pub fn save_file(&self, data: String) -> Result<()> {
if self.file.is_none() {
bail!("could not find the file");
}
let file = self.file.clone().unwrap();
let path = dirs::app_profiles_dir().join(file);
fs::write(path, data.as_bytes()).context("failed to save the file")
}
}
///
/// ## Profiles Config
///
@@ -332,6 +35,10 @@ macro_rules! patch {
}
impl Profiles {
pub fn new() -> Self {
Profiles::read_file()
}
/// read the config from the file
pub fn read_file() -> Self {
let mut profiles = config::read_yaml::<Self>(dirs::profiles_path());
@@ -340,6 +47,7 @@ impl Profiles {
profiles.items = Some(vec![]);
}
// compatiable with the old old old version
profiles.items.as_mut().map(|items| {
for mut item in items.iter_mut() {
if item.uid.is_none() {
@@ -360,19 +68,6 @@ impl Profiles {
)
}
/// sync the config between file and memory
pub fn sync_file(&mut self) -> Result<()> {
let data = Self::read_file();
if data.current.is_none() && data.items.is_none() {
bail!("failed to read profiles.yaml");
}
self.current = data.current;
self.chain = data.chain;
self.items = data.items;
Ok(())
}
/// get the current uid
pub fn get_current(&self) -> Option<String> {
self.current.clone()
@@ -387,11 +82,9 @@ impl Profiles {
let items = self.items.as_ref().unwrap();
let some_uid = Some(uid.clone());
for each in items.iter() {
if each.uid == some_uid {
self.current = some_uid;
return self.save_file();
}
if items.iter().find(|&each| each.uid == some_uid).is_some() {
self.current = some_uid;
return self.save_file();
}
bail!("invalid uid \"{uid}\"");
@@ -407,6 +100,11 @@ impl Profiles {
self.valid = valid;
}
/// get items ref
pub fn get_items(&self) -> Option<&Vec<PrfItem>> {
self.items.as_ref()
}
/// find the item by the uid
pub fn get_item(&self, uid: &String) -> Result<&PrfItem> {
if self.items.is_some() {
@@ -455,7 +153,7 @@ impl Profiles {
self.save_file()
}
/// update the item's value
/// update the item value
pub fn patch_item(&mut self, uid: String, item: PrfItem) -> Result<()> {
let mut items = self.items.take().unwrap_or(vec![]);
@@ -490,7 +188,7 @@ impl Profiles {
// find the item
let _ = self.get_item(&uid)?;
self.items.as_mut().map(|items| {
if let Some(items) = self.items.as_mut() {
let some_uid = Some(uid.clone());
for mut each in items.iter_mut() {
@@ -510,15 +208,15 @@ impl Profiles {
let path = dirs::app_profiles_dir().join(&file);
fs::File::create(path)
.unwrap()
.context(format!("failed to create file \"{}\"", file))?
.write(file_data.as_bytes())
.unwrap();
.context(format!("failed to write to file \"{}\"", file))?;
}
break;
}
}
});
}
self.save_file()
}
@@ -617,64 +315,3 @@ impl Profiles {
})
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct PrfEnhanced {
pub current: Mapping,
pub chain: Vec<PrfData>,
pub valid: Vec<String>,
pub callback: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct PrfEnhancedResult {
pub data: Option<Mapping>,
pub status: String,
pub error: Option<String>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct PrfData {
item: PrfItem,
#[serde(skip_serializing_if = "Option::is_none")]
merge: Option<Mapping>,
#[serde(skip_serializing_if = "Option::is_none")]
script: Option<String>,
}
impl PrfData {
pub fn from_item(item: &PrfItem) -> Option<PrfData> {
match item.itype.as_ref() {
Some(itype) => {
let file = item.file.clone()?;
let path = dirs::app_profiles_dir().join(file);
if !path.exists() {
return None;
}
match itype.as_str() {
"script" => Some(PrfData {
item: item.clone(),
script: Some(fs::read_to_string(path).unwrap_or("".into())),
merge: None,
}),
"merge" => Some(PrfData {
item: item.clone(),
merge: Some(config::read_yaml::<Mapping>(path)),
script: None,
}),
_ => None,
}
}
None => None,
}
}
}
+388
View File
@@ -0,0 +1,388 @@
use super::{notice::Notice, ClashInfo};
use crate::log_if_err;
use crate::utils::{config, dirs};
use anyhow::{bail, Result};
use reqwest::header::HeaderMap;
use serde::{Deserialize, Serialize};
use serde_yaml::Mapping;
use std::{collections::HashMap, time::Duration};
use tauri::api::process::{Command, CommandChild, CommandEvent};
use tokio::time::sleep;
#[derive(Debug)]
pub struct Service {
sidecar: Option<CommandChild>,
#[allow(unused)]
service_mode: bool,
}
impl Service {
pub fn new() -> Service {
Service {
sidecar: None,
service_mode: false,
}
}
#[allow(unused)]
pub fn set_mode(&mut self, enable: bool) {
self.service_mode = enable;
}
#[cfg(not(windows))]
pub fn start(&mut self) -> Result<()> {
self.start_clash_by_sidecar()
}
#[cfg(windows)]
pub fn start(&mut self) -> Result<()> {
if !self.service_mode {
return self.start_clash_by_sidecar();
}
tauri::async_runtime::spawn(async move {
match Self::check_service().await {
Ok(status) => {
// 未启动clash
if status.code != 0 {
if let Err(err) = Self::start_clash_by_service().await {
log::error!("{err}");
}
}
}
Err(err) => log::error!("{err}"),
}
});
Ok(())
}
#[cfg(not(windows))]
pub fn stop(&mut self) -> Result<()> {
self.stop_clash_by_sidecar()
}
#[cfg(windows)]
pub fn stop(&mut self) -> Result<()> {
if !self.service_mode {
return self.stop_clash_by_sidecar();
}
tauri::async_runtime::spawn(async move {
if let Err(err) = Self::stop_clash_by_service().await {
log::error!("{err}");
}
});
Ok(())
}
pub fn restart(&mut self) -> Result<()> {
self.stop()?;
self.start()
}
/// start the clash sidecar
fn start_clash_by_sidecar(&mut self) -> Result<()> {
if self.sidecar.is_some() {
bail!("could not run clash sidecar twice");
}
let app_dir = dirs::app_home_dir();
let app_dir = app_dir.as_os_str().to_str().unwrap();
let cmd = Command::new_sidecar("clash")?;
let (mut rx, cmd_child) = cmd.args(["-d", app_dir]).spawn()?;
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!("[clash]: {}", line),
CommandEvent::Stderr(err) => log::error!("[clash]: {}", err),
_ => {}
}
}
});
Ok(())
}
/// stop the clash sidecar
fn stop_clash_by_sidecar(&mut self) -> Result<()> {
if let Some(sidecar) = self.sidecar.take() {
sidecar.kill()?;
}
Ok(())
}
/// update clash config
/// using PUT methods
pub fn set_config(&self, info: ClashInfo, config: Mapping, notice: Notice) -> Result<()> {
if !self.service_mode && self.sidecar.is_none() {
bail!("did not start sidecar");
}
let temp_path = dirs::profiles_temp_path();
config::save_yaml(temp_path.clone(), &config, Some("# Clash Verge Temp File"))?;
if info.server.is_none() {
bail!("failed to parse the server");
}
let server = info.server.unwrap();
let server = format!("http://{server}/configs");
let mut headers = HeaderMap::new();
headers.insert("Content-Type", "application/json".parse().unwrap());
if let Some(secret) = info.secret.as_ref() {
let secret = format!("Bearer {}", secret.clone()).parse().unwrap();
headers.insert("Authorization", secret);
}
tauri::async_runtime::spawn(async move {
let mut data = HashMap::new();
data.insert("path", temp_path.as_os_str().to_str().unwrap());
// retry 5 times
for _ in 0..5 {
match reqwest::ClientBuilder::new().no_proxy().build() {
Ok(client) => {
let builder = client.put(&server).headers(headers.clone()).json(&data);
match builder.send().await {
Ok(resp) => {
if resp.status() != 204 {
log::error!("failed to activate clash with status \"{}\"", resp.status());
}
notice.refresh_clash();
// do not retry
break;
}
Err(err) => log::error!("failed to activate for `{err}`"),
}
}
Err(err) => log::error!("failed to activate for `{err}`"),
}
sleep(Duration::from_millis(500)).await;
}
});
Ok(())
}
}
impl Drop for Service {
fn drop(&mut self) {
log_if_err!(self.stop());
}
}
/// ### Service Mode
///
#[cfg(windows)]
pub mod win_service {
use super::*;
use anyhow::Context;
use deelevate::{PrivilegeLevel, Token};
use runas::Command as RunasCommand;
use std::os::windows::process::CommandExt;
use std::{env::current_exe, process::Command as StdCommand};
const SERVICE_NAME: &str = "clash_verge_service";
const SERVICE_URL: &str = "http://127.0.0.1:33211";
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ResponseBody {
pub bin_path: String,
pub config_dir: String,
pub log_file: String,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct JsonResponse {
pub code: u64,
pub msg: String,
pub data: Option<ResponseBody>,
}
impl Service {
/// Install the Clash Verge Service
/// 该函数应该在协程或者线程中执行,避免UAC弹窗阻塞主线程
pub async fn install_service() -> Result<()> {
let binary_path = dirs::service_path();
let install_path = binary_path.with_file_name("install-service.exe");
if !install_path.exists() {
bail!("installer exe not found");
}
let token = Token::with_current_process()?;
let level = token.privilege_level()?;
let status = match level {
PrivilegeLevel::NotPrivileged => RunasCommand::new(install_path).status()?,
_ => StdCommand::new(install_path)
.creation_flags(0x08000000)
.status()?,
};
if !status.success() {
bail!(
"failed to install service with status {}",
status.code().unwrap()
);
}
Ok(())
}
/// Uninstall the Clash Verge Service
/// 该函数应该在协程或者线程中执行,避免UAC弹窗阻塞主线程
pub async fn uninstall_service() -> Result<()> {
let binary_path = dirs::service_path();
let uninstall_path = binary_path.with_file_name("uninstall-service.exe");
if !uninstall_path.exists() {
bail!("uninstaller exe not found");
}
let token = Token::with_current_process()?;
let level = token.privilege_level()?;
let status = match level {
PrivilegeLevel::NotPrivileged => RunasCommand::new(uninstall_path).status()?,
_ => StdCommand::new(uninstall_path)
.creation_flags(0x08000000)
.status()?,
};
if !status.success() {
bail!(
"failed to uninstall service with status {}",
status.code().unwrap()
);
}
Ok(())
}
/// [deprecated]
/// start service
/// 该函数应该在协程或者线程中执行,避免UAC弹窗阻塞主线程
pub async fn start_service() -> Result<()> {
let token = Token::with_current_process()?;
let level = token.privilege_level()?;
let args = ["start", SERVICE_NAME];
let status = match level {
PrivilegeLevel::NotPrivileged => RunasCommand::new("sc").args(&args).status()?,
_ => StdCommand::new("sc").args(&args).status()?,
};
match status.success() {
true => Ok(()),
false => bail!(
"failed to start service with status {}",
status.code().unwrap()
),
}
}
/// stop service
pub async fn stop_service() -> Result<()> {
let url = format!("{SERVICE_URL}/stop_service");
let res = reqwest::Client::new()
.post(url)
.send()
.await?
.json::<JsonResponse>()
.await
.context("failed to connect to the Clash Verge Service")?;
if res.code != 0 {
bail!(res.msg);
}
Ok(())
}
/// check the windows service status
pub async fn check_service() -> Result<JsonResponse> {
let url = format!("{SERVICE_URL}/get_clash");
let response = reqwest::get(url)
.await?
.json::<JsonResponse>()
.await
.context("failed to connect to the Clash Verge Service")?;
Ok(response)
}
/// start the clash by service
pub(super) async fn start_clash_by_service() -> Result<()> {
let status = Self::check_service().await?;
if status.code == 0 {
Self::stop_clash_by_service().await?;
sleep(Duration::from_secs(1)).await;
}
let bin_path = current_exe().unwrap().with_file_name("clash.exe");
let bin_path = bin_path.as_os_str().to_str().unwrap();
let config_dir = dirs::app_home_dir();
let config_dir = config_dir.as_os_str().to_str().unwrap();
let log_path = dirs::service_log_file();
let log_path = log_path.as_os_str().to_str().unwrap();
let mut map = HashMap::new();
map.insert("bin_path", bin_path);
map.insert("config_dir", config_dir);
map.insert("log_file", log_path);
let url = format!("{SERVICE_URL}/start_clash");
let res = reqwest::Client::new()
.post(url)
.json(&map)
.send()
.await?
.json::<JsonResponse>()
.await
.context("failed to connect to the Clash Verge Service")?;
if res.code != 0 {
bail!(res.msg);
}
Ok(())
}
/// stop the clash by service
pub(super) async fn stop_clash_by_service() -> Result<()> {
let url = format!("{SERVICE_URL}/stop_clash");
let res = reqwest::Client::new()
.post(url)
.send()
.await?
.json::<JsonResponse>()
.await
.context("failed to connect to the Clash Verge Service")?;
if res.code != 0 {
bail!(res.msg);
}
Ok(())
}
}
}
+205
View File
@@ -0,0 +1,205 @@
use super::{Clash, Verge};
use crate::{log_if_err, utils::sysopt::SysProxyConfig};
use anyhow::{bail, Result};
use auto_launch::{AutoLaunch, AutoLaunchBuilder};
// use parking_lot::Mutex;
use std::sync::Arc;
use tauri::{async_runtime::Mutex, utils::platform::current_exe};
pub struct Sysopt {
/// current system proxy setting
cur_sysproxy: Option<SysProxyConfig>,
/// record the original system proxy
/// recover it when exit
old_sysproxy: Option<SysProxyConfig>,
/// helps to auto launch the app
auto_launch: Option<AutoLaunch>,
/// record whether the guard async is running or not
guard_state: Arc<Mutex<bool>>,
}
impl Sysopt {
pub fn new() -> Sysopt {
Sysopt {
cur_sysproxy: None,
old_sysproxy: None,
auto_launch: None,
guard_state: Arc::new(Mutex::new(false)),
}
}
/// init the sysproxy
pub fn init_sysproxy(&mut self, port: Option<String>, verge: &Verge) {
if let Some(port) = port {
let enable = verge.enable_system_proxy.clone().unwrap_or(false);
self.old_sysproxy = match SysProxyConfig::get_sys() {
Ok(proxy) => Some(proxy),
Err(_) => None,
};
let bypass = verge.system_proxy_bypass.clone();
let sysproxy = SysProxyConfig::new(enable, port, bypass);
if enable {
if let Err(err) = sysproxy.set_sys() {
log::error!("failed to set system proxy for `{err}`");
}
}
self.cur_sysproxy = Some(sysproxy);
}
// launchs the system proxy guard
self.guard_proxy();
}
/// update the system proxy
/// when the verge config is changed
pub fn update_sysproxy(&mut self, enable: Option<bool>, bypass: Option<String>) -> Result<()> {
let sysproxy = self.cur_sysproxy.take();
if sysproxy.is_none() {
bail!("unhandle error for sysproxy is none");
}
let mut sysproxy = sysproxy.unwrap();
if let Some(enable) = enable {
sysproxy.enable = enable;
}
if let Some(bypass) = bypass {
sysproxy.bypass = bypass;
}
self.cur_sysproxy = Some(sysproxy);
if self.cur_sysproxy.as_ref().unwrap().set_sys().is_err() {
bail!("failed to set system proxy");
}
Ok(())
}
/// 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"),
}
}
}
/// get current proxy
pub fn get_sysproxy(&self) -> Result<Option<SysProxyConfig>> {
Ok(self.cur_sysproxy.clone())
}
/// init the auto launch
pub fn init_launch(&mut self, enable: Option<bool>) -> Result<()> {
let app_exe = current_exe().unwrap();
let app_exe = dunce::canonicalize(app_exe).unwrap();
let app_name = app_exe.file_stem().unwrap().to_str().unwrap();
let app_path = app_exe.as_os_str().to_str().unwrap();
// fix issue #26
#[cfg(target_os = "windows")]
let app_path = format!("\"{app_path}\"");
#[cfg(target_os = "windows")]
let app_path = app_path.as_str();
let auto = AutoLaunchBuilder::new()
.set_app_name(app_name)
.set_app_path(app_path)
.build();
if let Some(enable) = enable {
// fix issue #26
if enable {
auto.enable()?;
}
}
self.auto_launch = Some(auto);
Ok(())
}
/// update the startup
pub fn update_launch(&mut self, enable: Option<bool>) -> Result<()> {
if enable.is_none() {
return Ok(());
}
let enable = enable.unwrap();
let auto_launch = self.auto_launch.as_ref().unwrap();
match enable {
true => auto_launch.enable()?,
false => auto_launch.disable()?,
};
Ok(())
}
/// launch a system proxy guard
/// read config from file directly
pub fn guard_proxy(&self) {
use tokio::time::{sleep, Duration};
let guard_state = self.guard_state.clone();
tauri::async_runtime::spawn(async move {
// if it is running, exit
let mut state = guard_state.lock().await;
if *state {
return;
}
*state = true;
drop(state);
// default duration is 10s
let mut wait_secs = 10u64;
loop {
sleep(Duration::from_secs(wait_secs)).await;
let verge = Verge::new();
let enable_proxy = verge.enable_system_proxy.unwrap_or(false);
let enable_guard = verge.enable_proxy_guard.unwrap_or(false);
let guard_duration = verge.proxy_guard_duration.unwrap_or(10);
// update duration
wait_secs = guard_duration;
// stop loop
if !enable_guard || !enable_proxy {
break;
}
log::debug!("try to guard the system proxy");
let clash = Clash::new();
match &clash.info.port {
Some(port) => {
let bypass = verge.system_proxy_bypass.clone();
let sysproxy = SysProxyConfig::new(true, port.clone(), bypass);
log_if_err!(sysproxy.set_sys());
}
None => log::error!("failed to parse clash port"),
}
}
let mut state = guard_state.lock().await;
*state = false;
});
}
}
+152
View File
@@ -0,0 +1,152 @@
use super::Core;
use crate::log_if_err;
use anyhow::{bail, Context, Result};
use delay_timer::prelude::{DelayTimer, DelayTimerBuilder, TaskBuilder};
use std::collections::HashMap;
type TaskID = u64;
pub struct Timer {
/// cron manager
delay_timer: DelayTimer,
/// save the current state
timer_map: HashMap<String, (TaskID, u64)>,
/// increment id
timer_count: TaskID,
/// save the instance of the app
core: Option<Core>,
}
impl Timer {
pub fn new() -> Self {
Timer {
delay_timer: DelayTimerBuilder::default().build(),
timer_map: HashMap::new(),
timer_count: 1,
core: None,
}
}
pub fn set_core(&mut self, core: Core) {
self.core = Some(core);
}
/// Correctly update all cron tasks
pub fn refresh(&mut self) -> Result<()> {
if self.core.is_none() {
bail!("unhandle error for core is none");
}
let diff_map = self.gen_diff();
for (uid, diff) in diff_map.into_iter() {
match diff {
DiffFlag::Del(tid) => {
let _ = self.timer_map.remove(&uid);
log_if_err!(self.delay_timer.remove_task(tid));
}
DiffFlag::Add(tid, val) => {
let _ = self.timer_map.insert(uid.clone(), (tid, val));
log_if_err!(self.add_task(uid, tid, val));
}
DiffFlag::Mod(tid, val) => {
let _ = self.timer_map.insert(uid.clone(), (tid, val));
log_if_err!(self.delay_timer.remove_task(tid));
log_if_err!(self.add_task(uid, tid, val));
}
}
}
Ok(())
}
/// generate a uid -> update_interval map
fn gen_map(&self) -> HashMap<String, u64> {
let profiles = self.core.as_ref().unwrap().profiles.lock();
let mut new_map = HashMap::new();
if let Some(items) = profiles.get_items() {
for item in items.iter() {
if item.option.is_some() {
let option = item.option.as_ref().unwrap();
let interval = option.update_interval.unwrap_or(0);
if interval > 0 {
new_map.insert(item.uid.clone().unwrap(), interval);
}
}
}
}
new_map
}
/// generate the diff map for refresh
fn gen_diff(&mut self) -> HashMap<String, DiffFlag> {
let mut diff_map = HashMap::new();
let new_map = self.gen_map();
let cur_map = &self.timer_map;
cur_map.iter().for_each(|(uid, (tid, val))| {
let new_val = new_map.get(uid).unwrap_or(&0);
if *new_val == 0 {
diff_map.insert(uid.clone(), DiffFlag::Del(*tid));
} else if new_val != val {
diff_map.insert(uid.clone(), DiffFlag::Mod(*tid, *new_val));
}
});
let mut count = self.timer_count;
new_map.iter().for_each(|(uid, val)| {
if cur_map.get(uid).is_none() {
diff_map.insert(uid.clone(), DiffFlag::Add(count, *val));
count += 1;
}
});
self.timer_count = count;
diff_map
}
/// add a cron task
fn add_task(&self, uid: String, tid: TaskID, minutes: u64) -> Result<()> {
let core = self.core.clone().unwrap();
let task = TaskBuilder::default()
.set_task_id(tid)
.set_maximum_parallel_runnable_num(1)
.set_frequency_repeated_by_minutes(minutes)
// .set_frequency_repeated_by_seconds(minutes) // for test
.spawn_async_routine(move || Self::async_task(core.clone(), uid.clone()))
.context("failed to create timer task")?;
self
.delay_timer
.add_task(task)
.context("failed to add timer task")?;
Ok(())
}
/// the task runner
async fn async_task(core: Core, uid: String) {
log::info!("running timer task `{uid}`");
log_if_err!(Core::update_profile_item(core, uid, None).await);
}
}
#[derive(Debug)]
enum DiffFlag {
Del(TaskID),
Add(TaskID, u64),
Mod(TaskID, u64),
}
+34 -256
View File
@@ -1,17 +1,10 @@
use crate::log_if_err;
use crate::{
core::Clash,
utils::{config, dirs, sysopt::SysProxyConfig},
};
use anyhow::{bail, Result};
use auto_launch::{AutoLaunch, AutoLaunchBuilder};
use crate::utils::{config, dirs};
use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tauri::{async_runtime::Mutex, utils::platform::current_exe};
/// ### `verge.yaml` schema
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct VergeConfig {
pub struct Verge {
// i18n
pub language: Option<String>,
@@ -28,6 +21,10 @@ pub struct VergeConfig {
/// clash tun mode
pub enable_tun_mode: Option<bool>,
/// windows service mode
#[serde(skip_serializing_if = "Option::is_none")]
pub enable_service_mode: Option<bool>,
/// can the app auto startup
pub enable_auto_launch: Option<bool>,
@@ -66,9 +63,9 @@ pub struct VergeTheme {
pub css_injection: Option<String>,
}
impl VergeConfig {
impl Verge {
pub fn new() -> Self {
config::read_yaml::<VergeConfig>(dirs::verge_path())
config::read_yaml::<Verge>(dirs::verge_path())
}
/// Save Verge App Config
@@ -79,276 +76,57 @@ impl VergeConfig {
Some("# The Config for Clash Verge App\n\n"),
)
}
}
/// Verge App abilities
#[derive(Debug)]
pub struct Verge {
/// manage the verge config
pub config: VergeConfig,
/// current system proxy setting
pub cur_sysproxy: Option<SysProxyConfig>,
/// record the original system proxy
/// recover it when exit
old_sysproxy: Option<SysProxyConfig>,
/// helps to auto launch the app
auto_launch: Option<AutoLaunch>,
/// record whether the guard async is running or not
guard_state: Arc<Mutex<bool>>,
}
impl Default for Verge {
fn default() -> Self {
Verge::new()
}
}
impl Verge {
pub fn new() -> Self {
Verge {
config: VergeConfig::new(),
old_sysproxy: None,
cur_sysproxy: None,
auto_launch: None,
guard_state: Arc::new(Mutex::new(false)),
}
}
/// init the sysproxy
pub fn init_sysproxy(&mut self, port: Option<String>) {
if let Some(port) = port {
let enable = self.config.enable_system_proxy.clone().unwrap_or(false);
self.old_sysproxy = match SysProxyConfig::get_sys() {
Ok(proxy) => Some(proxy),
Err(_) => None,
};
let bypass = self.config.system_proxy_bypass.clone();
let sysproxy = SysProxyConfig::new(enable, port, bypass);
if enable {
if sysproxy.set_sys().is_err() {
log::error!("failed to set system proxy");
}
}
self.cur_sysproxy = Some(sysproxy);
}
// launchs the system proxy guard
Verge::guard_proxy(self.guard_state.clone());
}
/// reset the sysproxy
pub fn reset_sysproxy(&mut self) {
if let Some(sysproxy) = self.old_sysproxy.take() {
match sysproxy.set_sys() {
Ok(_) => self.cur_sysproxy = None,
Err(_) => log::error!("failed to reset proxy for"),
}
}
}
/// init the auto launch
pub fn init_launch(&mut self) -> Result<()> {
let app_exe = current_exe().unwrap();
let app_exe = dunce::canonicalize(app_exe).unwrap();
let app_name = app_exe.file_stem().unwrap().to_str().unwrap();
let app_path = app_exe.as_os_str().to_str().unwrap();
// fix issue #26
#[cfg(target_os = "windows")]
let app_path = format!("\"{app_path}\"");
#[cfg(target_os = "windows")]
let app_path = app_path.as_str();
let auto = AutoLaunchBuilder::new()
.set_app_name(app_name)
.set_app_path(app_path)
.build();
if let Some(enable) = self.config.enable_auto_launch.as_ref() {
// fix issue #26
if *enable {
auto.enable()?;
}
}
self.auto_launch = Some(auto);
Ok(())
}
/// update the startup
fn update_launch(&mut self, enable: bool) -> Result<()> {
let conf_enable = self.config.enable_auto_launch.clone().unwrap_or(false);
if enable == conf_enable {
return Ok(());
}
let auto_launch = self.auto_launch.clone().unwrap();
match enable {
true => auto_launch.enable()?,
false => auto_launch.disable()?,
};
Ok(())
}
/// patch verge config
/// There should be only one update at a time here
/// so call the save_file at the end is savely
pub fn patch_config(&mut self, patch: VergeConfig) -> Result<()> {
/// only save to file
pub fn patch_config(&mut self, patch: Verge) -> Result<()> {
// only change it
if patch.language.is_some() {
self.config.language = patch.language;
self.language = patch.language;
}
if patch.theme_mode.is_some() {
self.config.theme_mode = patch.theme_mode;
self.theme_mode = patch.theme_mode;
}
if patch.theme_blur.is_some() {
self.config.theme_blur = patch.theme_blur;
}
if patch.traffic_graph.is_some() {
self.config.traffic_graph = patch.traffic_graph;
}
if patch.enable_silent_start.is_some() {
self.config.enable_silent_start = patch.enable_silent_start;
self.theme_blur = patch.theme_blur;
}
if patch.theme_setting.is_some() {
self.config.theme_setting = patch.theme_setting;
self.theme_setting = patch.theme_setting;
}
if patch.traffic_graph.is_some() {
self.traffic_graph = patch.traffic_graph;
}
// should update system startup
// system setting
if patch.enable_silent_start.is_some() {
self.enable_silent_start = patch.enable_silent_start;
}
if patch.enable_auto_launch.is_some() {
let enable = patch.enable_auto_launch.unwrap();
self.update_launch(enable)?;
self.config.enable_auto_launch = Some(enable);
self.enable_auto_launch = patch.enable_auto_launch;
}
// should update system proxy
// proxy
if patch.enable_system_proxy.is_some() {
let enable = patch.enable_system_proxy.unwrap();
if let Some(mut sysproxy) = self.cur_sysproxy.take() {
sysproxy.enable = enable;
if sysproxy.set_sys().is_err() {
self.cur_sysproxy = Some(sysproxy);
log::error!("failed to set system proxy");
bail!("failed to set system proxy");
}
self.cur_sysproxy = Some(sysproxy);
}
self.config.enable_system_proxy = Some(enable);
self.enable_system_proxy = patch.enable_system_proxy;
}
// should update system proxy too
if patch.system_proxy_bypass.is_some() {
let bypass = patch.system_proxy_bypass.unwrap();
if let Some(mut sysproxy) = self.cur_sysproxy.take() {
if sysproxy.enable {
sysproxy.bypass = bypass.clone();
if sysproxy.set_sys().is_err() {
self.cur_sysproxy = Some(sysproxy);
log::error!("failed to set system proxy");
bail!("failed to set system proxy");
}
}
self.cur_sysproxy = Some(sysproxy);
}
self.config.system_proxy_bypass = Some(bypass);
self.system_proxy_bypass = patch.system_proxy_bypass;
}
// proxy guard
// only change it
if patch.enable_proxy_guard.is_some() {
self.config.enable_proxy_guard = patch.enable_proxy_guard;
self.enable_proxy_guard = patch.enable_proxy_guard;
}
if patch.proxy_guard_duration.is_some() {
self.config.proxy_guard_duration = patch.proxy_guard_duration;
self.proxy_guard_duration = patch.proxy_guard_duration;
}
// relaunch the guard
if patch.enable_system_proxy.is_some() || patch.enable_proxy_guard.is_some() {
Verge::guard_proxy(self.guard_state.clone());
}
// handle the tun mode
// tun mode
if patch.enable_tun_mode.is_some() {
self.config.enable_tun_mode = patch.enable_tun_mode;
self.enable_tun_mode = patch.enable_tun_mode;
}
if patch.enable_service_mode.is_some() {
self.enable_service_mode = patch.enable_service_mode;
}
self.config.save_file()
}
}
impl Verge {
/// launch a system proxy guard
/// read config from file directly
pub fn guard_proxy(guard_state: Arc<Mutex<bool>>) {
use tokio::time::{sleep, Duration};
tauri::async_runtime::spawn(async move {
// if it is running, exit
let mut state = guard_state.lock().await;
if *state {
return;
}
*state = true;
std::mem::drop(state);
// default duration is 10s
let mut wait_secs = 10u64;
loop {
sleep(Duration::from_secs(wait_secs)).await;
log::debug!("guard heartbeat detection");
let verge = Verge::new();
let enable_proxy = verge.config.enable_system_proxy.unwrap_or(false);
let enable_guard = verge.config.enable_proxy_guard.unwrap_or(false);
let guard_duration = verge.config.proxy_guard_duration.unwrap_or(10);
// update duration
wait_secs = guard_duration;
// stop loop
if !enable_guard || !enable_proxy {
break;
}
log::info!("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);
log_if_err!(sysproxy.set_sys());
}
None => log::error!("fail to parse clash port"),
}
}
let mut state = guard_state.lock().await;
*state = false;
});
self.save_file()
}
}
+49 -35
View File
@@ -5,11 +5,10 @@
mod cmds;
mod core;
mod states;
mod utils;
use crate::{
core::VergeConfig,
core::Verge,
utils::{resolve, server},
};
use tauri::{
@@ -22,18 +21,24 @@ fn main() -> std::io::Result<()> {
return Ok(());
}
#[cfg(target_os = "windows")]
unsafe {
use crate::utils::dirs;
dirs::init_portable_flag();
}
let tray_menu = SystemTrayMenu::new()
.add_item(CustomMenuItem::new("open_window", "Show"))
.add_item(CustomMenuItem::new("system_proxy", "System Proxy"))
.add_item(CustomMenuItem::new("tun_mode", "Tun Mode"))
.add_item(CustomMenuItem::new("restart_clash", "Restart Clash"))
.add_native_item(SystemTrayMenuItem::Separator)
.add_item(CustomMenuItem::new("quit", "Quit").accelerator("CmdOrControl+Q"));
#[allow(unused_mut)]
let mut builder = tauri::Builder::default()
.manage(states::VergeState::default())
.manage(states::ClashState::default())
.manage(states::ProfilesState::default())
.manage(core::Core::new())
.setup(|app| Ok(resolve::resolve_setup(app)))
.system_tray(SystemTray::new().with_menu(tray_menu))
.on_system_tray_event(move |app_handle, event| match event {
@@ -45,42 +50,42 @@ fn main() -> std::io::Result<()> {
window.set_focus().unwrap();
}
"system_proxy" => {
let verge_state = app_handle.state::<states::VergeState>();
let mut verge = verge_state.0.lock().unwrap();
let core = app_handle.state::<core::Core>();
let old_value = verge.config.enable_system_proxy.clone().unwrap_or(false);
let new_value = !old_value;
let new_value = {
let verge = core.verge.lock();
!verge.enable_system_proxy.clone().unwrap_or(false)
};
match verge.patch_config(VergeConfig {
let patch = Verge {
enable_system_proxy: Some(new_value),
..VergeConfig::default()
}) {
Ok(_) => {
app_handle
.tray_handle()
.get_item(id.as_str())
.set_selected(new_value)
.unwrap();
..Verge::default()
};
// update verge config
let window = app_handle.get_window("main").unwrap();
window.emit("verge://refresh-verge-config", "yes").unwrap();
}
Err(err) => log::error!("{err}"),
}
crate::log_if_err!(core.patch_verge(patch, app_handle));
}
"tun_mode" => {
let core = app_handle.state::<core::Core>();
let new_value = {
let verge = core.verge.lock();
!verge.enable_tun_mode.clone().unwrap_or(false)
};
let patch = Verge {
enable_tun_mode: Some(new_value),
..Verge::default()
};
crate::log_if_err!(core.patch_verge(patch, app_handle));
}
"restart_clash" => {
let clash_state = app_handle.state::<states::ClashState>();
let profiles_state = app_handle.state::<states::ProfilesState>();
let mut clash = clash_state.0.lock().unwrap();
let mut profiles = profiles_state.0.lock().unwrap();
crate::log_if_err!(clash.restart_sidecar(&mut profiles));
let core = app_handle.state::<core::Core>();
crate::log_if_err!(core.restart_clash());
}
"quit" => {
resolve::resolve_reset(app_handle);
api::process::kill_children();
std::process::exit(0);
app_handle.exit(0);
}
_ => {}
},
@@ -98,7 +103,7 @@ fn main() -> std::io::Result<()> {
cmds::restart_sidecar,
cmds::get_sys_proxy,
cmds::get_cur_proxy,
cmds::kill_sidecars,
cmds::kill_sidecar,
cmds::open_app_dir,
cmds::open_logs_dir,
// clash
@@ -116,12 +121,17 @@ fn main() -> std::io::Result<()> {
cmds::delete_profile,
cmds::select_profile,
cmds::get_profiles,
cmds::sync_profiles,
cmds::enhance_profiles,
cmds::change_profile_chain,
cmds::change_profile_valid,
cmds::read_profile_file,
cmds::save_profile_file
cmds::save_profile_file,
// service mode
cmds::service::start_service,
cmds::service::stop_service,
cmds::service::check_service,
cmds::service::install_service,
cmds::service::uninstall_service,
]);
#[cfg(target_os = "macos")]
@@ -157,6 +167,10 @@ fn main() -> std::io::Result<()> {
resolve::resolve_reset(app_handle);
api::process::kill_children();
}
tauri::RunEvent::Exit => {
resolve::resolve_reset(app_handle);
api::process::kill_children();
}
_ => {}
});
+8 -8
View File
@@ -1,11 +1,11 @@
use crate::core::{Clash, Profiles, Verge};
use std::sync::{Arc, Mutex};
// use crate::core::{Clash, Profiles, Verge};
// use std::sync::{Arc, Mutex};
#[derive(Default)]
pub struct ProfilesState(pub Arc<Mutex<Profiles>>);
// #[derive(Default)]
// pub struct ProfilesState(pub Arc<Mutex<Profiles>>);
#[derive(Default)]
pub struct ClashState(pub Arc<Mutex<Clash>>);
// #[derive(Default)]
// pub struct ClashState(pub Arc<Mutex<Clash>>);
#[derive(Default)]
pub struct VergeState(pub Arc<Mutex<Verge>>);
// #[derive(Default)]
// pub struct VergeState(pub Arc<Mutex<Verge>>);
+76 -7
View File
@@ -1,5 +1,5 @@
use std::env::temp_dir;
use std::path::{Path, PathBuf};
use std::path::PathBuf;
use tauri::{
api::path::{home_dir, resource_dir},
Env, PackageInfo,
@@ -15,19 +15,62 @@ static VERGE_CONFIG: &str = "verge.yaml";
static PROFILE_YAML: &str = "profiles.yaml";
static PROFILE_TEMP: &str = "clash-verge-runtime.yaml";
#[cfg(windows)]
static mut RESOURCE_DIR: Option<PathBuf> = None;
/// portable flag
#[allow(unused)]
static mut PORTABLE_FLAG: bool = false;
/// initialize portable flag
#[allow(unused)]
pub unsafe fn init_portable_flag() {
#[cfg(target_os = "windows")]
{
use tauri::utils::platform::current_exe;
let exe = current_exe().unwrap();
let dir = exe.parent().unwrap();
let dir = PathBuf::from(dir).join(".config/PORTABLE");
if dir.exists() {
PORTABLE_FLAG = true;
}
}
}
/// get the verge app home dir
pub fn app_home_dir() -> PathBuf {
home_dir()
.unwrap()
.join(Path::new(".config"))
.join(Path::new(APP_DIR))
#[cfg(target_os = "windows")]
unsafe {
use tauri::utils::platform::current_exe;
if !PORTABLE_FLAG {
home_dir().unwrap().join(".config").join(APP_DIR)
} else {
let app_exe = current_exe().unwrap();
let app_exe = dunce::canonicalize(app_exe).unwrap();
let app_dir = app_exe.parent().unwrap();
PathBuf::from(app_dir).join(".config").join(APP_DIR)
}
}
#[cfg(not(target_os = "windows"))]
home_dir().unwrap().join(".config").join(APP_DIR)
}
/// get the resources dir
pub fn app_resources_dir(package_info: &PackageInfo) -> PathBuf {
resource_dir(package_info, &Env::default())
let res_dir = resource_dir(package_info, &Env::default())
.unwrap()
.join("resources")
.join("resources");
#[cfg(windows)]
unsafe {
RESOURCE_DIR = Some(res_dir.clone());
}
res_dir
}
/// profiles dir
@@ -59,3 +102,29 @@ pub fn profiles_temp_path() -> PathBuf {
#[cfg(feature = "debug-yml")]
return app_home_dir().join(PROFILE_TEMP);
}
#[cfg(windows)]
static SERVICE_PATH: &str = "clash-verge-service.exe";
#[cfg(windows)]
pub fn service_path() -> PathBuf {
unsafe {
let res_dir = RESOURCE_DIR.clone().unwrap();
res_dir.join(SERVICE_PATH)
}
}
#[cfg(windows)]
pub fn service_log_file() -> PathBuf {
use chrono::Local;
let log_dir = app_logs_dir().join("service");
let local_time = Local::now().format("%Y-%m-%d-%H%M%S").to_string();
let log_file = format!("{}.log", local_time);
let log_file = log_dir.join(log_file);
std::fs::create_dir_all(&log_dir).unwrap();
log_file
}
+35
View File
@@ -1,4 +1,7 @@
use anyhow::{bail, Result};
use nanoid::nanoid;
use std::path::PathBuf;
use std::process::Command;
use std::str::FromStr;
use std::time::{SystemTime, UNIX_EPOCH};
@@ -41,6 +44,38 @@ pub fn parse_str<T: FromStr>(target: &str, key: &str) -> Option<T> {
}
}
/// open file
/// use vscode by default
pub fn open_file(path: PathBuf) -> Result<()> {
// use vscode first
if let Ok(code) = which::which("code") {
#[cfg(target_os = "windows")]
{
use std::os::windows::process::CommandExt;
if let Err(err) = Command::new(code)
.creation_flags(0x08000000)
.arg(path)
.spawn()
{
bail!(format!("failed to open file by VScode for `{err}`"));
}
}
#[cfg(not(target_os = "windows"))]
if let Err(err) = Command::new(code).arg(path).spawn() {
bail!(format!("failed to open file by VScode for `{err}`"));
}
return Ok(());
}
match open::that(path) {
Ok(_) => Ok(()),
Err(err) => bail!(format!("failed to open file for `{err}`")),
}
}
#[macro_export]
macro_rules! log_if_err {
($result: expr) => {
+1
View File
@@ -6,3 +6,4 @@ pub mod resolve;
pub mod server;
pub mod sysopt;
pub mod tmpl;
mod winhelp;
+27 -52
View File
@@ -1,5 +1,4 @@
use super::{init, server};
use crate::{core::Profiles, log_if_err, states};
use crate::{core::Core, utils::init, utils::server};
use tauri::{App, AppHandle, Manager};
/// handle something when start app
@@ -11,78 +10,54 @@ pub fn resolve_setup(app: &App) {
init::init_app(app.package_info());
// init states
let clash_state = app.state::<states::ClashState>();
let verge_state = app.state::<states::VergeState>();
let profiles_state = app.state::<states::ProfilesState>();
let core = app.state::<Core>();
let mut clash = clash_state.0.lock().unwrap();
let mut verge = verge_state.0.lock().unwrap();
let mut profiles = profiles_state.0.lock().unwrap();
core.set_win(app.get_window("main"));
core.init(app.app_handle());
log_if_err!(clash.run_sidecar());
*profiles = Profiles::read_file();
clash.set_window(app.get_window("main"));
log_if_err!(clash.activate(&profiles));
log_if_err!(clash.activate_enhanced(&profiles, true, true));
verge.init_sysproxy(clash.info.port.clone());
log_if_err!(verge.init_launch());
verge.config.enable_system_proxy.map(|enable| {
log_if_err!(app
.tray_handle()
.get_item("system_proxy")
.set_selected(enable));
});
resolve_window(app, verge.config.enable_silent_start.clone());
resolve_window(app);
}
/// reset system proxy
pub fn resolve_reset(app_handle: &AppHandle) {
let verge_state = app_handle.state::<states::VergeState>();
let mut verge = verge_state.0.lock().unwrap();
let core = app_handle.state::<Core>();
let mut sysopt = core.sysopt.lock();
sysopt.reset_sysproxy();
drop(sysopt);
verge.reset_sysproxy();
let mut service = core.service.lock();
crate::log_if_err!(service.stop());
}
/// customize the window theme
fn resolve_window(app: &App, hide: Option<bool>) {
fn resolve_window(app: &App) {
let window = app.get_window("main").unwrap();
// silent start
hide.map(|hide| {
if hide {
window.hide().unwrap();
}
});
#[cfg(target_os = "windows")]
{
use crate::utils::winhelp;
use window_shadows::set_shadow;
use window_vibrancy::apply_blur;
window.set_decorations(false).unwrap();
set_shadow(&window, true).unwrap();
apply_blur(&window, None).unwrap();
let _ = window.set_decorations(false);
let _ = set_shadow(&window, true);
// todo
// win11 disable this feature temporarily due to lag
if !winhelp::is_win11() {
let _ = apply_blur(&window, None);
}
}
#[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);
let _ = window.set_decorations(true);
let _ = window.set_size(Logical(LogicalSize {
width: 800.0,
height: 620.0,
}));
}
}
+69
View File
@@ -0,0 +1,69 @@
#![cfg(target_os = "windows")]
#![allow(non_snake_case)]
#![allow(non_camel_case_types)]
//!
//! From https://github.com/tauri-apps/window-vibrancy/blob/dev/src/windows.rs
//!
use windows_sys::Win32::{
Foundation::*,
System::{LibraryLoader::*, SystemInformation::*},
};
fn get_function_impl(library: &str, function: &str) -> Option<FARPROC> {
assert_eq!(library.chars().last(), Some('\0'));
assert_eq!(function.chars().last(), Some('\0'));
let module = unsafe { LoadLibraryA(library.as_ptr()) };
if module == 0 {
return None;
}
Some(unsafe { GetProcAddress(module, function.as_ptr()) })
}
macro_rules! get_function {
($lib:expr, $func:ident) => {
get_function_impl(concat!($lib, '\0'), concat!(stringify!($func), '\0')).map(|f| unsafe {
std::mem::transmute::<::windows_sys::Win32::Foundation::FARPROC, $func>(f)
})
};
}
/// Returns a tuple of (major, minor, buildnumber)
fn get_windows_ver() -> Option<(u32, u32, u32)> {
type RtlGetVersion = unsafe extern "system" fn(*mut OSVERSIONINFOW) -> i32;
let handle = get_function!("ntdll.dll", RtlGetVersion);
if let Some(rtl_get_version) = handle {
unsafe {
let mut vi = OSVERSIONINFOW {
dwOSVersionInfoSize: 0,
dwMajorVersion: 0,
dwMinorVersion: 0,
dwBuildNumber: 0,
dwPlatformId: 0,
szCSDVersion: [0; 128],
};
let status = (rtl_get_version)(&mut vi as _);
if status >= 0 {
Some((vi.dwMajorVersion, vi.dwMinorVersion, vi.dwBuildNumber))
} else {
None
}
}
} else {
None
}
}
pub fn is_win11() -> bool {
let v = get_windows_ver().unwrap_or_default();
v.2 >= 22000
}
#[test]
fn test_version() {
dbg!(get_windows_ver().unwrap_or_default());
}
+3 -5
View File
@@ -1,7 +1,7 @@
{
"package": {
"productName": "Clash Verge",
"version": "0.0.28"
"version": "1.0.1"
},
"build": {
"distDir": "../dist",
@@ -32,13 +32,11 @@
"shortDescription": "A Clash GUI based on tauri.",
"longDescription": "A Clash GUI based on tauri.",
"deb": {
"depends": [],
"useBootstrapper": false
"depends": []
},
"macOS": {
"frameworks": [],
"minimumSystemVersion": "",
"useBootstrapper": false,
"exceptionDomain": "",
"signingIdentity": null,
"entitlements": null
@@ -73,7 +71,7 @@
{
"title": "Clash Verge",
"width": 800,
"height": 600,
"height": 636,
"resizable": true,
"fullscreen": false,
"decorations": false,
+2 -1
View File
@@ -11,6 +11,7 @@ body {
--primary-main: #5b5c9d;
--text-primary: #637381;
--selection-color: #f5f5f5;
--scroller-color: #90939980;
}
::selection {
@@ -25,7 +26,7 @@ body {
}
*::-webkit-scrollbar-thumb {
border-radius: 6px;
background-color: rgba(#909399, 0.5);
background-color: var(--scroller-color);
}
@import "./layout.scss";
+5 -5
View File
@@ -10,7 +10,7 @@
height: 100%;
max-width: 225px;
min-width: 125px;
padding: 8px 0;
padding: 16px 0 8px;
flex-direction: column;
box-sizing: border-box;
user-select: none;
@@ -23,14 +23,14 @@
max-width: 168px;
max-height: 168px;
margin: 0 auto;
padding: 0 8px;
padding: 0 16px;
text-align: center;
box-sizing: border-box;
img,
svg {
width: 100%;
height: 100%;
width: 96%;
height: 96%;
pointer-events: none;
}
@@ -43,7 +43,7 @@
}
.the-menu {
flex: 1 1 75%;
flex: 1 1 80%;
overflow-y: auto;
margin-bottom: 8px;
}
+17 -9
View File
@@ -4,6 +4,7 @@ import { styled, ListItem, IconButton, ListItemText } from "@mui/material";
import { CloseRounded } from "@mui/icons-material";
import { ApiType } from "../../services/types";
import { deleteConnection } from "../../services/api";
import parseTraffic from "../../utils/parse-traffic";
const Tag = styled("span")(({ theme }) => ({
display: "inline-block",
@@ -23,32 +24,39 @@ interface Props {
const ConnectionItem = (props: Props) => {
const { value } = props;
const onDelete = useLockFn(async () => deleteConnection(value.id));
const { id, metadata, chains, start, curUpload, curDownload } = value;
const onDelete = useLockFn(async () => deleteConnection(id));
const showTraffic = curUpload! > 1024 || curDownload! > 1024;
return (
<ListItem
dense
secondaryAction={
<IconButton edge="end" onClick={onDelete}>
<IconButton edge="end" color="inherit" onClick={onDelete}>
<CloseRounded />
</IconButton>
}
>
<ListItemText
primary={value.metadata.host || value.metadata.destinationIP}
primary={metadata.host || metadata.destinationIP}
secondary={
<>
<Tag sx={{ textTransform: "uppercase", color: "success" }}>
{value.metadata.network}
{metadata.network}
</Tag>
<Tag>{value.metadata.type}</Tag>
<Tag>{metadata.type}</Tag>
{value.chains.length > 0 && (
<Tag>{value.chains[value.chains.length - 1]}</Tag>
{chains.length > 0 && <Tag>{chains[value.chains.length - 1]}</Tag>}
<Tag>{dayjs(start).fromNow()}</Tag>
{showTraffic && (
<Tag>
{parseTraffic(curUpload!)} / {parseTraffic(curDownload!)}
</Tag>
)}
<Tag>{dayjs(value.start).fromNow()}</Tag>
</>
}
/>
+15 -11
View File
@@ -1,24 +1,25 @@
import useSWR from "swr";
import { useEffect, useState } from "react";
import { useEffect, useRef, useState } from "react";
import { useRecoilValue } from "recoil";
import { Box, Typography } from "@mui/material";
import { ArrowDownward, ArrowUpward } from "@mui/icons-material";
import { listen } from "@tauri-apps/api/event";
import { ApiType } from "../../services/types";
import { getInfomation } from "../../services/api";
import { getInformation } from "../../services/api";
import { getVergeConfig } from "../../services/cmds";
import { atomClashPort } from "../../services/states";
import TrafficGraph from "./traffic-graph";
import useLogSetup from "./use-log-setup";
import useTrafficGraph from "./use-traffic-graph";
import parseTraffic from "../../utils/parse-traffic";
// setup the traffic
const LayoutTraffic = () => {
const portValue = useRecoilValue(atomClashPort);
const [traffic, setTraffic] = useState({ up: 0, down: 0 });
const { canvasRef, appendData, toggleStyle } = useTrafficGraph();
const [refresh, setRefresh] = useState({});
const trafficRef = useRef<any>();
// whether hide traffic graph
const { data } = useSWR("getVergeConfig", getVergeConfig);
const trafficGraph = data?.traffic_graph ?? true;
@@ -40,13 +41,13 @@ const LayoutTraffic = () => {
useEffect(() => {
let ws: WebSocket | null = null;
getInfomation().then((result) => {
getInformation().then((result) => {
const { server = "", secret = "" } = result;
ws = new WebSocket(`ws://${server}/traffic?token=${secret}`);
ws.addEventListener("message", (event) => {
const data = JSON.parse(event.data) as ApiType.TrafficItem;
appendData(data);
trafficRef.current?.appendData(data);
setTraffic(data);
});
});
@@ -72,12 +73,15 @@ const LayoutTraffic = () => {
};
return (
<Box width="110px" position="relative" onClick={toggleStyle}>
<Box
width="110px"
position="relative"
onClick={trafficRef.current?.toggleStyle}
>
{trafficGraph && (
<canvas
ref={canvasRef}
style={{ width: "100%", height: 60, marginBottom: 6 }}
/>
<div style={{ width: "100%", height: 60, marginBottom: 6 }}>
<TrafficGraph instance={trafficRef} />
</div>
)}
<Box mb={1.5} display="flex" alignItems="center" whiteSpace="nowrap">
+224
View File
@@ -0,0 +1,224 @@
import { useEffect, useRef, useState } from "react";
import { useTheme } from "@mui/material";
import { listen } from "@tauri-apps/api/event";
import { appWindow } from "@tauri-apps/api/window";
const maxPoint = 30;
const refLineAlpha = 1;
const refLineWidth = 2;
const upLineAlpha = 0.6;
const upLineWidth = 4;
const downLineAlpha = 1;
const downLineWidth = 4;
const defaultList = Array(maxPoint + 2).fill({ up: 0, down: 0 });
type TrafficData = { up: number; down: number };
interface Props {
instance: React.MutableRefObject<{
appendData: (data: TrafficData) => void;
toggleStyle: () => void;
}>;
}
/**
* draw the traffic graph
*/
const TrafficGraph = (props: Props) => {
const { instance } = props;
const countRef = useRef(0);
const styleRef = useRef(true);
const listRef = useRef<TrafficData[]>(defaultList);
const canvasRef = useRef<HTMLCanvasElement>(null!);
const { palette } = useTheme();
useEffect(() => {
let timer: any;
let cache: TrafficData | null = null;
const zero = { up: 0, down: 0 };
const handleData = () => {
const data = cache ? cache : zero;
cache = null;
const list = listRef.current;
if (list.length > maxPoint + 2) list.shift();
list.push(data);
countRef.current = 0;
timer = setTimeout(handleData, 1000);
};
instance.current = {
appendData: (data: TrafficData) => {
cache = data;
},
toggleStyle: () => {
styleRef.current = !styleRef.current;
},
};
handleData();
return () => {
instance.current = null!;
if (timer) clearTimeout(timer);
};
}, []);
// reduce the GPU usage when hidden
const [enablePaint, setEnablePaint] = useState(true);
useEffect(() => {
appWindow.isVisible().then(setEnablePaint);
const unlistenBlur = listen("tauri://blur", async () => {
setEnablePaint(await appWindow.isVisible());
});
const unlistenFocus = listen("tauri://focus", async () => {
setEnablePaint(await appWindow.isVisible());
});
return () => {
unlistenBlur.then((fn) => fn());
unlistenFocus.then((fn) => fn());
};
}, []);
useEffect(() => {
if (!enablePaint) return;
let raf = 0;
const canvas = canvasRef.current!;
if (!canvas) return;
const context = canvas.getContext("2d")!;
if (!context) return;
const { primary, secondary, divider } = palette;
const refLineColor = divider || "rgba(0, 0, 0, 0.12)";
const upLineColor = secondary.main || "#9c27b0";
const downLineColor = primary.main || "#5b5c9d";
const width = canvas.width;
const height = canvas.height;
const dx = width / maxPoint;
const dy = height / 7;
const l1 = dy;
const l2 = dy * 4;
const countY = (v: number) => {
const h = height;
if (v == 0) return h - 1;
if (v <= 10) return h - (v / 10) * dy;
if (v <= 100) return h - (v / 100 + 1) * dy;
if (v <= 1024) return h - (v / 1024 + 2) * dy;
if (v <= 10240) return h - (v / 10240 + 3) * dy;
if (v <= 102400) return h - (v / 102400 + 4) * dy;
if (v <= 1048576) return h - (v / 1048576 + 5) * dy;
if (v <= 10485760) return h - (v / 10485760 + 6) * dy;
return 1;
};
const drawBezier = (list: number[], offset: number) => {
const points = list.map((y, i) => [
(dx * (i - 1) - offset + 3) | 0,
countY(y),
]);
let x = points[0][0];
let y = points[0][1];
context.moveTo(x, y);
for (let i = 1; i < points.length; i++) {
const p1 = points[i];
const p2 = points[i + 1] || p1;
const x1 = (p1[0] + p2[0]) / 2;
const y1 = (p1[1] + p2[1]) / 2;
context.quadraticCurveTo(p1[0], p1[1], x1, y1);
x = x1;
y = y1;
}
};
const drawLine = (list: number[], offset: number) => {
const points = list.map((y, i) => [
(dx * (i - 1) - offset) | 0,
countY(y),
]);
context.moveTo(points[0][0], points[0][1]);
for (let i = 1; i < points.length; i++) {
const p = points[i];
context.lineTo(p[0], p[1]);
}
};
const drawGraph = (lastTime: number) => {
const listUp = listRef.current.map((v) => v.up);
const listDown = listRef.current.map((v) => v.down);
const lineStyle = styleRef.current;
const now = Date.now();
const diff = now - lastTime;
const temp = Math.min((diff / 1000) * dx + countRef.current, dx);
const offset = countRef.current === 0 ? 0 : temp;
countRef.current = temp;
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();
context.beginPath();
context.globalAlpha = upLineAlpha;
context.lineWidth = upLineWidth;
context.strokeStyle = upLineColor;
lineStyle ? drawBezier(listUp, offset) : drawLine(listUp, offset);
context.stroke();
context.closePath();
context.beginPath();
context.globalAlpha = downLineAlpha;
context.lineWidth = downLineWidth;
context.strokeStyle = downLineColor;
lineStyle ? drawBezier(listDown, offset) : drawLine(listDown, offset);
context.stroke();
context.closePath();
raf = requestAnimationFrame(() => drawGraph(now));
};
drawGraph(Date.now());
return () => {
cancelAnimationFrame(raf);
};
}, [enablePaint, palette]);
return <canvas ref={canvasRef} style={{ width: "100%", height: "100%" }} />;
};
export default TrafficGraph;
+2 -2
View File
@@ -13,7 +13,7 @@ import {
} from "@mui/material";
import { relaunch } from "@tauri-apps/api/process";
import { checkUpdate, installUpdate } from "@tauri-apps/api/updater";
import { killSidecars, restartSidecar } from "../../services/cmds";
import { killSidecar, restartSidecar } from "../../services/cmds";
import { atomUpdateState } from "../../services/states";
import Notice from "../base/base-notice";
@@ -41,7 +41,7 @@ const UpdateDialog = (props: Props) => {
setUpdateState(true);
try {
await killSidecars();
await killSidecar();
await installUpdate();
await relaunch();
} catch (err: any) {
+12 -7
View File
@@ -2,7 +2,7 @@ import useSWR from "swr";
import { useMemo } from "react";
import { createTheme } from "@mui/material";
import { getVergeConfig } from "../../services/cmds";
import { defaultTheme as dt } from "../../pages/_theme";
import { defaultTheme, defaultDarkTheme } from "../../pages/_theme";
/**
* custome theme
@@ -13,14 +13,9 @@ export default function useCustomTheme() {
const theme = useMemo(() => {
const mode = theme_mode ?? "light";
// const background = mode === "light" ? "#f5f5f5" : "#000";
const selectColor = mode === "light" ? "#f5f5f5" : "#d5d5d5";
const rootEle = document.documentElement;
rootEle.style.background = "transparent";
rootEle.style.setProperty("--selection-color", selectColor);
const setting = theme_setting || {};
const dt = mode === "light" ? defaultTheme : defaultDarkTheme;
const theme = createTheme({
breakpoints: {
@@ -47,6 +42,16 @@ export default function useCustomTheme() {
},
});
// css
const selectColor = mode === "light" ? "#f5f5f5" : "#d5d5d5";
const scrollColor = mode === "light" ? "#90939980" : "#54545480";
const rootEle = document.documentElement;
rootEle.style.background = "transparent";
rootEle.style.setProperty("--selection-color", selectColor);
rootEle.style.setProperty("--scroller-color", scrollColor);
rootEle.style.setProperty("--primary-main", theme.palette.primary.main);
// inject css
let style = document.querySelector("style#verge-theme");
if (!style) {
+2 -2
View File
@@ -3,7 +3,7 @@ import { useEffect, useState } from "react";
import { useSetRecoilState } from "recoil";
import { listen } from "@tauri-apps/api/event";
import { ApiType } from "../../services/types";
import { getInfomation } from "../../services/api";
import { getInformation } from "../../services/api";
import { atomLogData } from "../../services/states";
const MAX_LOG_NUM = 1000;
@@ -25,7 +25,7 @@ export default function useLogSetup() {
});
};
getInfomation().then((info) => {
getInformation().then((info) => {
const { server = "", secret = "" } = info;
ws = new WebSocket(`ws://${server}/logs?token=${secret}`);
ws.addEventListener("message", handler);
-156
View File
@@ -1,156 +0,0 @@
import { useEffect, useRef } from "react";
import { useTheme } from "@mui/material";
const minPoint = 10;
const maxPoint = 36;
const refLineAlpha = 1;
const refLineWidth = 2;
const upLineAlpha = 0.6;
const upLineWidth = 4;
const downLineAlpha = 1;
const downLineWidth = 4;
/**
* 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 { palette } = useTheme();
const paletteRef = useRef(palette);
useEffect(() => {
paletteRef.current = palette;
}, [palette]);
const drawGraph = () => {
const canvas = canvasRef.current!;
if (!canvas) return;
const { primary, secondary, divider } = paletteRef.current;
const refLineColor = divider || "rgba(0, 0, 0, 0.12)";
const upLineColor = secondary.main || "#9c27b0";
const downLineColor = primary.main || "#5b5c9d";
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,
};
}
+32 -5
View File
@@ -1,6 +1,7 @@
import { mutate } from "swr";
import { useEffect, useState } from "react";
import { useLockFn, useSetState } from "ahooks";
import { useTranslation } from "react-i18next";
import {
Button,
Dialog,
@@ -25,6 +26,8 @@ interface Props {
// remote / local file / merge / script
const ProfileEdit = (props: Props) => {
const { open, itemData, onClose } = props;
const { t } = useTranslation();
const [form, setForm] = useSetState({ ...itemData });
const [option, setOption] = useSetState(itemData.option ?? {});
const [showOpt, setShowOpt] = useState(!!itemData.option);
@@ -33,7 +36,10 @@ const ProfileEdit = (props: Props) => {
if (itemData) {
setForm({ ...itemData });
setOption(itemData.option ?? {});
setShowOpt(!!itemData.option?.user_agent);
setShowOpt(
itemData.type === "remote" &&
(!!itemData.option?.user_agent || !!itemData.option?.update_interval)
);
}
}, [itemData]);
@@ -41,7 +47,10 @@ const ProfileEdit = (props: Props) => {
try {
const { uid } = itemData;
const { name, desc, url } = form;
const option_ = itemData.type === "remote" ? option : undefined;
const option_ =
itemData.type === "remote" || itemData.type === "local"
? option
: undefined;
if (itemData.type === "remote" && !url) {
throw new Error("Remote URL should not be null");
@@ -65,11 +74,11 @@ const ProfileEdit = (props: Props) => {
const type =
form.type ||
(form.url ? "remote" : form.file?.endsWith("js") ? "script" : "local");
(form.url ? "remote" : form.file?.endsWith(".js") ? "script" : "local");
return (
<Dialog open={open} onClose={onClose}>
<DialogTitle sx={{ pb: 0.5 }}>Edit Profile</DialogTitle>
<DialogTitle sx={{ pb: 0.5 }}>{t("Edit Info")}</DialogTitle>
<DialogContent sx={{ width: 336, pb: 1 }}>
<TextField
@@ -86,6 +95,7 @@ const ProfileEdit = (props: Props) => {
label="Name"
value={form.name}
onChange={(e) => setForm({ name: e.target.value })}
onKeyDown={(e) => e.key === "Enter" && onUpdate()}
/>
<TextField
@@ -93,14 +103,16 @@ const ProfileEdit = (props: Props) => {
label="Descriptions"
value={form.desc}
onChange={(e) => setForm({ desc: e.target.value })}
onKeyDown={(e) => e.key === "Enter" && onUpdate()}
/>
{type === "remote" && (
<TextField
{...textFieldProps}
label="Subscription Url"
label="Subscription URL"
value={form.url}
onChange={(e) => setForm({ url: e.target.value })}
onKeyDown={(e) => e.key === "Enter" && onUpdate()}
/>
)}
@@ -109,7 +121,22 @@ const ProfileEdit = (props: Props) => {
{...textFieldProps}
label="User Agent"
value={option.user_agent}
placeholder="clash-verge/v1.0.0"
onChange={(e) => setOption({ user_agent: e.target.value })}
onKeyDown={(e) => e.key === "Enter" && onUpdate()}
/>
)}
{((type === "remote" && showOpt) || type === "local") && (
<TextField
{...textFieldProps}
label="Update Interval (mins)"
value={option.update_interval}
onChange={(e) => {
const str = e.target.value?.replace(/\D/, "");
setOption({ update_interval: str != null ? +str : str });
}}
onKeyDown={(e) => e.key === "Enter" && onUpdate()}
/>
)}
</DialogContent>
+38 -9
View File
@@ -1,5 +1,5 @@
import dayjs from "dayjs";
import { useState } from "react";
import { useEffect, useState } from "react";
import { useLockFn } from "ahooks";
import { useSWRConfig } from "swr";
import { useRecoilState } from "recoil";
@@ -59,11 +59,6 @@ const ProfileItem = (props: Props) => {
const [loadingCache, setLoadingCache] = useRecoilState(atomLoadingCache);
const { uid, name = "Profile", extra, updated = 0 } = itemData;
const { upload = 0, download = 0, total = 0 } = extra ?? {};
const from = parseUrl(itemData.url);
const expire = parseExpire(extra?.expire);
const progress = Math.round(((download + upload) * 100) / (total + 0.1));
const fromnow = updated > 0 ? dayjs(updated * 1000).fromNow() : "";
// local file mode
// remote file mode
@@ -71,8 +66,42 @@ const ProfileItem = (props: Props) => {
const hasUrl = !!itemData.url;
const hasExtra = !!extra; // only subscription url has extra info
const { upload = 0, download = 0, total = 0 } = extra ?? {};
const from = parseUrl(itemData.url);
const expire = parseExpire(extra?.expire);
const progress = Math.round(((download + upload) * 100) / (total + 0.1));
const loading = loadingCache[itemData.uid] ?? false;
// interval update from now field
const [, setRefresh] = useState({});
useEffect(() => {
if (!hasUrl) return;
let timer: any = null;
const handler = () => {
const now = Date.now();
const lastUpdate = updated * 1000;
// 大于一天的不管
if (now - lastUpdate >= 24 * 36e5) return;
const wait = now - lastUpdate >= 36e5 ? 30e5 : 5e4;
timer = setTimeout(() => {
setRefresh({});
handler();
}, wait);
};
handler();
return () => {
if (timer) clearTimeout(timer);
};
}, [hasUrl, updated]);
const [editOpen, setEditOpen] = useState(false);
const [fileOpen, setFileOpen] = useState(false);
@@ -165,8 +194,8 @@ const ProfileItem = (props: Props) => {
const color = {
"light-true": text.secondary,
"light-false": text.secondary,
"dark-true": alpha(text.secondary, 0.6),
"dark-false": alpha(text.secondary, 0.6),
"dark-true": alpha(text.secondary, 0.75),
"dark-false": alpha(text.secondary, 0.75),
}[key]!;
const h2color = {
@@ -231,7 +260,7 @@ const ProfileItem = (props: Props) => {
textAlign="right"
title="updated time"
>
{fromnow}
{updated > 0 ? dayjs(updated * 1000).fromNow() : ""}
</Typography>
</Box>
) : (
+25 -83
View File
@@ -2,20 +2,13 @@ import useSWR, { useSWRConfig } from "swr";
import { useEffect, useRef, useState } from "react";
import { useLockFn } from "ahooks";
import { Virtuoso } from "react-virtuoso";
import { Box, IconButton, TextField } from "@mui/material";
import {
MyLocationRounded,
NetworkCheckRounded,
FilterAltRounded,
FilterAltOffRounded,
VisibilityRounded,
VisibilityOffRounded,
} from "@mui/icons-material";
import { ApiType } from "../../services/types";
import { updateProxy } from "../../services/api";
import { getProfiles, patchProfile } from "../../services/cmds";
import delayManager from "../../services/delay";
import useSortProxy, { ProxySortType } from "./use-sort-proxy";
import useFilterProxy from "./use-filter-proxy";
import delayManager from "../../services/delay";
import ProxyHead from "./proxy-head";
import ProxyItem from "./proxy-item";
interface Props {
@@ -30,12 +23,14 @@ const ProxyGlobal = (props: Props) => {
const { mutate } = useSWRConfig();
const [now, setNow] = useState(curProxy || "DIRECT");
const [showType, setShowType] = useState(true);
const [showFilter, setShowFilter] = useState(false);
const [sortType, setSortType] = useState<ProxySortType>(0);
const [filterText, setFilterText] = useState("");
const virtuosoRef = useRef<any>();
const filterProxies = useFilterProxy(proxies, groupName, filterText);
const sortedProxies = useSortProxy(filterProxies, groupName, sortType);
const { data: profiles } = useSWR("getProfiles", getProfiles);
@@ -61,7 +56,7 @@ const ProxyGlobal = (props: Props) => {
});
const onLocation = (smooth = true) => {
const index = filterProxies.findIndex((p) => p.name === now);
const index = sortedProxies.findIndex((p) => p.name === now);
if (index >= 0) {
virtuosoRef.current?.scrollToIndex?.({
@@ -73,22 +68,15 @@ const ProxyGlobal = (props: Props) => {
};
const onCheckAll = useLockFn(async () => {
const names = filterProxies.map((p) => p.name);
const names = sortedProxies.map((p) => p.name);
await delayManager.checkListDelay(
{ names, groupName, skipNum: 8, maxTimeout: 600 },
() => mutate("getProxies")
await delayManager.checkListDelay({ names, groupName, skipNum: 8 }, () =>
mutate("getProxies")
);
mutate("getProxies");
});
useEffect(() => onLocation(false), [groupName]);
useEffect(() => {
if (!showFilter) setFilterText("");
}, [showFilter]);
useEffect(() => {
if (groupName === "DIRECT") setNow("DIRECT");
else if (groupName === "GLOBAL") {
@@ -112,74 +100,28 @@ const ProxyGlobal = (props: Props) => {
return (
<>
<Box
sx={{
px: 3,
my: 0.5,
display: "flex",
alignItems: "center",
button: { mr: 0.5 },
}}
>
<IconButton
size="small"
title="location"
color="inherit"
onClick={() => onLocation(true)}
>
<MyLocationRounded />
</IconButton>
<IconButton
size="small"
title="delay check"
color="inherit"
onClick={onCheckAll}
>
<NetworkCheckRounded />
</IconButton>
<IconButton
size="small"
title="proxy detail"
color="inherit"
onClick={() => setShowType(!showType)}
>
{showType ? <VisibilityRounded /> : <VisibilityOffRounded />}
</IconButton>
<IconButton
size="small"
title="filter"
color="inherit"
onClick={() => setShowFilter(!showFilter)}
>
{showFilter ? <FilterAltRounded /> : <FilterAltOffRounded />}
</IconButton>
{showFilter && (
<TextField
autoFocus
hiddenLabel
value={filterText}
size="small"
variant="outlined"
placeholder="Filter conditions"
onChange={(e) => setFilterText(e.target.value)}
sx={{ ml: 0.5, flex: "1 1 auto", input: { py: 0.65, px: 1 } }}
/>
)}
</Box>
<ProxyHead
sx={{ px: 3, my: 0.5, button: { mr: 0.5 } }}
showType={showType}
sortType={sortType}
groupName={groupName}
filterText={filterText}
onLocation={onLocation}
onCheckDelay={onCheckAll}
onShowType={setShowType}
onSortType={setSortType}
onFilterText={setFilterText}
/>
<Virtuoso
ref={virtuosoRef}
style={{ height: "calc(100% - 40px)" }}
totalCount={filterProxies.length}
totalCount={sortedProxies.length}
itemContent={(index) => (
<ProxyItem
groupName={groupName}
proxy={filterProxies[index]}
selected={filterProxies[index].name === now}
proxy={sortedProxies[index]}
selected={sortedProxies[index].name === now}
showType={showType}
onClick={onChangeProxy}
sx={{ py: 0, px: 2 }}
+29 -87
View File
@@ -6,28 +6,22 @@ import {
Box,
Collapse,
Divider,
IconButton,
List,
ListItem,
ListItemText,
TextField,
} from "@mui/material";
import {
SendRounded,
ExpandLessRounded,
ExpandMoreRounded,
MyLocationRounded,
NetworkCheckRounded,
FilterAltRounded,
FilterAltOffRounded,
VisibilityRounded,
VisibilityOffRounded,
} from "@mui/icons-material";
import { ApiType } from "../../services/types";
import { updateProxy } from "../../services/api";
import { getProfiles, patchProfile } from "../../services/cmds";
import delayManager from "../../services/delay";
import useSortProxy, { ProxySortType } from "./use-sort-proxy";
import useFilterProxy from "./use-filter-proxy";
import delayManager from "../../services/delay";
import ProxyHead from "./proxy-head";
import ProxyItem from "./proxy-item";
interface Props {
@@ -38,13 +32,14 @@ const ProxyGroup = ({ group }: Props) => {
const { mutate } = useSWRConfig();
const [open, setOpen] = useState(false);
const [now, setNow] = useState(group.now);
const [showType, setShowType] = useState(false);
const [showFilter, setShowFilter] = useState(false);
const [sortType, setSortType] = useState<ProxySortType>(0);
const [filterText, setFilterText] = useState("");
const proxies = group.all ?? [];
const virtuosoRef = useRef<any>();
const filterProxies = useFilterProxy(proxies, group.name, filterText);
const filterProxies = useFilterProxy(group.all, group.name, filterText);
const sortedProxies = useSortProxy(filterProxies, group.name, sortType);
const { data: profiles } = useSWR("getProfiles", getProfiles);
@@ -82,7 +77,7 @@ const ProxyGroup = ({ group }: Props) => {
});
const onLocation = (smooth = true) => {
const index = filterProxies.findIndex((p) => p.name === now);
const index = sortedProxies.findIndex((p) => p.name === now);
if (index >= 0) {
virtuosoRef.current?.scrollToIndex?.({
@@ -94,21 +89,14 @@ const ProxyGroup = ({ group }: Props) => {
};
const onCheckAll = useLockFn(async () => {
const names = filterProxies.map((p) => p.name);
const names = sortedProxies.map((p) => p.name);
const groupName = group.name;
await delayManager.checkListDelay(
{ names, groupName, skipNum: 8, maxTimeout: 600 },
() => mutate("getProxies")
await delayManager.checkListDelay({ names, groupName, skipNum: 8 }, () =>
mutate("getProxies")
);
mutate("getProxies");
});
useEffect(() => {
if (!showFilter) setFilterText("");
}, [showFilter]);
// auto scroll to current index
useEffect(() => {
if (open) {
@@ -136,66 +124,20 @@ const ProxyGroup = ({ group }: Props) => {
</ListItem>
<Collapse in={open} timeout="auto" unmountOnExit>
<Box
sx={{
pl: 4,
pr: 3,
my: 0.5,
display: "flex",
alignItems: "center",
button: { mr: 0.5 },
}}
>
<IconButton
size="small"
title="location"
color="inherit"
onClick={() => onLocation(true)}
>
<MyLocationRounded />
</IconButton>
<ProxyHead
sx={{ pl: 4, pr: 3, my: 0.5, button: { mr: 0.5 } }}
showType={showType}
sortType={sortType}
groupName={group.name}
filterText={filterText}
onLocation={onLocation}
onCheckDelay={onCheckAll}
onShowType={setShowType}
onSortType={setSortType}
onFilterText={setFilterText}
/>
<IconButton
size="small"
title="delay check"
color="inherit"
onClick={onCheckAll}
>
<NetworkCheckRounded />
</IconButton>
<IconButton
size="small"
title="proxy detail"
color="inherit"
onClick={() => setShowType(!showType)}
>
{showType ? <VisibilityRounded /> : <VisibilityOffRounded />}
</IconButton>
<IconButton
size="small"
title="filter"
color="inherit"
onClick={() => setShowFilter(!showFilter)}
>
{showFilter ? <FilterAltRounded /> : <FilterAltOffRounded />}
</IconButton>
{showFilter && (
<TextField
hiddenLabel
value={filterText}
size="small"
variant="outlined"
placeholder="Filter conditions"
onChange={(e) => setFilterText(e.target.value)}
sx={{ ml: 0.5, flex: "1 1 auto", input: { py: 0.65, px: 1 } }}
/>
)}
</Box>
{!filterProxies.length && (
{!sortedProxies.length && (
<Box
sx={{
py: 3,
@@ -208,16 +150,16 @@ const ProxyGroup = ({ group }: Props) => {
</Box>
)}
{filterProxies.length >= 10 ? (
{sortedProxies.length >= 10 ? (
<Virtuoso
ref={virtuosoRef}
style={{ height: "320px", marginBottom: "4px" }}
totalCount={filterProxies.length}
totalCount={sortedProxies.length}
itemContent={(index) => (
<ProxyItem
groupName={group.name}
proxy={filterProxies[index]}
selected={filterProxies[index].name === now}
proxy={sortedProxies[index]}
selected={sortedProxies[index].name === now}
showType={showType}
sx={{ py: 0, pl: 4 }}
onClick={onChangeProxy}
@@ -230,7 +172,7 @@ const ProxyGroup = ({ group }: Props) => {
disablePadding
sx={{ maxHeight: "320px", overflow: "auto", mb: "4px" }}
>
{filterProxies.map((proxy) => (
{sortedProxies.map((proxy) => (
<ProxyItem
key={proxy.name}
groupName={group.name}
+147
View File
@@ -0,0 +1,147 @@
import { useState } from "react";
import { Box, IconButton, TextField, SxProps } from "@mui/material";
import {
AccessTimeRounded,
MyLocationRounded,
NetworkCheckRounded,
FilterAltRounded,
FilterAltOffRounded,
VisibilityRounded,
VisibilityOffRounded,
WifiTetheringRounded,
WifiTetheringOffRounded,
SortByAlphaRounded,
SortRounded,
} from "@mui/icons-material";
import delayManager from "../../services/delay";
import type { ProxySortType } from "./use-sort-proxy";
interface Props {
sx?: SxProps;
groupName: string;
showType: boolean;
sortType: ProxySortType;
filterText: string;
onLocation: () => void;
onCheckDelay: () => void;
onShowType: (val: boolean) => void;
onSortType: (val: ProxySortType) => void;
onFilterText: (val: string) => void;
}
const ProxyHead = (props: Props) => {
const { sx = {}, groupName, showType, sortType, filterText } = props;
const [textState, setTextState] = useState<"url" | "filter" | null>(null);
const [testUrl, setTestUrl] = useState(delayManager.getUrl(groupName) || "");
return (
<Box sx={{ display: "flex", alignItems: "center", ...sx }}>
<IconButton
size="small"
title="location"
color="inherit"
onClick={props.onLocation}
>
<MyLocationRounded />
</IconButton>
<IconButton
size="small"
color="inherit"
title="delay check"
onClick={() => {
// Remind the user that it is custom test url
if (testUrl?.trim() && textState !== "filter") {
setTextState("url");
}
props.onCheckDelay();
}}
>
<NetworkCheckRounded />
</IconButton>
<IconButton
size="small"
color="inherit"
title={["sort by default", "sort by delay", "sort by name"][sortType]}
onClick={() => props.onSortType(((sortType + 1) % 3) as ProxySortType)}
>
{sortType === 0 && <SortRounded />}
{sortType === 1 && <AccessTimeRounded />}
{sortType === 2 && <SortByAlphaRounded />}
</IconButton>
<IconButton
size="small"
color="inherit"
title="edit test url"
onClick={() => setTextState((ts) => (ts === "url" ? null : "url"))}
>
{textState === "url" ? (
<WifiTetheringRounded />
) : (
<WifiTetheringOffRounded />
)}
</IconButton>
<IconButton
size="small"
color="inherit"
title="proxy detail"
onClick={() => props.onShowType(!showType)}
>
{showType ? <VisibilityRounded /> : <VisibilityOffRounded />}
</IconButton>
<IconButton
size="small"
color="inherit"
title="filter"
onClick={() =>
setTextState((ts) => (ts === "filter" ? null : "filter"))
}
>
{textState === "filter" ? (
<FilterAltRounded />
) : (
<FilterAltOffRounded />
)}
</IconButton>
{textState === "filter" && (
<TextField
autoFocus
hiddenLabel
value={filterText}
size="small"
variant="outlined"
placeholder="Filter conditions"
onChange={(e) => props.onFilterText(e.target.value)}
sx={{ ml: 0.5, flex: "1 1 auto", input: { py: 0.65, px: 1 } }}
/>
)}
{textState === "url" && (
<TextField
autoFocus
hiddenLabel
autoSave="off"
autoComplete="off"
value={testUrl}
size="small"
variant="outlined"
placeholder="Test url"
onChange={(e) => {
setTestUrl(e.target.value);
delayManager.setUrl(groupName, e.target.value);
}}
sx={{ ml: 0.5, flex: "1 1 auto", input: { py: 0.65, px: 1 } }}
/>
)}
</Box>
);
};
export default ProxyHead;
+27 -16
View File
@@ -1,4 +1,5 @@
import { useEffect, useRef, useState } from "react";
import { useEffect, useState } from "react";
import { useLockFn } from "ahooks";
import { CheckCircleOutlineRounded } from "@mui/icons-material";
import {
alpha,
@@ -24,8 +25,9 @@ interface Props {
}
const Widget = styled(Box)(() => ({
padding: "4px 6px",
padding: "3px 6px",
fontSize: 14,
borderRadius: "4px",
}));
const TypeBox = styled(Box)(({ theme }) => ({
@@ -50,20 +52,12 @@ const ProxyItem = (props: Props) => {
}
}, [proxy]);
const delayRef = useRef(false);
const onDelay = (e: any) => {
e.preventDefault();
e.stopPropagation();
if (delayRef.current) return;
delayRef.current = true;
delayManager
const onDelay = useLockFn(async () => {
return delayManager
.checkDelay(proxy.name, groupName)
.then((result) => setDelay(result))
.catch(() => setDelay(1e6))
.finally(() => (delayRef.current = false));
};
.catch(() => setDelay(1e6));
});
return (
<ListItem sx={sx}>
@@ -111,13 +105,27 @@ const ProxyItem = (props: Props) => {
<ListItemIcon
sx={{ justifyContent: "flex-end", color: "primary.main" }}
>
<Widget className="the-check" onClick={onDelay}>
<Widget
className="the-check"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
onDelay();
}}
sx={(theme) => ({
":hover": { bgcolor: alpha(theme.palette.primary.main, 0.15) },
})}
>
Check
</Widget>
<Widget
className="the-delay"
onClick={onDelay}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
onDelay();
}}
color={
delay > 500
? "error.main"
@@ -125,6 +133,9 @@ const ProxyItem = (props: Props) => {
? "success.main"
: "text.secondary"
}
sx={(theme) => ({
":hover": { bgcolor: alpha(theme.palette.primary.main, 0.15) },
})}
>
{delay > 1e5 ? "Error" : delay > 3000 ? "Timeout" : `${delay}ms`}
</Widget>
+1
View File
@@ -15,6 +15,7 @@ export default function useFilterProxy(
filterText: string
) {
return useMemo(() => {
if (!proxies) return [];
if (!filterText) return proxies;
const res1 = regex1.exec(filterText);
+38
View File
@@ -0,0 +1,38 @@
import { useMemo } from "react";
import { ApiType } from "../../services/types";
import delayManager from "../../services/delay";
// default | delay | alpha
export type ProxySortType = 0 | 1 | 2;
/**
* sort the proxy
*/
export default function useSortProxy(
proxies: ApiType.ProxyItem[],
groupName: string,
sortType: ProxySortType
) {
return useMemo(() => {
if (!proxies) return [];
if (sortType === 0) return proxies;
const list = proxies.slice();
if (sortType === 1) {
list.sort((a, b) => {
const ad = delayManager.getDelay(a.name, groupName);
const bd = delayManager.getDelay(b.name, groupName);
if (ad === -1) return 1;
if (bd === -1) return -1;
return ad - bd;
});
} else {
list.sort((a, b) => a.name.localeCompare(b.name));
}
return list;
}, [proxies, groupName, sortType]);
}
+104
View File
@@ -0,0 +1,104 @@
import useSWR, { useSWRConfig } from "swr";
import { useLockFn } from "ahooks";
import { useTranslation } from "react-i18next";
import {
Button,
Dialog,
DialogContent,
DialogTitle,
Stack,
Typography,
} from "@mui/material";
import {
checkService,
installService,
uninstallService,
patchVergeConfig,
} from "../../services/cmds";
import Notice from "../base/base-notice";
import noop from "../../utils/noop";
interface Props {
open: boolean;
enable: boolean;
onClose: () => void;
onError?: (err: Error) => void;
}
const ServiceMode = (props: Props) => {
const { open, enable, onClose, onError = noop } = props;
const { t } = useTranslation();
const { mutate } = useSWRConfig();
const { data: status } = useSWR("checkService", checkService, {
revalidateIfStale: true,
shouldRetryOnError: false,
});
const state = status != null ? status : "pending";
const onInstall = useLockFn(async () => {
try {
await installService();
mutate("checkService");
onClose();
Notice.success("Service installed successfully");
} catch (err: any) {
mutate("checkService");
onError(err);
}
});
const onUninstall = useLockFn(async () => {
try {
if (state === "active" && enable) {
await patchVergeConfig({ enable_service_mode: false });
}
await uninstallService();
mutate("checkService");
onClose();
Notice.success("Service uninstalled successfully");
} catch (err: any) {
mutate("checkService");
onError(err);
}
});
return (
<Dialog open={open} onClose={onClose}>
<DialogTitle>{t("Service Mode")}</DialogTitle>
<DialogContent sx={{ width: 360, userSelect: "text" }}>
<Typography>Current State: {state}</Typography>
{(state === "unknown" || state === "uninstall") && (
<Typography>
Infomation: Please make sure the Clash Verge Service is installed
and enabled
</Typography>
)}
<Stack
direction="row"
spacing={1}
sx={{ mt: 4, justifyContent: "flex-end" }}
>
{state === "uninstall" && (
<Button variant="contained" onClick={onInstall}>
Install
</Button>
)}
{(state === "active" || state === "installed") && (
<Button variant="outlined" onClick={onUninstall}>
Uninstall
</Button>
)}
</Stack>
</DialogContent>
</Dialog>
);
};
export default ServiceMode;
+1 -1
View File
@@ -122,7 +122,7 @@ const SettingClash = ({ onError }: Props) => {
onFormat={(e: any) => +e.target.value?.replace(/\D+/, "")}
onChange={(e) => onChangeData({ "mixed-port": e })}
onGuard={onUpdatePort}
waitTime={800}
waitTime={1000}
>
<TextField autoComplete="off" size="small" sx={{ width: 120 }} />
</GuardState>
+78 -3
View File
@@ -1,24 +1,49 @@
import useSWR, { useSWRConfig } from "swr";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Box, ListItemText, Switch, TextField } from "@mui/material";
import { getVergeConfig, patchVergeConfig } from "../../services/cmds";
import {
Box,
IconButton,
ListItemText,
Switch,
TextField,
} from "@mui/material";
import { ArrowForward, PrivacyTipRounded } from "@mui/icons-material";
import {
checkService,
getVergeConfig,
patchVergeConfig,
} from "../../services/cmds";
import { SettingList, SettingItem } from "./setting";
import { CmdType } from "../../services/types";
import GuardState from "./guard-state";
import ServiceMode from "./service-mode";
import SysproxyTooltip from "./sysproxy-tooltip";
import getSystem from "../../utils/get-system";
interface Props {
onError?: (err: Error) => void;
}
const isWIN = getSystem() === "windows";
const SettingSystem = ({ onError }: Props) => {
const { t } = useTranslation();
const { mutate } = useSWRConfig();
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
// service mode
const [serviceOpen, setServiceOpen] = useState(false);
const { data: serviceStatus } = useSWR(
isWIN ? "checkService" : null,
checkService,
{ revalidateIfStale: true, shouldRetryOnError: false }
);
const {
enable_tun_mode,
enable_auto_launch,
enable_service_mode,
enable_silent_start,
enable_system_proxy,
system_proxy_bypass,
@@ -46,6 +71,56 @@ const SettingSystem = ({ onError }: Props) => {
</GuardState>
</SettingItem>
{isWIN && (
<SettingItem>
<ListItemText
primary={
<Box sx={{ display: "flex", alignItems: "center" }}>
<span style={{ marginRight: 4 }}>{t("Service Mode")}</span>
{(serviceStatus === "active" ||
serviceStatus === "installed") && (
<PrivacyTipRounded
fontSize="small"
onClick={() => setServiceOpen(true)}
/>
)}
</Box>
}
/>
{serviceStatus === "active" || serviceStatus === "installed" ? (
<GuardState
value={enable_service_mode ?? false}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_service_mode: e })}
onGuard={(e) => patchVergeConfig({ enable_service_mode: e })}
>
<Switch edge="end" />
</GuardState>
) : (
<IconButton
color="inherit"
size="small"
onClick={() => setServiceOpen(true)}
>
<ArrowForward />
</IconButton>
)}
{serviceOpen && (
<ServiceMode
open={serviceOpen}
enable={!!enable_service_mode}
onError={onError}
onClose={() => setServiceOpen(false)}
/>
)}
</SettingItem>
)}
<SettingItem>
<ListItemText primary={t("Auto Launch")} />
<GuardState
@@ -78,7 +153,7 @@ const SettingSystem = ({ onError }: Props) => {
<ListItemText
primary={
<Box sx={{ display: "flex", alignItems: "center" }}>
{t("System Proxy")}
<span style={{ marginRight: 4 }}>{t("System Proxy")}</span>
<SysproxyTooltip />
</Box>
}
+12 -4
View File
@@ -13,9 +13,10 @@ import {
ListItemText,
styled,
TextField,
useTheme,
} from "@mui/material";
import { getVergeConfig, patchVergeConfig } from "../../services/cmds";
import { defaultTheme } from "../../pages/_theme";
import { defaultTheme, defaultDarkTheme } from "../../pages/_theme";
interface Props {
open: boolean;
@@ -71,15 +72,22 @@ const SettingTheme = (props: Props) => {
}
});
const renderItem = (label: string, key: keyof typeof defaultTheme) => {
// default theme
const { palette } = useTheme();
const dt = palette.mode === "light" ? defaultTheme : defaultDarkTheme;
type ThemeKey = keyof typeof theme & keyof typeof defaultTheme;
const renderItem = (label: string, key: ThemeKey) => {
return (
<Item>
<ListItemText primary={label} />
<Round sx={{ background: theme[key] || defaultTheme[key] }} />
<Round sx={{ background: theme[key] || dt[key] }} />
<TextField
{...textProps}
value={theme[key] ?? ""}
placeholder={defaultTheme[key]}
placeholder={dt[key]}
onChange={handleChange(key)}
onKeyDown={(e) => e.key === "Enter" && onSave()}
/>
+1
View File
@@ -41,6 +41,7 @@
"Mixed Port": "Mixed Port",
"Clash core": "Clash core",
"Tun Mode": "Tun Mode",
"Service Mode": "Service Mode",
"Auto Launch": "Auto Launch",
"Silent Start": "Silent Start",
"System Proxy": "System Proxy",
+1
View File
@@ -41,6 +41,7 @@
"Mixed Port": "端口设置",
"Clash core": "Clash 内核",
"Tun Mode": "Tun 模式",
"Service Mode": "服务模式",
"Auto Launch": "开机自启",
"Silent Start": "静默启动",
"System Proxy": "系统代理",
+2 -2
View File
@@ -72,7 +72,7 @@ const Layout = () => {
}}
sx={[
({ palette }) => ({
bgcolor: alpha(palette.background.paper, theme_blur ? 0.85 : 1),
bgcolor: alpha(palette.background.paper, theme_blur ? 0.8 : 1),
}),
]}
>
@@ -83,7 +83,7 @@ const Layout = () => {
<UpdateButton className="the-newbtn" />
</div>
<List className="the-menu" data-windrag>
<List className="the-menu">
{routers.map((router) => (
<LayoutItem key={router.label} to={router.link}>
{t(router.label)}
+7
View File
@@ -10,3 +10,10 @@ export const defaultTheme = {
success_color: "#2e7d32",
font_family: `"Roboto", "Helvetica", "Arial", sans-serif`,
};
// dark mode
export const defaultDarkTheme = {
...defaultTheme,
primary_text: "#757575",
secondary_text: "#637381",
};
+77 -30
View File
@@ -1,54 +1,65 @@
import { useEffect, useState } from "react";
import { useEffect, useMemo, useState } from "react";
import { useLockFn } from "ahooks";
import { Button, Paper } from "@mui/material";
import { Box, Button, Paper, TextField } from "@mui/material";
import { Virtuoso } from "react-virtuoso";
import { useTranslation } from "react-i18next";
import { ApiType } from "../services/types";
import { closeAllConnections, getInfomation } from "../services/api";
import { closeAllConnections, getInformation } from "../services/api";
import BasePage from "../components/base/base-page";
import ConnectionItem from "../components/connection/connection-item";
const ConnectionsPage = () => {
const initConn = { uploadTotal: 0, downloadTotal: 0, connections: [] };
const initConn = { uploadTotal: 0, downloadTotal: 0, connections: [] };
const ConnectionsPage = () => {
const { t } = useTranslation();
const [filterText, setFilterText] = useState("");
const [connData, setConnData] = useState<ApiType.Connections>(initConn);
const filterConn = useMemo(() => {
return connData.connections.filter((conn) =>
(conn.metadata.host || conn.metadata.destinationIP)?.includes(filterText)
);
}, [connData, filterText]);
useEffect(() => {
let ws: WebSocket | null = null;
getInfomation().then((result) => {
getInformation().then((result) => {
const { server = "", secret = "" } = result;
ws = new WebSocket(`ws://${server}/connections?token=${secret}`);
ws.addEventListener("message", (event) => {
const data = JSON.parse(event.data) as ApiType.Connections;
// 与前一次connections的展示顺序尽量保持一致
setConnData((old) => {
const oldConn = old.connections;
const oldList = oldConn.map((each) => each.id);
const maxLen = data.connections.length;
const connections: typeof oldConn = [];
// 与前一次连接的顺序尽量保持一致
data.connections
.filter((each) => {
const index = oldList.indexOf(each.id);
const rest = data.connections.filter((each) => {
const index = oldConn.findIndex((o) => o.id === each.id);
if (index >= 0 && index < maxLen) {
connections[index] = each;
return false;
}
return true;
})
.forEach((each) => {
for (let i = 0; i < maxLen; ++i) {
if (!connections[i]) {
connections[i] = each;
return;
}
}
});
if (index >= 0 && index < maxLen) {
const old = oldConn[index];
each.curUpload = each.upload - old.upload;
each.curDownload = each.download - old.download;
connections[index] = each;
return false;
}
return true;
});
for (let i = 0; i < maxLen; ++i) {
if (!connections[i] && rest.length > 0) {
connections[i] = rest.shift()!;
connections[i].curUpload = 0;
connections[i].curDownload = 0;
}
}
return { ...data, connections };
});
@@ -76,11 +87,47 @@ const ConnectionsPage = () => {
}
>
<Paper sx={{ boxShadow: 2, height: "100%" }}>
<Virtuoso
initialTopMostItemIndex={999}
data={connData.connections}
itemContent={(index, item) => <ConnectionItem value={item} />}
/>
<Box
sx={{
pt: 1,
mb: 0.5,
mx: "12px",
height: "36px",
display: "flex",
alignItems: "center",
}}
>
{/* <Select
size="small"
autoComplete="off"
value={logState}
onChange={(e) => setLogState(e.target.value)}
sx={{ width: 120, mr: 1, '[role="button"]': { py: 0.65 } }}
>
<MenuItem value="all">ALL</MenuItem>
<MenuItem value="info">INFO</MenuItem>
<MenuItem value="warn">WARN</MenuItem>
</Select> */}
<TextField
hiddenLabel
fullWidth
size="small"
autoComplete="off"
variant="outlined"
placeholder="Filter conditions"
value={filterText}
onChange={(e) => setFilterText(e.target.value)}
sx={{ input: { py: 0.65, px: 1.25 } }}
/>
</Box>
<Box height="calc(100% - 50px)">
<Virtuoso
data={filterConn}
itemContent={(index, item) => <ConnectionItem value={item} />}
/>
</Box>
</Paper>
</BasePage>
);
+58 -8
View File
@@ -1,5 +1,6 @@
import { useMemo, useState } from "react";
import { useRecoilState } from "recoil";
import { Button, Paper } from "@mui/material";
import { Box, Button, MenuItem, Paper, Select, TextField } from "@mui/material";
import { Virtuoso } from "react-virtuoso";
import { useTranslation } from "react-i18next";
import { atomLogData } from "../services/states";
@@ -10,6 +11,18 @@ const LogPage = () => {
const { t } = useTranslation();
const [logData, setLogData] = useRecoilState(atomLogData);
const [logState, setLogState] = useState("all");
const [filterText, setFilterText] = useState("");
const filterLogs = useMemo(() => {
return logData.filter((data) => {
return (
data.payload.includes(filterText) &&
(logState === "all" ? true : data.type.includes(logState))
);
});
}, [logData, logState, filterText]);
return (
<BasePage
title={t("Logs")}
@@ -25,13 +38,50 @@ const LogPage = () => {
</Button>
}
>
<Paper sx={{ boxShadow: 2, height: "100%" }}>
<Virtuoso
initialTopMostItemIndex={999}
data={logData}
itemContent={(index, item) => <LogItem value={item} />}
followOutput={"smooth"}
/>
<Paper sx={{ boxSizing: "border-box", boxShadow: 2, height: "100%" }}>
<Box
sx={{
pt: 1,
mb: 0.5,
mx: "12px",
height: "36px",
display: "flex",
alignItems: "center",
}}
>
<Select
size="small"
autoComplete="off"
value={logState}
onChange={(e) => setLogState(e.target.value)}
sx={{ width: 120, mr: 1, '[role="button"]': { py: 0.65 } }}
>
<MenuItem value="all">ALL</MenuItem>
<MenuItem value="info">INFO</MenuItem>
<MenuItem value="warn">WARN</MenuItem>
</Select>
<TextField
hiddenLabel
fullWidth
size="small"
autoComplete="off"
variant="outlined"
placeholder="Filter conditions"
value={filterText}
onChange={(e) => setFilterText(e.target.value)}
sx={{ input: { py: 0.65, px: 1.25 } }}
/>
</Box>
<Box height="calc(100% - 50px)">
<Virtuoso
initialTopMostItemIndex={999}
data={filterLogs}
itemContent={(index, item) => <LogItem value={item} />}
followOutput={"smooth"}
/>
</Box>
</Paper>
</BasePage>
);
+2 -2
View File
@@ -32,8 +32,8 @@ export async function getAxios(force: boolean = false) {
return axiosIns;
}
/// get infomation
export async function getInfomation() {
/// get information
export async function getInformation() {
if (server) return { server, secret };
const info = await getClashInfo();
return info!;
+31 -6
View File
@@ -6,10 +6,6 @@ export async function getProfiles() {
return invoke<CmdType.ProfilesConfig>("get_profiles");
}
export async function syncProfiles() {
return invoke<void>("sync_profiles");
}
export async function enhanceProfiles() {
return invoke<void>("enhance_profiles");
}
@@ -94,8 +90,8 @@ export async function restartSidecar() {
return invoke<void>("restart_sidecar");
}
export async function killSidecars() {
return invoke<any>("kill_sidecars");
export async function killSidecar() {
return invoke<any>("kill_sidecar");
}
export async function openAppDir() {
@@ -109,3 +105,32 @@ export async function openLogsDir() {
Notice.error(err?.message || err.toString(), 1500)
);
}
/// service mode
export async function startService() {
return invoke<void>("start_service");
}
export async function stopService() {
return invoke<void>("stop_service");
}
export async function checkService() {
try {
const result = await invoke<any>("check_service");
if (result?.code === 0) return "active";
if (result?.code === 400) return "installed";
return "unknown";
} catch (err: any) {
return "uninstall";
}
}
export async function installService() {
return invoke<void>("install_service");
}
export async function uninstallService() {
return invoke<void>("uninstall_service");
}
+34 -20
View File
@@ -4,6 +4,15 @@ const hashKey = (name: string, group: string) => `${group ?? ""}::${name}`;
class DelayManager {
private cache = new Map<string, [number, number]>();
private urlMap = new Map<string, string>();
setUrl(group: string, url: string) {
this.urlMap.set(group, url);
}
getUrl(group: string) {
return this.urlMap.get(group);
}
setDelay(name: string, group: string, delay: number) {
this.cache.set(hashKey(name, group), [Date.now(), delay]);
@@ -23,7 +32,8 @@ class DelayManager {
let delay = -1;
try {
const result = await getProxyDelay(name);
const url = this.getUrl(group);
const result = await getProxyDelay(name, url);
delay = result.delay;
} catch {
delay = 1e6; // error
@@ -38,32 +48,36 @@ class DelayManager {
names: readonly string[];
groupName: string;
skipNum: number;
maxTimeout: number;
},
callback: Function
) {
let names = [...options.names];
const { groupName, skipNum, maxTimeout } = options;
const { groupName, skipNum } = options;
while (names.length) {
const list = names.slice(0, skipNum);
names = names.slice(skipNum);
const names = [...options.names];
const total = names.length;
let called = false;
setTimeout(() => {
if (!called) {
called = true;
callback();
}
}, maxTimeout);
let count = 0;
let current = 0;
await Promise.all(list.map((n) => this.checkDelay(n, groupName)));
return new Promise((resolve) => {
const help = async (): Promise<void> => {
if (current >= skipNum) return;
if (!called) {
called = true;
callback();
}
}
const task = names.shift();
if (!task) return;
current += 1;
await this.checkDelay(task, groupName);
current -= 1;
if (count++ % skipNum === 0 || count === total) callback();
if (count === total) resolve(null);
return help();
};
for (let i = 0; i < skipNum; ++i) help();
});
}
}
+5 -1
View File
@@ -1,7 +1,7 @@
/**
* Some interface for clash api
*/
export namespace ApiType {
export namespace ApiType {
export interface ConfigData {
port: number;
mode: string;
@@ -65,6 +65,8 @@ export namespace ApiType {
chains: string[];
rule: string;
rulePayload: string;
curUpload?: number; // calculate
curDownload?: number; // calculate
}
export interface Connections {
@@ -111,6 +113,7 @@ export namespace CmdType {
export interface ProfileOption {
user_agent?: string;
with_proxy?: boolean;
update_interval?: number;
}
export interface ProfilesConfig {
@@ -127,6 +130,7 @@ export namespace CmdType {
traffic_graph?: boolean;
enable_tun_mode?: boolean;
enable_auto_launch?: boolean;
enable_service_mode?: boolean;
enable_silent_start?: boolean;
enable_system_proxy?: boolean;
enable_proxy_guard?: boolean;
+115 -100
View File
@@ -386,37 +386,37 @@
"@jridgewell/resolve-uri" "^3.0.3"
"@jridgewell/sourcemap-codec" "^1.4.10"
"@mui/base@5.0.0-alpha.74":
version "5.0.0-alpha.74"
resolved "https://registry.yarnpkg.com/@mui/base/-/base-5.0.0-alpha.74.tgz#15509242e7911446d5957375b1b18cbb72b3a750"
integrity sha512-pw3T1xNXpW8pLo9+BvtyazZb0CSjNJsjbzznlbV/aNkBfjNPXQVI3X1NDm3WSI8y6M96WDIVO7XrHAohOwALSQ==
"@mui/base@5.0.0-alpha.79":
version "5.0.0-alpha.79"
resolved "https://registry.yarnpkg.com/@mui/base/-/base-5.0.0-alpha.79.tgz#1994a6382a162b52ec93b66f3c74d193820d2365"
integrity sha512-/lZLF027BkiEjM8MIYoeS/FEhTKf+41ePU9SOijMGrCin1Y0Igucw+IHa1fF8HXD7wDbFKqHuso3J1jMG8wyNw==
dependencies:
"@babel/runtime" "^7.17.2"
"@emotion/is-prop-valid" "^1.1.2"
"@mui/types" "^7.1.3"
"@mui/utils" "^5.5.3"
"@popperjs/core" "^2.11.4"
"@mui/utils" "^5.6.1"
"@popperjs/core" "^2.11.5"
clsx "^1.1.1"
prop-types "^15.7.2"
react-is "^17.0.2"
"@mui/icons-material@^5.5.1":
version "5.5.1"
resolved "https://registry.yarnpkg.com/@mui/icons-material/-/icons-material-5.5.1.tgz#848a57972617411370775980cbc6990588d4aafb"
integrity sha512-40f68p5+Yhq3dCn3QYHqQt5RETPyR3AkDw+fma8PtcjqvZ+d+jF84kFmT6NqwA3he7TlwluEtkyAmPzUE4uPdA==
"@mui/icons-material@^5.6.2":
version "5.6.2"
resolved "https://registry.yarnpkg.com/@mui/icons-material/-/icons-material-5.6.2.tgz#239c40fc5841dc7c6af7d00e4e988550de170fcd"
integrity sha512-9QdI7axKuBAyaGz4mtdi7Uy1j73/thqFmEuxpJHxNC7O8ADEK1Da3t2veK2tgmsXsUlAHcAG63gg+GvWWeQNqQ==
dependencies:
"@babel/runtime" "^7.17.2"
"@mui/material@^5.5.3":
version "5.5.3"
resolved "https://registry.yarnpkg.com/@mui/material/-/material-5.5.3.tgz#411e53a69da3f9d6664e99f1bdcdaf2760540fdc"
integrity sha512-eADa3kUYbbr1jNjcufn0a7HeU8cSo0agbrkj720hodxVFNIfzq7a2e58Z+PaZqll55kMGBvlYJ7rTcXU399x5A==
"@mui/material@^5.6.4":
version "5.6.4"
resolved "https://registry.yarnpkg.com/@mui/material/-/material-5.6.4.tgz#5c6d6770acaea84d7b1c6492639627baed62f65b"
integrity sha512-7TD+u/SExZK2a55w6reX56oPk37gKr/M/XGt156X+m0d9LhzOsW864nkErIX/H8oSkX/6kCimxu1FDsO+gjiVw==
dependencies:
"@babel/runtime" "^7.17.2"
"@mui/base" "5.0.0-alpha.74"
"@mui/system" "^5.5.3"
"@mui/base" "5.0.0-alpha.79"
"@mui/system" "^5.6.4"
"@mui/types" "^7.1.3"
"@mui/utils" "^5.5.3"
"@mui/utils" "^5.6.1"
"@types/react-transition-group" "^4.4.4"
clsx "^1.1.1"
csstype "^3.0.11"
@@ -425,34 +425,34 @@
react-is "^17.0.2"
react-transition-group "^4.4.2"
"@mui/private-theming@^5.5.3":
version "5.5.3"
resolved "https://registry.yarnpkg.com/@mui/private-theming/-/private-theming-5.5.3.tgz#c232a39dd3c268fdef7e92ccc40d51bda9eec3ab"
integrity sha512-Wf7NurY7lk8SBWelSBY2U02zxLt1773JpIcXTHuEC9/GZdQA4CXCJGl2cVQzheKhee5rZ+8JwGulrRiVl1m+4A==
"@mui/private-theming@^5.6.2":
version "5.6.2"
resolved "https://registry.yarnpkg.com/@mui/private-theming/-/private-theming-5.6.2.tgz#c42da32f8b9481ba12885176c0168a355727c189"
integrity sha512-IbrSfFXfiZdyhRMC2bgGTFtb16RBQ5mccmjeh3MtAERWuepiCK7gkW5D9WhEsfTu6iez+TEjeUKSgmMHlsM2mg==
dependencies:
"@babel/runtime" "^7.17.2"
"@mui/utils" "^5.5.3"
"@mui/utils" "^5.6.1"
prop-types "^15.7.2"
"@mui/styled-engine@^5.5.2":
version "5.5.2"
resolved "https://registry.yarnpkg.com/@mui/styled-engine/-/styled-engine-5.5.2.tgz#1f92dd27d76f0b7df7aa52c7c7a710e59b2275a6"
integrity sha512-jkz5AHHbA43akBo5L3y1X1/X0f+RvXvCp3eXKt+iOf3qnKSAausbtlVz7gBbC4xIWDnP1Jb/6T+t/0/7gObRYA==
"@mui/styled-engine@^5.6.1":
version "5.6.1"
resolved "https://registry.yarnpkg.com/@mui/styled-engine/-/styled-engine-5.6.1.tgz#e2c859a4dbdd65af89e77703a0725285aef471fd"
integrity sha512-jEhH6TBY8jc9S8yVncXmoTYTbATjEu44RMFXj6sIYfKr5NArVwTwRo3JexLL0t3BOAiYM4xsFLgfKEIvB9SAeQ==
dependencies:
"@babel/runtime" "^7.17.2"
"@emotion/cache" "^11.7.1"
prop-types "^15.7.2"
"@mui/system@^5.5.3":
version "5.5.3"
resolved "https://registry.yarnpkg.com/@mui/system/-/system-5.5.3.tgz#c78d4c16009430389ffd3495d694945422d72ca5"
integrity sha512-J9JcySJuEqfEoP334K/2gEWm2vOx73Uqjii3qlFVhWRBOAJ0Pjyk0sN5W/eVRbwhUm95DNgh2V5s8dRK3vzyVw==
"@mui/system@^5.6.4":
version "5.6.4"
resolved "https://registry.yarnpkg.com/@mui/system/-/system-5.6.4.tgz#b1c615c70b3573d61a8a56dbaee6700bb9a5ca9b"
integrity sha512-7rsWED1wMFMePySJobsBerFZNu7ga580QSi3Zd6sJR8nVj12qD3yIdfvxA70/PxJ/805KbIT0GX7edKI+hpyhA==
dependencies:
"@babel/runtime" "^7.17.2"
"@mui/private-theming" "^5.5.3"
"@mui/styled-engine" "^5.5.2"
"@mui/private-theming" "^5.6.2"
"@mui/styled-engine" "^5.6.1"
"@mui/types" "^7.1.3"
"@mui/utils" "^5.5.3"
"@mui/utils" "^5.6.1"
clsx "^1.1.1"
csstype "^3.0.11"
prop-types "^15.7.2"
@@ -462,10 +462,10 @@
resolved "https://registry.yarnpkg.com/@mui/types/-/types-7.1.3.tgz#d7636f3046110bcccc63e6acfd100e2ad9ca712a"
integrity sha512-DDF0UhMBo4Uezlk+6QxrlDbchF79XG6Zs0zIewlR4c0Dt6GKVFfUtzPtHCH1tTbcSlq/L2bGEdiaoHBJ9Y1gSA==
"@mui/utils@^5.5.3":
version "5.5.3"
resolved "https://registry.yarnpkg.com/@mui/utils/-/utils-5.5.3.tgz#f6e1f10c0e8f4d0bf750588c2c3a96ad819c5b65"
integrity sha512-t627eVRpl3SlxVya0cIVNs8jPl4KCEiGaTSWY9iKKTcMNaeDbuRML+zv/CFHDPr1zFv+FjJSP02ySB+tZ8xIag==
"@mui/utils@^5.6.1":
version "5.6.1"
resolved "https://registry.yarnpkg.com/@mui/utils/-/utils-5.6.1.tgz#4ab79a21bd481555d9a588f4b18061b3c28ea5db"
integrity sha512-CPrzrkiBusCZBLWu0Sg5MJvR3fKJyK3gKecLVX012LULyqg2U64Oz04BKhfkbtBrPBbSQxM+DWW9B1c9hmV9nQ==
dependencies:
"@babel/runtime" "^7.17.2"
"@types/prop-types" "^15.7.4"
@@ -559,10 +559,10 @@
dependencies:
"@octokit/openapi-types" "^11.2.0"
"@popperjs/core@^2.11.4":
version "2.11.4"
resolved "https://registry.yarnpkg.com/@popperjs/core/-/core-2.11.4.tgz#d8c7b8db9226d2d7664553a0741ad7d0397ee503"
integrity sha512-q/ytXxO5NKvyT37pmisQAItCFqA7FD/vNb8dgaJy3/630Fsc+Mz9/9f2SziBoIZ30TJooXyTwZmhi1zjXmObYg==
"@popperjs/core@^2.11.5":
version "2.11.5"
resolved "https://registry.yarnpkg.com/@popperjs/core/-/core-2.11.5.tgz#db5a11bf66bdab39569719555b0f76e138d7bd64"
integrity sha512-9X2obfABZuDVLCgPK9aX0a/x4jaOEweTTWE2+9sr0Qqqevj2Uv5XorvusThmc9XGYpS9yI+fhh8RTafBtGposw==
"@rollup/pluginutils@^4.1.2":
version "4.2.0"
@@ -653,72 +653,72 @@
"@svgr/hast-util-to-babel-ast" "^6.2.1"
svg-parser "^2.0.2"
"@tauri-apps/api@^1.0.0-rc.3":
version "1.0.0-rc.3"
resolved "https://registry.yarnpkg.com/@tauri-apps/api/-/api-1.0.0-rc.3.tgz#e80ddbe832bf003537d94801d508a7f7e25ac48b"
integrity sha512-/ZbyBjuUoU6mYm8RzibIUvVuJ31ZwYA2+fTRl7FF4LVFhzCVJ1YI1BS5ohGb2GsLNmLpfeo7kDHaIhV2uaOchQ==
"@tauri-apps/api@^1.0.0-rc.4":
version "1.0.0-rc.4"
resolved "https://registry.yarnpkg.com/@tauri-apps/api/-/api-1.0.0-rc.4.tgz#454ef7b15237f3d5752bbfc09c8997a00b1e8a9b"
integrity sha512-1HaUsx8+TzFHDoQ+Mmd6RWaMsPyZlurQHgACDt+il5e/ui6pDkumVXaS92SnY5XOcS4gBC0BkgjVfkWgcm/Oww==
dependencies:
type-fest "2.12.1"
type-fest "2.12.2"
"@tauri-apps/cli-darwin-arm64@1.0.0-rc.8":
version "1.0.0-rc.8"
resolved "https://registry.yarnpkg.com/@tauri-apps/cli-darwin-arm64/-/cli-darwin-arm64-1.0.0-rc.8.tgz#84eac830714d1819c72f4e3d7e334bee3719d673"
integrity sha512-sbV4fkd3YBlX0gEBldEVmN/NbBdHzrn8wCRRiFaNBocDWC6Ji6DNvpp1Vy1xgY0RgtGOisGD+3+HelmKP4Mh/A==
"@tauri-apps/cli-darwin-arm64@1.0.0-rc.9":
version "1.0.0-rc.9"
resolved "https://registry.yarnpkg.com/@tauri-apps/cli-darwin-arm64/-/cli-darwin-arm64-1.0.0-rc.9.tgz#8786ce2eacbad4b69eaa8e4e0b7ae16819923b11"
integrity sha512-cpcSRyVOh3n5GsCdKtVQpLJ36yx7h+KY868l7KhPnM5EL1cQbFwYzD/VHlzFvfrpS19YvPBB/AHln4rll5iWvw==
"@tauri-apps/cli-darwin-x64@1.0.0-rc.8":
version "1.0.0-rc.8"
resolved "https://registry.yarnpkg.com/@tauri-apps/cli-darwin-x64/-/cli-darwin-x64-1.0.0-rc.8.tgz#675b8cdbf2a0ade23159e964ac3a1e5dd767ffcf"
integrity sha512-VmuYbBZKKal/YxSTbzHTaM04C9zUlTXq7ePoXc1PRAa/Xafo16N37OGzhzBlsKHrvh6BtPp9ZWk5UhHIDiJBsw==
"@tauri-apps/cli-darwin-x64@1.0.0-rc.9":
version "1.0.0-rc.9"
resolved "https://registry.yarnpkg.com/@tauri-apps/cli-darwin-x64/-/cli-darwin-x64-1.0.0-rc.9.tgz#b4aa98ebf26018b3e9013ea4ce16a294f2cb8c4f"
integrity sha512-ku8QpMNrfqyCk2adLdVB+zzaCb7T0/RgVvaqEZqK54WW4blUxkeKHbKqZ/SKRdxTkghHbgJIoBtlk1A5GUbAwg==
"@tauri-apps/cli-linux-arm-gnueabihf@1.0.0-rc.8":
version "1.0.0-rc.8"
resolved "https://registry.yarnpkg.com/@tauri-apps/cli-linux-arm-gnueabihf/-/cli-linux-arm-gnueabihf-1.0.0-rc.8.tgz#b7ecece513c7ba828c0e794eca4f3125f83f2cf6"
integrity sha512-2VKkS1c2pK56sgtGxtsm9nKKWefG7dgPnynTuCoEngkgQfNIlZ1ns/eAIZpBmwhvOMOw2OesKvK9ZQo0/lE/IA==
"@tauri-apps/cli-linux-arm-gnueabihf@1.0.0-rc.9":
version "1.0.0-rc.9"
resolved "https://registry.yarnpkg.com/@tauri-apps/cli-linux-arm-gnueabihf/-/cli-linux-arm-gnueabihf-1.0.0-rc.9.tgz#d77c329168eaa2a5d66b9648deda8d98783d781d"
integrity sha512-Qlwm4eWo0uCeL3kmowfaLghPehYTYvnM4fH6cRZndzs6/abqsFdghmEmhP5mn34/RAnHXAUANItqlgk6L7C4iw==
"@tauri-apps/cli-linux-arm64-gnu@1.0.0-rc.8":
version "1.0.0-rc.8"
resolved "https://registry.yarnpkg.com/@tauri-apps/cli-linux-arm64-gnu/-/cli-linux-arm64-gnu-1.0.0-rc.8.tgz#6c08741be40d0148da16b26d568c1595e3b99332"
integrity sha512-jykbrTJyx0uJhhL/3PPYGx5ETqEzacJ3YChnHzVClSzPkrdoGC61/xY9dMD9ZFJsLMJkV4VJj8sGRd1OPKCa/w==
"@tauri-apps/cli-linux-arm64-gnu@1.0.0-rc.9":
version "1.0.0-rc.9"
resolved "https://registry.yarnpkg.com/@tauri-apps/cli-linux-arm64-gnu/-/cli-linux-arm64-gnu-1.0.0-rc.9.tgz#ecf229e8176b55046d64c2fab9c831fa0fe39a77"
integrity sha512-Rr4S902dYjRnDCu141f5Cz3JxwKxX/ax7LiMhSifQu5o2wSiezmZ20VRHBwW1UuZxvGV+hxTuZVnfD6NKQdWdA==
"@tauri-apps/cli-linux-arm64-musl@1.0.0-rc.8":
version "1.0.0-rc.8"
resolved "https://registry.yarnpkg.com/@tauri-apps/cli-linux-arm64-musl/-/cli-linux-arm64-musl-1.0.0-rc.8.tgz#70fdfbf5e4fe4d42bc5984a7bc8914d08a3dcbf6"
integrity sha512-HAIm8BKpLIWkvYgxoRzDIaqWIW3UtH2HO1qDd0aov5FTx/9dtCTtylpvd/6mWs5LGaEmsLoSokfJloI2sMZ/WQ==
"@tauri-apps/cli-linux-arm64-musl@1.0.0-rc.9":
version "1.0.0-rc.9"
resolved "https://registry.yarnpkg.com/@tauri-apps/cli-linux-arm64-musl/-/cli-linux-arm64-musl-1.0.0-rc.9.tgz#10a6052d9a6bd720da5ffb1a98bc862564d7a93f"
integrity sha512-MxqjspY2aS/nxtvBMT8TExZfDWDEsUvQRHHY/2KoBYpqpzucW6WXRGmeOvS1GeA3vnub2/Kq5i32jGRDT1tvrA==
"@tauri-apps/cli-linux-x64-gnu@1.0.0-rc.8":
version "1.0.0-rc.8"
resolved "https://registry.yarnpkg.com/@tauri-apps/cli-linux-x64-gnu/-/cli-linux-x64-gnu-1.0.0-rc.8.tgz#bf21f03128e1d6f8ae4d4e043ac2620d8489a69d"
integrity sha512-fnPrkX6Uy9Qz2vqnT3D3sgbJzXTR4arNUIQl8HIYi2YCZZVmDWczz4x4++ilZWwk0I3a7d612/WzTeBzQjn3kg==
"@tauri-apps/cli-linux-x64-gnu@1.0.0-rc.9":
version "1.0.0-rc.9"
resolved "https://registry.yarnpkg.com/@tauri-apps/cli-linux-x64-gnu/-/cli-linux-x64-gnu-1.0.0-rc.9.tgz#34891286ffe0eba1c0602baaa5c3f198f5247a0a"
integrity sha512-LD7KnJuH1mYFwQfcALPttBnaSG6pgO87Z6nY3xXJjo+A4ttPHcmIBaNdXCTjAmib/umD0nD8k95Hw9iJFYTuiA==
"@tauri-apps/cli-linux-x64-musl@1.0.0-rc.8":
version "1.0.0-rc.8"
resolved "https://registry.yarnpkg.com/@tauri-apps/cli-linux-x64-musl/-/cli-linux-x64-musl-1.0.0-rc.8.tgz#647286cb6826d0ff1503a9d6d88959ab8f5de4fb"
integrity sha512-kHrpBsJFRAwqFL7xnsrKdNxnYjzI/J9/Dr7T3rl+IIPbi1sIojh6DydxFOYepnuoINA6zWYQJpo0FQeASJsXrw==
"@tauri-apps/cli-linux-x64-musl@1.0.0-rc.9":
version "1.0.0-rc.9"
resolved "https://registry.yarnpkg.com/@tauri-apps/cli-linux-x64-musl/-/cli-linux-x64-musl-1.0.0-rc.9.tgz#32e6550964e559b158d4b9c83b3a7e3c3d58abee"
integrity sha512-ifocAxBYhk7qrO5x1mizxx/yABvkmyia0kw9eXUn7d5a30HoBcl/A9t+w+7c4B/n/D+gxEMSr6CPaIZv7KnTog==
"@tauri-apps/cli-win32-ia32-msvc@1.0.0-rc.8":
version "1.0.0-rc.8"
resolved "https://registry.yarnpkg.com/@tauri-apps/cli-win32-ia32-msvc/-/cli-win32-ia32-msvc-1.0.0-rc.8.tgz#69fff6f746631345649d2abf788e9f0954eb7ce8"
integrity sha512-y8uT7AaIZVdLAWL4pxj/GXitwWn828er23yniOvTo1mJMCZsSFdwiOGiRSXI6OZsVCOPiJmvqq7eWaskQKYA0A==
"@tauri-apps/cli-win32-ia32-msvc@1.0.0-rc.9":
version "1.0.0-rc.9"
resolved "https://registry.yarnpkg.com/@tauri-apps/cli-win32-ia32-msvc/-/cli-win32-ia32-msvc-1.0.0-rc.9.tgz#01f5c7f1f9a359ea7f6d203dd03d8b98cf8bdcb6"
integrity sha512-ClDYF4CstoccPMVkIHyvy1jzlWXIYZX2mjKB6z18MdJ0O7Je8TC115K30lqXtSdPuKX35xWDcWU2b/gllcUUzA==
"@tauri-apps/cli-win32-x64-msvc@1.0.0-rc.8":
version "1.0.0-rc.8"
resolved "https://registry.yarnpkg.com/@tauri-apps/cli-win32-x64-msvc/-/cli-win32-x64-msvc-1.0.0-rc.8.tgz#bf58e24c42fccf098f78dc51e43f5cd7b7ff6842"
integrity sha512-PiDr/iAKoL9nQSiWHkUSjRVHbvCJaa7Xj3P9UnGkjJQ9LGTr7AYZdLk4zISegF+/fZnOmaqUdZW9yWPPyJAzPw==
"@tauri-apps/cli-win32-x64-msvc@1.0.0-rc.9":
version "1.0.0-rc.9"
resolved "https://registry.yarnpkg.com/@tauri-apps/cli-win32-x64-msvc/-/cli-win32-x64-msvc-1.0.0-rc.9.tgz#4136d9837efb3c1bf56340d3b5abf56c10b8c7a5"
integrity sha512-hJjnpl864OhpIp2lTMTW4ad2Aia5/Tbf7k8GJILzUY/XkBhZjNIgZORa8bDcnZRCTU+RDgMFc+AoKtDIircjnA==
"@tauri-apps/cli@^1.0.0-rc.8":
version "1.0.0-rc.8"
resolved "https://registry.yarnpkg.com/@tauri-apps/cli/-/cli-1.0.0-rc.8.tgz#ee8c9a587739853bd5f8a46a456a43ae594610f6"
integrity sha512-FWpNwbgGMPgDb41oO7wdBhBsBE6FMG9yHKbtbrkJ/8d/hWcT6e3UUTfFL9cR2VGdp1pdWlul5+BKH0PTf8rB9w==
"@tauri-apps/cli@^1.0.0-rc.9":
version "1.0.0-rc.9"
resolved "https://registry.yarnpkg.com/@tauri-apps/cli/-/cli-1.0.0-rc.9.tgz#727159fa07bb2829b27abc3540324adfcff59f7a"
integrity sha512-j+HZ65wdfFrMwisYeQpdZnldONevBPHjAo9v9Impf0irUU2UR5nwyvyArHTaWCvNeqEs+YV4XXHsfm2xVpnaug==
optionalDependencies:
"@tauri-apps/cli-darwin-arm64" "1.0.0-rc.8"
"@tauri-apps/cli-darwin-x64" "1.0.0-rc.8"
"@tauri-apps/cli-linux-arm-gnueabihf" "1.0.0-rc.8"
"@tauri-apps/cli-linux-arm64-gnu" "1.0.0-rc.8"
"@tauri-apps/cli-linux-arm64-musl" "1.0.0-rc.8"
"@tauri-apps/cli-linux-x64-gnu" "1.0.0-rc.8"
"@tauri-apps/cli-linux-x64-musl" "1.0.0-rc.8"
"@tauri-apps/cli-win32-ia32-msvc" "1.0.0-rc.8"
"@tauri-apps/cli-win32-x64-msvc" "1.0.0-rc.8"
"@tauri-apps/cli-darwin-arm64" "1.0.0-rc.9"
"@tauri-apps/cli-darwin-x64" "1.0.0-rc.9"
"@tauri-apps/cli-linux-arm-gnueabihf" "1.0.0-rc.9"
"@tauri-apps/cli-linux-arm64-gnu" "1.0.0-rc.9"
"@tauri-apps/cli-linux-arm64-musl" "1.0.0-rc.9"
"@tauri-apps/cli-linux-x64-gnu" "1.0.0-rc.9"
"@tauri-apps/cli-linux-x64-musl" "1.0.0-rc.9"
"@tauri-apps/cli-win32-ia32-msvc" "1.0.0-rc.9"
"@tauri-apps/cli-win32-x64-msvc" "1.0.0-rc.9"
"@types/fs-extra@^9.0.13":
version "9.0.13"
@@ -828,6 +828,13 @@ adm-zip@^0.5.9:
resolved "https://registry.yarnpkg.com/adm-zip/-/adm-zip-0.5.9.tgz#b33691028333821c0cf95c31374c5462f2905a83"
integrity sha512-s+3fXLkeeLjZ2kLjCBwQufpI5fuN+kIGBxu6530nVQZGVol0d7Y/M88/xw9HGGUcJjKf8LutN3VPRUBq6N7Ajg==
agent-base@6:
version "6.0.2"
resolved "https://registry.yarnpkg.com/agent-base/-/agent-base-6.0.2.tgz#49fff58577cfee3f37176feab4c22e00f86d7f77"
integrity sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==
dependencies:
debug "4"
ahooks-v3-count@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/ahooks-v3-count/-/ahooks-v3-count-1.0.0.tgz#ddeb392e009ad6e748905b3cbf63a9fd8262ca80"
@@ -1075,7 +1082,7 @@ dayjs@^1.11.0, dayjs@^1.9.1:
resolved "https://registry.yarnpkg.com/dayjs/-/dayjs-1.11.0.tgz#009bf7ef2e2ea2d5db2e6583d2d39a4b5061e805"
integrity sha512-JLC809s6Y948/FuCZPm5IX8rRhQwOiyMb2TfVVQEixG7P8Lm/gt5S7yoQZmC8x1UehI9Pb7sksEt4xx14m+7Ug==
debug@^4.1.0:
debug@4, debug@^4.1.0:
version "4.3.4"
resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.4.tgz#1319f6579357f2338d3337d2cdd4914bb5dcc865"
integrity sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==
@@ -1416,6 +1423,14 @@ html-parse-stringify@^3.0.1:
dependencies:
void-elements "3.1.0"
https-proxy-agent@^5.0.1:
version "5.0.1"
resolved "https://registry.yarnpkg.com/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz#c59ef224a04fe8b754f3db0063a25ea30d0005d6"
integrity sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==
dependencies:
agent-base "6"
debug "4"
human-signals@^1.1.1:
version "1.1.1"
resolved "https://registry.yarnpkg.com/human-signals/-/human-signals-1.1.1.tgz#c5b1cd14f50aeae09ab6c59fe63ba3395fe4dfa3"
@@ -2018,10 +2033,10 @@ tunnel@0.0.6:
resolved "https://registry.yarnpkg.com/tunnel/-/tunnel-0.0.6.tgz#72f1314b34a5b192db012324df2cc587ca47f92c"
integrity sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg==
type-fest@2.12.1:
version "2.12.1"
resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-2.12.1.tgz#d2be8f50bf5f8f0a5fd916d29bf3e98c17e960be"
integrity sha512-AiknQSEqKVGDDjtZqeKrUoTlcj7FKhupmnVUgz6KoOKtvMwRGE6hUNJ/nVear+h7fnUPO1q/htSkYKb1pyntkQ==
type-fest@2.12.2:
version "2.12.2"
resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-2.12.2.tgz#80a53614e6b9b475eb9077472fb7498dc7aa51d0"
integrity sha512-qt6ylCGpLjZ7AaODxbpyBZSs9fCI9SkL3Z9q2oxMBQhs/uyY+VD8jHA8ULCGmWQJlBgqvO3EJeAngOHD8zQCrQ==
typescript@^4.5.5:
version "4.6.3"