mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-11-26 23:30:09 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
77ef3847ce | ||
|
|
b8291837fc | ||
|
|
423a7f951a | ||
|
|
557f5fe364 | ||
|
|
5308970ad8 | ||
|
|
6b368953f4 | ||
|
|
2d0b63c29d | ||
|
|
34e941c8cb | ||
|
|
76cf007fff | ||
|
|
321963be83 | ||
|
|
c733bda6c3 | ||
|
|
e67b50b976 | ||
|
|
9e3c080909 | ||
|
|
cb661aaebd | ||
|
|
573571978c | ||
|
|
dc492a2a0a | ||
|
|
e47747dd0e | ||
|
|
4de944b41e | ||
|
|
5f7a1fa5cd | ||
|
|
b8ad328cde | ||
|
|
3076fd19c1 | ||
|
|
fac437b8c1 | ||
|
|
697c25015e | ||
|
|
d83b404fc3 | ||
|
|
ab7313cbc4 | ||
|
|
1b8d70322b | ||
|
|
844ffab4ed | ||
|
|
f5d0513d1f | ||
|
|
557abd4285 | ||
|
|
f4f1a0fbc6 | ||
|
|
74e10dc012 | ||
|
|
359812b7ed | ||
|
|
c2449e53c4 | ||
|
|
1a91249da2 | ||
|
|
b9162f9576 | ||
|
|
f726e8a7b3 | ||
|
|
2f284cfdc9 | ||
|
|
b74696adba | ||
|
|
c8ccba0192 | ||
|
|
41b0e05f62 | ||
|
|
847d5f1b3b | ||
|
|
0445f9dfc2 | ||
|
|
3001c780bd | ||
|
|
68ad5e2320 | ||
|
|
b5e229b19c | ||
|
|
453d798fcf |
@@ -76,7 +76,7 @@ jobs:
|
|||||||
- name: Green zip bundle
|
- name: Green zip bundle
|
||||||
if: matrix.os == 'windows-latest'
|
if: matrix.os == 'windows-latest'
|
||||||
run: |
|
run: |
|
||||||
yarn run green
|
yarn run portable
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,33 @@
|
|||||||
|
## 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
|
## v0.0.28
|
||||||
|
|
||||||
### Features
|
### Features
|
||||||
|
|||||||
+6
-5
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "clash-verge",
|
"name": "clash-verge",
|
||||||
"version": "0.0.28",
|
"version": "1.0.0",
|
||||||
"license": "GPL-3.0",
|
"license": "GPL-3.0",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "tauri dev",
|
"dev": "tauri dev",
|
||||||
@@ -10,16 +10,16 @@
|
|||||||
"web:build": "tsc && vite build",
|
"web:build": "tsc && vite build",
|
||||||
"web:serve": "vite preview",
|
"web:serve": "vite preview",
|
||||||
"check": "node scripts/check.mjs",
|
"check": "node scripts/check.mjs",
|
||||||
"green": "node scripts/green.mjs",
|
|
||||||
"publish": "node scripts/publish.mjs",
|
|
||||||
"updater": "node scripts/updater.mjs",
|
"updater": "node scripts/updater.mjs",
|
||||||
|
"publish": "node scripts/publish.mjs",
|
||||||
|
"portable": "node scripts/portable.mjs",
|
||||||
"prepare": "husky install"
|
"prepare": "husky install"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@emotion/react": "^11.8.2",
|
"@emotion/react": "^11.8.2",
|
||||||
"@emotion/styled": "^11.8.1",
|
"@emotion/styled": "^11.8.1",
|
||||||
"@mui/icons-material": "^5.5.1",
|
"@mui/icons-material": "^5.6.1",
|
||||||
"@mui/material": "^5.5.3",
|
"@mui/material": "^5.6.1",
|
||||||
"@tauri-apps/api": "^1.0.0-rc.3",
|
"@tauri-apps/api": "^1.0.0-rc.3",
|
||||||
"ahooks": "^3.2.0",
|
"ahooks": "^3.2.0",
|
||||||
"axios": "^0.26.0",
|
"axios": "^0.26.0",
|
||||||
@@ -46,6 +46,7 @@
|
|||||||
"@vitejs/plugin-react": "^1.2.0",
|
"@vitejs/plugin-react": "^1.2.0",
|
||||||
"adm-zip": "^0.5.9",
|
"adm-zip": "^0.5.9",
|
||||||
"fs-extra": "^10.0.0",
|
"fs-extra": "^10.0.0",
|
||||||
|
"https-proxy-agent": "^5.0.1",
|
||||||
"husky": "^7.0.0",
|
"husky": "^7.0.0",
|
||||||
"node-fetch": "^3.2.0",
|
"node-fetch": "^3.2.0",
|
||||||
"pretty-quick": "^3.1.3",
|
"pretty-quick": "^3.1.3",
|
||||||
|
|||||||
+47
-5
@@ -3,9 +3,12 @@ import zlib from "zlib";
|
|||||||
import path from "path";
|
import path from "path";
|
||||||
import AdmZip from "adm-zip";
|
import AdmZip from "adm-zip";
|
||||||
import fetch from "node-fetch";
|
import fetch from "node-fetch";
|
||||||
|
import proxyAgent from "https-proxy-agent";
|
||||||
import { execSync } from "child_process";
|
import { execSync } from "child_process";
|
||||||
|
|
||||||
const cwd = process.cwd();
|
const cwd = process.cwd();
|
||||||
|
const TEMP_DIR = path.join(cwd, "node_modules/.verge");
|
||||||
|
|
||||||
const FORCE = process.argv.includes("--force");
|
const FORCE = process.argv.includes("--force");
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -16,7 +19,7 @@ function resolveClash() {
|
|||||||
|
|
||||||
const CLASH_URL_PREFIX =
|
const CLASH_URL_PREFIX =
|
||||||
"https://github.com/Dreamacro/clash/releases/download/premium/";
|
"https://github.com/Dreamacro/clash/releases/download/premium/";
|
||||||
const CLASH_LATEST_DATE = "2022.03.21";
|
const CLASH_LATEST_DATE = "2022.04.17";
|
||||||
|
|
||||||
// todo
|
// todo
|
||||||
const map = {
|
const map = {
|
||||||
@@ -57,7 +60,7 @@ async function resolveSidecar() {
|
|||||||
|
|
||||||
// download sidecar
|
// download sidecar
|
||||||
const binInfo = resolveClash();
|
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 tempZip = path.join(tempDir, binInfo.zipfile);
|
||||||
const tempExe = path.join(tempDir, binInfo.exefile);
|
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 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 tempZip = path.join(tempDir, "wintun.zip");
|
||||||
|
|
||||||
const wintunPath = path.join(tempDir, "wintun/bin/amd64/wintun.dll");
|
const wintunPath = path.join(tempDir, "wintun/bin/amd64/wintun.dll");
|
||||||
@@ -125,14 +128,37 @@ async function resolveWintun() {
|
|||||||
throw new Error(`path not found "${wintunPath}"`);
|
throw new Error(`path not found "${wintunPath}"`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// move wintun.dll to resources
|
|
||||||
await fs.rename(wintunPath, targetPath);
|
await fs.rename(wintunPath, targetPath);
|
||||||
// delete temp dir
|
|
||||||
await fs.remove(tempDir);
|
await fs.remove(tempDir);
|
||||||
|
|
||||||
console.log(`[INFO]: resolve wintun.dll finished`);
|
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 url =
|
||||||
|
"https://github.com/zzzgydi/clash-verge-service/releases/download/latest/clash-verge-service.exe";
|
||||||
|
|
||||||
|
const binName = "clash-verge-service.exe";
|
||||||
|
|
||||||
|
const resDir = path.join(cwd, "src-tauri/resources");
|
||||||
|
const targetPath = path.join(resDir, binName);
|
||||||
|
|
||||||
|
if (!FORCE && (await fs.pathExists(targetPath))) return;
|
||||||
|
|
||||||
|
await fs.mkdirp(resDir);
|
||||||
|
await downloadFile(url, targetPath);
|
||||||
|
|
||||||
|
console.log(`[INFO]: resolve ${binName} finished`);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* get the Country.mmdb (not required)
|
* get the Country.mmdb (not required)
|
||||||
*/
|
*/
|
||||||
@@ -142,7 +168,9 @@ async function resolveMmdb() {
|
|||||||
|
|
||||||
const resDir = path.join(cwd, "src-tauri", "resources");
|
const resDir = path.join(cwd, "src-tauri", "resources");
|
||||||
const resPath = path.join(resDir, "Country.mmdb");
|
const resPath = path.join(resDir, "Country.mmdb");
|
||||||
|
|
||||||
if (!FORCE && (await fs.pathExists(resPath))) return;
|
if (!FORCE && (await fs.pathExists(resPath))) return;
|
||||||
|
|
||||||
await fs.mkdirp(resDir);
|
await fs.mkdirp(resDir);
|
||||||
await downloadFile(url, resPath);
|
await downloadFile(url, resPath);
|
||||||
}
|
}
|
||||||
@@ -153,7 +181,20 @@ async function resolveMmdb() {
|
|||||||
async function downloadFile(url, path) {
|
async function downloadFile(url, path) {
|
||||||
console.log(`[INFO]: downloading from "${url}"`);
|
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, {
|
const response = await fetch(url, {
|
||||||
|
...options,
|
||||||
method: "GET",
|
method: "GET",
|
||||||
headers: { "Content-Type": "application/octet-stream" },
|
headers: { "Content-Type": "application/octet-stream" },
|
||||||
});
|
});
|
||||||
@@ -167,3 +208,4 @@ async function downloadFile(url, path) {
|
|||||||
resolveSidecar().catch(console.error);
|
resolveSidecar().catch(console.error);
|
||||||
resolveWintun().catch(console.error);
|
resolveWintun().catch(console.error);
|
||||||
resolveMmdb().catch(console.error);
|
resolveMmdb().catch(console.error);
|
||||||
|
resolveService().catch(console.error);
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import { getOctokit, context } from "@actions/github";
|
|||||||
|
|
||||||
/// Script for ci
|
/// Script for ci
|
||||||
/// 打包绿色版/便携版 (only Windows)
|
/// 打包绿色版/便携版 (only Windows)
|
||||||
async function resolveGreen() {
|
async function resolvePortable() {
|
||||||
if (process.platform !== "win32") return;
|
if (process.platform !== "win32") return;
|
||||||
|
|
||||||
const releaseDir = "./src-tauri/target/release";
|
const releaseDir = "./src-tauri/target/release";
|
||||||
@@ -25,10 +25,10 @@ async function resolveGreen() {
|
|||||||
const packageJson = require("../package.json");
|
const packageJson = require("../package.json");
|
||||||
const { version } = packageJson;
|
const { version } = packageJson;
|
||||||
|
|
||||||
const zipFile = `Clash.Verge_${version}_x64_green.zip`;
|
const zipFile = `Clash.Verge_${version}_x64_portable.zip`;
|
||||||
zip.writeZip(zipFile);
|
zip.writeZip(zipFile);
|
||||||
|
|
||||||
console.log("[INFO]: create green zip successfully");
|
console.log("[INFO]: create portable zip successfully");
|
||||||
|
|
||||||
// push release assets
|
// push release assets
|
||||||
if (process.env.GITHUB_TOKEN === undefined) {
|
if (process.env.GITHUB_TOKEN === undefined) {
|
||||||
@@ -53,4 +53,4 @@ async function resolveGreen() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
resolveGreen().catch(console.error);
|
resolvePortable().catch(console.error);
|
||||||
Generated
+617
-28
File diff suppressed because it is too large
Load Diff
@@ -21,6 +21,8 @@ nanoid = "0.4.0"
|
|||||||
chrono = "0.4.19"
|
chrono = "0.4.19"
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
serde_yaml = "0.8"
|
serde_yaml = "0.8"
|
||||||
|
delay_timer = "0.11.1"
|
||||||
|
parking_lot = "0.12.0"
|
||||||
serde = { version = "1.0", features = ["derive"] }
|
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.6", features = ["process-all", "shell-all", "system-tray", "updater", "window-all"] }
|
||||||
window-shadows = { git = "https://github.com/tauri-apps/window-shadows" }
|
window-shadows = { git = "https://github.com/tauri-apps/window-shadows" }
|
||||||
@@ -36,11 +38,13 @@ auto-launch = "0.2"
|
|||||||
port_scanner = "0.1.5"
|
port_scanner = "0.1.5"
|
||||||
|
|
||||||
[target.'cfg(windows)'.dependencies]
|
[target.'cfg(windows)'.dependencies]
|
||||||
|
runas = "0.2.1"
|
||||||
|
deelevate = "0.2.0"
|
||||||
winreg = { version = "0.10", features = ["transactions"] }
|
winreg = { version = "0.10", features = ["transactions"] }
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = [ "custom-protocol" ]
|
default = ["custom-protocol"]
|
||||||
custom-protocol = [ "tauri/custom-protocol" ]
|
custom-protocol = ["tauri/custom-protocol"]
|
||||||
verge-dev = []
|
verge-dev = []
|
||||||
debug-yml = []
|
debug-yml = []
|
||||||
|
|
||||||
|
|||||||
+157
-238
@@ -1,26 +1,25 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
core::{ClashInfo, PrfItem, PrfOption, Profiles, VergeConfig},
|
core::{ClashInfo, Core, PrfItem, PrfOption, Profiles, Verge},
|
||||||
states::{ClashState, ProfilesState, VergeState},
|
utils::{dirs, help, sysopt::SysProxyConfig},
|
||||||
utils::{dirs, sysopt::SysProxyConfig},
|
|
||||||
};
|
};
|
||||||
use crate::{ret_err, wrap_err};
|
use crate::{log_if_err, ret_err, wrap_err};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use serde_yaml::Mapping;
|
use serde_yaml::Mapping;
|
||||||
use std::process::Command;
|
use tauri::{api, State};
|
||||||
use tauri::{api, Manager, State};
|
|
||||||
|
type CmdResult<T = ()> = Result<T, String>;
|
||||||
|
|
||||||
/// get all profiles from `profiles.yaml`
|
/// get all profiles from `profiles.yaml`
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn get_profiles<'a>(profiles_state: State<'_, ProfilesState>) -> Result<Profiles, String> {
|
pub fn get_profiles(core: State<'_, Core>) -> CmdResult<Profiles> {
|
||||||
let profiles = profiles_state.0.lock().unwrap();
|
let profiles = core.profiles.lock();
|
||||||
Ok(profiles.clone())
|
Ok(profiles.clone())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// synchronize data irregularly
|
/// manually exec enhanced profile
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn sync_profiles(profiles_state: State<'_, ProfilesState>) -> Result<(), String> {
|
pub fn enhance_profiles(core: State<'_, Core>) -> CmdResult {
|
||||||
let mut profiles = profiles_state.0.lock().unwrap();
|
wrap_err!(core.activate_enhanced(false))
|
||||||
wrap_err!(profiles.sync_file())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// import the profile from url
|
/// import the profile from url
|
||||||
@@ -29,11 +28,11 @@ pub fn sync_profiles(profiles_state: State<'_, ProfilesState>) -> Result<(), Str
|
|||||||
pub async fn import_profile(
|
pub async fn import_profile(
|
||||||
url: String,
|
url: String,
|
||||||
option: Option<PrfOption>,
|
option: Option<PrfOption>,
|
||||||
profiles_state: State<'_, ProfilesState>,
|
core: State<'_, Core>,
|
||||||
) -> Result<(), String> {
|
) -> CmdResult {
|
||||||
let item = wrap_err!(PrfItem::from_url(&url, None, None, option).await)?;
|
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))
|
wrap_err!(profiles.append_item(item))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -44,11 +43,11 @@ pub async fn import_profile(
|
|||||||
pub async fn create_profile(
|
pub async fn create_profile(
|
||||||
item: PrfItem, // partial
|
item: PrfItem, // partial
|
||||||
file_data: Option<String>,
|
file_data: Option<String>,
|
||||||
profiles_state: State<'_, ProfilesState>,
|
core: State<'_, Core>,
|
||||||
) -> Result<(), String> {
|
) -> CmdResult {
|
||||||
let item = wrap_err!(PrfItem::from(item, file_data).await)?;
|
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))
|
wrap_err!(profiles.append_item(item))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,118 +56,53 @@ pub async fn create_profile(
|
|||||||
pub async fn update_profile(
|
pub async fn update_profile(
|
||||||
index: String,
|
index: String,
|
||||||
option: Option<PrfOption>,
|
option: Option<PrfOption>,
|
||||||
clash_state: State<'_, ClashState>,
|
core: State<'_, Core>,
|
||||||
profiles_state: State<'_, ProfilesState>,
|
) -> CmdResult {
|
||||||
) -> Result<(), String> {
|
wrap_err!(Core::update_profile_item(core.inner().clone(), index, option).await)
|
||||||
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(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// change the current profile
|
/// change the current profile
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn select_profile(
|
pub fn select_profile(index: String, core: State<'_, Core>) -> CmdResult {
|
||||||
index: String,
|
let mut profiles = core.profiles.lock();
|
||||||
clash_state: State<'_, ClashState>,
|
|
||||||
profiles_state: State<'_, ProfilesState>,
|
|
||||||
) -> Result<(), String> {
|
|
||||||
let mut profiles = profiles_state.0.lock().unwrap();
|
|
||||||
wrap_err!(profiles.put_current(index))?;
|
wrap_err!(profiles.put_current(index))?;
|
||||||
|
|
||||||
let clash = clash_state.0.lock().unwrap();
|
drop(profiles);
|
||||||
wrap_err!(clash.activate_enhanced(&profiles, false, false))
|
|
||||||
|
wrap_err!(core.activate_enhanced(false))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// change the profile chain
|
/// change the profile chain
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn change_profile_chain(
|
pub fn change_profile_chain(chain: Option<Vec<String>>, core: State<'_, Core>) -> CmdResult {
|
||||||
chain: Option<Vec<String>>,
|
let mut profiles = core.profiles.lock();
|
||||||
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();
|
|
||||||
|
|
||||||
profiles.put_chain(chain);
|
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
|
/// change the profile valid fields
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn change_profile_valid(
|
pub fn change_profile_valid(valid: Option<Vec<String>>, core: State<Core>) -> CmdResult {
|
||||||
valid: Option<Vec<String>>,
|
let mut profiles = core.profiles.lock();
|
||||||
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();
|
|
||||||
|
|
||||||
profiles.put_valid(valid);
|
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
|
wrap_err!(core.activate_enhanced(false))
|
||||||
#[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))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// delete profile item
|
/// delete profile item
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn delete_profile(
|
pub fn delete_profile(index: String, core: State<'_, Core>) -> CmdResult {
|
||||||
index: String,
|
let mut profiles = core.profiles.lock();
|
||||||
clash_state: State<'_, ClashState>,
|
|
||||||
profiles_state: State<'_, ProfilesState>,
|
|
||||||
) -> Result<(), String> {
|
|
||||||
let mut profiles = profiles_state.0.lock().unwrap();
|
|
||||||
|
|
||||||
if wrap_err!(profiles.delete_item(index))? {
|
if wrap_err!(profiles.delete_item(index))? {
|
||||||
let clash = clash_state.0.lock().unwrap();
|
drop(profiles);
|
||||||
wrap_err!(clash.activate_enhanced(&profiles, false, false))?;
|
|
||||||
|
log_if_err!(core.activate_enhanced(false));
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -176,19 +110,20 @@ pub fn delete_profile(
|
|||||||
|
|
||||||
/// patch the profile config
|
/// patch the profile config
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn patch_profile(
|
pub fn patch_profile(index: String, profile: PrfItem, core: State<'_, Core>) -> CmdResult {
|
||||||
index: String,
|
let mut profiles = core.profiles.lock();
|
||||||
profile: PrfItem,
|
wrap_err!(profiles.patch_item(index, profile))?;
|
||||||
profiles_state: State<'_, ProfilesState>,
|
drop(profiles);
|
||||||
) -> Result<(), String> {
|
|
||||||
let mut profiles = profiles_state.0.lock().unwrap();
|
// update cron task
|
||||||
wrap_err!(profiles.patch_item(index, profile))
|
let mut timer = core.timer.lock();
|
||||||
|
wrap_err!(timer.refresh())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// run vscode command to edit the profile
|
/// run vscode command to edit the profile
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn view_profile(index: String, profiles_state: State<'_, ProfilesState>) -> Result<(), String> {
|
pub fn view_profile(index: String, core: State<'_, Core>) -> CmdResult {
|
||||||
let profiles = profiles_state.0.lock().unwrap();
|
let profiles = core.profiles.lock();
|
||||||
let item = wrap_err!(profiles.get_item(&index))?;
|
let item = wrap_err!(profiles.get_item(&index))?;
|
||||||
|
|
||||||
let file = item.file.clone();
|
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");
|
ret_err!("the file not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
// use vscode first
|
wrap_err!(help::open_file(path))
|
||||||
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))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// read the profile item file data
|
/// read the profile item file data
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn read_profile_file(
|
pub fn read_profile_file(index: String, core: State<'_, Core>) -> CmdResult<String> {
|
||||||
index: String,
|
let profiles = core.profiles.lock();
|
||||||
profiles_state: State<'_, ProfilesState>,
|
|
||||||
) -> Result<String, String> {
|
|
||||||
let profiles = profiles_state.0.lock().unwrap();
|
|
||||||
let item = wrap_err!(profiles.get_item(&index))?;
|
let item = wrap_err!(profiles.get_item(&index))?;
|
||||||
let data = wrap_err!(item.read_file())?;
|
let data = wrap_err!(item.read_file())?;
|
||||||
|
|
||||||
@@ -247,34 +155,22 @@ pub fn read_profile_file(
|
|||||||
pub fn save_profile_file(
|
pub fn save_profile_file(
|
||||||
index: String,
|
index: String,
|
||||||
file_data: Option<String>,
|
file_data: Option<String>,
|
||||||
profiles_state: State<'_, ProfilesState>,
|
core: State<'_, Core>,
|
||||||
) -> Result<(), String> {
|
) -> CmdResult {
|
||||||
if file_data.is_none() {
|
if file_data.is_none() {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
let profiles = profiles_state.0.lock().unwrap();
|
let profiles = core.profiles.lock();
|
||||||
let item = wrap_err!(profiles.get_item(&index))?;
|
let item = wrap_err!(profiles.get_item(&index))?;
|
||||||
wrap_err!(item.save_file(file_data.unwrap()))
|
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
|
/// get the clash core info from the state
|
||||||
/// the caller can also get the infomation by clash's api
|
/// the caller can also get the infomation by clash's api
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn get_clash_info(clash_state: State<'_, ClashState>) -> Result<ClashInfo, String> {
|
pub fn get_clash_info(core: State<'_, Core>) -> CmdResult<ClashInfo> {
|
||||||
let clash = clash_state.0.lock().unwrap();
|
let clash = core.clash.lock();
|
||||||
Ok(clash.info.clone())
|
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
|
/// after putting the change to the clash core
|
||||||
/// then we should save the latest config
|
/// then we should save the latest config
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn patch_clash_config(
|
pub fn patch_clash_config(payload: Mapping, core: State<'_, Core>) -> CmdResult {
|
||||||
payload: Mapping,
|
wrap_err!(core.patch_clash(payload))
|
||||||
clash_state: State<'_, ClashState>,
|
}
|
||||||
verge_state: State<'_, VergeState>,
|
|
||||||
profiles_state: State<'_, ProfilesState>,
|
/// 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> {
|
) -> Result<(), String> {
|
||||||
let mut clash = clash_state.0.lock().unwrap();
|
wrap_err!(core.patch_verge(payload, &app_handle))
|
||||||
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))
|
/// 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
|
/// get the system proxy
|
||||||
@@ -303,73 +221,9 @@ pub fn get_sys_proxy() -> Result<SysProxyConfig, String> {
|
|||||||
/// get the current proxy config
|
/// get the current proxy config
|
||||||
/// which may not the same as system proxy
|
/// which may not the same as system proxy
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn get_cur_proxy(verge_state: State<'_, VergeState>) -> Result<Option<SysProxyConfig>, String> {
|
pub fn get_cur_proxy(core: State<'_, Core>) -> CmdResult<Option<SysProxyConfig>> {
|
||||||
let verge = verge_state.0.lock().unwrap();
|
let sysopt = core.sysopt.lock();
|
||||||
Ok(verge.cur_sysproxy.clone())
|
wrap_err!(sysopt.get_sysproxy())
|
||||||
}
|
|
||||||
|
|
||||||
/// 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();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// open app config dir
|
/// open app config dir
|
||||||
@@ -385,3 +239,68 @@ pub fn open_logs_dir() -> Result<(), String> {
|
|||||||
let log_dir = dirs::app_logs_dir();
|
let log_dir = dirs::app_logs_dir();
|
||||||
wrap_err!(open::that(log_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> {
|
||||||
|
wrap_err!(crate::core::Service::check_service().await)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn install_service() -> Result<(), String> {
|
||||||
|
log_if_err!(crate::core::Service::install_service().await);
|
||||||
|
let ret = wrap_err!(crate::core::Service::start_service().await);
|
||||||
|
log::info!("clash verge service started successfully");
|
||||||
|
ret
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn uninstall_service() -> Result<(), String> {
|
||||||
|
log_if_err!(crate::core::Service::stop_service().await);
|
||||||
|
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
@@ -1,14 +1,7 @@
|
|||||||
use super::{PrfEnhancedResult, Profiles, Verge, VergeConfig};
|
use crate::utils::{config, dirs};
|
||||||
use crate::log_if_err;
|
use anyhow::Result;
|
||||||
use crate::utils::{config, dirs, help};
|
|
||||||
use anyhow::{bail, Result};
|
|
||||||
use reqwest::header::HeaderMap;
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use serde_yaml::{Mapping, Value};
|
use serde_yaml::{Mapping, Value};
|
||||||
use std::{collections::HashMap, time::Duration};
|
|
||||||
use tauri::api::process::{Command, CommandChild, CommandEvent};
|
|
||||||
use tauri::Window;
|
|
||||||
use tokio::time::sleep;
|
|
||||||
|
|
||||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||||
pub struct ClashInfo {
|
pub struct ClashInfo {
|
||||||
@@ -25,56 +18,16 @@ pub struct ClashInfo {
|
|||||||
pub secret: Option<String>,
|
pub secret: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct Clash {
|
impl ClashInfo {
|
||||||
/// 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"),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// parse the clash's config.yaml
|
/// parse the clash's config.yaml
|
||||||
/// get some information
|
/// get some information
|
||||||
fn get_info(clash_config: &Mapping) -> ClashInfo {
|
pub fn from(config: &Mapping) -> ClashInfo {
|
||||||
let key_port_1 = Value::String("port".to_string());
|
let key_port_1 = Value::from("port");
|
||||||
let key_port_2 = Value::String("mixed-port".to_string());
|
let key_port_2 = Value::from("mixed-port");
|
||||||
let key_server = Value::String("external-controller".to_string());
|
let key_server = Value::from("external-controller");
|
||||||
let key_secret = Value::String("secret".to_string());
|
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 {
|
Some(value) => match value {
|
||||||
Value::String(val_str) => Some(val_str.clone()),
|
Value::String(val_str) => Some(val_str.clone()),
|
||||||
Value::Number(val_num) => Some(val_num.to_string()),
|
Value::Number(val_num) => Some(val_num.to_string()),
|
||||||
@@ -84,7 +37,7 @@ impl Clash {
|
|||||||
};
|
};
|
||||||
let port = match port {
|
let port = match port {
|
||||||
Some(_) => port,
|
Some(_) => port,
|
||||||
None => match clash_config.get(&key_port_2) {
|
None => match config.get(&key_port_2) {
|
||||||
Some(value) => match value {
|
Some(value) => match value {
|
||||||
Value::String(val_str) => Some(val_str.clone()),
|
Value::String(val_str) => Some(val_str.clone()),
|
||||||
Value::Number(val_num) => Some(val_num.to_string()),
|
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 {
|
Some(value) => match value {
|
||||||
Value::String(val_str) => {
|
Value::String(val_str) => match val_str.starts_with(":") {
|
||||||
// `external-controller` could be
|
true => Some(format!("127.0.0.1{val_str}")),
|
||||||
// "127.0.0.1:9090" or ":9090"
|
false => Some(val_str.clone()),
|
||||||
// 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)
|
|
||||||
}
|
|
||||||
_ => None,
|
_ => None,
|
||||||
},
|
},
|
||||||
_ => None,
|
_ => None,
|
||||||
};
|
};
|
||||||
let secret = match clash_config.get(&key_secret) {
|
|
||||||
|
let secret = match config.get(&key_secret) {
|
||||||
Some(value) => match value {
|
Some(value) => match value {
|
||||||
Value::String(val_str) => Some(val_str.clone()),
|
Value::String(val_str) => Some(val_str.clone()),
|
||||||
Value::Bool(val_bool) => Some(val_bool.to_string()),
|
Value::Bool(val_bool) => Some(val_bool.to_string()),
|
||||||
@@ -129,101 +78,71 @@ impl Clash {
|
|||||||
secret,
|
secret,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// save the main window
|
pub struct Clash {
|
||||||
pub fn set_window(&mut self, win: Option<Window>) {
|
/// maintain the clash config
|
||||||
self.window = win;
|
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
|
/// get clash config
|
||||||
pub fn run_sidecar(&mut self) -> Result<()> {
|
pub fn read_config() -> Mapping {
|
||||||
let app_dir = dirs::app_home_dir();
|
config::read_yaml::<Mapping>(dirs::clash_path())
|
||||||
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()),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// drop clash sidecar
|
/// save the clash config
|
||||||
pub fn drop_sidecar(&mut self) -> Result<()> {
|
pub fn save_config(&self) -> Result<()> {
|
||||||
if let Some(sidecar) = self.sidecar.take() {
|
config::save_yaml(
|
||||||
sidecar.kill()?;
|
dirs::clash_path(),
|
||||||
}
|
&self.config,
|
||||||
Ok(())
|
Some("# Default Config For Clash Core\n\n"),
|
||||||
}
|
)
|
||||||
|
|
||||||
/// 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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// patch update the clash config
|
/// patch update the clash config
|
||||||
pub fn patch_config(
|
/// if the port is changed then return true
|
||||||
&mut self,
|
pub fn patch_config(&mut self, patch: Mapping) -> Result<bool> {
|
||||||
patch: Mapping,
|
let port_key = Value::from("mixed-port");
|
||||||
verge: &mut Verge,
|
let server_key = Value::from("external-controller");
|
||||||
profiles: &mut Profiles,
|
let secret_key = Value::from("secret");
|
||||||
) -> Result<()> {
|
|
||||||
let mix_port_key = Value::from("mixed-port");
|
let mut change_port = false;
|
||||||
let mut port = None;
|
let mut change_info = false;
|
||||||
|
|
||||||
for (key, value) in patch.into_iter() {
|
for (key, value) in patch.into_iter() {
|
||||||
let value = value.clone();
|
if key == port_key {
|
||||||
|
change_port = true;
|
||||||
// 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());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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()?;
|
self.save_config()?;
|
||||||
|
|
||||||
if let Some(port) = port {
|
Ok(change_port)
|
||||||
self.restart_sidecar(profiles)?;
|
|
||||||
verge.init_sysproxy(Some(port));
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// revise the `tun` and `dns` config
|
/// 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 {
|
macro_rules! revise {
|
||||||
($map: expr, $key: expr, $val: expr) => {
|
($map: expr, $key: expr, $val: expr) => {
|
||||||
let ret_key = Value::String($key.into());
|
let ret_key = Value::String($key.into());
|
||||||
@@ -260,18 +179,17 @@ impl Clash {
|
|||||||
|
|
||||||
revise!(config, "tun", new_tun);
|
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 {
|
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, "enhanced-mode", "fake-ip");
|
||||||
append!(
|
append!(
|
||||||
new_dns,
|
new_dns,
|
||||||
@@ -290,156 +208,16 @@ impl Clash {
|
|||||||
"www.msftconnecttest.com"
|
"www.msftconnecttest.com"
|
||||||
]
|
]
|
||||||
);
|
);
|
||||||
|
|
||||||
|
revise!(config, "dns", new_dns);
|
||||||
}
|
}
|
||||||
|
|
||||||
revise!(config, "dns", new_dns);
|
|
||||||
config
|
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)
|
/// only 5 default fields available (clash config fields)
|
||||||
/// convert to lowercase
|
/// convert to lowercase
|
||||||
fn strict_filter(config: Mapping) -> Mapping {
|
pub fn strict_filter(config: Mapping) -> Mapping {
|
||||||
// Only the following fields are allowed:
|
// Only the following fields are allowed:
|
||||||
// proxies/proxy-providers/proxy-groups/rule-providers/rules
|
// proxies/proxy-providers/proxy-groups/rule-providers/rules
|
||||||
let valid_keys = vec![
|
let valid_keys = vec![
|
||||||
@@ -470,7 +248,7 @@ impl Clash {
|
|||||||
|
|
||||||
/// more clash config fields available
|
/// more clash config fields available
|
||||||
/// convert to lowercase
|
/// 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
|
// all of these can not be revised by script or merge
|
||||||
// http/https/socks port should be under control
|
// http/https/socks port should be under control
|
||||||
let not_allow = vec![
|
let not_allow = vec![
|
||||||
@@ -508,11 +286,3 @@ impl Default for Clash {
|
|||||||
Clash::new()
|
Clash::new()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Drop for Clash {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
if let Err(err) = self.drop_sidecar() {
|
|
||||||
log::error!("{err}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -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,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 clash;
|
||||||
|
mod enhance;
|
||||||
|
mod notice;
|
||||||
|
mod prfitem;
|
||||||
mod profiles;
|
mod profiles;
|
||||||
|
mod service;
|
||||||
|
mod sysopt;
|
||||||
|
mod timer;
|
||||||
mod verge;
|
mod verge;
|
||||||
|
|
||||||
pub use self::clash::*;
|
pub use self::clash::*;
|
||||||
|
pub use self::prfitem::*;
|
||||||
pub use self::profiles::*;
|
pub use self::profiles::*;
|
||||||
|
pub use self::service::*;
|
||||||
pub use self::verge::*;
|
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(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -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"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,309 @@
|
|||||||
|
use crate::utils::{dirs, help, tmpl};
|
||||||
|
use anyhow::{bail, Context, Result};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
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 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, 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 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/v0.1.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,
|
||||||
|
};
|
||||||
|
|
||||||
|
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")
|
||||||
|
}
|
||||||
|
}
|
||||||
+21
-384
@@ -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 anyhow::{bail, Context, Result};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use serde_yaml::Mapping;
|
use serde_yaml::Mapping;
|
||||||
use std::{fs, io::Write};
|
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
|
/// ## Profiles Config
|
||||||
///
|
///
|
||||||
@@ -332,6 +35,10 @@ macro_rules! patch {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Profiles {
|
impl Profiles {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Profiles::read_file()
|
||||||
|
}
|
||||||
|
|
||||||
/// read the config from the file
|
/// read the config from the file
|
||||||
pub fn read_file() -> Self {
|
pub fn read_file() -> Self {
|
||||||
let mut profiles = config::read_yaml::<Self>(dirs::profiles_path());
|
let mut profiles = config::read_yaml::<Self>(dirs::profiles_path());
|
||||||
@@ -340,6 +47,7 @@ impl Profiles {
|
|||||||
profiles.items = Some(vec![]);
|
profiles.items = Some(vec![]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// compatiable with the old old old version
|
||||||
profiles.items.as_mut().map(|items| {
|
profiles.items.as_mut().map(|items| {
|
||||||
for mut item in items.iter_mut() {
|
for mut item in items.iter_mut() {
|
||||||
if item.uid.is_none() {
|
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
|
/// get the current uid
|
||||||
pub fn get_current(&self) -> Option<String> {
|
pub fn get_current(&self) -> Option<String> {
|
||||||
self.current.clone()
|
self.current.clone()
|
||||||
@@ -387,11 +82,9 @@ impl Profiles {
|
|||||||
let items = self.items.as_ref().unwrap();
|
let items = self.items.as_ref().unwrap();
|
||||||
let some_uid = Some(uid.clone());
|
let some_uid = Some(uid.clone());
|
||||||
|
|
||||||
for each in items.iter() {
|
if items.iter().find(|&each| each.uid == some_uid).is_some() {
|
||||||
if each.uid == some_uid {
|
self.current = some_uid;
|
||||||
self.current = some_uid;
|
return self.save_file();
|
||||||
return self.save_file();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
bail!("invalid uid \"{uid}\"");
|
bail!("invalid uid \"{uid}\"");
|
||||||
@@ -407,6 +100,11 @@ impl Profiles {
|
|||||||
self.valid = valid;
|
self.valid = valid;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// get items ref
|
||||||
|
pub fn get_items(&self) -> Option<&Vec<PrfItem>> {
|
||||||
|
self.items.as_ref()
|
||||||
|
}
|
||||||
|
|
||||||
/// find the item by the uid
|
/// find the item by the uid
|
||||||
pub fn get_item(&self, uid: &String) -> Result<&PrfItem> {
|
pub fn get_item(&self, uid: &String) -> Result<&PrfItem> {
|
||||||
if self.items.is_some() {
|
if self.items.is_some() {
|
||||||
@@ -455,7 +153,7 @@ impl Profiles {
|
|||||||
self.save_file()
|
self.save_file()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// update the item's value
|
/// update the item value
|
||||||
pub fn patch_item(&mut self, uid: String, item: PrfItem) -> Result<()> {
|
pub fn patch_item(&mut self, uid: String, item: PrfItem) -> Result<()> {
|
||||||
let mut items = self.items.take().unwrap_or(vec![]);
|
let mut items = self.items.take().unwrap_or(vec![]);
|
||||||
|
|
||||||
@@ -490,7 +188,7 @@ impl Profiles {
|
|||||||
// find the item
|
// find the item
|
||||||
let _ = self.get_item(&uid)?;
|
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());
|
let some_uid = Some(uid.clone());
|
||||||
|
|
||||||
for mut each in items.iter_mut() {
|
for mut each in items.iter_mut() {
|
||||||
@@ -510,15 +208,15 @@ impl Profiles {
|
|||||||
let path = dirs::app_profiles_dir().join(&file);
|
let path = dirs::app_profiles_dir().join(&file);
|
||||||
|
|
||||||
fs::File::create(path)
|
fs::File::create(path)
|
||||||
.unwrap()
|
.context(format!("failed to create file \"{}\"", file))?
|
||||||
.write(file_data.as_bytes())
|
.write(file_data.as_bytes())
|
||||||
.unwrap();
|
.context(format!("failed to write to file \"{}\"", file))?;
|
||||||
}
|
}
|
||||||
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
}
|
||||||
|
|
||||||
self.save_file()
|
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,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,385 @@
|
|||||||
|
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 RunasCommond;
|
||||||
|
use std::{env::current_exe, process::Command as StdCommond};
|
||||||
|
|
||||||
|
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 arg = format!("binpath={}", binary_path.as_os_str().to_string_lossy());
|
||||||
|
|
||||||
|
let token = Token::with_current_process()?;
|
||||||
|
let level = token.privilege_level()?;
|
||||||
|
|
||||||
|
let args = [
|
||||||
|
"create",
|
||||||
|
SERVICE_NAME,
|
||||||
|
arg.as_str(),
|
||||||
|
"type=own",
|
||||||
|
"start=AUTO",
|
||||||
|
"displayname=Clash Verge Service",
|
||||||
|
];
|
||||||
|
|
||||||
|
let status = match level {
|
||||||
|
PrivilegeLevel::NotPrivileged => RunasCommond::new("sc").args(&args).status()?,
|
||||||
|
_ => StdCommond::new("sc").args(&args).status()?,
|
||||||
|
};
|
||||||
|
|
||||||
|
if status.success() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
if status.code() == Some(1073i32) {
|
||||||
|
bail!("clash verge service is installed");
|
||||||
|
}
|
||||||
|
|
||||||
|
bail!(
|
||||||
|
"failed to install service with status {}",
|
||||||
|
status.code().unwrap()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Uninstall the Clash Verge Service
|
||||||
|
/// 该函数应该在协程或者线程中执行,避免UAC弹窗阻塞主线程
|
||||||
|
pub async fn uninstall_service() -> Result<()> {
|
||||||
|
let token = Token::with_current_process()?;
|
||||||
|
let level = token.privilege_level()?;
|
||||||
|
|
||||||
|
let args = ["delete", SERVICE_NAME];
|
||||||
|
|
||||||
|
let status = match level {
|
||||||
|
PrivilegeLevel::NotPrivileged => RunasCommond::new("sc").args(&args).status()?,
|
||||||
|
_ => StdCommond::new("sc").args(&args).status()?,
|
||||||
|
};
|
||||||
|
|
||||||
|
match status.success() {
|
||||||
|
true => Ok(()),
|
||||||
|
false => bail!(
|
||||||
|
"failed to uninstall service with status {}",
|
||||||
|
status.code().unwrap()
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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 => RunasCommond::new("sc").args(&args).status()?,
|
||||||
|
_ => StdCommond::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(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
@@ -1,17 +1,10 @@
|
|||||||
use crate::log_if_err;
|
use crate::utils::{config, dirs};
|
||||||
use crate::{
|
use anyhow::Result;
|
||||||
core::Clash,
|
|
||||||
utils::{config, dirs, sysopt::SysProxyConfig},
|
|
||||||
};
|
|
||||||
use anyhow::{bail, Result};
|
|
||||||
use auto_launch::{AutoLaunch, AutoLaunchBuilder};
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::sync::Arc;
|
|
||||||
use tauri::{async_runtime::Mutex, utils::platform::current_exe};
|
|
||||||
|
|
||||||
/// ### `verge.yaml` schema
|
/// ### `verge.yaml` schema
|
||||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||||
pub struct VergeConfig {
|
pub struct Verge {
|
||||||
// i18n
|
// i18n
|
||||||
pub language: Option<String>,
|
pub language: Option<String>,
|
||||||
|
|
||||||
@@ -28,6 +21,10 @@ pub struct VergeConfig {
|
|||||||
/// clash tun mode
|
/// clash tun mode
|
||||||
pub enable_tun_mode: Option<bool>,
|
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
|
/// can the app auto startup
|
||||||
pub enable_auto_launch: Option<bool>,
|
pub enable_auto_launch: Option<bool>,
|
||||||
|
|
||||||
@@ -66,9 +63,9 @@ pub struct VergeTheme {
|
|||||||
pub css_injection: Option<String>,
|
pub css_injection: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl VergeConfig {
|
impl Verge {
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
config::read_yaml::<VergeConfig>(dirs::verge_path())
|
config::read_yaml::<Verge>(dirs::verge_path())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Save Verge App Config
|
/// Save Verge App Config
|
||||||
@@ -79,276 +76,57 @@ impl VergeConfig {
|
|||||||
Some("# The Config for Clash Verge App\n\n"),
|
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
|
/// patch verge config
|
||||||
/// There should be only one update at a time here
|
/// only save to file
|
||||||
/// so call the save_file at the end is savely
|
pub fn patch_config(&mut self, patch: Verge) -> Result<()> {
|
||||||
pub fn patch_config(&mut self, patch: VergeConfig) -> Result<()> {
|
|
||||||
// only change it
|
// only change it
|
||||||
if patch.language.is_some() {
|
if patch.language.is_some() {
|
||||||
self.config.language = patch.language;
|
self.language = patch.language;
|
||||||
}
|
}
|
||||||
if patch.theme_mode.is_some() {
|
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() {
|
if patch.theme_blur.is_some() {
|
||||||
self.config.theme_blur = patch.theme_blur;
|
self.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;
|
|
||||||
}
|
}
|
||||||
if patch.theme_setting.is_some() {
|
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() {
|
if patch.enable_auto_launch.is_some() {
|
||||||
let enable = patch.enable_auto_launch.unwrap();
|
self.enable_auto_launch = patch.enable_auto_launch;
|
||||||
self.update_launch(enable)?;
|
|
||||||
self.config.enable_auto_launch = Some(enable);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// should update system proxy
|
// proxy
|
||||||
if patch.enable_system_proxy.is_some() {
|
if patch.enable_system_proxy.is_some() {
|
||||||
let enable = patch.enable_system_proxy.unwrap();
|
self.enable_system_proxy = patch.enable_system_proxy;
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// should update system proxy too
|
|
||||||
if patch.system_proxy_bypass.is_some() {
|
if patch.system_proxy_bypass.is_some() {
|
||||||
let bypass = patch.system_proxy_bypass.unwrap();
|
self.system_proxy_bypass = patch.system_proxy_bypass;
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// proxy guard
|
|
||||||
// only change it
|
|
||||||
if patch.enable_proxy_guard.is_some() {
|
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() {
|
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
|
// tun mode
|
||||||
if patch.enable_system_proxy.is_some() || patch.enable_proxy_guard.is_some() {
|
|
||||||
Verge::guard_proxy(self.guard_state.clone());
|
|
||||||
}
|
|
||||||
|
|
||||||
// handle the tun mode
|
|
||||||
if patch.enable_tun_mode.is_some() {
|
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()
|
self.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;
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+49
-35
@@ -5,11 +5,10 @@
|
|||||||
|
|
||||||
mod cmds;
|
mod cmds;
|
||||||
mod core;
|
mod core;
|
||||||
mod states;
|
|
||||||
mod utils;
|
mod utils;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
core::VergeConfig,
|
core::Verge,
|
||||||
utils::{resolve, server},
|
utils::{resolve, server},
|
||||||
};
|
};
|
||||||
use tauri::{
|
use tauri::{
|
||||||
@@ -22,18 +21,24 @@ fn main() -> std::io::Result<()> {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
unsafe {
|
||||||
|
use crate::utils::dirs;
|
||||||
|
|
||||||
|
dirs::init_portable_flag();
|
||||||
|
}
|
||||||
|
|
||||||
let tray_menu = SystemTrayMenu::new()
|
let tray_menu = SystemTrayMenu::new()
|
||||||
.add_item(CustomMenuItem::new("open_window", "Show"))
|
.add_item(CustomMenuItem::new("open_window", "Show"))
|
||||||
.add_item(CustomMenuItem::new("system_proxy", "System Proxy"))
|
.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_item(CustomMenuItem::new("restart_clash", "Restart Clash"))
|
||||||
.add_native_item(SystemTrayMenuItem::Separator)
|
.add_native_item(SystemTrayMenuItem::Separator)
|
||||||
.add_item(CustomMenuItem::new("quit", "Quit").accelerator("CmdOrControl+Q"));
|
.add_item(CustomMenuItem::new("quit", "Quit").accelerator("CmdOrControl+Q"));
|
||||||
|
|
||||||
#[allow(unused_mut)]
|
#[allow(unused_mut)]
|
||||||
let mut builder = tauri::Builder::default()
|
let mut builder = tauri::Builder::default()
|
||||||
.manage(states::VergeState::default())
|
.manage(core::Core::new())
|
||||||
.manage(states::ClashState::default())
|
|
||||||
.manage(states::ProfilesState::default())
|
|
||||||
.setup(|app| Ok(resolve::resolve_setup(app)))
|
.setup(|app| Ok(resolve::resolve_setup(app)))
|
||||||
.system_tray(SystemTray::new().with_menu(tray_menu))
|
.system_tray(SystemTray::new().with_menu(tray_menu))
|
||||||
.on_system_tray_event(move |app_handle, event| match event {
|
.on_system_tray_event(move |app_handle, event| match event {
|
||||||
@@ -45,42 +50,42 @@ fn main() -> std::io::Result<()> {
|
|||||||
window.set_focus().unwrap();
|
window.set_focus().unwrap();
|
||||||
}
|
}
|
||||||
"system_proxy" => {
|
"system_proxy" => {
|
||||||
let verge_state = app_handle.state::<states::VergeState>();
|
let core = app_handle.state::<core::Core>();
|
||||||
let mut verge = verge_state.0.lock().unwrap();
|
|
||||||
|
|
||||||
let old_value = verge.config.enable_system_proxy.clone().unwrap_or(false);
|
let new_value = {
|
||||||
let new_value = !old_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),
|
enable_system_proxy: Some(new_value),
|
||||||
..VergeConfig::default()
|
..Verge::default()
|
||||||
}) {
|
};
|
||||||
Ok(_) => {
|
|
||||||
app_handle
|
|
||||||
.tray_handle()
|
|
||||||
.get_item(id.as_str())
|
|
||||||
.set_selected(new_value)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
// update verge config
|
crate::log_if_err!(core.patch_verge(patch, app_handle));
|
||||||
let window = app_handle.get_window("main").unwrap();
|
}
|
||||||
window.emit("verge://refresh-verge-config", "yes").unwrap();
|
"tun_mode" => {
|
||||||
}
|
let core = app_handle.state::<core::Core>();
|
||||||
Err(err) => log::error!("{err}"),
|
|
||||||
}
|
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" => {
|
"restart_clash" => {
|
||||||
let clash_state = app_handle.state::<states::ClashState>();
|
let core = app_handle.state::<core::Core>();
|
||||||
let profiles_state = app_handle.state::<states::ProfilesState>();
|
crate::log_if_err!(core.restart_clash());
|
||||||
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));
|
|
||||||
}
|
}
|
||||||
"quit" => {
|
"quit" => {
|
||||||
resolve::resolve_reset(app_handle);
|
resolve::resolve_reset(app_handle);
|
||||||
api::process::kill_children();
|
app_handle.exit(0);
|
||||||
std::process::exit(0);
|
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
},
|
},
|
||||||
@@ -98,7 +103,7 @@ fn main() -> std::io::Result<()> {
|
|||||||
cmds::restart_sidecar,
|
cmds::restart_sidecar,
|
||||||
cmds::get_sys_proxy,
|
cmds::get_sys_proxy,
|
||||||
cmds::get_cur_proxy,
|
cmds::get_cur_proxy,
|
||||||
cmds::kill_sidecars,
|
cmds::kill_sidecar,
|
||||||
cmds::open_app_dir,
|
cmds::open_app_dir,
|
||||||
cmds::open_logs_dir,
|
cmds::open_logs_dir,
|
||||||
// clash
|
// clash
|
||||||
@@ -116,12 +121,17 @@ fn main() -> std::io::Result<()> {
|
|||||||
cmds::delete_profile,
|
cmds::delete_profile,
|
||||||
cmds::select_profile,
|
cmds::select_profile,
|
||||||
cmds::get_profiles,
|
cmds::get_profiles,
|
||||||
cmds::sync_profiles,
|
|
||||||
cmds::enhance_profiles,
|
cmds::enhance_profiles,
|
||||||
cmds::change_profile_chain,
|
cmds::change_profile_chain,
|
||||||
cmds::change_profile_valid,
|
cmds::change_profile_valid,
|
||||||
cmds::read_profile_file,
|
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")]
|
#[cfg(target_os = "macos")]
|
||||||
@@ -157,6 +167,10 @@ fn main() -> std::io::Result<()> {
|
|||||||
resolve::resolve_reset(app_handle);
|
resolve::resolve_reset(app_handle);
|
||||||
api::process::kill_children();
|
api::process::kill_children();
|
||||||
}
|
}
|
||||||
|
tauri::RunEvent::Exit => {
|
||||||
|
resolve::resolve_reset(app_handle);
|
||||||
|
api::process::kill_children();
|
||||||
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
use crate::core::{Clash, Profiles, Verge};
|
// use crate::core::{Clash, Profiles, Verge};
|
||||||
use std::sync::{Arc, Mutex};
|
// use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
#[derive(Default)]
|
// #[derive(Default)]
|
||||||
pub struct ProfilesState(pub Arc<Mutex<Profiles>>);
|
// pub struct ProfilesState(pub Arc<Mutex<Profiles>>);
|
||||||
|
|
||||||
#[derive(Default)]
|
// #[derive(Default)]
|
||||||
pub struct ClashState(pub Arc<Mutex<Clash>>);
|
// pub struct ClashState(pub Arc<Mutex<Clash>>);
|
||||||
|
|
||||||
#[derive(Default)]
|
// #[derive(Default)]
|
||||||
pub struct VergeState(pub Arc<Mutex<Verge>>);
|
// pub struct VergeState(pub Arc<Mutex<Verge>>);
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use std::env::temp_dir;
|
use std::env::temp_dir;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::PathBuf;
|
||||||
use tauri::{
|
use tauri::{
|
||||||
api::path::{home_dir, resource_dir},
|
api::path::{home_dir, resource_dir},
|
||||||
Env, PackageInfo,
|
Env, PackageInfo,
|
||||||
@@ -15,19 +15,62 @@ static VERGE_CONFIG: &str = "verge.yaml";
|
|||||||
static PROFILE_YAML: &str = "profiles.yaml";
|
static PROFILE_YAML: &str = "profiles.yaml";
|
||||||
static PROFILE_TEMP: &str = "clash-verge-runtime.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
|
/// get the verge app home dir
|
||||||
pub fn app_home_dir() -> PathBuf {
|
pub fn app_home_dir() -> PathBuf {
|
||||||
home_dir()
|
#[cfg(target_os = "windows")]
|
||||||
.unwrap()
|
unsafe {
|
||||||
.join(Path::new(".config"))
|
use tauri::utils::platform::current_exe;
|
||||||
.join(Path::new(APP_DIR))
|
|
||||||
|
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
|
/// get the resources dir
|
||||||
pub fn app_resources_dir(package_info: &PackageInfo) -> PathBuf {
|
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()
|
.unwrap()
|
||||||
.join("resources")
|
.join("resources");
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
unsafe {
|
||||||
|
RESOURCE_DIR = Some(res_dir.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
res_dir
|
||||||
}
|
}
|
||||||
|
|
||||||
/// profiles dir
|
/// profiles dir
|
||||||
@@ -59,3 +102,29 @@ pub fn profiles_temp_path() -> PathBuf {
|
|||||||
#[cfg(feature = "debug-yml")]
|
#[cfg(feature = "debug-yml")]
|
||||||
return app_home_dir().join(PROFILE_TEMP);
|
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
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
|
use anyhow::{bail, Result};
|
||||||
use nanoid::nanoid;
|
use nanoid::nanoid;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::process::Command;
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
use std::time::{SystemTime, UNIX_EPOCH};
|
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_export]
|
||||||
macro_rules! log_if_err {
|
macro_rules! log_if_err {
|
||||||
($result: expr) => {
|
($result: expr) => {
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
use super::{init, server};
|
use crate::{core::Core, utils::init, utils::server};
|
||||||
use crate::{core::Profiles, log_if_err, states};
|
|
||||||
use tauri::{App, AppHandle, Manager};
|
use tauri::{App, AppHandle, Manager};
|
||||||
|
|
||||||
/// handle something when start app
|
/// handle something when start app
|
||||||
@@ -11,55 +10,29 @@ pub fn resolve_setup(app: &App) {
|
|||||||
init::init_app(app.package_info());
|
init::init_app(app.package_info());
|
||||||
|
|
||||||
// init states
|
// init states
|
||||||
let clash_state = app.state::<states::ClashState>();
|
let core = app.state::<Core>();
|
||||||
let verge_state = app.state::<states::VergeState>();
|
|
||||||
let profiles_state = app.state::<states::ProfilesState>();
|
|
||||||
|
|
||||||
let mut clash = clash_state.0.lock().unwrap();
|
core.set_win(app.get_window("main"));
|
||||||
let mut verge = verge_state.0.lock().unwrap();
|
core.init(app.app_handle());
|
||||||
let mut profiles = profiles_state.0.lock().unwrap();
|
|
||||||
|
|
||||||
log_if_err!(clash.run_sidecar());
|
resolve_window(app);
|
||||||
|
|
||||||
*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());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// reset system proxy
|
/// reset system proxy
|
||||||
pub fn resolve_reset(app_handle: &AppHandle) {
|
pub fn resolve_reset(app_handle: &AppHandle) {
|
||||||
let verge_state = app_handle.state::<states::VergeState>();
|
let core = app_handle.state::<Core>();
|
||||||
let mut verge = verge_state.0.lock().unwrap();
|
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
|
/// customize the window theme
|
||||||
fn resolve_window(app: &App, hide: Option<bool>) {
|
fn resolve_window(app: &App) {
|
||||||
let window = app.get_window("main").unwrap();
|
let window = app.get_window("main").unwrap();
|
||||||
|
|
||||||
// silent start
|
|
||||||
hide.map(|hide| {
|
|
||||||
if hide {
|
|
||||||
window.hide().unwrap();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
{
|
{
|
||||||
use window_shadows::set_shadow;
|
use window_shadows::set_shadow;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"package": {
|
"package": {
|
||||||
"productName": "Clash Verge",
|
"productName": "Clash Verge",
|
||||||
"version": "0.0.28"
|
"version": "1.0.0"
|
||||||
},
|
},
|
||||||
"build": {
|
"build": {
|
||||||
"distDir": "../dist",
|
"distDir": "../dist",
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { styled, ListItem, IconButton, ListItemText } from "@mui/material";
|
|||||||
import { CloseRounded } from "@mui/icons-material";
|
import { CloseRounded } from "@mui/icons-material";
|
||||||
import { ApiType } from "../../services/types";
|
import { ApiType } from "../../services/types";
|
||||||
import { deleteConnection } from "../../services/api";
|
import { deleteConnection } from "../../services/api";
|
||||||
|
import parseTraffic from "../../utils/parse-traffic";
|
||||||
|
|
||||||
const Tag = styled("span")(({ theme }) => ({
|
const Tag = styled("span")(({ theme }) => ({
|
||||||
display: "inline-block",
|
display: "inline-block",
|
||||||
@@ -23,32 +24,39 @@ interface Props {
|
|||||||
const ConnectionItem = (props: Props) => {
|
const ConnectionItem = (props: Props) => {
|
||||||
const { value } = 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 (
|
return (
|
||||||
<ListItem
|
<ListItem
|
||||||
dense
|
dense
|
||||||
secondaryAction={
|
secondaryAction={
|
||||||
<IconButton edge="end" onClick={onDelete}>
|
<IconButton edge="end" color="inherit" onClick={onDelete}>
|
||||||
<CloseRounded />
|
<CloseRounded />
|
||||||
</IconButton>
|
</IconButton>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<ListItemText
|
<ListItemText
|
||||||
primary={value.metadata.host || value.metadata.destinationIP}
|
primary={metadata.host || metadata.destinationIP}
|
||||||
secondary={
|
secondary={
|
||||||
<>
|
<>
|
||||||
<Tag sx={{ textTransform: "uppercase", color: "success" }}>
|
<Tag sx={{ textTransform: "uppercase", color: "success" }}>
|
||||||
{value.metadata.network}
|
{metadata.network}
|
||||||
</Tag>
|
</Tag>
|
||||||
|
|
||||||
<Tag>{value.metadata.type}</Tag>
|
<Tag>{metadata.type}</Tag>
|
||||||
|
|
||||||
{value.chains.length > 0 && (
|
{chains.length > 0 && <Tag>{chains[value.chains.length - 1]}</Tag>}
|
||||||
<Tag>{value.chains[value.chains.length - 1]}</Tag>
|
|
||||||
|
<Tag>{dayjs(start).fromNow()}</Tag>
|
||||||
|
|
||||||
|
{showTraffic && (
|
||||||
|
<Tag>
|
||||||
|
{parseTraffic(curUpload!)} / {parseTraffic(curDownload!)}
|
||||||
|
</Tag>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<Tag>{dayjs(value.start).fromNow()}</Tag>
|
|
||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import useSWR from "swr";
|
import useSWR from "swr";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
import { useRecoilValue } from "recoil";
|
import { useRecoilValue } from "recoil";
|
||||||
import { Box, Typography } from "@mui/material";
|
import { Box, Typography } from "@mui/material";
|
||||||
import { ArrowDownward, ArrowUpward } from "@mui/icons-material";
|
import { ArrowDownward, ArrowUpward } from "@mui/icons-material";
|
||||||
@@ -8,17 +8,18 @@ import { ApiType } from "../../services/types";
|
|||||||
import { getInfomation } from "../../services/api";
|
import { getInfomation } from "../../services/api";
|
||||||
import { getVergeConfig } from "../../services/cmds";
|
import { getVergeConfig } from "../../services/cmds";
|
||||||
import { atomClashPort } from "../../services/states";
|
import { atomClashPort } from "../../services/states";
|
||||||
|
import TrafficGraph from "./traffic-graph";
|
||||||
import useLogSetup from "./use-log-setup";
|
import useLogSetup from "./use-log-setup";
|
||||||
import useTrafficGraph from "./use-traffic-graph";
|
|
||||||
import parseTraffic from "../../utils/parse-traffic";
|
import parseTraffic from "../../utils/parse-traffic";
|
||||||
|
|
||||||
// setup the traffic
|
// setup the traffic
|
||||||
const LayoutTraffic = () => {
|
const LayoutTraffic = () => {
|
||||||
const portValue = useRecoilValue(atomClashPort);
|
const portValue = useRecoilValue(atomClashPort);
|
||||||
const [traffic, setTraffic] = useState({ up: 0, down: 0 });
|
const [traffic, setTraffic] = useState({ up: 0, down: 0 });
|
||||||
const { canvasRef, appendData, toggleStyle } = useTrafficGraph();
|
|
||||||
const [refresh, setRefresh] = useState({});
|
const [refresh, setRefresh] = useState({});
|
||||||
|
|
||||||
|
const trafficRef = useRef<any>();
|
||||||
|
|
||||||
// whether hide traffic graph
|
// whether hide traffic graph
|
||||||
const { data } = useSWR("getVergeConfig", getVergeConfig);
|
const { data } = useSWR("getVergeConfig", getVergeConfig);
|
||||||
const trafficGraph = data?.traffic_graph ?? true;
|
const trafficGraph = data?.traffic_graph ?? true;
|
||||||
@@ -46,7 +47,7 @@ const LayoutTraffic = () => {
|
|||||||
|
|
||||||
ws.addEventListener("message", (event) => {
|
ws.addEventListener("message", (event) => {
|
||||||
const data = JSON.parse(event.data) as ApiType.TrafficItem;
|
const data = JSON.parse(event.data) as ApiType.TrafficItem;
|
||||||
appendData(data);
|
trafficRef.current?.appendData(data);
|
||||||
setTraffic(data);
|
setTraffic(data);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -72,12 +73,15 @@ const LayoutTraffic = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box width="110px" position="relative" onClick={toggleStyle}>
|
<Box
|
||||||
|
width="110px"
|
||||||
|
position="relative"
|
||||||
|
onClick={trafficRef.current?.toggleStyle}
|
||||||
|
>
|
||||||
{trafficGraph && (
|
{trafficGraph && (
|
||||||
<canvas
|
<div style={{ width: "100%", height: 60, marginBottom: 6 }}>
|
||||||
ref={canvasRef}
|
<TrafficGraph instance={trafficRef} />
|
||||||
style={{ width: "100%", height: 60, marginBottom: 6 }}
|
</div>
|
||||||
/>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<Box mb={1.5} display="flex" alignItems="center" whiteSpace="nowrap">
|
<Box mb={1.5} display="flex" alignItems="center" whiteSpace="nowrap">
|
||||||
|
|||||||
@@ -0,0 +1,201 @@
|
|||||||
|
import { useEffect, useRef } from "react";
|
||||||
|
import { useTheme } from "@mui/material";
|
||||||
|
|
||||||
|
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);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
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);
|
||||||
|
};
|
||||||
|
}, [palette]);
|
||||||
|
|
||||||
|
return <canvas ref={canvasRef} style={{ width: "100%", height: "100%" }} />;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default TrafficGraph;
|
||||||
@@ -13,7 +13,7 @@ import {
|
|||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import { relaunch } from "@tauri-apps/api/process";
|
import { relaunch } from "@tauri-apps/api/process";
|
||||||
import { checkUpdate, installUpdate } from "@tauri-apps/api/updater";
|
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 { atomUpdateState } from "../../services/states";
|
||||||
import Notice from "../base/base-notice";
|
import Notice from "../base/base-notice";
|
||||||
|
|
||||||
@@ -41,7 +41,7 @@ const UpdateDialog = (props: Props) => {
|
|||||||
setUpdateState(true);
|
setUpdateState(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await killSidecars();
|
await killSidecar();
|
||||||
await installUpdate();
|
await installUpdate();
|
||||||
await relaunch();
|
await relaunch();
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
|
|||||||
@@ -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,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -86,6 +86,7 @@ const ProfileEdit = (props: Props) => {
|
|||||||
label="Name"
|
label="Name"
|
||||||
value={form.name}
|
value={form.name}
|
||||||
onChange={(e) => setForm({ name: e.target.value })}
|
onChange={(e) => setForm({ name: e.target.value })}
|
||||||
|
onKeyDown={(e) => e.key === "Enter" && onUpdate()}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<TextField
|
<TextField
|
||||||
@@ -93,6 +94,7 @@ const ProfileEdit = (props: Props) => {
|
|||||||
label="Descriptions"
|
label="Descriptions"
|
||||||
value={form.desc}
|
value={form.desc}
|
||||||
onChange={(e) => setForm({ desc: e.target.value })}
|
onChange={(e) => setForm({ desc: e.target.value })}
|
||||||
|
onKeyDown={(e) => e.key === "Enter" && onUpdate()}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{type === "remote" && (
|
{type === "remote" && (
|
||||||
@@ -101,16 +103,31 @@ const ProfileEdit = (props: Props) => {
|
|||||||
label="Subscription Url"
|
label="Subscription Url"
|
||||||
value={form.url}
|
value={form.url}
|
||||||
onChange={(e) => setForm({ url: e.target.value })}
|
onChange={(e) => setForm({ url: e.target.value })}
|
||||||
|
onKeyDown={(e) => e.key === "Enter" && onUpdate()}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{showOpt && (
|
{showOpt && (
|
||||||
<TextField
|
<>
|
||||||
{...textFieldProps}
|
<TextField
|
||||||
label="User Agent"
|
{...textFieldProps}
|
||||||
value={option.user_agent}
|
label="User Agent"
|
||||||
onChange={(e) => setOption({ user_agent: e.target.value })}
|
value={option.user_agent}
|
||||||
/>
|
onChange={(e) => setOption({ user_agent: e.target.value })}
|
||||||
|
onKeyDown={(e) => e.key === "Enter" && onUpdate()}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<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>
|
</DialogContent>
|
||||||
|
|
||||||
|
|||||||
@@ -2,20 +2,13 @@ import useSWR, { useSWRConfig } from "swr";
|
|||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
import { useLockFn } from "ahooks";
|
import { useLockFn } from "ahooks";
|
||||||
import { Virtuoso } from "react-virtuoso";
|
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 { ApiType } from "../../services/types";
|
||||||
import { updateProxy } from "../../services/api";
|
import { updateProxy } from "../../services/api";
|
||||||
import { getProfiles, patchProfile } from "../../services/cmds";
|
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 useFilterProxy from "./use-filter-proxy";
|
||||||
|
import delayManager from "../../services/delay";
|
||||||
|
import ProxyHead from "./proxy-head";
|
||||||
import ProxyItem from "./proxy-item";
|
import ProxyItem from "./proxy-item";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
@@ -30,12 +23,14 @@ const ProxyGlobal = (props: Props) => {
|
|||||||
|
|
||||||
const { mutate } = useSWRConfig();
|
const { mutate } = useSWRConfig();
|
||||||
const [now, setNow] = useState(curProxy || "DIRECT");
|
const [now, setNow] = useState(curProxy || "DIRECT");
|
||||||
|
|
||||||
const [showType, setShowType] = useState(true);
|
const [showType, setShowType] = useState(true);
|
||||||
const [showFilter, setShowFilter] = useState(false);
|
const [sortType, setSortType] = useState<ProxySortType>(0);
|
||||||
const [filterText, setFilterText] = useState("");
|
const [filterText, setFilterText] = useState("");
|
||||||
|
|
||||||
const virtuosoRef = useRef<any>();
|
const virtuosoRef = useRef<any>();
|
||||||
const filterProxies = useFilterProxy(proxies, groupName, filterText);
|
const filterProxies = useFilterProxy(proxies, groupName, filterText);
|
||||||
|
const sortedProxies = useSortProxy(filterProxies, groupName, sortType);
|
||||||
|
|
||||||
const { data: profiles } = useSWR("getProfiles", getProfiles);
|
const { data: profiles } = useSWR("getProfiles", getProfiles);
|
||||||
|
|
||||||
@@ -61,7 +56,7 @@ const ProxyGlobal = (props: Props) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const onLocation = (smooth = true) => {
|
const onLocation = (smooth = true) => {
|
||||||
const index = filterProxies.findIndex((p) => p.name === now);
|
const index = sortedProxies.findIndex((p) => p.name === now);
|
||||||
|
|
||||||
if (index >= 0) {
|
if (index >= 0) {
|
||||||
virtuosoRef.current?.scrollToIndex?.({
|
virtuosoRef.current?.scrollToIndex?.({
|
||||||
@@ -73,22 +68,15 @@ const ProxyGlobal = (props: Props) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const onCheckAll = useLockFn(async () => {
|
const onCheckAll = useLockFn(async () => {
|
||||||
const names = filterProxies.map((p) => p.name);
|
const names = sortedProxies.map((p) => p.name);
|
||||||
|
|
||||||
await delayManager.checkListDelay(
|
await delayManager.checkListDelay({ names, groupName, skipNum: 8 }, () =>
|
||||||
{ names, groupName, skipNum: 8, maxTimeout: 600 },
|
mutate("getProxies")
|
||||||
() => mutate("getProxies")
|
|
||||||
);
|
);
|
||||||
|
|
||||||
mutate("getProxies");
|
|
||||||
});
|
});
|
||||||
|
|
||||||
useEffect(() => onLocation(false), [groupName]);
|
useEffect(() => onLocation(false), [groupName]);
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!showFilter) setFilterText("");
|
|
||||||
}, [showFilter]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (groupName === "DIRECT") setNow("DIRECT");
|
if (groupName === "DIRECT") setNow("DIRECT");
|
||||||
else if (groupName === "GLOBAL") {
|
else if (groupName === "GLOBAL") {
|
||||||
@@ -112,74 +100,28 @@ const ProxyGlobal = (props: Props) => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Box
|
<ProxyHead
|
||||||
sx={{
|
sx={{ px: 3, my: 0.5, button: { mr: 0.5 } }}
|
||||||
px: 3,
|
showType={showType}
|
||||||
my: 0.5,
|
sortType={sortType}
|
||||||
display: "flex",
|
groupName={groupName}
|
||||||
alignItems: "center",
|
filterText={filterText}
|
||||||
button: { mr: 0.5 },
|
onLocation={onLocation}
|
||||||
}}
|
onCheckDelay={onCheckAll}
|
||||||
>
|
onShowType={setShowType}
|
||||||
<IconButton
|
onSortType={setSortType}
|
||||||
size="small"
|
onFilterText={setFilterText}
|
||||||
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>
|
|
||||||
|
|
||||||
<Virtuoso
|
<Virtuoso
|
||||||
ref={virtuosoRef}
|
ref={virtuosoRef}
|
||||||
style={{ height: "calc(100% - 40px)" }}
|
style={{ height: "calc(100% - 40px)" }}
|
||||||
totalCount={filterProxies.length}
|
totalCount={sortedProxies.length}
|
||||||
itemContent={(index) => (
|
itemContent={(index) => (
|
||||||
<ProxyItem
|
<ProxyItem
|
||||||
groupName={groupName}
|
groupName={groupName}
|
||||||
proxy={filterProxies[index]}
|
proxy={sortedProxies[index]}
|
||||||
selected={filterProxies[index].name === now}
|
selected={sortedProxies[index].name === now}
|
||||||
showType={showType}
|
showType={showType}
|
||||||
onClick={onChangeProxy}
|
onClick={onChangeProxy}
|
||||||
sx={{ py: 0, px: 2 }}
|
sx={{ py: 0, px: 2 }}
|
||||||
|
|||||||
@@ -6,28 +6,22 @@ import {
|
|||||||
Box,
|
Box,
|
||||||
Collapse,
|
Collapse,
|
||||||
Divider,
|
Divider,
|
||||||
IconButton,
|
|
||||||
List,
|
List,
|
||||||
ListItem,
|
ListItem,
|
||||||
ListItemText,
|
ListItemText,
|
||||||
TextField,
|
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import {
|
import {
|
||||||
SendRounded,
|
SendRounded,
|
||||||
ExpandLessRounded,
|
ExpandLessRounded,
|
||||||
ExpandMoreRounded,
|
ExpandMoreRounded,
|
||||||
MyLocationRounded,
|
|
||||||
NetworkCheckRounded,
|
|
||||||
FilterAltRounded,
|
|
||||||
FilterAltOffRounded,
|
|
||||||
VisibilityRounded,
|
|
||||||
VisibilityOffRounded,
|
|
||||||
} from "@mui/icons-material";
|
} from "@mui/icons-material";
|
||||||
import { ApiType } from "../../services/types";
|
import { ApiType } from "../../services/types";
|
||||||
import { updateProxy } from "../../services/api";
|
import { updateProxy } from "../../services/api";
|
||||||
import { getProfiles, patchProfile } from "../../services/cmds";
|
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 useFilterProxy from "./use-filter-proxy";
|
||||||
|
import delayManager from "../../services/delay";
|
||||||
|
import ProxyHead from "./proxy-head";
|
||||||
import ProxyItem from "./proxy-item";
|
import ProxyItem from "./proxy-item";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
@@ -38,13 +32,14 @@ const ProxyGroup = ({ group }: Props) => {
|
|||||||
const { mutate } = useSWRConfig();
|
const { mutate } = useSWRConfig();
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const [now, setNow] = useState(group.now);
|
const [now, setNow] = useState(group.now);
|
||||||
|
|
||||||
const [showType, setShowType] = useState(false);
|
const [showType, setShowType] = useState(false);
|
||||||
const [showFilter, setShowFilter] = useState(false);
|
const [sortType, setSortType] = useState<ProxySortType>(0);
|
||||||
const [filterText, setFilterText] = useState("");
|
const [filterText, setFilterText] = useState("");
|
||||||
|
|
||||||
const proxies = group.all ?? [];
|
|
||||||
const virtuosoRef = useRef<any>();
|
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);
|
const { data: profiles } = useSWR("getProfiles", getProfiles);
|
||||||
|
|
||||||
@@ -82,7 +77,7 @@ const ProxyGroup = ({ group }: Props) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const onLocation = (smooth = true) => {
|
const onLocation = (smooth = true) => {
|
||||||
const index = filterProxies.findIndex((p) => p.name === now);
|
const index = sortedProxies.findIndex((p) => p.name === now);
|
||||||
|
|
||||||
if (index >= 0) {
|
if (index >= 0) {
|
||||||
virtuosoRef.current?.scrollToIndex?.({
|
virtuosoRef.current?.scrollToIndex?.({
|
||||||
@@ -94,21 +89,14 @@ const ProxyGroup = ({ group }: Props) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const onCheckAll = useLockFn(async () => {
|
const onCheckAll = useLockFn(async () => {
|
||||||
const names = filterProxies.map((p) => p.name);
|
const names = sortedProxies.map((p) => p.name);
|
||||||
const groupName = group.name;
|
const groupName = group.name;
|
||||||
|
|
||||||
await delayManager.checkListDelay(
|
await delayManager.checkListDelay({ names, groupName, skipNum: 8 }, () =>
|
||||||
{ names, groupName, skipNum: 8, maxTimeout: 600 },
|
mutate("getProxies")
|
||||||
() => mutate("getProxies")
|
|
||||||
);
|
);
|
||||||
|
|
||||||
mutate("getProxies");
|
|
||||||
});
|
});
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!showFilter) setFilterText("");
|
|
||||||
}, [showFilter]);
|
|
||||||
|
|
||||||
// auto scroll to current index
|
// auto scroll to current index
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (open) {
|
if (open) {
|
||||||
@@ -136,66 +124,20 @@ const ProxyGroup = ({ group }: Props) => {
|
|||||||
</ListItem>
|
</ListItem>
|
||||||
|
|
||||||
<Collapse in={open} timeout="auto" unmountOnExit>
|
<Collapse in={open} timeout="auto" unmountOnExit>
|
||||||
<Box
|
<ProxyHead
|
||||||
sx={{
|
sx={{ pl: 4, pr: 3, my: 0.5, button: { mr: 0.5 } }}
|
||||||
pl: 4,
|
showType={showType}
|
||||||
pr: 3,
|
sortType={sortType}
|
||||||
my: 0.5,
|
groupName={group.name}
|
||||||
display: "flex",
|
filterText={filterText}
|
||||||
alignItems: "center",
|
onLocation={onLocation}
|
||||||
button: { mr: 0.5 },
|
onCheckDelay={onCheckAll}
|
||||||
}}
|
onShowType={setShowType}
|
||||||
>
|
onSortType={setSortType}
|
||||||
<IconButton
|
onFilterText={setFilterText}
|
||||||
size="small"
|
/>
|
||||||
title="location"
|
|
||||||
color="inherit"
|
|
||||||
onClick={() => onLocation(true)}
|
|
||||||
>
|
|
||||||
<MyLocationRounded />
|
|
||||||
</IconButton>
|
|
||||||
|
|
||||||
<IconButton
|
{!sortedProxies.length && (
|
||||||
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 && (
|
|
||||||
<Box
|
<Box
|
||||||
sx={{
|
sx={{
|
||||||
py: 3,
|
py: 3,
|
||||||
@@ -208,16 +150,16 @@ const ProxyGroup = ({ group }: Props) => {
|
|||||||
</Box>
|
</Box>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{filterProxies.length >= 10 ? (
|
{sortedProxies.length >= 10 ? (
|
||||||
<Virtuoso
|
<Virtuoso
|
||||||
ref={virtuosoRef}
|
ref={virtuosoRef}
|
||||||
style={{ height: "320px", marginBottom: "4px" }}
|
style={{ height: "320px", marginBottom: "4px" }}
|
||||||
totalCount={filterProxies.length}
|
totalCount={sortedProxies.length}
|
||||||
itemContent={(index) => (
|
itemContent={(index) => (
|
||||||
<ProxyItem
|
<ProxyItem
|
||||||
groupName={group.name}
|
groupName={group.name}
|
||||||
proxy={filterProxies[index]}
|
proxy={sortedProxies[index]}
|
||||||
selected={filterProxies[index].name === now}
|
selected={sortedProxies[index].name === now}
|
||||||
showType={showType}
|
showType={showType}
|
||||||
sx={{ py: 0, pl: 4 }}
|
sx={{ py: 0, pl: 4 }}
|
||||||
onClick={onChangeProxy}
|
onClick={onChangeProxy}
|
||||||
@@ -230,7 +172,7 @@ const ProxyGroup = ({ group }: Props) => {
|
|||||||
disablePadding
|
disablePadding
|
||||||
sx={{ maxHeight: "320px", overflow: "auto", mb: "4px" }}
|
sx={{ maxHeight: "320px", overflow: "auto", mb: "4px" }}
|
||||||
>
|
>
|
||||||
{filterProxies.map((proxy) => (
|
{sortedProxies.map((proxy) => (
|
||||||
<ProxyItem
|
<ProxyItem
|
||||||
key={proxy.name}
|
key={proxy.name}
|
||||||
groupName={group.name}
|
groupName={group.name}
|
||||||
|
|||||||
@@ -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;
|
||||||
@@ -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 { CheckCircleOutlineRounded } from "@mui/icons-material";
|
||||||
import {
|
import {
|
||||||
alpha,
|
alpha,
|
||||||
@@ -24,8 +25,9 @@ interface Props {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const Widget = styled(Box)(() => ({
|
const Widget = styled(Box)(() => ({
|
||||||
padding: "4px 6px",
|
padding: "3px 6px",
|
||||||
fontSize: 14,
|
fontSize: 14,
|
||||||
|
borderRadius: "4px",
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const TypeBox = styled(Box)(({ theme }) => ({
|
const TypeBox = styled(Box)(({ theme }) => ({
|
||||||
@@ -50,20 +52,12 @@ const ProxyItem = (props: Props) => {
|
|||||||
}
|
}
|
||||||
}, [proxy]);
|
}, [proxy]);
|
||||||
|
|
||||||
const delayRef = useRef(false);
|
const onDelay = useLockFn(async () => {
|
||||||
const onDelay = (e: any) => {
|
return delayManager
|
||||||
e.preventDefault();
|
|
||||||
e.stopPropagation();
|
|
||||||
|
|
||||||
if (delayRef.current) return;
|
|
||||||
delayRef.current = true;
|
|
||||||
|
|
||||||
delayManager
|
|
||||||
.checkDelay(proxy.name, groupName)
|
.checkDelay(proxy.name, groupName)
|
||||||
.then((result) => setDelay(result))
|
.then((result) => setDelay(result))
|
||||||
.catch(() => setDelay(1e6))
|
.catch(() => setDelay(1e6));
|
||||||
.finally(() => (delayRef.current = false));
|
});
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ListItem sx={sx}>
|
<ListItem sx={sx}>
|
||||||
@@ -111,13 +105,27 @@ const ProxyItem = (props: Props) => {
|
|||||||
<ListItemIcon
|
<ListItemIcon
|
||||||
sx={{ justifyContent: "flex-end", color: "primary.main" }}
|
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
|
Check
|
||||||
</Widget>
|
</Widget>
|
||||||
|
|
||||||
<Widget
|
<Widget
|
||||||
className="the-delay"
|
className="the-delay"
|
||||||
onClick={onDelay}
|
onClick={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
onDelay();
|
||||||
|
}}
|
||||||
color={
|
color={
|
||||||
delay > 500
|
delay > 500
|
||||||
? "error.main"
|
? "error.main"
|
||||||
@@ -125,6 +133,9 @@ const ProxyItem = (props: Props) => {
|
|||||||
? "success.main"
|
? "success.main"
|
||||||
: "text.secondary"
|
: "text.secondary"
|
||||||
}
|
}
|
||||||
|
sx={(theme) => ({
|
||||||
|
":hover": { bgcolor: alpha(theme.palette.primary.main, 0.15) },
|
||||||
|
})}
|
||||||
>
|
>
|
||||||
{delay > 1e5 ? "Error" : delay > 3000 ? "Timeout" : `${delay}ms`}
|
{delay > 1e5 ? "Error" : delay > 3000 ? "Timeout" : `${delay}ms`}
|
||||||
</Widget>
|
</Widget>
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ export default function useFilterProxy(
|
|||||||
filterText: string
|
filterText: string
|
||||||
) {
|
) {
|
||||||
return useMemo(() => {
|
return useMemo(() => {
|
||||||
|
if (!proxies) return [];
|
||||||
if (!filterText) return proxies;
|
if (!filterText) return proxies;
|
||||||
|
|
||||||
const res1 = regex1.exec(filterText);
|
const res1 = regex1.exec(filterText);
|
||||||
|
|||||||
@@ -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]);
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
@@ -122,7 +122,7 @@ const SettingClash = ({ onError }: Props) => {
|
|||||||
onFormat={(e: any) => +e.target.value?.replace(/\D+/, "")}
|
onFormat={(e: any) => +e.target.value?.replace(/\D+/, "")}
|
||||||
onChange={(e) => onChangeData({ "mixed-port": e })}
|
onChange={(e) => onChangeData({ "mixed-port": e })}
|
||||||
onGuard={onUpdatePort}
|
onGuard={onUpdatePort}
|
||||||
waitTime={800}
|
waitTime={1000}
|
||||||
>
|
>
|
||||||
<TextField autoComplete="off" size="small" sx={{ width: 120 }} />
|
<TextField autoComplete="off" size="small" sx={{ width: 120 }} />
|
||||||
</GuardState>
|
</GuardState>
|
||||||
|
|||||||
@@ -1,24 +1,49 @@
|
|||||||
import useSWR, { useSWRConfig } from "swr";
|
import useSWR, { useSWRConfig } from "swr";
|
||||||
|
import { useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { Box, ListItemText, Switch, TextField } from "@mui/material";
|
import {
|
||||||
import { getVergeConfig, patchVergeConfig } from "../../services/cmds";
|
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 { SettingList, SettingItem } from "./setting";
|
||||||
import { CmdType } from "../../services/types";
|
import { CmdType } from "../../services/types";
|
||||||
import GuardState from "./guard-state";
|
import GuardState from "./guard-state";
|
||||||
|
import ServiceMode from "./service-mode";
|
||||||
import SysproxyTooltip from "./sysproxy-tooltip";
|
import SysproxyTooltip from "./sysproxy-tooltip";
|
||||||
|
import getSystem from "../../utils/get-system";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
onError?: (err: Error) => void;
|
onError?: (err: Error) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const isWIN = getSystem() === "windows";
|
||||||
|
|
||||||
const SettingSystem = ({ onError }: Props) => {
|
const SettingSystem = ({ onError }: Props) => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const { mutate } = useSWRConfig();
|
const { mutate } = useSWRConfig();
|
||||||
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
|
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 {
|
const {
|
||||||
enable_tun_mode,
|
enable_tun_mode,
|
||||||
enable_auto_launch,
|
enable_auto_launch,
|
||||||
|
enable_service_mode,
|
||||||
enable_silent_start,
|
enable_silent_start,
|
||||||
enable_system_proxy,
|
enable_system_proxy,
|
||||||
system_proxy_bypass,
|
system_proxy_bypass,
|
||||||
@@ -46,6 +71,56 @@ const SettingSystem = ({ onError }: Props) => {
|
|||||||
</GuardState>
|
</GuardState>
|
||||||
</SettingItem>
|
</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>
|
<SettingItem>
|
||||||
<ListItemText primary={t("Auto Launch")} />
|
<ListItemText primary={t("Auto Launch")} />
|
||||||
<GuardState
|
<GuardState
|
||||||
@@ -78,7 +153,7 @@ const SettingSystem = ({ onError }: Props) => {
|
|||||||
<ListItemText
|
<ListItemText
|
||||||
primary={
|
primary={
|
||||||
<Box sx={{ display: "flex", alignItems: "center" }}>
|
<Box sx={{ display: "flex", alignItems: "center" }}>
|
||||||
{t("System Proxy")}
|
<span style={{ marginRight: 4 }}>{t("System Proxy")}</span>
|
||||||
<SysproxyTooltip />
|
<SysproxyTooltip />
|
||||||
</Box>
|
</Box>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,6 +41,7 @@
|
|||||||
"Mixed Port": "Mixed Port",
|
"Mixed Port": "Mixed Port",
|
||||||
"Clash core": "Clash core",
|
"Clash core": "Clash core",
|
||||||
"Tun Mode": "Tun Mode",
|
"Tun Mode": "Tun Mode",
|
||||||
|
"Service Mode": "Service Mode",
|
||||||
"Auto Launch": "Auto Launch",
|
"Auto Launch": "Auto Launch",
|
||||||
"Silent Start": "Silent Start",
|
"Silent Start": "Silent Start",
|
||||||
"System Proxy": "System Proxy",
|
"System Proxy": "System Proxy",
|
||||||
|
|||||||
@@ -41,6 +41,7 @@
|
|||||||
"Mixed Port": "端口设置",
|
"Mixed Port": "端口设置",
|
||||||
"Clash core": "Clash 内核",
|
"Clash core": "Clash 内核",
|
||||||
"Tun Mode": "Tun 模式",
|
"Tun Mode": "Tun 模式",
|
||||||
|
"Service Mode": "服务模式",
|
||||||
"Auto Launch": "开机自启",
|
"Auto Launch": "开机自启",
|
||||||
"Silent Start": "静默启动",
|
"Silent Start": "静默启动",
|
||||||
"System Proxy": "系统代理",
|
"System Proxy": "系统代理",
|
||||||
|
|||||||
+75
-28
@@ -1,6 +1,6 @@
|
|||||||
import { useEffect, useState } from "react";
|
import { useEffect, useMemo, useState } from "react";
|
||||||
import { useLockFn } from "ahooks";
|
import { useLockFn } from "ahooks";
|
||||||
import { Button, Paper } from "@mui/material";
|
import { Box, Button, Paper, TextField } from "@mui/material";
|
||||||
import { Virtuoso } from "react-virtuoso";
|
import { Virtuoso } from "react-virtuoso";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { ApiType } from "../services/types";
|
import { ApiType } from "../services/types";
|
||||||
@@ -8,12 +8,20 @@ import { closeAllConnections, getInfomation } from "../services/api";
|
|||||||
import BasePage from "../components/base/base-page";
|
import BasePage from "../components/base/base-page";
|
||||||
import ConnectionItem from "../components/connection/connection-item";
|
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 { t } = useTranslation();
|
||||||
|
|
||||||
|
const [filterText, setFilterText] = useState("");
|
||||||
const [connData, setConnData] = useState<ApiType.Connections>(initConn);
|
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(() => {
|
useEffect(() => {
|
||||||
let ws: WebSocket | null = null;
|
let ws: WebSocket | null = null;
|
||||||
|
|
||||||
@@ -23,32 +31,35 @@ const ConnectionsPage = () => {
|
|||||||
|
|
||||||
ws.addEventListener("message", (event) => {
|
ws.addEventListener("message", (event) => {
|
||||||
const data = JSON.parse(event.data) as ApiType.Connections;
|
const data = JSON.parse(event.data) as ApiType.Connections;
|
||||||
|
|
||||||
|
// 与前一次connections的展示顺序尽量保持一致
|
||||||
setConnData((old) => {
|
setConnData((old) => {
|
||||||
const oldConn = old.connections;
|
const oldConn = old.connections;
|
||||||
const oldList = oldConn.map((each) => each.id);
|
|
||||||
const maxLen = data.connections.length;
|
const maxLen = data.connections.length;
|
||||||
|
|
||||||
const connections: typeof oldConn = [];
|
const connections: typeof oldConn = [];
|
||||||
|
|
||||||
// 与前一次连接的顺序尽量保持一致
|
const rest = data.connections.filter((each) => {
|
||||||
data.connections
|
const index = oldConn.findIndex((o) => o.id === each.id);
|
||||||
.filter((each) => {
|
|
||||||
const index = oldList.indexOf(each.id);
|
|
||||||
|
|
||||||
if (index >= 0 && index < maxLen) {
|
if (index >= 0 && index < maxLen) {
|
||||||
connections[index] = each;
|
const old = oldConn[index];
|
||||||
return false;
|
each.curUpload = each.upload - old.upload;
|
||||||
}
|
each.curDownload = each.download - old.download;
|
||||||
return true;
|
|
||||||
})
|
connections[index] = each;
|
||||||
.forEach((each) => {
|
return false;
|
||||||
for (let i = 0; i < maxLen; ++i) {
|
}
|
||||||
if (!connections[i]) {
|
return true;
|
||||||
connections[i] = each;
|
});
|
||||||
return;
|
|
||||||
}
|
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 };
|
return { ...data, connections };
|
||||||
});
|
});
|
||||||
@@ -76,11 +87,47 @@ const ConnectionsPage = () => {
|
|||||||
}
|
}
|
||||||
>
|
>
|
||||||
<Paper sx={{ boxShadow: 2, height: "100%" }}>
|
<Paper sx={{ boxShadow: 2, height: "100%" }}>
|
||||||
<Virtuoso
|
<Box
|
||||||
initialTopMostItemIndex={999}
|
sx={{
|
||||||
data={connData.connections}
|
pt: 1,
|
||||||
itemContent={(index, item) => <ConnectionItem value={item} />}
|
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>
|
</Paper>
|
||||||
</BasePage>
|
</BasePage>
|
||||||
);
|
);
|
||||||
|
|||||||
+58
-8
@@ -1,5 +1,6 @@
|
|||||||
|
import { useMemo, useState } from "react";
|
||||||
import { useRecoilState } from "recoil";
|
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 { Virtuoso } from "react-virtuoso";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { atomLogData } from "../services/states";
|
import { atomLogData } from "../services/states";
|
||||||
@@ -10,6 +11,18 @@ const LogPage = () => {
|
|||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const [logData, setLogData] = useRecoilState(atomLogData);
|
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 (
|
return (
|
||||||
<BasePage
|
<BasePage
|
||||||
title={t("Logs")}
|
title={t("Logs")}
|
||||||
@@ -25,13 +38,50 @@ const LogPage = () => {
|
|||||||
</Button>
|
</Button>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<Paper sx={{ boxShadow: 2, height: "100%" }}>
|
<Paper sx={{ boxSizing: "border-box", boxShadow: 2, height: "100%" }}>
|
||||||
<Virtuoso
|
<Box
|
||||||
initialTopMostItemIndex={999}
|
sx={{
|
||||||
data={logData}
|
pt: 1,
|
||||||
itemContent={(index, item) => <LogItem value={item} />}
|
mb: 0.5,
|
||||||
followOutput={"smooth"}
|
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>
|
</Paper>
|
||||||
</BasePage>
|
</BasePage>
|
||||||
);
|
);
|
||||||
|
|||||||
+31
-6
@@ -6,10 +6,6 @@ export async function getProfiles() {
|
|||||||
return invoke<CmdType.ProfilesConfig>("get_profiles");
|
return invoke<CmdType.ProfilesConfig>("get_profiles");
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function syncProfiles() {
|
|
||||||
return invoke<void>("sync_profiles");
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function enhanceProfiles() {
|
export async function enhanceProfiles() {
|
||||||
return invoke<void>("enhance_profiles");
|
return invoke<void>("enhance_profiles");
|
||||||
}
|
}
|
||||||
@@ -94,8 +90,8 @@ export async function restartSidecar() {
|
|||||||
return invoke<void>("restart_sidecar");
|
return invoke<void>("restart_sidecar");
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function killSidecars() {
|
export async function killSidecar() {
|
||||||
return invoke<any>("kill_sidecars");
|
return invoke<any>("kill_sidecar");
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function openAppDir() {
|
export async function openAppDir() {
|
||||||
@@ -109,3 +105,32 @@ export async function openLogsDir() {
|
|||||||
Notice.error(err?.message || err.toString(), 1500)
|
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
@@ -4,6 +4,15 @@ const hashKey = (name: string, group: string) => `${group ?? ""}::${name}`;
|
|||||||
|
|
||||||
class DelayManager {
|
class DelayManager {
|
||||||
private cache = new Map<string, [number, number]>();
|
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) {
|
setDelay(name: string, group: string, delay: number) {
|
||||||
this.cache.set(hashKey(name, group), [Date.now(), delay]);
|
this.cache.set(hashKey(name, group), [Date.now(), delay]);
|
||||||
@@ -23,7 +32,8 @@ class DelayManager {
|
|||||||
let delay = -1;
|
let delay = -1;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const result = await getProxyDelay(name);
|
const url = this.getUrl(group);
|
||||||
|
const result = await getProxyDelay(name, url);
|
||||||
delay = result.delay;
|
delay = result.delay;
|
||||||
} catch {
|
} catch {
|
||||||
delay = 1e6; // error
|
delay = 1e6; // error
|
||||||
@@ -38,32 +48,36 @@ class DelayManager {
|
|||||||
names: readonly string[];
|
names: readonly string[];
|
||||||
groupName: string;
|
groupName: string;
|
||||||
skipNum: number;
|
skipNum: number;
|
||||||
maxTimeout: number;
|
|
||||||
},
|
},
|
||||||
callback: Function
|
callback: Function
|
||||||
) {
|
) {
|
||||||
let names = [...options.names];
|
const { groupName, skipNum } = options;
|
||||||
const { groupName, skipNum, maxTimeout } = options;
|
|
||||||
|
|
||||||
while (names.length) {
|
const names = [...options.names];
|
||||||
const list = names.slice(0, skipNum);
|
const total = names.length;
|
||||||
names = names.slice(skipNum);
|
|
||||||
|
|
||||||
let called = false;
|
let count = 0;
|
||||||
setTimeout(() => {
|
let current = 0;
|
||||||
if (!called) {
|
|
||||||
called = true;
|
|
||||||
callback();
|
|
||||||
}
|
|
||||||
}, maxTimeout);
|
|
||||||
|
|
||||||
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) {
|
const task = names.shift();
|
||||||
called = true;
|
if (!task) return;
|
||||||
callback();
|
|
||||||
}
|
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();
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
/**
|
/**
|
||||||
* Some interface for clash api
|
* Some interface for clash api
|
||||||
*/
|
*/
|
||||||
export namespace ApiType {
|
export namespace ApiType {
|
||||||
export interface ConfigData {
|
export interface ConfigData {
|
||||||
port: number;
|
port: number;
|
||||||
mode: string;
|
mode: string;
|
||||||
@@ -65,6 +65,8 @@ export namespace ApiType {
|
|||||||
chains: string[];
|
chains: string[];
|
||||||
rule: string;
|
rule: string;
|
||||||
rulePayload: string;
|
rulePayload: string;
|
||||||
|
curUpload?: number; // calculate
|
||||||
|
curDownload?: number; // calculate
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Connections {
|
export interface Connections {
|
||||||
@@ -111,6 +113,7 @@ export namespace CmdType {
|
|||||||
export interface ProfileOption {
|
export interface ProfileOption {
|
||||||
user_agent?: string;
|
user_agent?: string;
|
||||||
with_proxy?: boolean;
|
with_proxy?: boolean;
|
||||||
|
update_interval?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ProfilesConfig {
|
export interface ProfilesConfig {
|
||||||
@@ -127,6 +130,7 @@ export namespace CmdType {
|
|||||||
traffic_graph?: boolean;
|
traffic_graph?: boolean;
|
||||||
enable_tun_mode?: boolean;
|
enable_tun_mode?: boolean;
|
||||||
enable_auto_launch?: boolean;
|
enable_auto_launch?: boolean;
|
||||||
|
enable_service_mode?: boolean;
|
||||||
enable_silent_start?: boolean;
|
enable_silent_start?: boolean;
|
||||||
enable_system_proxy?: boolean;
|
enable_system_proxy?: boolean;
|
||||||
enable_proxy_guard?: boolean;
|
enable_proxy_guard?: boolean;
|
||||||
|
|||||||
@@ -386,37 +386,37 @@
|
|||||||
"@jridgewell/resolve-uri" "^3.0.3"
|
"@jridgewell/resolve-uri" "^3.0.3"
|
||||||
"@jridgewell/sourcemap-codec" "^1.4.10"
|
"@jridgewell/sourcemap-codec" "^1.4.10"
|
||||||
|
|
||||||
"@mui/base@5.0.0-alpha.74":
|
"@mui/base@5.0.0-alpha.76":
|
||||||
version "5.0.0-alpha.74"
|
version "5.0.0-alpha.76"
|
||||||
resolved "https://registry.yarnpkg.com/@mui/base/-/base-5.0.0-alpha.74.tgz#15509242e7911446d5957375b1b18cbb72b3a750"
|
resolved "https://registry.yarnpkg.com/@mui/base/-/base-5.0.0-alpha.76.tgz#683d68eff6d52e19e9962f608a5d3b8b6fb6ef55"
|
||||||
integrity sha512-pw3T1xNXpW8pLo9+BvtyazZb0CSjNJsjbzznlbV/aNkBfjNPXQVI3X1NDm3WSI8y6M96WDIVO7XrHAohOwALSQ==
|
integrity sha512-Pd0l4DvjXiGRyipn/CTDlYB2XrJwhpLktVXvbvcmzL2SMDaNprSarZqBkPHIubkulmRDZEEcnFDrpKgeSJDg4A==
|
||||||
dependencies:
|
dependencies:
|
||||||
"@babel/runtime" "^7.17.2"
|
"@babel/runtime" "^7.17.2"
|
||||||
"@emotion/is-prop-valid" "^1.1.2"
|
"@emotion/is-prop-valid" "^1.1.2"
|
||||||
"@mui/types" "^7.1.3"
|
"@mui/types" "^7.1.3"
|
||||||
"@mui/utils" "^5.5.3"
|
"@mui/utils" "^5.6.1"
|
||||||
"@popperjs/core" "^2.11.4"
|
"@popperjs/core" "^2.11.5"
|
||||||
clsx "^1.1.1"
|
clsx "^1.1.1"
|
||||||
prop-types "^15.7.2"
|
prop-types "^15.7.2"
|
||||||
react-is "^17.0.2"
|
react-is "^17.0.2"
|
||||||
|
|
||||||
"@mui/icons-material@^5.5.1":
|
"@mui/icons-material@^5.6.1":
|
||||||
version "5.5.1"
|
version "5.6.1"
|
||||||
resolved "https://registry.yarnpkg.com/@mui/icons-material/-/icons-material-5.5.1.tgz#848a57972617411370775980cbc6990588d4aafb"
|
resolved "https://registry.yarnpkg.com/@mui/icons-material/-/icons-material-5.6.1.tgz#421e2b73992349abb07f8f03074d7e56e20bf7ba"
|
||||||
integrity sha512-40f68p5+Yhq3dCn3QYHqQt5RETPyR3AkDw+fma8PtcjqvZ+d+jF84kFmT6NqwA3he7TlwluEtkyAmPzUE4uPdA==
|
integrity sha512-I1x8u+FRLOmoJpRJASMx9UG+jZrSkNLyRQmBXivQQwXu3m3iasMoaKYhhI0J18t8+FWktbkNTp63oEUHE9Gw0Q==
|
||||||
dependencies:
|
dependencies:
|
||||||
"@babel/runtime" "^7.17.2"
|
"@babel/runtime" "^7.17.2"
|
||||||
|
|
||||||
"@mui/material@^5.5.3":
|
"@mui/material@^5.6.1":
|
||||||
version "5.5.3"
|
version "5.6.1"
|
||||||
resolved "https://registry.yarnpkg.com/@mui/material/-/material-5.5.3.tgz#411e53a69da3f9d6664e99f1bdcdaf2760540fdc"
|
resolved "https://registry.yarnpkg.com/@mui/material/-/material-5.6.1.tgz#b74cfbe4666586e054a28cf3df448369892085e1"
|
||||||
integrity sha512-eADa3kUYbbr1jNjcufn0a7HeU8cSo0agbrkj720hodxVFNIfzq7a2e58Z+PaZqll55kMGBvlYJ7rTcXU399x5A==
|
integrity sha512-xg6pPq+1jxWupwmPpnfmsHNjrsOe2xynUQWrRfcH8WHrrr1sQulq0VF4gORq/l8DD8a/jb4s8SsC20e/e6mHKQ==
|
||||||
dependencies:
|
dependencies:
|
||||||
"@babel/runtime" "^7.17.2"
|
"@babel/runtime" "^7.17.2"
|
||||||
"@mui/base" "5.0.0-alpha.74"
|
"@mui/base" "5.0.0-alpha.76"
|
||||||
"@mui/system" "^5.5.3"
|
"@mui/system" "^5.6.1"
|
||||||
"@mui/types" "^7.1.3"
|
"@mui/types" "^7.1.3"
|
||||||
"@mui/utils" "^5.5.3"
|
"@mui/utils" "^5.6.1"
|
||||||
"@types/react-transition-group" "^4.4.4"
|
"@types/react-transition-group" "^4.4.4"
|
||||||
clsx "^1.1.1"
|
clsx "^1.1.1"
|
||||||
csstype "^3.0.11"
|
csstype "^3.0.11"
|
||||||
@@ -425,34 +425,34 @@
|
|||||||
react-is "^17.0.2"
|
react-is "^17.0.2"
|
||||||
react-transition-group "^4.4.2"
|
react-transition-group "^4.4.2"
|
||||||
|
|
||||||
"@mui/private-theming@^5.5.3":
|
"@mui/private-theming@^5.6.1":
|
||||||
version "5.5.3"
|
version "5.6.1"
|
||||||
resolved "https://registry.yarnpkg.com/@mui/private-theming/-/private-theming-5.5.3.tgz#c232a39dd3c268fdef7e92ccc40d51bda9eec3ab"
|
resolved "https://registry.yarnpkg.com/@mui/private-theming/-/private-theming-5.6.1.tgz#198ccec972375db999c293109b5f26456b9c3a22"
|
||||||
integrity sha512-Wf7NurY7lk8SBWelSBY2U02zxLt1773JpIcXTHuEC9/GZdQA4CXCJGl2cVQzheKhee5rZ+8JwGulrRiVl1m+4A==
|
integrity sha512-8lgh+tUt/3ftStfvml3dwAzhW3fe/cUFjLcBViOTnWk7UixWR79me4qehsO4NVj0THpu3d2qclrLzdD8qBAWAQ==
|
||||||
dependencies:
|
dependencies:
|
||||||
"@babel/runtime" "^7.17.2"
|
"@babel/runtime" "^7.17.2"
|
||||||
"@mui/utils" "^5.5.3"
|
"@mui/utils" "^5.6.1"
|
||||||
prop-types "^15.7.2"
|
prop-types "^15.7.2"
|
||||||
|
|
||||||
"@mui/styled-engine@^5.5.2":
|
"@mui/styled-engine@^5.6.1":
|
||||||
version "5.5.2"
|
version "5.6.1"
|
||||||
resolved "https://registry.yarnpkg.com/@mui/styled-engine/-/styled-engine-5.5.2.tgz#1f92dd27d76f0b7df7aa52c7c7a710e59b2275a6"
|
resolved "https://registry.yarnpkg.com/@mui/styled-engine/-/styled-engine-5.6.1.tgz#e2c859a4dbdd65af89e77703a0725285aef471fd"
|
||||||
integrity sha512-jkz5AHHbA43akBo5L3y1X1/X0f+RvXvCp3eXKt+iOf3qnKSAausbtlVz7gBbC4xIWDnP1Jb/6T+t/0/7gObRYA==
|
integrity sha512-jEhH6TBY8jc9S8yVncXmoTYTbATjEu44RMFXj6sIYfKr5NArVwTwRo3JexLL0t3BOAiYM4xsFLgfKEIvB9SAeQ==
|
||||||
dependencies:
|
dependencies:
|
||||||
"@babel/runtime" "^7.17.2"
|
"@babel/runtime" "^7.17.2"
|
||||||
"@emotion/cache" "^11.7.1"
|
"@emotion/cache" "^11.7.1"
|
||||||
prop-types "^15.7.2"
|
prop-types "^15.7.2"
|
||||||
|
|
||||||
"@mui/system@^5.5.3":
|
"@mui/system@^5.6.1":
|
||||||
version "5.5.3"
|
version "5.6.1"
|
||||||
resolved "https://registry.yarnpkg.com/@mui/system/-/system-5.5.3.tgz#c78d4c16009430389ffd3495d694945422d72ca5"
|
resolved "https://registry.yarnpkg.com/@mui/system/-/system-5.6.1.tgz#dd47a15b82012f44464a0f25765e3dec6182ba98"
|
||||||
integrity sha512-J9JcySJuEqfEoP334K/2gEWm2vOx73Uqjii3qlFVhWRBOAJ0Pjyk0sN5W/eVRbwhUm95DNgh2V5s8dRK3vzyVw==
|
integrity sha512-Y5pDvEOK6VOY+0vgNeyDuEEO5QCinhXbZQDyLOlaGLKuAoRGLXO9pcSsjZoGkewYZitXD44EDfgBQ+BqsAfgUA==
|
||||||
dependencies:
|
dependencies:
|
||||||
"@babel/runtime" "^7.17.2"
|
"@babel/runtime" "^7.17.2"
|
||||||
"@mui/private-theming" "^5.5.3"
|
"@mui/private-theming" "^5.6.1"
|
||||||
"@mui/styled-engine" "^5.5.2"
|
"@mui/styled-engine" "^5.6.1"
|
||||||
"@mui/types" "^7.1.3"
|
"@mui/types" "^7.1.3"
|
||||||
"@mui/utils" "^5.5.3"
|
"@mui/utils" "^5.6.1"
|
||||||
clsx "^1.1.1"
|
clsx "^1.1.1"
|
||||||
csstype "^3.0.11"
|
csstype "^3.0.11"
|
||||||
prop-types "^15.7.2"
|
prop-types "^15.7.2"
|
||||||
@@ -462,10 +462,10 @@
|
|||||||
resolved "https://registry.yarnpkg.com/@mui/types/-/types-7.1.3.tgz#d7636f3046110bcccc63e6acfd100e2ad9ca712a"
|
resolved "https://registry.yarnpkg.com/@mui/types/-/types-7.1.3.tgz#d7636f3046110bcccc63e6acfd100e2ad9ca712a"
|
||||||
integrity sha512-DDF0UhMBo4Uezlk+6QxrlDbchF79XG6Zs0zIewlR4c0Dt6GKVFfUtzPtHCH1tTbcSlq/L2bGEdiaoHBJ9Y1gSA==
|
integrity sha512-DDF0UhMBo4Uezlk+6QxrlDbchF79XG6Zs0zIewlR4c0Dt6GKVFfUtzPtHCH1tTbcSlq/L2bGEdiaoHBJ9Y1gSA==
|
||||||
|
|
||||||
"@mui/utils@^5.5.3":
|
"@mui/utils@^5.6.1":
|
||||||
version "5.5.3"
|
version "5.6.1"
|
||||||
resolved "https://registry.yarnpkg.com/@mui/utils/-/utils-5.5.3.tgz#f6e1f10c0e8f4d0bf750588c2c3a96ad819c5b65"
|
resolved "https://registry.yarnpkg.com/@mui/utils/-/utils-5.6.1.tgz#4ab79a21bd481555d9a588f4b18061b3c28ea5db"
|
||||||
integrity sha512-t627eVRpl3SlxVya0cIVNs8jPl4KCEiGaTSWY9iKKTcMNaeDbuRML+zv/CFHDPr1zFv+FjJSP02ySB+tZ8xIag==
|
integrity sha512-CPrzrkiBusCZBLWu0Sg5MJvR3fKJyK3gKecLVX012LULyqg2U64Oz04BKhfkbtBrPBbSQxM+DWW9B1c9hmV9nQ==
|
||||||
dependencies:
|
dependencies:
|
||||||
"@babel/runtime" "^7.17.2"
|
"@babel/runtime" "^7.17.2"
|
||||||
"@types/prop-types" "^15.7.4"
|
"@types/prop-types" "^15.7.4"
|
||||||
@@ -559,10 +559,10 @@
|
|||||||
dependencies:
|
dependencies:
|
||||||
"@octokit/openapi-types" "^11.2.0"
|
"@octokit/openapi-types" "^11.2.0"
|
||||||
|
|
||||||
"@popperjs/core@^2.11.4":
|
"@popperjs/core@^2.11.5":
|
||||||
version "2.11.4"
|
version "2.11.5"
|
||||||
resolved "https://registry.yarnpkg.com/@popperjs/core/-/core-2.11.4.tgz#d8c7b8db9226d2d7664553a0741ad7d0397ee503"
|
resolved "https://registry.yarnpkg.com/@popperjs/core/-/core-2.11.5.tgz#db5a11bf66bdab39569719555b0f76e138d7bd64"
|
||||||
integrity sha512-q/ytXxO5NKvyT37pmisQAItCFqA7FD/vNb8dgaJy3/630Fsc+Mz9/9f2SziBoIZ30TJooXyTwZmhi1zjXmObYg==
|
integrity sha512-9X2obfABZuDVLCgPK9aX0a/x4jaOEweTTWE2+9sr0Qqqevj2Uv5XorvusThmc9XGYpS9yI+fhh8RTafBtGposw==
|
||||||
|
|
||||||
"@rollup/pluginutils@^4.1.2":
|
"@rollup/pluginutils@^4.1.2":
|
||||||
version "4.2.0"
|
version "4.2.0"
|
||||||
@@ -828,6 +828,13 @@ adm-zip@^0.5.9:
|
|||||||
resolved "https://registry.yarnpkg.com/adm-zip/-/adm-zip-0.5.9.tgz#b33691028333821c0cf95c31374c5462f2905a83"
|
resolved "https://registry.yarnpkg.com/adm-zip/-/adm-zip-0.5.9.tgz#b33691028333821c0cf95c31374c5462f2905a83"
|
||||||
integrity sha512-s+3fXLkeeLjZ2kLjCBwQufpI5fuN+kIGBxu6530nVQZGVol0d7Y/M88/xw9HGGUcJjKf8LutN3VPRUBq6N7Ajg==
|
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:
|
ahooks-v3-count@^1.0.0:
|
||||||
version "1.0.0"
|
version "1.0.0"
|
||||||
resolved "https://registry.yarnpkg.com/ahooks-v3-count/-/ahooks-v3-count-1.0.0.tgz#ddeb392e009ad6e748905b3cbf63a9fd8262ca80"
|
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"
|
resolved "https://registry.yarnpkg.com/dayjs/-/dayjs-1.11.0.tgz#009bf7ef2e2ea2d5db2e6583d2d39a4b5061e805"
|
||||||
integrity sha512-JLC809s6Y948/FuCZPm5IX8rRhQwOiyMb2TfVVQEixG7P8Lm/gt5S7yoQZmC8x1UehI9Pb7sksEt4xx14m+7Ug==
|
integrity sha512-JLC809s6Y948/FuCZPm5IX8rRhQwOiyMb2TfVVQEixG7P8Lm/gt5S7yoQZmC8x1UehI9Pb7sksEt4xx14m+7Ug==
|
||||||
|
|
||||||
debug@^4.1.0:
|
debug@4, debug@^4.1.0:
|
||||||
version "4.3.4"
|
version "4.3.4"
|
||||||
resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.4.tgz#1319f6579357f2338d3337d2cdd4914bb5dcc865"
|
resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.4.tgz#1319f6579357f2338d3337d2cdd4914bb5dcc865"
|
||||||
integrity sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==
|
integrity sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==
|
||||||
@@ -1416,6 +1423,14 @@ html-parse-stringify@^3.0.1:
|
|||||||
dependencies:
|
dependencies:
|
||||||
void-elements "3.1.0"
|
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:
|
human-signals@^1.1.1:
|
||||||
version "1.1.1"
|
version "1.1.1"
|
||||||
resolved "https://registry.yarnpkg.com/human-signals/-/human-signals-1.1.1.tgz#c5b1cd14f50aeae09ab6c59fe63ba3395fe4dfa3"
|
resolved "https://registry.yarnpkg.com/human-signals/-/human-signals-1.1.1.tgz#c5b1cd14f50aeae09ab6c59fe63ba3395fe4dfa3"
|
||||||
|
|||||||
Reference in New Issue
Block a user