Compare commits
25 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5cff4e299b | ||
|
|
bce33639da | ||
|
|
366c465cad | ||
|
|
acc6e05bdc | ||
|
|
4ce15577cd | ||
|
|
98fa4d5e65 | ||
|
|
7fe94076c7 | ||
|
|
b8b0c8fa63 | ||
|
|
e585e87bec | ||
|
|
6a4924bb16 | ||
|
|
ab0d516d91 | ||
|
|
b756ae39d0 | ||
|
|
c15c38ea8f | ||
|
|
743963318f | ||
|
|
ed3fc50858 | ||
|
|
5b886fe6be | ||
|
|
7074bbc405 | ||
|
|
ef314c1707 | ||
|
|
a3e7626dd9 | ||
|
|
5cb5d74eed | ||
|
|
6eee10d46d | ||
|
|
2d95f2b0d6 | ||
|
|
ec41bb9c70 | ||
|
|
2d1780b1cf | ||
|
|
d9ce99887c |
15
.github/workflows/ci.yml
vendored
15
.github/workflows/ci.yml
vendored
@@ -10,7 +10,7 @@ jobs:
|
||||
release:
|
||||
strategy:
|
||||
matrix:
|
||||
os: [windows-latest, macos-11]
|
||||
os: [windows-latest, ubuntu-latest, macos-latest]
|
||||
runs-on: ${{ matrix.os }}
|
||||
if: |
|
||||
startsWith(github.repository, 'zzzgydi') &&
|
||||
@@ -34,6 +34,12 @@ jobs:
|
||||
with:
|
||||
node-version: 14
|
||||
|
||||
- name: Install Dependencies (ubuntu only)
|
||||
if: matrix.os == 'ubuntu-latest'
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libgtk-3-dev webkit2gtk-4.0 libappindicator3-dev librsvg2-dev patchelf
|
||||
|
||||
- name: Get yarn cache dir path
|
||||
id: yarn-cache-dir-path
|
||||
run: echo "::set-output name=dir::$(yarn cache dir)"
|
||||
@@ -68,12 +74,15 @@ jobs:
|
||||
prerelease: true
|
||||
|
||||
- name: Green zip bundle
|
||||
if: matrix.os == 'windows-latest'
|
||||
run: |
|
||||
yarn run green
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
release-update:
|
||||
needs: release
|
||||
runs-on: macos-11
|
||||
runs-on: macos-latest
|
||||
if: |
|
||||
startsWith(github.repository, 'zzzgydi') &&
|
||||
startsWith(github.ref, 'refs/tags/v')
|
||||
@@ -95,7 +104,7 @@ jobs:
|
||||
${{ runner.os }}-yarn-
|
||||
|
||||
- name: Yarn install
|
||||
run: yarn
|
||||
run: yarn install
|
||||
|
||||
- name: Release update.json
|
||||
run: yarn run release
|
||||
|
||||
18
README.md
18
README.md
@@ -11,7 +11,17 @@ A <a href="https://github.com/Dreamacro/clash">Clash</a> GUI based on <a href="h
|
||||
|
||||
## 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
|
||||
|
||||
@@ -33,6 +43,12 @@ Then run
|
||||
yarn dev
|
||||
```
|
||||
|
||||
Or you can build it
|
||||
|
||||
```shell
|
||||
yarn build
|
||||
```
|
||||
|
||||
## Todos
|
||||
|
||||
> This keng is a little big...
|
||||
|
||||
29
UPDATELOG.md
Normal file
29
UPDATELOG.md
Normal 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
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "clash-verge",
|
||||
"version": "0.0.23",
|
||||
"version": "0.0.24",
|
||||
"license": "GPL-3.0",
|
||||
"scripts": {
|
||||
"dev": "tauri dev",
|
||||
@@ -31,6 +31,7 @@
|
||||
"react-router-dom": "^6.2.2",
|
||||
"react-virtuoso": "^2.7.0",
|
||||
"recoil": "^0.6.1",
|
||||
"snarkdown": "^2.0.0",
|
||||
"swr": "^1.2.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -8,16 +8,16 @@ import { execSync } from "child_process";
|
||||
const cwd = process.cwd();
|
||||
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
|
||||
*/
|
||||
function resolveClash() {
|
||||
const { platform, arch } = process;
|
||||
|
||||
const CLASH_URL_PREFIX =
|
||||
"https://github.com/Dreamacro/clash/releases/download/premium/";
|
||||
const CLASH_LATEST_DATE = "2022.03.19";
|
||||
|
||||
// todo
|
||||
const map = {
|
||||
"win32-x64": "clash-windows-amd64",
|
||||
@@ -84,13 +84,55 @@ async function resolveSidecar() {
|
||||
console.log(`[INFO]: gunzip finished`);
|
||||
execSync(`chmod 755 ${sidecarPath}`);
|
||||
console.log(`[INFO]: chmod binary finished`);
|
||||
});
|
||||
})
|
||||
.on("error", (error) => console.error(error));
|
||||
}
|
||||
|
||||
// delete temp dir
|
||||
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)
|
||||
*/
|
||||
@@ -123,4 +165,5 @@ async function downloadFile(url, path) {
|
||||
|
||||
/// main
|
||||
resolveSidecar().catch(console.error);
|
||||
resolveWintun().catch(console.error);
|
||||
resolveMmdb().catch(console.error);
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import fs from "fs-extra";
|
||||
import { createRequire } from "module";
|
||||
import { execSync } from "child_process";
|
||||
import { resolveUpdateLog } from "./updatelog.mjs";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
|
||||
// publish
|
||||
async function resolvePublish() {
|
||||
const flag = process.argv[2] ?? "patch";
|
||||
const packageJson = require("../package.json");
|
||||
@@ -26,6 +28,10 @@ async function resolvePublish() {
|
||||
packageJson.version = nextVersion;
|
||||
tauriJson.package.version = nextVersion;
|
||||
|
||||
// 发布更新前先写更新日志
|
||||
const nextTag = `v${nextVersion}`;
|
||||
await resolveUpdateLog(nextTag);
|
||||
|
||||
await fs.writeFile(
|
||||
"./package.json",
|
||||
JSON.stringify(packageJson, undefined, 2)
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import fetch from "node-fetch";
|
||||
import { getOctokit, context } from "@actions/github";
|
||||
import { resolveUpdateLog } from "./updatelog.mjs";
|
||||
|
||||
const UPDATE_TAG_NAME = "updater";
|
||||
const UPDATE_JSON_FILE = "update.json";
|
||||
const UPDATE_JSON_PROXY = "update-proxy.json";
|
||||
|
||||
/// generate update.json
|
||||
/// upload to update tag's release asset
|
||||
@@ -33,10 +35,11 @@ async function resolveRelease() {
|
||||
|
||||
const updateData = {
|
||||
name: tag.name,
|
||||
notes: latestRelease.body, // use the release body directly
|
||||
notes: await resolveUpdateLog(tag.name), // use updatelog.md
|
||||
pub_date: new Date().toISOString(),
|
||||
platforms: {
|
||||
win64: { signature: "", url: "" },
|
||||
linux: { signature: "", url: "" },
|
||||
darwin: { signature: "", url: "" },
|
||||
},
|
||||
};
|
||||
@@ -48,29 +51,41 @@ async function resolveRelease() {
|
||||
if (/\.msi\.zip$/.test(name)) {
|
||||
updateData.platforms.win64.url = browser_download_url;
|
||||
}
|
||||
// darwin url
|
||||
if (/\.app\.tar\.gz$/.test(name)) {
|
||||
updateData.platforms.darwin.url = browser_download_url;
|
||||
}
|
||||
// win64 signature
|
||||
if (/\.msi\.zip\.sig$/.test(name)) {
|
||||
updateData.platforms.win64.signature = await getSignature(
|
||||
browser_download_url
|
||||
);
|
||||
}
|
||||
|
||||
// darwin url
|
||||
if (/\.app\.tar\.gz$/.test(name)) {
|
||||
updateData.platforms.darwin.url = browser_download_url;
|
||||
}
|
||||
// darwin signature
|
||||
if (/\.app\.tar\.gz\.sig$/.test(name)) {
|
||||
updateData.platforms.darwin.signature = await getSignature(
|
||||
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);
|
||||
console.log(updateData);
|
||||
|
||||
// maybe should test the signature as well
|
||||
const { darwin, win64 } = updateData.platforms;
|
||||
const { darwin, win64, linux } = updateData.platforms;
|
||||
if (!darwin.url) {
|
||||
console.log(`[Error]: failed to parse release for darwin`);
|
||||
delete updateData.platforms.darwin;
|
||||
@@ -79,6 +94,24 @@ async function resolveRelease() {
|
||||
console.log(`[Error]: failed to parse release for 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
|
||||
const { data: updateRelease } = await github.rest.repos.getReleaseByTag({
|
||||
@@ -86,22 +119,36 @@ async function resolveRelease() {
|
||||
tag: UPDATE_TAG_NAME,
|
||||
});
|
||||
|
||||
// delete the old assets
|
||||
for (let asset of updateRelease.assets) {
|
||||
if (asset.name === UPDATE_JSON_FILE) {
|
||||
await github.rest.repos.deleteReleaseAsset({
|
||||
...options,
|
||||
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({
|
||||
...options,
|
||||
release_id: updateRelease.id,
|
||||
name: UPDATE_JSON_FILE,
|
||||
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
|
||||
|
||||
44
scripts/updatelog.mjs
Normal file
44
scripts/updatelog.mjs
Normal 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();
|
||||
}
|
||||
2
src-tauri/.gitignore
vendored
2
src-tauri/.gitignore
vendored
@@ -2,5 +2,5 @@
|
||||
# will have compiled files and executables
|
||||
/target/
|
||||
WixTools
|
||||
resources/Country.mmdb
|
||||
resources
|
||||
sidecar
|
||||
|
||||
@@ -40,3 +40,4 @@ winreg = { version = "0.10", features = ["transactions"] }
|
||||
[features]
|
||||
default = [ "custom-protocol" ]
|
||||
custom-protocol = [ "tauri/custom-protocol" ]
|
||||
verge-dev = []
|
||||
|
||||
@@ -43,9 +43,10 @@ pub async fn import_profile(
|
||||
#[tauri::command]
|
||||
pub async fn create_profile(
|
||||
item: PrfItem, // partial
|
||||
file_data: Option<String>,
|
||||
profiles_state: State<'_, ProfilesState>,
|
||||
) -> 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();
|
||||
|
||||
wrap_err!(profiles.append_item(item))
|
||||
@@ -279,14 +280,13 @@ pub fn get_verge_config(verge_state: State<'_, VergeState>) -> Result<VergeConfi
|
||||
#[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 mut verge = verge_state.0.lock().unwrap();
|
||||
wrap_err!(verge.patch_config(payload))?;
|
||||
let system_proxy = payload.enable_system_proxy.clone();
|
||||
|
||||
// change tun mode
|
||||
if tun_mode.is_some() {
|
||||
@@ -298,6 +298,18 @@ pub fn patch_verge_config(
|
||||
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(())
|
||||
}
|
||||
|
||||
@@ -348,24 +360,26 @@ fn open_path_cmd(path: PathBuf, err_str: &str) -> Result<(), String> {
|
||||
match result {
|
||||
Ok(child) => match child.wait_with_output() {
|
||||
Ok(out) => {
|
||||
// 退出码不为0 不一定没有调用成功
|
||||
// 因此仅做warn log且不返回错误
|
||||
if let Some(code) = out.status.code() {
|
||||
if code != 0 {
|
||||
log::error!(
|
||||
"failed to open path {:?} for {} (code {code})",
|
||||
&path,
|
||||
log::warn!("failed to open {:?} (code {})", &path, code);
|
||||
log::warn!(
|
||||
"open cmd stdout: {}, stderr: {}",
|
||||
String::from_utf8_lossy(&out.stdout),
|
||||
String::from_utf8_lossy(&out.stderr),
|
||||
);
|
||||
return Err(err_str.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
log::error!("failed to open path {:?} for {err}", &path);
|
||||
log::error!("failed to open {:?} for {err}", &path);
|
||||
return Err(err_str.into());
|
||||
}
|
||||
},
|
||||
Err(err) => {
|
||||
log::error!("failed to open path {:?} for {err}", &path);
|
||||
log::error!("failed to open {:?} for {err}", &path);
|
||||
return Err(err_str.into());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -192,71 +192,109 @@ impl Clash {
|
||||
verge: &mut Verge,
|
||||
profiles: &mut Profiles,
|
||||
) -> 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 key_str = key.as_str().clone().unwrap_or("");
|
||||
|
||||
// restart the clash
|
||||
if key_str == "mixed-port" {
|
||||
self.restart_sidecar(profiles)?;
|
||||
|
||||
let port = if value.is_number() {
|
||||
match value.as_i64().clone() {
|
||||
Some(num) => Some(format!("{num}")),
|
||||
None => None,
|
||||
}
|
||||
// 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 {
|
||||
match value.as_str().clone() {
|
||||
Some(num) => Some(num.into()),
|
||||
None => None,
|
||||
}
|
||||
};
|
||||
verge.init_sysproxy(port);
|
||||
port = value.as_str().as_ref().map(|s| s.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
/// only revise the config and restart the
|
||||
pub fn tun_mode(&mut self, enable: bool) -> Result<()> {
|
||||
let tun_key = Value::String("tun".into());
|
||||
let tun_val = self.config.get(&tun_key);
|
||||
|
||||
let mut new_val = Mapping::new();
|
||||
|
||||
if tun_val.is_some() && tun_val.as_ref().unwrap().is_mapping() {
|
||||
new_val = tun_val.as_ref().unwrap().as_mapping().unwrap().clone();
|
||||
// Windows 需要wintun.dll文件
|
||||
#[cfg(target_os = "windows")]
|
||||
if enable {
|
||||
let wintun_dll = dirs::app_home_dir().join("wintun.dll");
|
||||
if !wintun_dll.exists() {
|
||||
bail!("failed to enable TUN for missing `wintun.dll`");
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! revise {
|
||||
($map: expr, $key: expr, $val: expr) => {
|
||||
let ret_key = Value::String($key.into());
|
||||
if $map.contains_key(&ret_key) {
|
||||
$map[&ret_key] = $val;
|
||||
} else {
|
||||
$map.insert(ret_key, $val);
|
||||
}
|
||||
$map.insert(ret_key, Value::from($val));
|
||||
};
|
||||
}
|
||||
|
||||
// if key not exists then append value
|
||||
macro_rules! append {
|
||||
($map: expr, $key: expr, $val: expr) => {
|
||||
let ret_key = Value::String($key.into());
|
||||
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));
|
||||
append!(new_val, "stack", Value::from("gvisor"));
|
||||
append!(new_val, "auto-route", Value::from(true));
|
||||
append!(new_val, "auto-detect-interface", Value::from(true));
|
||||
// tun config
|
||||
let tun_val = self.config.get(&Value::from("tun"));
|
||||
let mut new_tun = Mapping::new();
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
@@ -119,7 +119,7 @@ impl Default for PrfItem {
|
||||
impl PrfItem {
|
||||
/// From partial item
|
||||
/// 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() {
|
||||
bail!("type should not be null");
|
||||
}
|
||||
@@ -137,7 +137,7 @@ impl PrfItem {
|
||||
"local" => {
|
||||
let name = item.name.unwrap_or("Local File".into());
|
||||
let desc = item.desc.unwrap_or("".into());
|
||||
PrfItem::from_local(name, desc)
|
||||
PrfItem::from_local(name, desc, file_data)
|
||||
}
|
||||
"merge" => {
|
||||
let name = item.name.unwrap_or("Merge".into());
|
||||
@@ -155,7 +155,7 @@ impl PrfItem {
|
||||
|
||||
/// ## Local type
|
||||
/// 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 file = format!("{uid}.yaml");
|
||||
|
||||
@@ -170,7 +170,7 @@ impl PrfItem {
|
||||
extra: None,
|
||||
option: None,
|
||||
updated: Some(help::get_now()),
|
||||
file_data: Some(tmpl::ITEM_LOCAL.into()),
|
||||
file_data: Some(file_data.unwrap_or(tmpl::ITEM_LOCAL.into())),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -133,37 +133,31 @@ impl Verge {
|
||||
}
|
||||
|
||||
/// 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 = 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);
|
||||
}
|
||||
|
||||
/// 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(())
|
||||
}
|
||||
|
||||
@@ -8,7 +8,10 @@ mod core;
|
||||
mod states;
|
||||
mod utils;
|
||||
|
||||
use crate::utils::{resolve, server};
|
||||
use crate::{
|
||||
core::VergeConfig,
|
||||
utils::{resolve, server},
|
||||
};
|
||||
use tauri::{
|
||||
api, CustomMenuItem, Manager, SystemTray, SystemTrayEvent, SystemTrayMenu, SystemTrayMenuItem,
|
||||
};
|
||||
@@ -21,6 +24,7 @@ fn main() -> std::io::Result<()> {
|
||||
|
||||
let tray_menu = SystemTrayMenu::new()
|
||||
.add_item(CustomMenuItem::new("open_window", "Show"))
|
||||
.add_item(CustomMenuItem::new("system_proxy", "System Proxy"))
|
||||
.add_item(CustomMenuItem::new("restart_clash", "Restart Clash"))
|
||||
.add_native_item(SystemTrayMenuItem::Separator)
|
||||
.add_item(CustomMenuItem::new("quit", "Quit").accelerator("CmdOrControl+Q"));
|
||||
@@ -40,6 +44,31 @@ fn main() -> std::io::Result<()> {
|
||||
window.show().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" => {
|
||||
let clash_state = app_handle.state::<states::ClashState>();
|
||||
let profiles_state = app_handle.state::<states::ProfilesState>();
|
||||
@@ -55,13 +84,12 @@ fn main() -> std::io::Result<()> {
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
#[cfg(target_os = "windows")]
|
||||
SystemTrayEvent::LeftClick { .. } => {
|
||||
if cfg![target_os = "windows"] {
|
||||
let window = app_handle.get_window("main").unwrap();
|
||||
window.unminimize().unwrap();
|
||||
window.show().unwrap();
|
||||
window.set_focus().unwrap();
|
||||
}
|
||||
let window = app_handle.get_window("main").unwrap();
|
||||
window.unminimize().unwrap();
|
||||
window.show().unwrap();
|
||||
window.set_focus().unwrap();
|
||||
}
|
||||
_ => {}
|
||||
})
|
||||
|
||||
@@ -5,12 +5,22 @@ use tauri::{
|
||||
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
|
||||
pub fn app_home_dir() -> PathBuf {
|
||||
home_dir()
|
||||
.unwrap()
|
||||
.join(Path::new(".config"))
|
||||
.join(Path::new("clash-verge"))
|
||||
.join(Path::new(APP_DIR))
|
||||
}
|
||||
|
||||
/// get the resources dir
|
||||
@@ -30,11 +40,6 @@ pub fn app_logs_dir() -> PathBuf {
|
||||
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 {
|
||||
app_home_dir().join(CLASH_CONFIG)
|
||||
}
|
||||
|
||||
@@ -87,4 +87,14 @@ pub fn init_app(package_info: &PackageInfo) {
|
||||
if !mmdb_path.exists() && mmdb_tmpl.exists() {
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,8 +38,14 @@ pub fn resolve_setup(app: &App) {
|
||||
clash.tun_mode(true).unwrap();
|
||||
}
|
||||
|
||||
verge.init_launch();
|
||||
log_if_err!(verge.sync_launch());
|
||||
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));
|
||||
});
|
||||
}
|
||||
|
||||
/// reset system proxy
|
||||
|
||||
@@ -4,7 +4,10 @@ use port_scanner::local_port_available;
|
||||
use tauri::{AppHandle, Manager};
|
||||
use warp::Filter;
|
||||
|
||||
#[cfg(not(feature = "verge-dev"))]
|
||||
const SERVER_PORT: u16 = 33333;
|
||||
#[cfg(feature = "verge-dev")]
|
||||
const SERVER_PORT: u16 = 11233;
|
||||
|
||||
/// check whether there is already exists
|
||||
pub fn check_singleton() -> Result<(), ()> {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"package": {
|
||||
"productName": "Clash Verge",
|
||||
"version": "0.0.23"
|
||||
"version": "0.0.24"
|
||||
},
|
||||
"build": {
|
||||
"distDir": "../dist",
|
||||
@@ -52,7 +52,8 @@
|
||||
"updater": {
|
||||
"active": true,
|
||||
"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,
|
||||
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDExNUFBNTBBN0FDNEFBRTUKUldUbHFzUjZDcVZhRVRJM25NS3NkSFlFVElxUkNZMzZ6bHUwRVJjb2F3alJXVzRaeDdSaTA2YWYK"
|
||||
|
||||
@@ -72,7 +72,7 @@
|
||||
|
||||
.the-content {
|
||||
position: absolute;
|
||||
top: 30px;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 2px;
|
||||
bottom: 10px;
|
||||
@@ -80,8 +80,8 @@
|
||||
}
|
||||
}
|
||||
|
||||
.macos.layout {
|
||||
.windows.layout {
|
||||
.layout__right .the-content {
|
||||
top: 0;
|
||||
top: 30px;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 { 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 {
|
||||
value: ApiType.ConnectionsItem;
|
||||
@@ -7,7 +23,34 @@ interface Props {
|
||||
const ConnectionItem = (props: 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;
|
||||
|
||||
@@ -32,7 +32,9 @@ const UpdateButton = (props: Props) => {
|
||||
New
|
||||
</Button>
|
||||
|
||||
<UpdateDialog open={dialogOpen} onClose={() => setDialogOpen(false)} />
|
||||
{dialogOpen && (
|
||||
<UpdateDialog open={dialogOpen} onClose={() => setDialogOpen(false)} />
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import useSWR from "swr";
|
||||
import { useState } from "react";
|
||||
import snarkdown from "snarkdown";
|
||||
import { useState, useMemo } from "react";
|
||||
import {
|
||||
Box,
|
||||
Button,
|
||||
Dialog,
|
||||
DialogActions,
|
||||
DialogContent,
|
||||
DialogContentText,
|
||||
DialogTitle,
|
||||
styled,
|
||||
} from "@mui/material";
|
||||
import { relaunch } from "@tauri-apps/api/process";
|
||||
import { checkUpdate, installUpdate } from "@tauri-apps/api/updater";
|
||||
@@ -18,6 +20,10 @@ interface Props {
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
const UpdateLog = styled(Box)(() => ({
|
||||
"h1,h2,h3,ul,ol,p": { margin: "0.5em 0", color: "inherit" },
|
||||
}));
|
||||
|
||||
let uploadingState = false;
|
||||
|
||||
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 (
|
||||
<Dialog open={open} onClose={onClose}>
|
||||
<DialogTitle>New Version v{updateInfo?.manifest?.version}</DialogTitle>
|
||||
|
||||
<DialogContent sx={{ minWidth: 360, maxWidth: 400, maxHeight: "50vh" }}>
|
||||
<DialogContentText>{updateInfo?.manifest?.body}</DialogContentText>
|
||||
<UpdateLog dangerouslySetInnerHTML={{ __html: parseContent }} />
|
||||
</DialogContent>
|
||||
|
||||
<DialogActions>
|
||||
<Button onClick={onClose}>Cancel</Button>
|
||||
<Button
|
||||
variant="contained"
|
||||
autoFocus
|
||||
onClick={onUpdate}
|
||||
variant="contained"
|
||||
disabled={uploading}
|
||||
onClick={onUpdate}
|
||||
>
|
||||
Update
|
||||
</Button>
|
||||
|
||||
61
src/components/profile/file-input.tsx
Normal file
61
src/components/profile/file-input.tsx
Normal 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;
|
||||
@@ -2,6 +2,7 @@ import dayjs from "dayjs";
|
||||
import { useLockFn } from "ahooks";
|
||||
import { useSWRConfig } from "swr";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
alpha,
|
||||
Box,
|
||||
@@ -16,13 +17,10 @@ import {
|
||||
import { RefreshRounded } from "@mui/icons-material";
|
||||
import { CmdType } from "../../services/types";
|
||||
import { updateProfile, deleteProfile, viewProfile } from "../../services/cmds";
|
||||
import relativeTime from "dayjs/plugin/relativeTime";
|
||||
import parseTraffic from "../../utils/parse-traffic";
|
||||
import ProfileEdit from "./profile-edit";
|
||||
import Notice from "../base/base-notice";
|
||||
|
||||
dayjs.extend(relativeTime);
|
||||
|
||||
const Wrapper = styled(Box)(({ theme }) => ({
|
||||
width: "100%",
|
||||
display: "block",
|
||||
@@ -51,6 +49,7 @@ interface Props {
|
||||
const ProfileItem = (props: Props) => {
|
||||
const { selected, itemData, onSelect } = props;
|
||||
|
||||
const { t } = useTranslation();
|
||||
const { mutate } = useSWRConfig();
|
||||
const [loading, setLoading] = useState(loadingCache[itemData.uid] ?? false);
|
||||
const [anchorEl, setAnchorEl] = useState<any>(null);
|
||||
@@ -271,7 +270,7 @@ const ProfileItem = (props: Props) => {
|
||||
onClick={item.handler}
|
||||
sx={{ minWidth: 133 }}
|
||||
>
|
||||
{item.label}
|
||||
{t(item.label)}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Menu>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import dayjs from "dayjs";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
alpha,
|
||||
Box,
|
||||
@@ -11,13 +12,10 @@ import {
|
||||
} from "@mui/material";
|
||||
import { CmdType } from "../../services/types";
|
||||
import { viewProfile } from "../../services/cmds";
|
||||
import relativeTime from "dayjs/plugin/relativeTime";
|
||||
import ProfileEdit from "./profile-edit";
|
||||
import Notice from "../base/base-notice";
|
||||
import enhance from "../../services/enhance";
|
||||
|
||||
dayjs.extend(relativeTime);
|
||||
|
||||
const Wrapper = styled(Box)(({ theme }) => ({
|
||||
width: "100%",
|
||||
display: "block",
|
||||
@@ -54,6 +52,8 @@ const ProfileMore = (props: Props) => {
|
||||
} = props;
|
||||
|
||||
const { uid, type } = itemData;
|
||||
const { t } = useTranslation();
|
||||
|
||||
const [anchorEl, setAnchorEl] = useState<any>(null);
|
||||
const [position, setPosition] = useState({ left: 0, top: 0 });
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
@@ -221,7 +221,7 @@ const ProfileMore = (props: Props) => {
|
||||
onClick={item.handler}
|
||||
sx={{ minWidth: 133 }}
|
||||
>
|
||||
{item.label}
|
||||
{t(item.label)}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Menu>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState } from "react";
|
||||
import { useRef, useState } from "react";
|
||||
import { useSWRConfig } from "swr";
|
||||
import { useLockFn, useSetState } from "ahooks";
|
||||
import {
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
import { Settings } from "@mui/icons-material";
|
||||
import { createProfile } from "../../services/cmds";
|
||||
import Notice from "../base/base-notice";
|
||||
import FileInput from "./file-input";
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
@@ -37,9 +38,10 @@ const ProfileNew = (props: Props) => {
|
||||
});
|
||||
|
||||
const [showOpt, setShowOpt] = useState(false);
|
||||
const [option, setOption] = useSetState({
|
||||
user_agent: "",
|
||||
}); // able to add more option
|
||||
// can add more option
|
||||
const [option, setOption] = useSetState({ user_agent: "" });
|
||||
// file input
|
||||
const fileDataRef = useRef<string | null>(null);
|
||||
|
||||
const onCreate = useLockFn(async () => {
|
||||
if (!form.type) {
|
||||
@@ -55,10 +57,15 @@ const ProfileNew = (props: Props) => {
|
||||
}
|
||||
|
||||
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: "" });
|
||||
setOption({ user_agent: "" });
|
||||
setShowOpt(false);
|
||||
fileDataRef.current = null;
|
||||
|
||||
mutate("getProfiles");
|
||||
onClose();
|
||||
@@ -97,6 +104,7 @@ const ProfileNew = (props: Props) => {
|
||||
<TextField
|
||||
{...textFieldProps}
|
||||
label="Name"
|
||||
autoComplete="off"
|
||||
value={form.name}
|
||||
onChange={(e) => setForm({ name: e.target.value })}
|
||||
/>
|
||||
@@ -104,6 +112,7 @@ const ProfileNew = (props: Props) => {
|
||||
<TextField
|
||||
{...textFieldProps}
|
||||
label="Descriptions"
|
||||
autoComplete="off"
|
||||
value={form.desc}
|
||||
onChange={(e) => setForm({ desc: e.target.value })}
|
||||
/>
|
||||
@@ -112,15 +121,21 @@ const ProfileNew = (props: Props) => {
|
||||
<TextField
|
||||
{...textFieldProps}
|
||||
label="Subscription Url"
|
||||
autoComplete="off"
|
||||
value={form.url}
|
||||
onChange={(e) => setForm({ url: e.target.value })}
|
||||
/>
|
||||
)}
|
||||
|
||||
{form.type === "local" && (
|
||||
<FileInput onChange={(val) => (fileDataRef.current = val)} />
|
||||
)}
|
||||
|
||||
{showOpt && (
|
||||
<TextField
|
||||
{...textFieldProps}
|
||||
label="User Agent"
|
||||
autoComplete="off"
|
||||
value={option.user_agent}
|
||||
onChange={(e) => setOption({ user_agent: e.target.value })}
|
||||
/>
|
||||
|
||||
@@ -17,6 +17,18 @@
|
||||
"Profile URL": "Profile URL",
|
||||
"Import": "Import",
|
||||
"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",
|
||||
"Clash Setting": "Clash Setting",
|
||||
|
||||
@@ -17,6 +17,18 @@
|
||||
"Profile URL": "配置文件链接",
|
||||
"Import": "导入",
|
||||
"New": "新建",
|
||||
"Close All": "关闭全部",
|
||||
"Select": "使用",
|
||||
"Edit": "编辑信息",
|
||||
"File": "打开文件",
|
||||
"Update": "更新",
|
||||
"Update(Proxy)": "更新(代理)",
|
||||
"Delete": "删除",
|
||||
"Enable": "启用",
|
||||
"Disable": "禁用",
|
||||
"Refresh": "刷新",
|
||||
"To Top": "移到最前",
|
||||
"To End": "移到末尾",
|
||||
|
||||
"Settings": "设置",
|
||||
"Clash Setting": "Clash 设置",
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import dayjs from "dayjs";
|
||||
import i18next from "i18next";
|
||||
import relativeTime from "dayjs/plugin/relativeTime";
|
||||
import useSWR, { SWRConfig, useSWRConfig } from "swr";
|
||||
import { useEffect, useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -14,8 +16,11 @@ import LayoutItem from "../components/layout/layout-item";
|
||||
import LayoutControl from "../components/layout/layout-control";
|
||||
import LayoutTraffic from "../components/layout/layout-traffic";
|
||||
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 { t } = useTranslation();
|
||||
@@ -36,10 +41,14 @@ const Layout = () => {
|
||||
mutate("getProxies");
|
||||
mutate("getClashConfig");
|
||||
});
|
||||
|
||||
// update the verge config
|
||||
listen("verge://refresh-verge-config", () => mutate("getVergeConfig"));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (data?.language) {
|
||||
dayjs.locale(data.language === "zh" ? "zh-cn" : data.language);
|
||||
i18next.changeLanguage(data.language);
|
||||
}
|
||||
}, [data?.language]);
|
||||
@@ -76,8 +85,12 @@ const Layout = () => {
|
||||
<Paper
|
||||
square
|
||||
elevation={0}
|
||||
className={`${isMacos ? "macos " : ""}layout`}
|
||||
className={`${isWinOs ? "windows " : ""}layout`}
|
||||
onPointerDown={onDragging}
|
||||
onContextMenu={(e) => {
|
||||
// only prevent it on Windows
|
||||
if (isWinOs) e.preventDefault();
|
||||
}}
|
||||
sx={[
|
||||
(theme) => ({
|
||||
bgcolor: alpha(theme.palette.background.paper, blur ? 0.85 : 1),
|
||||
@@ -105,7 +118,7 @@ const Layout = () => {
|
||||
</div>
|
||||
|
||||
<div className="layout__right" data-windrag>
|
||||
{!isMacos && (
|
||||
{isWinOs && (
|
||||
<div className="the-bar">
|
||||
<LayoutControl />
|
||||
</div>
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
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 { useTranslation } from "react-i18next";
|
||||
import { ApiType } from "../services/types";
|
||||
import { getInfomation } from "../services/api";
|
||||
import { closeAllConnections, getInfomation } from "../services/api";
|
||||
import BasePage from "../components/base/base-page";
|
||||
import ConnectionItem from "../components/connection/connection-item";
|
||||
|
||||
@@ -29,10 +30,26 @@ const ConnectionsPage = () => {
|
||||
return () => ws?.close();
|
||||
}, []);
|
||||
|
||||
const onCloseAll = useLockFn(closeAllConnections);
|
||||
|
||||
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%" }}>
|
||||
<Virtuoso
|
||||
initialTopMostItemIndex={999}
|
||||
data={conn.connections}
|
||||
itemContent={(index, item) => <ConnectionItem value={item} />}
|
||||
/>
|
||||
|
||||
@@ -141,3 +141,15 @@ export async function getProviders() {
|
||||
const response = await instance.get<any, any>("/providers/proxies");
|
||||
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`);
|
||||
}
|
||||
|
||||
@@ -14,8 +14,11 @@ export async function enhanceProfiles() {
|
||||
return invoke<void>("enhance_profiles");
|
||||
}
|
||||
|
||||
export async function createProfile(item: Partial<CmdType.ProfileItem>) {
|
||||
return invoke<void>("create_profile", { item });
|
||||
export async function createProfile(
|
||||
item: Partial<CmdType.ProfileItem>,
|
||||
fileData?: string | null
|
||||
) {
|
||||
return invoke<void>("create_profile", { item, fileData });
|
||||
}
|
||||
|
||||
export async function viewProfile(index: string) {
|
||||
|
||||
@@ -101,6 +101,8 @@ class Enhance {
|
||||
const payload = event.payload as CmdType.EnhancedPayload;
|
||||
let pdata = payload.current || {};
|
||||
|
||||
let hasScript = false;
|
||||
|
||||
for (const each of payload.chain) {
|
||||
const { uid, type = "" } = each.item;
|
||||
|
||||
@@ -109,6 +111,7 @@ class Enhance {
|
||||
if (type === "script") {
|
||||
// support async main function
|
||||
pdata = await toScript(each.script!, { ...pdata });
|
||||
hasScript = true;
|
||||
}
|
||||
|
||||
// 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" };
|
||||
emit(payload.callback, JSON.stringify(result)).catch(console.error);
|
||||
});
|
||||
|
||||
@@ -1831,6 +1831,11 @@ signal-exit@^3.0.2:
|
||||
resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.7.tgz#a9a1767f8af84155114eaabd73f99273c8f59ad9"
|
||||
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:
|
||||
version "1.0.2"
|
||||
resolved "https://registry.yarnpkg.com/source-map-js/-/source-map-js-1.0.2.tgz#adbc361d9c62df380125e7f161f71c826f1e490c"
|
||||
|
||||
Reference in New Issue
Block a user