25 Commits

Author SHA1 Message Date
GyDi
5cff4e299b chore: update clash version 2022-03-20 12:37:55 +08:00
GyDi
bce33639da v0.0.24 2022-03-20 01:50:39 +08:00
GyDi
366c465cad chore: update log 2022-03-20 01:50:15 +08:00
GyDi
acc6e05bdc feat: system tray supports system proxy setting 2022-03-20 01:36:43 +08:00
GyDi
4ce15577cd feat: prevent context menu on Windows close #22 2022-03-19 19:28:53 +08:00
GyDi
98fa4d5e65 feat: create local profile with selected file 2022-03-19 19:21:55 +08:00
GyDi
7fe94076c7 feat: reduce the impact of the enhanced mode 2022-03-19 16:02:47 +08:00
GyDi
b8b0c8fa63 fix: adjust windows style 2022-03-19 15:35:59 +08:00
GyDi
e585e87bec feat: parse update log 2022-03-19 15:31:58 +08:00
GyDi
6a4924bb16 chore: update log supports 2022-03-19 14:04:58 +08:00
GyDi
ab0d516d91 chore: updater proxy 2022-03-19 11:14:12 +08:00
GyDi
b756ae39d0 chore: ci support linux 2022-03-19 10:50:44 +08:00
GyDi
c15c38ea8f chore: readme 2022-03-18 19:02:53 +08:00
GyDi
743963318f feat: fill i18n 2022-03-18 14:59:23 +08:00
GyDi
ed3fc50858 feat: dayjs i18n 2022-03-18 14:45:24 +08:00
GyDi
5b886fe6be feat: connections page simply support 2022-03-18 14:43:22 +08:00
GyDi
7074bbc405 feat: add wintun.dll by default 2022-03-18 11:49:00 +08:00
GyDi
ef314c1707 fix: change mixed port error 2022-03-18 11:39:02 +08:00
GyDi
a3e7626dd9 chore: add dev feature 2022-03-18 10:59:35 +08:00
GyDi
5cb5d74eed chore: rename temp dir 2022-03-18 10:20:24 +08:00
GyDi
6eee10d46d chore: resolve wintun.dll 2022-03-17 19:29:30 +08:00
GyDi
2d95f2b0d6 fix: auto launch path 2022-03-16 18:44:25 +08:00
GyDi
ec41bb9c70 fix: tun mode config 2022-03-15 14:23:57 +08:00
GyDi
2d1780b1cf fix: adjsut open cmd error 2022-03-15 12:51:39 +08:00
GyDi
d9ce99887c chore: fix ci env 2022-03-15 00:00:20 +08:00
36 changed files with 667 additions and 136 deletions

View File

@@ -10,7 +10,7 @@ jobs:
release: release:
strategy: strategy:
matrix: matrix:
os: [windows-latest, macos-11] os: [windows-latest, ubuntu-latest, macos-latest]
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
if: | if: |
startsWith(github.repository, 'zzzgydi') && startsWith(github.repository, 'zzzgydi') &&
@@ -34,6 +34,12 @@ jobs:
with: with:
node-version: 14 node-version: 14
- name: Install Dependencies (ubuntu only)
if: matrix.os == 'ubuntu-latest'
run: |
sudo apt-get update
sudo apt-get install -y libgtk-3-dev webkit2gtk-4.0 libappindicator3-dev librsvg2-dev patchelf
- name: Get yarn cache dir path - name: Get yarn cache dir path
id: yarn-cache-dir-path id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)" run: echo "::set-output name=dir::$(yarn cache dir)"
@@ -68,12 +74,15 @@ jobs:
prerelease: true prerelease: true
- name: Green zip bundle - name: Green zip bundle
if: matrix.os == 'windows-latest'
run: | run: |
yarn run green yarn run green
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
release-update: release-update:
needs: release needs: release
runs-on: macos-11 runs-on: macos-latest
if: | if: |
startsWith(github.repository, 'zzzgydi') && startsWith(github.repository, 'zzzgydi') &&
startsWith(github.ref, 'refs/tags/v') startsWith(github.ref, 'refs/tags/v')
@@ -95,7 +104,7 @@ jobs:
${{ runner.os }}-yarn- ${{ runner.os }}-yarn-
- name: Yarn install - name: Yarn install
run: yarn run: yarn install
- name: Release update.json - name: Release update.json
run: yarn run release run: yarn run release

View File

@@ -11,7 +11,17 @@ A <a href="https://github.com/Dreamacro/clash">Clash</a> GUI based on <a href="h
## Features ## Features
Now it's no different from the others, maybe fewer. (WIP) - Full `clash` config supported, Partial `clash premium` config supported.
- Profiles management and enhancement (by yaml and Javascript).
- System proxy setting and guard.
## Install
Download from [release](https://github.com/zzzgydi/clash-verge/releases). Supports Windows x64 and macOS 11+
Or you can build it yourself. Supports Windows, Linux and macOS 10.15+
Notes: If you could not start the app on Windows, please check that you have [Webview2](https://developer.microsoft.com/en-us/microsoft-edge/webview2/#download-section) installed.
## Development ## Development
@@ -33,6 +43,12 @@ Then run
yarn dev yarn dev
``` ```
Or you can build it
```shell
yarn build
```
## Todos ## Todos
> This keng is a little big... > This keng is a little big...

29
UPDATELOG.md Normal file
View File

@@ -0,0 +1,29 @@
## v0.0.24
### Features
- Connections page
- add wintun.dll (Windows)
- supports create local profile with selected file (Windows)
- system tray enable set system proxy
### Bug Fixes
- open dir error
- auto launch path (Windows)
- fix some clash config error
- reduce the impact of the enhanced mode
---
## v0.0.23
### Features
- i18n supports
- Remote profile User Agent supports
### Bug Fixes
- clash config file case ignore
- clash `external-controller` only port

View File

@@ -1,6 +1,6 @@
{ {
"name": "clash-verge", "name": "clash-verge",
"version": "0.0.23", "version": "0.0.24",
"license": "GPL-3.0", "license": "GPL-3.0",
"scripts": { "scripts": {
"dev": "tauri dev", "dev": "tauri dev",
@@ -31,6 +31,7 @@
"react-router-dom": "^6.2.2", "react-router-dom": "^6.2.2",
"react-virtuoso": "^2.7.0", "react-virtuoso": "^2.7.0",
"recoil": "^0.6.1", "recoil": "^0.6.1",
"snarkdown": "^2.0.0",
"swr": "^1.2.1" "swr": "^1.2.1"
}, },
"devDependencies": { "devDependencies": {

View File

@@ -8,16 +8,16 @@ import { execSync } from "child_process";
const cwd = process.cwd(); const cwd = process.cwd();
const FORCE = process.argv.includes("--force"); const FORCE = process.argv.includes("--force");
const CLASH_URL_PREFIX =
"https://github.com/Dreamacro/clash/releases/download/premium/";
const CLASH_LATEST_DATE = "2022.01.27";
/** /**
* get the correct clash release infomation * get the correct clash release infomation
*/ */
function resolveClash() { function resolveClash() {
const { platform, arch } = process; const { platform, arch } = process;
const CLASH_URL_PREFIX =
"https://github.com/Dreamacro/clash/releases/download/premium/";
const CLASH_LATEST_DATE = "2022.03.19";
// todo // todo
const map = { const map = {
"win32-x64": "clash-windows-amd64", "win32-x64": "clash-windows-amd64",
@@ -84,13 +84,55 @@ async function resolveSidecar() {
console.log(`[INFO]: gunzip finished`); console.log(`[INFO]: gunzip finished`);
execSync(`chmod 755 ${sidecarPath}`); execSync(`chmod 755 ${sidecarPath}`);
console.log(`[INFO]: chmod binary finished`); console.log(`[INFO]: chmod binary finished`);
}); })
.on("error", (error) => console.error(error));
} }
// delete temp dir // delete temp dir
await fs.remove(tempDir); await fs.remove(tempDir);
} }
/**
* only Windows
* get the wintun.dll (not required)
*/
async function resolveWintun() {
const { platform } = process;
if (platform !== "win32") return;
const url = "https://www.wintun.net/builds/wintun-0.14.1.zip";
const tempDir = path.join(cwd, "pre-dev-temp-1");
const tempZip = path.join(tempDir, "wintun.zip");
const wintunPath = path.join(tempDir, "wintun/bin/amd64/wintun.dll");
const targetPath = path.join(cwd, "src-tauri/resources", "wintun.dll");
if (!FORCE && (await fs.pathExists(targetPath))) return;
await fs.mkdirp(tempDir);
if (!(await fs.pathExists(tempZip))) {
await downloadFile(url, tempZip);
}
// unzip
const zip = new AdmZip(tempZip);
zip.extractAllTo(tempDir, true);
if (!(await fs.pathExists(wintunPath))) {
throw new Error(`path not found "${wintunPath}"`);
}
// move wintun.dll to resources
await fs.rename(wintunPath, targetPath);
// delete temp dir
await fs.remove(tempDir);
console.log(`[INFO]: resolve wintun.dll finished`);
}
/** /**
* get the Country.mmdb (not required) * get the Country.mmdb (not required)
*/ */
@@ -123,4 +165,5 @@ async function downloadFile(url, path) {
/// main /// main
resolveSidecar().catch(console.error); resolveSidecar().catch(console.error);
resolveWintun().catch(console.error);
resolveMmdb().catch(console.error); resolveMmdb().catch(console.error);

View File

@@ -1,9 +1,11 @@
import fs from "fs-extra"; import fs from "fs-extra";
import { createRequire } from "module"; import { createRequire } from "module";
import { execSync } from "child_process"; import { execSync } from "child_process";
import { resolveUpdateLog } from "./updatelog.mjs";
const require = createRequire(import.meta.url); const require = createRequire(import.meta.url);
// publish
async function resolvePublish() { async function resolvePublish() {
const flag = process.argv[2] ?? "patch"; const flag = process.argv[2] ?? "patch";
const packageJson = require("../package.json"); const packageJson = require("../package.json");
@@ -26,6 +28,10 @@ async function resolvePublish() {
packageJson.version = nextVersion; packageJson.version = nextVersion;
tauriJson.package.version = nextVersion; tauriJson.package.version = nextVersion;
// 发布更新前先写更新日志
const nextTag = `v${nextVersion}`;
await resolveUpdateLog(nextTag);
await fs.writeFile( await fs.writeFile(
"./package.json", "./package.json",
JSON.stringify(packageJson, undefined, 2) JSON.stringify(packageJson, undefined, 2)

View File

@@ -1,8 +1,10 @@
import fetch from "node-fetch"; import fetch from "node-fetch";
import { getOctokit, context } from "@actions/github"; import { getOctokit, context } from "@actions/github";
import { resolveUpdateLog } from "./updatelog.mjs";
const UPDATE_TAG_NAME = "updater"; const UPDATE_TAG_NAME = "updater";
const UPDATE_JSON_FILE = "update.json"; const UPDATE_JSON_FILE = "update.json";
const UPDATE_JSON_PROXY = "update-proxy.json";
/// generate update.json /// generate update.json
/// upload to update tag's release asset /// upload to update tag's release asset
@@ -33,10 +35,11 @@ async function resolveRelease() {
const updateData = { const updateData = {
name: tag.name, name: tag.name,
notes: latestRelease.body, // use the release body directly notes: await resolveUpdateLog(tag.name), // use updatelog.md
pub_date: new Date().toISOString(), pub_date: new Date().toISOString(),
platforms: { platforms: {
win64: { signature: "", url: "" }, win64: { signature: "", url: "" },
linux: { signature: "", url: "" },
darwin: { signature: "", url: "" }, darwin: { signature: "", url: "" },
}, },
}; };
@@ -48,29 +51,41 @@ async function resolveRelease() {
if (/\.msi\.zip$/.test(name)) { if (/\.msi\.zip$/.test(name)) {
updateData.platforms.win64.url = browser_download_url; updateData.platforms.win64.url = browser_download_url;
} }
// darwin url
if (/\.app\.tar\.gz$/.test(name)) {
updateData.platforms.darwin.url = browser_download_url;
}
// win64 signature // win64 signature
if (/\.msi\.zip\.sig$/.test(name)) { if (/\.msi\.zip\.sig$/.test(name)) {
updateData.platforms.win64.signature = await getSignature( updateData.platforms.win64.signature = await getSignature(
browser_download_url browser_download_url
); );
} }
// darwin url
if (/\.app\.tar\.gz$/.test(name)) {
updateData.platforms.darwin.url = browser_download_url;
}
// darwin signature // darwin signature
if (/\.app\.tar\.gz\.sig$/.test(name)) { if (/\.app\.tar\.gz\.sig$/.test(name)) {
updateData.platforms.darwin.signature = await getSignature( updateData.platforms.darwin.signature = await getSignature(
browser_download_url browser_download_url
); );
} }
// linux url
if (/\.AppImage\.tar\.gz$/.test(name)) {
updateData.platforms.linux.url = browser_download_url;
}
// linux signature
if (/\.AppImage\.tar\.gz\.sig$/.test(name)) {
updateData.platforms.linux.signature = await getSignature(
browser_download_url
);
}
}); });
await Promise.allSettled(promises); await Promise.allSettled(promises);
console.log(updateData); console.log(updateData);
// maybe should test the signature as well // maybe should test the signature as well
const { darwin, win64 } = updateData.platforms; const { darwin, win64, linux } = updateData.platforms;
if (!darwin.url) { if (!darwin.url) {
console.log(`[Error]: failed to parse release for darwin`); console.log(`[Error]: failed to parse release for darwin`);
delete updateData.platforms.darwin; delete updateData.platforms.darwin;
@@ -79,6 +94,24 @@ async function resolveRelease() {
console.log(`[Error]: failed to parse release for win64`); console.log(`[Error]: failed to parse release for win64`);
delete updateData.platforms.win64; delete updateData.platforms.win64;
} }
if (!linux.url) {
console.log(`[Error]: failed to parse release for linux`);
delete updateData.platforms.linux;
}
// 生成一个代理github的更新文件
// 使用 https://hub.fastgit.xyz/ 做github资源的加速
const updateDataNew = JSON.parse(JSON.stringify(updateData));
Object.keys(updateDataNew.platforms).forEach((key) => {
if (updateDataNew.platforms[key]) {
updateDataNew.platforms[key].url = updateDataNew.platforms[
key
].url.replace("https://github.com/", "https://hub.fastgit.xyz/");
} else {
console.log(`[Error]: updateDataNew.platforms.${key} is null`);
}
});
// update the update.json // update the update.json
const { data: updateRelease } = await github.rest.repos.getReleaseByTag({ const { data: updateRelease } = await github.rest.repos.getReleaseByTag({
@@ -86,22 +119,36 @@ async function resolveRelease() {
tag: UPDATE_TAG_NAME, tag: UPDATE_TAG_NAME,
}); });
// delete the old assets
for (let asset of updateRelease.assets) { for (let asset of updateRelease.assets) {
if (asset.name === UPDATE_JSON_FILE) { if (asset.name === UPDATE_JSON_FILE) {
await github.rest.repos.deleteReleaseAsset({ await github.rest.repos.deleteReleaseAsset({
...options, ...options,
asset_id: asset.id, asset_id: asset.id,
}); });
break; }
if (asset.name === UPDATE_JSON_PROXY) {
await github.rest.repos
.deleteReleaseAsset({ ...options, asset_id: asset.id })
.catch(console.error); // do not break the pipeline
} }
} }
// upload assets
await github.rest.repos.uploadReleaseAsset({ await github.rest.repos.uploadReleaseAsset({
...options, ...options,
release_id: updateRelease.id, release_id: updateRelease.id,
name: UPDATE_JSON_FILE, name: UPDATE_JSON_FILE,
data: JSON.stringify(updateData, null, 2), data: JSON.stringify(updateData, null, 2),
}); });
await github.rest.repos.uploadReleaseAsset({
...options,
release_id: updateRelease.id,
name: UPDATE_JSON_PROXY,
data: JSON.stringify(updateDataNew, null, 2),
});
} }
// get the signature file content // get the signature file content

44
scripts/updatelog.mjs Normal file
View File

@@ -0,0 +1,44 @@
import fs from "fs-extra";
import path from "path";
const UPDATE_LOG = "UPDATELOG.md";
// parse the UPDATELOG.md
export async function resolveUpdateLog(tag) {
const cwd = process.cwd();
const reTitle = /^## v[\d\.]+/;
const reEnd = /^---/;
const file = path.join(cwd, UPDATE_LOG);
if (!(await fs.pathExists(file))) {
throw new Error("could not found UPDATELOG.md");
}
const data = await fs.readFile(file).then((d) => d.toString("utf8"));
const map = {};
let p = "";
data.split("\n").forEach((line) => {
if (reTitle.test(line)) {
p = line.slice(3).trim();
if (!map[p]) {
map[p] = [];
} else {
throw new Error(`Tag ${p} dup`);
}
} else if (reEnd.test(line)) {
p = "";
} else if (p) {
map[p].push(line);
}
});
if (!map[tag]) {
throw new Error(`could not found "${tag}" in UPDATELOG.md`);
}
return map[tag].join("\n").trim();
}

View File

@@ -2,5 +2,5 @@
# will have compiled files and executables # will have compiled files and executables
/target/ /target/
WixTools WixTools
resources/Country.mmdb resources
sidecar sidecar

View File

@@ -40,3 +40,4 @@ 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 = []

View File

@@ -43,9 +43,10 @@ pub async fn import_profile(
#[tauri::command] #[tauri::command]
pub async fn create_profile( pub async fn create_profile(
item: PrfItem, // partial item: PrfItem, // partial
file_data: Option<String>,
profiles_state: State<'_, ProfilesState>, profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> { ) -> Result<(), String> {
let item = wrap_err!(PrfItem::from(item).await)?; let item = wrap_err!(PrfItem::from(item, file_data).await)?;
let mut profiles = profiles_state.0.lock().unwrap(); let mut profiles = profiles_state.0.lock().unwrap();
wrap_err!(profiles.append_item(item)) wrap_err!(profiles.append_item(item))
@@ -279,14 +280,13 @@ pub fn get_verge_config(verge_state: State<'_, VergeState>) -> Result<VergeConfi
#[tauri::command] #[tauri::command]
pub fn patch_verge_config( pub fn patch_verge_config(
payload: VergeConfig, payload: VergeConfig,
app_handle: tauri::AppHandle,
clash_state: State<'_, ClashState>, clash_state: State<'_, ClashState>,
verge_state: State<'_, VergeState>, verge_state: State<'_, VergeState>,
profiles_state: State<'_, ProfilesState>, profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> { ) -> Result<(), String> {
let tun_mode = payload.enable_tun_mode.clone(); 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 tun mode // change tun mode
if tun_mode.is_some() { if tun_mode.is_some() {
@@ -298,6 +298,18 @@ pub fn patch_verge_config(
wrap_err!(clash.activate(&profiles, false))?; wrap_err!(clash.activate(&profiles, false))?;
} }
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();
}
Ok(()) Ok(())
} }
@@ -348,24 +360,26 @@ fn open_path_cmd(path: PathBuf, err_str: &str) -> Result<(), String> {
match result { match result {
Ok(child) => match child.wait_with_output() { Ok(child) => match child.wait_with_output() {
Ok(out) => { Ok(out) => {
// 退出码不为0 不一定没有调用成功
// 因此仅做warn log且不返回错误
if let Some(code) = out.status.code() { if let Some(code) = out.status.code() {
if code != 0 { if code != 0 {
log::error!( log::warn!("failed to open {:?} (code {})", &path, code);
"failed to open path {:?} for {} (code {code})", log::warn!(
&path, "open cmd stdout: {}, stderr: {}",
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr), String::from_utf8_lossy(&out.stderr),
); );
return Err(err_str.into());
} }
} }
} }
Err(err) => { Err(err) => {
log::error!("failed to open path {:?} for {err}", &path); log::error!("failed to open {:?} for {err}", &path);
return Err(err_str.into()); return Err(err_str.into());
} }
}, },
Err(err) => { Err(err) => {
log::error!("failed to open path {:?} for {err}", &path); log::error!("failed to open {:?} for {err}", &path);
return Err(err_str.into()); return Err(err_str.into());
} }
} }

View File

@@ -192,71 +192,109 @@ impl Clash {
verge: &mut Verge, verge: &mut Verge,
profiles: &mut Profiles, profiles: &mut Profiles,
) -> Result<()> { ) -> Result<()> {
for (key, value) in patch.iter() { let mix_port_key = Value::from("mixed-port");
let mut port = None;
for (key, value) in patch.into_iter() {
let value = value.clone(); let value = value.clone();
let key_str = key.as_str().clone().unwrap_or("");
// restart the clash // check whether the mix_port is changed
if key_str == "mixed-port" { if key == mix_port_key {
self.restart_sidecar(profiles)?; if value.is_number() {
port = value.as_i64().as_ref().map(|n| n.to_string());
let port = if value.is_number() {
match value.as_i64().clone() {
Some(num) => Some(format!("{num}")),
None => None,
}
} else { } else {
match value.as_str().clone() { port = value.as_str().as_ref().map(|s| s.to_string());
Some(num) => Some(num.into()), }
None => None,
}
};
verge.init_sysproxy(port);
} }
self.config.insert(key.clone(), value); self.config.insert(key.clone(), value);
} }
self.save_config()
self.save_config()?;
if let Some(port) = port {
self.restart_sidecar(profiles)?;
verge.init_sysproxy(Some(port));
}
Ok(())
} }
/// enable tun mode /// enable tun mode
/// only revise the config and restart the /// only revise the config and restart the
pub fn tun_mode(&mut self, enable: bool) -> Result<()> { pub fn tun_mode(&mut self, enable: bool) -> Result<()> {
let tun_key = Value::String("tun".into()); // Windows 需要wintun.dll文件
let tun_val = self.config.get(&tun_key); #[cfg(target_os = "windows")]
if enable {
let mut new_val = Mapping::new(); let wintun_dll = dirs::app_home_dir().join("wintun.dll");
if !wintun_dll.exists() {
if tun_val.is_some() && tun_val.as_ref().unwrap().is_mapping() { bail!("failed to enable TUN for missing `wintun.dll`");
new_val = tun_val.as_ref().unwrap().as_mapping().unwrap().clone(); }
} }
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());
if $map.contains_key(&ret_key) { $map.insert(ret_key, Value::from($val));
$map[&ret_key] = $val;
} else {
$map.insert(ret_key, $val);
}
}; };
} }
// if key not exists then append value
macro_rules! append { macro_rules! append {
($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());
if !$map.contains_key(&ret_key) { if !$map.contains_key(&ret_key) {
$map.insert(ret_key, $val); $map.insert(ret_key, Value::from($val));
} }
}; };
} }
revise!(new_val, "enable", Value::from(enable)); // tun config
append!(new_val, "stack", Value::from("gvisor")); let tun_val = self.config.get(&Value::from("tun"));
append!(new_val, "auto-route", Value::from(true)); let mut new_tun = Mapping::new();
append!(new_val, "auto-detect-interface", Value::from(true));
revise!(self.config, "tun", Value::from(new_val)); if tun_val.is_some() && tun_val.as_ref().unwrap().is_mapping() {
new_tun = tun_val.as_ref().unwrap().as_mapping().unwrap().clone();
}
revise!(new_tun, "enable", enable);
append!(new_tun, "stack", "gvisor");
append!(new_tun, "dns-hijack", vec!["198.18.0.2:53"]);
append!(new_tun, "auto-route", true);
append!(new_tun, "auto-detect-interface", true);
revise!(self.config, "tun", new_tun);
// dns config
let dns_val = self.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);
append!(new_dns, "enhanced-mode", "fake-ip");
append!(
new_dns,
"nameserver",
vec!["114.114.114.114", "223.5.5.5", "8.8.8.8"]
);
append!(new_dns, "fallback", vec![] as Vec<&str>);
#[cfg(target_os = "windows")]
append!(
new_dns,
"fake-ip-filter",
vec![
"dns.msftncsi.com",
"www.msftncsi.com",
"www.msftconnecttest.com"
]
);
revise!(self.config, "dns", new_dns);
self.save_config() self.save_config()
} }

View File

@@ -119,7 +119,7 @@ impl Default for PrfItem {
impl PrfItem { impl PrfItem {
/// From partial item /// From partial item
/// must contain `itype` /// must contain `itype`
pub async fn from(item: PrfItem) -> Result<PrfItem> { pub async fn from(item: PrfItem, file_data: Option<String>) -> Result<PrfItem> {
if item.itype.is_none() { if item.itype.is_none() {
bail!("type should not be null"); bail!("type should not be null");
} }
@@ -137,7 +137,7 @@ impl PrfItem {
"local" => { "local" => {
let name = item.name.unwrap_or("Local File".into()); let name = item.name.unwrap_or("Local File".into());
let desc = item.desc.unwrap_or("".into()); let desc = item.desc.unwrap_or("".into());
PrfItem::from_local(name, desc) PrfItem::from_local(name, desc, file_data)
} }
"merge" => { "merge" => {
let name = item.name.unwrap_or("Merge".into()); let name = item.name.unwrap_or("Merge".into());
@@ -155,7 +155,7 @@ impl PrfItem {
/// ## Local type /// ## Local type
/// create a new item from name/desc /// create a new item from name/desc
pub fn from_local(name: String, desc: String) -> Result<PrfItem> { pub fn from_local(name: String, desc: String, file_data: Option<String>) -> Result<PrfItem> {
let uid = help::get_uid("l"); let uid = help::get_uid("l");
let file = format!("{uid}.yaml"); let file = format!("{uid}.yaml");
@@ -170,7 +170,7 @@ impl PrfItem {
extra: None, extra: None,
option: None, option: None,
updated: Some(help::get_now()), updated: Some(help::get_now()),
file_data: Some(tmpl::ITEM_LOCAL.into()), file_data: Some(file_data.unwrap_or(tmpl::ITEM_LOCAL.into())),
}) })
} }

View File

@@ -133,37 +133,31 @@ impl Verge {
} }
/// init the auto launch /// init the auto launch
pub fn init_launch(&mut self) { pub fn init_launch(&mut self) -> Result<()> {
let app_exe = current_exe().unwrap(); let app_exe = current_exe().unwrap();
let app_exe = dunce::canonicalize(app_exe).unwrap(); let app_exe = dunce::canonicalize(app_exe).unwrap();
let app_name = app_exe.file_stem().unwrap().to_str().unwrap(); let app_name = app_exe.file_stem().unwrap().to_str().unwrap();
let app_path = app_exe.as_os_str().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() let auto = AutoLaunchBuilder::new()
.set_app_name(app_name) .set_app_name(app_name)
.set_app_path(app_path) .set_app_path(app_path)
.build(); .build();
if let Some(enable) = self.config.enable_auto_launch.as_ref() {
// fix issue #26
if *enable {
auto.enable()?;
}
}
self.auto_launch = Some(auto); self.auto_launch = Some(auto);
}
/// sync the startup when run the app
pub fn sync_launch(&self) -> Result<()> {
let enable = self.config.enable_auto_launch.clone().unwrap_or(false);
if !enable {
return Ok(());
}
if self.auto_launch.is_none() {
bail!("should init the auto launch first");
}
let auto_launch = self.auto_launch.clone().unwrap();
let is_enabled = auto_launch.is_enabled().unwrap_or(false);
if !is_enabled {
auto_launch.enable()?;
}
Ok(()) Ok(())
} }

View File

@@ -8,7 +8,10 @@ mod core;
mod states; mod states;
mod utils; mod utils;
use crate::utils::{resolve, server}; use crate::{
core::VergeConfig,
utils::{resolve, server},
};
use tauri::{ use tauri::{
api, CustomMenuItem, Manager, SystemTray, SystemTrayEvent, SystemTrayMenu, SystemTrayMenuItem, api, CustomMenuItem, Manager, SystemTray, SystemTrayEvent, SystemTrayMenu, SystemTrayMenuItem,
}; };
@@ -21,6 +24,7 @@ fn main() -> std::io::Result<()> {
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("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"));
@@ -40,6 +44,31 @@ fn main() -> std::io::Result<()> {
window.show().unwrap(); window.show().unwrap();
window.set_focus().unwrap(); window.set_focus().unwrap();
} }
"system_proxy" => {
let verge_state = app_handle.state::<states::VergeState>();
let mut verge = verge_state.0.lock().unwrap();
let old_value = verge.config.enable_system_proxy.clone().unwrap_or(false);
let new_value = !old_value;
match verge.patch_config(VergeConfig {
enable_system_proxy: Some(new_value),
..VergeConfig::default()
}) {
Ok(_) => {
app_handle
.tray_handle()
.get_item(id.as_str())
.set_selected(new_value)
.unwrap();
// update verge config
let window = app_handle.get_window("main").unwrap();
window.emit("verge://refresh-verge-config", "yes").unwrap();
}
Err(err) => log::error!("{err}"),
}
}
"restart_clash" => { "restart_clash" => {
let clash_state = app_handle.state::<states::ClashState>(); let clash_state = app_handle.state::<states::ClashState>();
let profiles_state = app_handle.state::<states::ProfilesState>(); let profiles_state = app_handle.state::<states::ProfilesState>();
@@ -55,13 +84,12 @@ fn main() -> std::io::Result<()> {
} }
_ => {} _ => {}
}, },
#[cfg(target_os = "windows")]
SystemTrayEvent::LeftClick { .. } => { SystemTrayEvent::LeftClick { .. } => {
if cfg![target_os = "windows"] { let window = app_handle.get_window("main").unwrap();
let window = app_handle.get_window("main").unwrap(); window.unminimize().unwrap();
window.unminimize().unwrap(); window.show().unwrap();
window.show().unwrap(); window.set_focus().unwrap();
window.set_focus().unwrap();
}
} }
_ => {} _ => {}
}) })

View File

@@ -5,12 +5,22 @@ use tauri::{
Env, PackageInfo, Env, PackageInfo,
}; };
#[cfg(not(feature = "verge-dev"))]
static APP_DIR: &str = "clash-verge";
#[cfg(feature = "verge-dev")]
static APP_DIR: &str = "clash-verge-dev";
static CLASH_CONFIG: &str = "config.yaml";
static VERGE_CONFIG: &str = "verge.yaml";
static PROFILE_YAML: &str = "profiles.yaml";
static PROFILE_TEMP: &str = "clash-verge-runtime.yaml";
/// 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() home_dir()
.unwrap() .unwrap()
.join(Path::new(".config")) .join(Path::new(".config"))
.join(Path::new("clash-verge")) .join(Path::new(APP_DIR))
} }
/// get the resources dir /// get the resources dir
@@ -30,11 +40,6 @@ pub fn app_logs_dir() -> PathBuf {
app_home_dir().join("logs") app_home_dir().join("logs")
} }
static CLASH_CONFIG: &str = "config.yaml";
static VERGE_CONFIG: &str = "verge.yaml";
static PROFILE_YAML: &str = "profiles.yaml";
static PROFILE_TEMP: &str = "clash-verge-runtime.yaml";
pub fn clash_path() -> PathBuf { pub fn clash_path() -> PathBuf {
app_home_dir().join(CLASH_CONFIG) app_home_dir().join(CLASH_CONFIG)
} }

View File

@@ -87,4 +87,14 @@ pub fn init_app(package_info: &PackageInfo) {
if !mmdb_path.exists() && mmdb_tmpl.exists() { if !mmdb_path.exists() && mmdb_tmpl.exists() {
fs::copy(mmdb_tmpl, mmdb_path).unwrap(); fs::copy(mmdb_tmpl, mmdb_path).unwrap();
} }
// copy the wintun.dll
#[cfg(target_os = "windows")]
{
let wintun_path = app_dir.join("wintun.dll");
let wintun_tmpl = res_dir.join("wintun.dll");
if !wintun_path.exists() && wintun_tmpl.exists() {
fs::copy(wintun_tmpl, wintun_path).unwrap();
}
}
} }

View File

@@ -38,8 +38,14 @@ pub fn resolve_setup(app: &App) {
clash.tun_mode(true).unwrap(); clash.tun_mode(true).unwrap();
} }
verge.init_launch(); log_if_err!(verge.init_launch());
log_if_err!(verge.sync_launch());
verge.config.enable_system_proxy.map(|enable| {
log_if_err!(app
.tray_handle()
.get_item("system_proxy")
.set_selected(enable));
});
} }
/// reset system proxy /// reset system proxy

View File

@@ -4,7 +4,10 @@ use port_scanner::local_port_available;
use tauri::{AppHandle, Manager}; use tauri::{AppHandle, Manager};
use warp::Filter; use warp::Filter;
#[cfg(not(feature = "verge-dev"))]
const SERVER_PORT: u16 = 33333; const SERVER_PORT: u16 = 33333;
#[cfg(feature = "verge-dev")]
const SERVER_PORT: u16 = 11233;
/// check whether there is already exists /// check whether there is already exists
pub fn check_singleton() -> Result<(), ()> { pub fn check_singleton() -> Result<(), ()> {

View File

@@ -1,7 +1,7 @@
{ {
"package": { "package": {
"productName": "Clash Verge", "productName": "Clash Verge",
"version": "0.0.23" "version": "0.0.24"
}, },
"build": { "build": {
"distDir": "../dist", "distDir": "../dist",
@@ -52,7 +52,8 @@
"updater": { "updater": {
"active": true, "active": true,
"endpoints": [ "endpoints": [
"https://github.com/zzzgydi/clash-verge/releases/download/updater/update.json" "https://github.com/zzzgydi/clash-verge/releases/download/updater/update.json",
"https://hub.fastgit.xyz/zzzgydi/clash-verge/releases/download/updater/update-proxy.json"
], ],
"dialog": false, "dialog": false,
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDExNUFBNTBBN0FDNEFBRTUKUldUbHFzUjZDcVZhRVRJM25NS3NkSFlFVElxUkNZMzZ6bHUwRVJjb2F3alJXVzRaeDdSaTA2YWYK" "pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDExNUFBNTBBN0FDNEFBRTUKUldUbHFzUjZDcVZhRVRJM25NS3NkSFlFVElxUkNZMzZ6bHUwRVJjb2F3alJXVzRaeDdSaTA2YWYK"

View File

@@ -72,7 +72,7 @@
.the-content { .the-content {
position: absolute; position: absolute;
top: 30px; top: 0;
left: 0; left: 0;
right: 2px; right: 2px;
bottom: 10px; bottom: 10px;
@@ -80,8 +80,8 @@
} }
} }
.macos.layout { .windows.layout {
.layout__right .the-content { .layout__right .the-content {
top: 0; top: 30px;
} }
} }

View File

@@ -1,4 +1,20 @@
import dayjs from "dayjs";
import { useLockFn } from "ahooks";
import { styled, Box, ListItem, IconButton, ListItemText } from "@mui/material";
import { CloseRounded } from "@mui/icons-material";
import { ApiType } from "../../services/types"; import { ApiType } from "../../services/types";
import { deleteConnection } from "../../services/api";
const Tag = styled(Box)(({ theme }) => ({
display: "inline-block",
fontSize: "12px",
padding: "0 4px",
lineHeight: 1.375,
border: "1px solid #ccc",
borderRadius: 4,
marginRight: "0.1em",
transform: "scale(0.92)",
}));
interface Props { interface Props {
value: ApiType.ConnectionsItem; value: ApiType.ConnectionsItem;
@@ -7,7 +23,34 @@ interface Props {
const ConnectionItem = (props: Props) => { const ConnectionItem = (props: Props) => {
const { value } = props; const { value } = props;
return <div>{value.metadata.host || value.metadata.destinationIP}</div>; const onDelete = useLockFn(async () => deleteConnection(value.id));
return (
<ListItem
dense
secondaryAction={
<IconButton edge="end" onClick={onDelete}>
<CloseRounded />
</IconButton>
}
>
<ListItemText
primary={value.metadata.host || value.metadata.destinationIP}
secondary={
<Box>
<Tag sx={{ textTransform: "uppercase", color: "success" }}>
{value.metadata.network}
</Tag>
<Tag>{value.metadata.type}</Tag>
{value.chains.length > 0 && (
<Tag>{value.chains[value.chains.length - 1]}</Tag>
)}
<Tag>{dayjs(value.start).fromNow()}</Tag>
</Box>
}
/>
</ListItem>
);
}; };
export default ConnectionItem; export default ConnectionItem;

View File

@@ -32,7 +32,9 @@ const UpdateButton = (props: Props) => {
New New
</Button> </Button>
<UpdateDialog open={dialogOpen} onClose={() => setDialogOpen(false)} /> {dialogOpen && (
<UpdateDialog open={dialogOpen} onClose={() => setDialogOpen(false)} />
)}
</> </>
); );
}; };

View File

@@ -1,12 +1,14 @@
import useSWR from "swr"; import useSWR from "swr";
import { useState } from "react"; import snarkdown from "snarkdown";
import { useState, useMemo } from "react";
import { import {
Box,
Button, Button,
Dialog, Dialog,
DialogActions, DialogActions,
DialogContent, DialogContent,
DialogContentText,
DialogTitle, DialogTitle,
styled,
} 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";
@@ -18,6 +20,10 @@ interface Props {
onClose: () => void; onClose: () => void;
} }
const UpdateLog = styled(Box)(() => ({
"h1,h2,h3,ul,ol,p": { margin: "0.5em 0", color: "inherit" },
}));
let uploadingState = false; let uploadingState = false;
const UpdateDialog = (props: Props) => { const UpdateDialog = (props: Props) => {
@@ -46,19 +52,29 @@ const UpdateDialog = (props: Props) => {
} }
}; };
// markdown parser
const parseContent = useMemo(() => {
if (!updateInfo?.manifest?.body) {
return "New Version is available";
}
return snarkdown(updateInfo?.manifest?.body);
}, [updateInfo]);
return ( return (
<Dialog open={open} onClose={onClose}> <Dialog open={open} onClose={onClose}>
<DialogTitle>New Version v{updateInfo?.manifest?.version}</DialogTitle> <DialogTitle>New Version v{updateInfo?.manifest?.version}</DialogTitle>
<DialogContent sx={{ minWidth: 360, maxWidth: 400, maxHeight: "50vh" }}> <DialogContent sx={{ minWidth: 360, maxWidth: 400, maxHeight: "50vh" }}>
<DialogContentText>{updateInfo?.manifest?.body}</DialogContentText> <UpdateLog dangerouslySetInnerHTML={{ __html: parseContent }} />
</DialogContent> </DialogContent>
<DialogActions> <DialogActions>
<Button onClick={onClose}>Cancel</Button> <Button onClick={onClose}>Cancel</Button>
<Button <Button
variant="contained"
autoFocus autoFocus
onClick={onUpdate} variant="contained"
disabled={uploading} disabled={uploading}
onClick={onUpdate}
> >
Update Update
</Button> </Button>

View File

@@ -0,0 +1,61 @@
import { useRef, useState } from "react";
import { useLockFn } from "ahooks";
import { Box, Button, Typography } from "@mui/material";
interface Props {
onChange: (value: string) => void;
}
const FileInput = (props: Props) => {
const { onChange } = props;
// file input
const inputRef = useRef<any>();
const [loading, setLoading] = useState(false);
const [fileName, setFileName] = useState("");
const onFileInput = useLockFn(async (e: any) => {
const file = e.target.files?.[0] as File;
if (!file) return;
setFileName(file.name);
setLoading(true);
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (event) => {
resolve(null);
onChange(event.target?.result as string);
};
reader.onerror = reject;
reader.readAsText(file);
}).finally(() => setLoading(false));
});
return (
<Box sx={{ mt: 2, mb: 1, display: "flex", alignItems: "center" }}>
<Button
variant="outlined"
sx={{ flex: "none" }}
onClick={() => inputRef.current?.click()}
>
Choose File
</Button>
<input
type="file"
accept=".yaml,.yml"
ref={inputRef}
style={{ display: "none" }}
onChange={onFileInput}
/>
<Typography noWrap sx={{ ml: 1 }}>
{loading ? "Loading..." : fileName}
</Typography>
</Box>
);
};
export default FileInput;

View File

@@ -2,6 +2,7 @@ import dayjs from "dayjs";
import { useLockFn } from "ahooks"; import { useLockFn } from "ahooks";
import { useSWRConfig } from "swr"; import { useSWRConfig } from "swr";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { import {
alpha, alpha,
Box, Box,
@@ -16,13 +17,10 @@ import {
import { RefreshRounded } from "@mui/icons-material"; import { RefreshRounded } from "@mui/icons-material";
import { CmdType } from "../../services/types"; import { CmdType } from "../../services/types";
import { updateProfile, deleteProfile, viewProfile } from "../../services/cmds"; import { updateProfile, deleteProfile, viewProfile } from "../../services/cmds";
import relativeTime from "dayjs/plugin/relativeTime";
import parseTraffic from "../../utils/parse-traffic"; import parseTraffic from "../../utils/parse-traffic";
import ProfileEdit from "./profile-edit"; import ProfileEdit from "./profile-edit";
import Notice from "../base/base-notice"; import Notice from "../base/base-notice";
dayjs.extend(relativeTime);
const Wrapper = styled(Box)(({ theme }) => ({ const Wrapper = styled(Box)(({ theme }) => ({
width: "100%", width: "100%",
display: "block", display: "block",
@@ -51,6 +49,7 @@ interface Props {
const ProfileItem = (props: Props) => { const ProfileItem = (props: Props) => {
const { selected, itemData, onSelect } = props; const { selected, itemData, onSelect } = props;
const { t } = useTranslation();
const { mutate } = useSWRConfig(); const { mutate } = useSWRConfig();
const [loading, setLoading] = useState(loadingCache[itemData.uid] ?? false); const [loading, setLoading] = useState(loadingCache[itemData.uid] ?? false);
const [anchorEl, setAnchorEl] = useState<any>(null); const [anchorEl, setAnchorEl] = useState<any>(null);
@@ -271,7 +270,7 @@ const ProfileItem = (props: Props) => {
onClick={item.handler} onClick={item.handler}
sx={{ minWidth: 133 }} sx={{ minWidth: 133 }}
> >
{item.label} {t(item.label)}
</MenuItem> </MenuItem>
))} ))}
</Menu> </Menu>

View File

@@ -1,5 +1,6 @@
import dayjs from "dayjs"; import dayjs from "dayjs";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { import {
alpha, alpha,
Box, Box,
@@ -11,13 +12,10 @@ import {
} from "@mui/material"; } from "@mui/material";
import { CmdType } from "../../services/types"; import { CmdType } from "../../services/types";
import { viewProfile } from "../../services/cmds"; import { viewProfile } from "../../services/cmds";
import relativeTime from "dayjs/plugin/relativeTime";
import ProfileEdit from "./profile-edit"; import ProfileEdit from "./profile-edit";
import Notice from "../base/base-notice"; import Notice from "../base/base-notice";
import enhance from "../../services/enhance"; import enhance from "../../services/enhance";
dayjs.extend(relativeTime);
const Wrapper = styled(Box)(({ theme }) => ({ const Wrapper = styled(Box)(({ theme }) => ({
width: "100%", width: "100%",
display: "block", display: "block",
@@ -54,6 +52,8 @@ const ProfileMore = (props: Props) => {
} = props; } = props;
const { uid, type } = itemData; const { uid, type } = itemData;
const { t } = useTranslation();
const [anchorEl, setAnchorEl] = useState<any>(null); const [anchorEl, setAnchorEl] = useState<any>(null);
const [position, setPosition] = useState({ left: 0, top: 0 }); const [position, setPosition] = useState({ left: 0, top: 0 });
const [editOpen, setEditOpen] = useState(false); const [editOpen, setEditOpen] = useState(false);
@@ -221,7 +221,7 @@ const ProfileMore = (props: Props) => {
onClick={item.handler} onClick={item.handler}
sx={{ minWidth: 133 }} sx={{ minWidth: 133 }}
> >
{item.label} {t(item.label)}
</MenuItem> </MenuItem>
))} ))}
</Menu> </Menu>

View File

@@ -1,4 +1,4 @@
import { useState } from "react"; import { useRef, useState } from "react";
import { useSWRConfig } from "swr"; import { useSWRConfig } from "swr";
import { useLockFn, useSetState } from "ahooks"; import { useLockFn, useSetState } from "ahooks";
import { import {
@@ -17,6 +17,7 @@ import {
import { Settings } from "@mui/icons-material"; import { Settings } from "@mui/icons-material";
import { createProfile } from "../../services/cmds"; import { createProfile } from "../../services/cmds";
import Notice from "../base/base-notice"; import Notice from "../base/base-notice";
import FileInput from "./file-input";
interface Props { interface Props {
open: boolean; open: boolean;
@@ -37,9 +38,10 @@ const ProfileNew = (props: Props) => {
}); });
const [showOpt, setShowOpt] = useState(false); const [showOpt, setShowOpt] = useState(false);
const [option, setOption] = useSetState({ // can add more option
user_agent: "", const [option, setOption] = useSetState({ user_agent: "" });
}); // able to add more option // file input
const fileDataRef = useRef<string | null>(null);
const onCreate = useLockFn(async () => { const onCreate = useLockFn(async () => {
if (!form.type) { if (!form.type) {
@@ -55,10 +57,15 @@ const ProfileNew = (props: Props) => {
} }
const option_ = form.type === "remote" ? option : undefined; const option_ = form.type === "remote" ? option : undefined;
await createProfile({ ...form, name, option: option_ }); const item = { ...form, name, option: option_ };
const fileData = form.type === "local" ? fileDataRef.current : null;
await createProfile(item, fileData);
setForm({ type: "remote", name: "", desc: "", url: "" }); setForm({ type: "remote", name: "", desc: "", url: "" });
setOption({ user_agent: "" }); setOption({ user_agent: "" });
setShowOpt(false); setShowOpt(false);
fileDataRef.current = null;
mutate("getProfiles"); mutate("getProfiles");
onClose(); onClose();
@@ -97,6 +104,7 @@ const ProfileNew = (props: Props) => {
<TextField <TextField
{...textFieldProps} {...textFieldProps}
label="Name" label="Name"
autoComplete="off"
value={form.name} value={form.name}
onChange={(e) => setForm({ name: e.target.value })} onChange={(e) => setForm({ name: e.target.value })}
/> />
@@ -104,6 +112,7 @@ const ProfileNew = (props: Props) => {
<TextField <TextField
{...textFieldProps} {...textFieldProps}
label="Descriptions" label="Descriptions"
autoComplete="off"
value={form.desc} value={form.desc}
onChange={(e) => setForm({ desc: e.target.value })} onChange={(e) => setForm({ desc: e.target.value })}
/> />
@@ -112,15 +121,21 @@ const ProfileNew = (props: Props) => {
<TextField <TextField
{...textFieldProps} {...textFieldProps}
label="Subscription Url" label="Subscription Url"
autoComplete="off"
value={form.url} value={form.url}
onChange={(e) => setForm({ url: e.target.value })} onChange={(e) => setForm({ url: e.target.value })}
/> />
)} )}
{form.type === "local" && (
<FileInput onChange={(val) => (fileDataRef.current = val)} />
)}
{showOpt && ( {showOpt && (
<TextField <TextField
{...textFieldProps} {...textFieldProps}
label="User Agent" label="User Agent"
autoComplete="off"
value={option.user_agent} value={option.user_agent}
onChange={(e) => setOption({ user_agent: e.target.value })} onChange={(e) => setOption({ user_agent: e.target.value })}
/> />

View File

@@ -17,6 +17,18 @@
"Profile URL": "Profile URL", "Profile URL": "Profile URL",
"Import": "Import", "Import": "Import",
"New": "New", "New": "New",
"Close All": "Close All",
"Select": "Select",
"Edit": "Edit",
"File": "File",
"Update": "Update",
"Update(Proxy)": "Update(Proxy)",
"Delete": "Delete",
"Enable": "Enable",
"Disable": "Disable",
"Refresh": "Refresh",
"To Top": "To Top",
"To End": "To End",
"Settings": "Settings", "Settings": "Settings",
"Clash Setting": "Clash Setting", "Clash Setting": "Clash Setting",

View File

@@ -17,6 +17,18 @@
"Profile URL": "配置文件链接", "Profile URL": "配置文件链接",
"Import": "导入", "Import": "导入",
"New": "新建", "New": "新建",
"Close All": "关闭全部",
"Select": "使用",
"Edit": "编辑信息",
"File": "打开文件",
"Update": "更新",
"Update(Proxy)": "更新(代理)",
"Delete": "删除",
"Enable": "启用",
"Disable": "禁用",
"Refresh": "刷新",
"To Top": "移到最前",
"To End": "移到末尾",
"Settings": "设置", "Settings": "设置",
"Clash Setting": "Clash 设置", "Clash Setting": "Clash 设置",

View File

@@ -1,4 +1,6 @@
import dayjs from "dayjs";
import i18next from "i18next"; import i18next from "i18next";
import relativeTime from "dayjs/plugin/relativeTime";
import useSWR, { SWRConfig, useSWRConfig } from "swr"; import useSWR, { SWRConfig, useSWRConfig } from "swr";
import { useEffect, useMemo } from "react"; import { useEffect, useMemo } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
@@ -14,8 +16,11 @@ import LayoutItem from "../components/layout/layout-item";
import LayoutControl from "../components/layout/layout-control"; import LayoutControl from "../components/layout/layout-control";
import LayoutTraffic from "../components/layout/layout-traffic"; import LayoutTraffic from "../components/layout/layout-traffic";
import UpdateButton from "../components/layout/update-button"; import UpdateButton from "../components/layout/update-button";
import "dayjs/locale/zh-cn";
const isMacos = navigator.userAgent.includes("Mac OS X"); dayjs.extend(relativeTime);
const isWinOs = /win64|win32/i.test(navigator.userAgent);
const Layout = () => { const Layout = () => {
const { t } = useTranslation(); const { t } = useTranslation();
@@ -36,10 +41,14 @@ const Layout = () => {
mutate("getProxies"); mutate("getProxies");
mutate("getClashConfig"); mutate("getClashConfig");
}); });
// update the verge config
listen("verge://refresh-verge-config", () => mutate("getVergeConfig"));
}, []); }, []);
useEffect(() => { useEffect(() => {
if (data?.language) { if (data?.language) {
dayjs.locale(data.language === "zh" ? "zh-cn" : data.language);
i18next.changeLanguage(data.language); i18next.changeLanguage(data.language);
} }
}, [data?.language]); }, [data?.language]);
@@ -76,8 +85,12 @@ const Layout = () => {
<Paper <Paper
square square
elevation={0} elevation={0}
className={`${isMacos ? "macos " : ""}layout`} className={`${isWinOs ? "windows " : ""}layout`}
onPointerDown={onDragging} onPointerDown={onDragging}
onContextMenu={(e) => {
// only prevent it on Windows
if (isWinOs) e.preventDefault();
}}
sx={[ sx={[
(theme) => ({ (theme) => ({
bgcolor: alpha(theme.palette.background.paper, blur ? 0.85 : 1), bgcolor: alpha(theme.palette.background.paper, blur ? 0.85 : 1),
@@ -105,7 +118,7 @@ const Layout = () => {
</div> </div>
<div className="layout__right" data-windrag> <div className="layout__right" data-windrag>
{!isMacos && ( {isWinOs && (
<div className="the-bar"> <div className="the-bar">
<LayoutControl /> <LayoutControl />
</div> </div>

View File

@@ -1,9 +1,10 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { Paper } from "@mui/material"; import { useLockFn } from "ahooks";
import { Button, Paper } 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";
import { getInfomation } from "../services/api"; 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";
@@ -29,10 +30,26 @@ const ConnectionsPage = () => {
return () => ws?.close(); return () => ws?.close();
}, []); }, []);
const onCloseAll = useLockFn(closeAllConnections);
return ( return (
<BasePage title={t("Connections")} contentStyle={{ height: "100%" }}> <BasePage
title={t("Connections")}
contentStyle={{ height: "100%" }}
header={
<Button
size="small"
sx={{ mt: 1 }}
variant="contained"
onClick={onCloseAll}
>
{t("Close All")}
</Button>
}
>
<Paper sx={{ boxShadow: 2, height: "100%" }}> <Paper sx={{ boxShadow: 2, height: "100%" }}>
<Virtuoso <Virtuoso
initialTopMostItemIndex={999}
data={conn.connections} data={conn.connections}
itemContent={(index, item) => <ConnectionItem value={item} />} itemContent={(index, item) => <ConnectionItem value={item} />}
/> />

View File

@@ -141,3 +141,15 @@ export async function getProviders() {
const response = await instance.get<any, any>("/providers/proxies"); const response = await instance.get<any, any>("/providers/proxies");
return response.providers as any; return response.providers as any;
} }
// Close specific connection
export async function deleteConnection(id: string) {
const instance = await getAxios();
await instance.delete<any, any>(`/connections/${encodeURIComponent(id)}`);
}
// Close all connections
export async function closeAllConnections() {
const instance = await getAxios();
await instance.delete<any, any>(`/connections`);
}

View File

@@ -14,8 +14,11 @@ export async function enhanceProfiles() {
return invoke<void>("enhance_profiles"); return invoke<void>("enhance_profiles");
} }
export async function createProfile(item: Partial<CmdType.ProfileItem>) { export async function createProfile(
return invoke<void>("create_profile", { item }); item: Partial<CmdType.ProfileItem>,
fileData?: string | null
) {
return invoke<void>("create_profile", { item, fileData });
} }
export async function viewProfile(index: string) { export async function viewProfile(index: string) {

View File

@@ -101,6 +101,8 @@ class Enhance {
const payload = event.payload as CmdType.EnhancedPayload; const payload = event.payload as CmdType.EnhancedPayload;
let pdata = payload.current || {}; let pdata = payload.current || {};
let hasScript = false;
for (const each of payload.chain) { for (const each of payload.chain) {
const { uid, type = "" } = each.item; const { uid, type = "" } = each.item;
@@ -109,6 +111,7 @@ class Enhance {
if (type === "script") { if (type === "script") {
// support async main function // support async main function
pdata = await toScript(each.script!, { ...pdata }); pdata = await toScript(each.script!, { ...pdata });
hasScript = true;
} }
// process merge // process merge
@@ -132,6 +135,29 @@ class Enhance {
} }
} }
// If script is never used
// filter other fields
if (!hasScript) {
const validKeys = [
"proxies",
"proxy-providers",
"proxy-groups",
"rule-providers",
"rules",
];
// to lowercase
const newData: any = {};
Object.keys(pdata).forEach((key) => {
const newKey = key.toLowerCase();
if (validKeys.includes(newKey)) {
newData[newKey] = (pdata as any)[key];
}
});
pdata = newData;
}
const result = { data: pdata, status: "ok" }; const result = { data: pdata, status: "ok" };
emit(payload.callback, JSON.stringify(result)).catch(console.error); emit(payload.callback, JSON.stringify(result)).catch(console.error);
}); });

View File

@@ -1831,6 +1831,11 @@ signal-exit@^3.0.2:
resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.7.tgz#a9a1767f8af84155114eaabd73f99273c8f59ad9" resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.7.tgz#a9a1767f8af84155114eaabd73f99273c8f59ad9"
integrity sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ== integrity sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==
snarkdown@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/snarkdown/-/snarkdown-2.0.0.tgz#b1feb4db91b9f94a8ebbd7a50f3e99aee18b1e03"
integrity sha512-MgL/7k/AZdXCTJiNgrO7chgDqaB9FGM/1Tvlcenenb7div6obaDATzs16JhFyHHBGodHT3B7RzRc5qk8pFhg3A==
"source-map-js@>=0.6.2 <2.0.0", source-map-js@^1.0.2: "source-map-js@>=0.6.2 <2.0.0", source-map-js@^1.0.2:
version "1.0.2" version "1.0.2"
resolved "https://registry.yarnpkg.com/source-map-js/-/source-map-js-1.0.2.tgz#adbc361d9c62df380125e7f161f71c826f1e490c" resolved "https://registry.yarnpkg.com/source-map-js/-/source-map-js-1.0.2.tgz#adbc361d9c62df380125e7f161f71c826f1e490c"