Compare commits

...

17 Commits

23 changed files with 613 additions and 335 deletions

View File

@@ -76,7 +76,7 @@ jobs:
- name: Green zip bundle
if: matrix.os == 'windows-latest'
run: |
yarn run green
yarn run portable
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -1,3 +1,15 @@
## v0.0.29
### Features
- sort proxy node
- custom proxy test url
- logs page filter
- connections page filter
- default user agent for subscription
- system tray add tun mode toggle
- enable to change the config dir (Windows only)
## v0.0.28
### Features

View File

@@ -1,6 +1,6 @@
{
"name": "clash-verge",
"version": "0.0.28",
"version": "0.0.29",
"license": "GPL-3.0",
"scripts": {
"dev": "tauri dev",
@@ -10,16 +10,16 @@
"web:build": "tsc && vite build",
"web:serve": "vite preview",
"check": "node scripts/check.mjs",
"green": "node scripts/green.mjs",
"publish": "node scripts/publish.mjs",
"updater": "node scripts/updater.mjs",
"publish": "node scripts/publish.mjs",
"portable": "node scripts/portable.mjs",
"prepare": "husky install"
},
"dependencies": {
"@emotion/react": "^11.8.2",
"@emotion/styled": "^11.8.1",
"@mui/icons-material": "^5.5.1",
"@mui/material": "^5.5.3",
"@mui/icons-material": "^5.6.1",
"@mui/material": "^5.6.1",
"@tauri-apps/api": "^1.0.0-rc.3",
"ahooks": "^3.2.0",
"axios": "^0.26.0",

View File

@@ -16,7 +16,7 @@ function resolveClash() {
const CLASH_URL_PREFIX =
"https://github.com/Dreamacro/clash/releases/download/premium/";
const CLASH_LATEST_DATE = "2022.03.21";
const CLASH_LATEST_DATE = "2022.04.11";
// todo
const map = {

View File

@@ -6,7 +6,7 @@ import { getOctokit, context } from "@actions/github";
/// Script for ci
/// 打包绿色版/便携版 (only Windows)
async function resolveGreen() {
async function resolvePortable() {
if (process.platform !== "win32") return;
const releaseDir = "./src-tauri/target/release";
@@ -25,10 +25,10 @@ async function resolveGreen() {
const packageJson = require("../package.json");
const { version } = packageJson;
const zipFile = `Clash.Verge_${version}_x64_green.zip`;
const zipFile = `Clash.Verge_${version}_x64_portable.zip`;
zip.writeZip(zipFile);
console.log("[INFO]: create green zip successfully");
console.log("[INFO]: create portable zip successfully");
// push release assets
if (process.env.GITHUB_TOKEN === undefined) {
@@ -53,4 +53,4 @@ async function resolveGreen() {
});
}
resolveGreen().catch(console.error);
resolvePortable().catch(console.error);

View File

@@ -337,15 +337,6 @@ pub fn patch_verge_config(
let mut verge = verge_state.0.lock().unwrap();
wrap_err!(verge.patch_config(payload))?;
// change system tray
if system_proxy.is_some() {
app_handle
.tray_handle()
.get_item("system_proxy")
.set_selected(system_proxy.unwrap())
.unwrap();
}
// change tun mode
if tun_mode.is_some() {
#[cfg(target_os = "windows")]
@@ -363,6 +354,11 @@ pub fn patch_verge_config(
wrap_err!(clash.activate_enhanced(&profiles, false, false))?;
}
// change system tray
if system_proxy.is_some() || tun_mode.is_some() {
verge.update_systray(&app_handle).unwrap();
}
Ok(())
}

View File

@@ -196,9 +196,8 @@ impl PrfItem {
if !with_proxy {
builder = builder.no_proxy();
}
if let Some(user_agent) = user_agent {
builder = builder.user_agent(user_agent);
}
builder = builder.user_agent(user_agent.unwrap_or("clash-verge/v0.1.0".into()));
let resp = builder.build()?.get(url).send().await?;
let header = resp.headers();

View File

@@ -8,6 +8,7 @@ use auto_launch::{AutoLaunch, AutoLaunchBuilder};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tauri::{async_runtime::Mutex, utils::platform::current_exe};
use tauri::{AppHandle, Manager};
/// ### `verge.yaml` schema
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
@@ -149,7 +150,7 @@ impl Verge {
if let Some(sysproxy) = self.old_sysproxy.take() {
match sysproxy.set_sys() {
Ok(_) => self.cur_sysproxy = None,
Err(_) => log::error!("failed to reset proxy for"),
Err(_) => log::error!("failed to reset proxy"),
}
}
}
@@ -242,7 +243,6 @@ impl Verge {
if sysproxy.set_sys().is_err() {
self.cur_sysproxy = Some(sysproxy);
log::error!("failed to set system proxy");
bail!("failed to set system proxy");
}
self.cur_sysproxy = Some(sysproxy);
@@ -261,7 +261,6 @@ impl Verge {
if sysproxy.set_sys().is_err() {
self.cur_sysproxy = Some(sysproxy);
log::error!("failed to set system proxy");
bail!("failed to set system proxy");
}
}
@@ -293,6 +292,35 @@ impl Verge {
self.config.save_file()
}
/// update the system tray state
pub fn update_systray(&self, app_handle: &AppHandle) -> Result<()> {
// system proxy
let system_proxy = self.config.enable_system_proxy.as_ref();
system_proxy.map(|system_proxy| {
app_handle
.tray_handle()
.get_item("system_proxy")
.set_selected(*system_proxy)
.unwrap();
});
// tun mode
let tun_mode = self.config.enable_tun_mode.as_ref();
tun_mode.map(|tun_mode| {
app_handle
.tray_handle()
.get_item("tun_mode")
.set_selected(*tun_mode)
.unwrap();
});
// update verge config
let window = app_handle.get_window("main").unwrap();
window.emit("verge://refresh-verge-config", "yes").unwrap();
Ok(())
}
}
impl Verge {

View File

@@ -10,7 +10,7 @@ mod utils;
use crate::{
core::VergeConfig,
utils::{resolve, server},
utils::{dirs, resolve, server},
};
use tauri::{
api, CustomMenuItem, Manager, SystemTray, SystemTrayEvent, SystemTrayMenu, SystemTrayMenuItem,
@@ -22,9 +22,15 @@ fn main() -> std::io::Result<()> {
return Ok(());
}
#[cfg(target_os = "windows")]
unsafe {
dirs::init_portable_flag();
}
let tray_menu = SystemTrayMenu::new()
.add_item(CustomMenuItem::new("open_window", "Show"))
.add_item(CustomMenuItem::new("system_proxy", "System Proxy"))
.add_item(CustomMenuItem::new("tun_mode", "Tun Mode"))
.add_item(CustomMenuItem::new("restart_clash", "Restart Clash"))
.add_native_item(SystemTrayMenuItem::Separator)
.add_item(CustomMenuItem::new("quit", "Quit").accelerator("CmdOrControl+Q"));
@@ -55,17 +61,22 @@ fn main() -> std::io::Result<()> {
enable_system_proxy: Some(new_value),
..VergeConfig::default()
}) {
Ok(_) => {
app_handle
.tray_handle()
.get_item(id.as_str())
.set_selected(new_value)
.unwrap();
Ok(_) => verge.update_systray(app_handle).unwrap(),
Err(err) => log::error!("{err}"),
}
}
"tun_mode" => {
let verge_state = app_handle.state::<states::VergeState>();
let mut verge = verge_state.0.lock().unwrap();
// update verge config
let window = app_handle.get_window("main").unwrap();
window.emit("verge://refresh-verge-config", "yes").unwrap();
}
let old_value = verge.config.enable_tun_mode.clone().unwrap_or(false);
let new_value = !old_value;
match verge.patch_config(VergeConfig {
enable_tun_mode: Some(new_value),
..VergeConfig::default()
}) {
Ok(_) => verge.update_systray(app_handle).unwrap(),
Err(err) => log::error!("{err}"),
}
}

View File

@@ -1,5 +1,6 @@
use std::env::temp_dir;
use std::path::{Path, PathBuf};
use std::path::PathBuf;
use tauri::utils::platform::current_exe;
use tauri::{
api::path::{home_dir, resource_dir},
Env, PackageInfo,
@@ -15,12 +16,40 @@ static VERGE_CONFIG: &str = "verge.yaml";
static PROFILE_YAML: &str = "profiles.yaml";
static PROFILE_TEMP: &str = "clash-verge-runtime.yaml";
/// portable flag
#[allow(unused)]
static mut PORTABLE_FLAG: bool = false;
/// initialize portable flag
pub unsafe fn init_portable_flag() {
#[cfg(target_os = "windows")]
{
let exe = current_exe().unwrap();
let dir = exe.parent().unwrap();
let dir = PathBuf::from(dir).join(".config/PORTABLE");
if dir.exists() {
PORTABLE_FLAG = true;
}
}
}
/// get the verge app home dir
pub fn app_home_dir() -> PathBuf {
home_dir()
.unwrap()
.join(Path::new(".config"))
.join(Path::new(APP_DIR))
#[cfg(target_os = "windows")]
unsafe {
if !PORTABLE_FLAG {
home_dir().unwrap().join(".config").join(APP_DIR)
} else {
let app_exe = current_exe().unwrap();
let app_exe = dunce::canonicalize(app_exe).unwrap();
let app_dir = app_exe.parent().unwrap();
PathBuf::from(app_dir).join(".config").join(APP_DIR)
}
}
#[cfg(not(target_os = "windows"))]
home_dir().unwrap().join(".config").join(APP_DIR)
}
/// get the resources dir

View File

@@ -1,7 +1,7 @@
{
"package": {
"productName": "Clash Verge",
"version": "0.0.28"
"version": "0.0.29"
},
"build": {
"distDir": "../dist",

View File

@@ -4,6 +4,7 @@ import { styled, ListItem, IconButton, ListItemText } from "@mui/material";
import { CloseRounded } from "@mui/icons-material";
import { ApiType } from "../../services/types";
import { deleteConnection } from "../../services/api";
import parseTraffic from "../../utils/parse-traffic";
const Tag = styled("span")(({ theme }) => ({
display: "inline-block",
@@ -23,32 +24,39 @@ interface Props {
const ConnectionItem = (props: Props) => {
const { value } = props;
const onDelete = useLockFn(async () => deleteConnection(value.id));
const { id, metadata, chains, start, curUpload, curDownload } = value;
const onDelete = useLockFn(async () => deleteConnection(id));
const showTraffic = curUpload! > 1024 || curDownload! > 1024;
return (
<ListItem
dense
secondaryAction={
<IconButton edge="end" onClick={onDelete}>
<IconButton edge="end" color="inherit" onClick={onDelete}>
<CloseRounded />
</IconButton>
}
>
<ListItemText
primary={value.metadata.host || value.metadata.destinationIP}
primary={metadata.host || metadata.destinationIP}
secondary={
<>
<Tag sx={{ textTransform: "uppercase", color: "success" }}>
{value.metadata.network}
{metadata.network}
</Tag>
<Tag>{value.metadata.type}</Tag>
<Tag>{metadata.type}</Tag>
{value.chains.length > 0 && (
<Tag>{value.chains[value.chains.length - 1]}</Tag>
{chains.length > 0 && <Tag>{chains[value.chains.length - 1]}</Tag>}
<Tag>{dayjs(start).fromNow()}</Tag>
{showTraffic && (
<Tag>
{parseTraffic(curUpload!)} / {parseTraffic(curDownload!)}
</Tag>
)}
<Tag>{dayjs(value.start).fromNow()}</Tag>
</>
}
/>

View File

@@ -2,20 +2,13 @@ import useSWR, { useSWRConfig } from "swr";
import { useEffect, useRef, useState } from "react";
import { useLockFn } from "ahooks";
import { Virtuoso } from "react-virtuoso";
import { Box, IconButton, TextField } from "@mui/material";
import {
MyLocationRounded,
NetworkCheckRounded,
FilterAltRounded,
FilterAltOffRounded,
VisibilityRounded,
VisibilityOffRounded,
} from "@mui/icons-material";
import { ApiType } from "../../services/types";
import { updateProxy } from "../../services/api";
import { getProfiles, patchProfile } from "../../services/cmds";
import delayManager from "../../services/delay";
import useSortProxy, { ProxySortType } from "./use-sort-proxy";
import useFilterProxy from "./use-filter-proxy";
import delayManager from "../../services/delay";
import ProxyHead from "./proxy-head";
import ProxyItem from "./proxy-item";
interface Props {
@@ -30,12 +23,14 @@ const ProxyGlobal = (props: Props) => {
const { mutate } = useSWRConfig();
const [now, setNow] = useState(curProxy || "DIRECT");
const [showType, setShowType] = useState(true);
const [showFilter, setShowFilter] = useState(false);
const [sortType, setSortType] = useState<ProxySortType>(0);
const [filterText, setFilterText] = useState("");
const virtuosoRef = useRef<any>();
const filterProxies = useFilterProxy(proxies, groupName, filterText);
const sortedProxies = useSortProxy(filterProxies, groupName, sortType);
const { data: profiles } = useSWR("getProfiles", getProfiles);
@@ -61,7 +56,7 @@ const ProxyGlobal = (props: Props) => {
});
const onLocation = (smooth = true) => {
const index = filterProxies.findIndex((p) => p.name === now);
const index = sortedProxies.findIndex((p) => p.name === now);
if (index >= 0) {
virtuosoRef.current?.scrollToIndex?.({
@@ -73,22 +68,15 @@ const ProxyGlobal = (props: Props) => {
};
const onCheckAll = useLockFn(async () => {
const names = filterProxies.map((p) => p.name);
const names = sortedProxies.map((p) => p.name);
await delayManager.checkListDelay(
{ names, groupName, skipNum: 8, maxTimeout: 600 },
() => mutate("getProxies")
await delayManager.checkListDelay({ names, groupName, skipNum: 8 }, () =>
mutate("getProxies")
);
mutate("getProxies");
});
useEffect(() => onLocation(false), [groupName]);
useEffect(() => {
if (!showFilter) setFilterText("");
}, [showFilter]);
useEffect(() => {
if (groupName === "DIRECT") setNow("DIRECT");
else if (groupName === "GLOBAL") {
@@ -112,74 +100,28 @@ const ProxyGlobal = (props: Props) => {
return (
<>
<Box
sx={{
px: 3,
my: 0.5,
display: "flex",
alignItems: "center",
button: { mr: 0.5 },
}}
>
<IconButton
size="small"
title="location"
color="inherit"
onClick={() => onLocation(true)}
>
<MyLocationRounded />
</IconButton>
<IconButton
size="small"
title="delay check"
color="inherit"
onClick={onCheckAll}
>
<NetworkCheckRounded />
</IconButton>
<IconButton
size="small"
title="proxy detail"
color="inherit"
onClick={() => setShowType(!showType)}
>
{showType ? <VisibilityRounded /> : <VisibilityOffRounded />}
</IconButton>
<IconButton
size="small"
title="filter"
color="inherit"
onClick={() => setShowFilter(!showFilter)}
>
{showFilter ? <FilterAltRounded /> : <FilterAltOffRounded />}
</IconButton>
{showFilter && (
<TextField
autoFocus
hiddenLabel
value={filterText}
size="small"
variant="outlined"
placeholder="Filter conditions"
onChange={(e) => setFilterText(e.target.value)}
sx={{ ml: 0.5, flex: "1 1 auto", input: { py: 0.65, px: 1 } }}
/>
)}
</Box>
<ProxyHead
sx={{ px: 3, my: 0.5, button: { mr: 0.5 } }}
showType={showType}
sortType={sortType}
groupName={groupName}
filterText={filterText}
onLocation={onLocation}
onCheckDelay={onCheckAll}
onShowType={setShowType}
onSortType={setSortType}
onFilterText={setFilterText}
/>
<Virtuoso
ref={virtuosoRef}
style={{ height: "calc(100% - 40px)" }}
totalCount={filterProxies.length}
totalCount={sortedProxies.length}
itemContent={(index) => (
<ProxyItem
groupName={groupName}
proxy={filterProxies[index]}
selected={filterProxies[index].name === now}
proxy={sortedProxies[index]}
selected={sortedProxies[index].name === now}
showType={showType}
onClick={onChangeProxy}
sx={{ py: 0, px: 2 }}

View File

@@ -6,28 +6,22 @@ import {
Box,
Collapse,
Divider,
IconButton,
List,
ListItem,
ListItemText,
TextField,
} from "@mui/material";
import {
SendRounded,
ExpandLessRounded,
ExpandMoreRounded,
MyLocationRounded,
NetworkCheckRounded,
FilterAltRounded,
FilterAltOffRounded,
VisibilityRounded,
VisibilityOffRounded,
} from "@mui/icons-material";
import { ApiType } from "../../services/types";
import { updateProxy } from "../../services/api";
import { getProfiles, patchProfile } from "../../services/cmds";
import delayManager from "../../services/delay";
import useSortProxy, { ProxySortType } from "./use-sort-proxy";
import useFilterProxy from "./use-filter-proxy";
import delayManager from "../../services/delay";
import ProxyHead from "./proxy-head";
import ProxyItem from "./proxy-item";
interface Props {
@@ -38,13 +32,14 @@ const ProxyGroup = ({ group }: Props) => {
const { mutate } = useSWRConfig();
const [open, setOpen] = useState(false);
const [now, setNow] = useState(group.now);
const [showType, setShowType] = useState(false);
const [showFilter, setShowFilter] = useState(false);
const [sortType, setSortType] = useState<ProxySortType>(0);
const [filterText, setFilterText] = useState("");
const proxies = group.all ?? [];
const virtuosoRef = useRef<any>();
const filterProxies = useFilterProxy(proxies, group.name, filterText);
const filterProxies = useFilterProxy(group.all, group.name, filterText);
const sortedProxies = useSortProxy(filterProxies, group.name, sortType);
const { data: profiles } = useSWR("getProfiles", getProfiles);
@@ -82,7 +77,7 @@ const ProxyGroup = ({ group }: Props) => {
});
const onLocation = (smooth = true) => {
const index = filterProxies.findIndex((p) => p.name === now);
const index = sortedProxies.findIndex((p) => p.name === now);
if (index >= 0) {
virtuosoRef.current?.scrollToIndex?.({
@@ -94,21 +89,14 @@ const ProxyGroup = ({ group }: Props) => {
};
const onCheckAll = useLockFn(async () => {
const names = filterProxies.map((p) => p.name);
const names = sortedProxies.map((p) => p.name);
const groupName = group.name;
await delayManager.checkListDelay(
{ names, groupName, skipNum: 8, maxTimeout: 600 },
() => mutate("getProxies")
await delayManager.checkListDelay({ names, groupName, skipNum: 8 }, () =>
mutate("getProxies")
);
mutate("getProxies");
});
useEffect(() => {
if (!showFilter) setFilterText("");
}, [showFilter]);
// auto scroll to current index
useEffect(() => {
if (open) {
@@ -136,66 +124,20 @@ const ProxyGroup = ({ group }: Props) => {
</ListItem>
<Collapse in={open} timeout="auto" unmountOnExit>
<Box
sx={{
pl: 4,
pr: 3,
my: 0.5,
display: "flex",
alignItems: "center",
button: { mr: 0.5 },
}}
>
<IconButton
size="small"
title="location"
color="inherit"
onClick={() => onLocation(true)}
>
<MyLocationRounded />
</IconButton>
<ProxyHead
sx={{ pl: 4, pr: 3, my: 0.5, button: { mr: 0.5 } }}
showType={showType}
sortType={sortType}
groupName={group.name}
filterText={filterText}
onLocation={onLocation}
onCheckDelay={onCheckAll}
onShowType={setShowType}
onSortType={setSortType}
onFilterText={setFilterText}
/>
<IconButton
size="small"
title="delay check"
color="inherit"
onClick={onCheckAll}
>
<NetworkCheckRounded />
</IconButton>
<IconButton
size="small"
title="proxy detail"
color="inherit"
onClick={() => setShowType(!showType)}
>
{showType ? <VisibilityRounded /> : <VisibilityOffRounded />}
</IconButton>
<IconButton
size="small"
title="filter"
color="inherit"
onClick={() => setShowFilter(!showFilter)}
>
{showFilter ? <FilterAltRounded /> : <FilterAltOffRounded />}
</IconButton>
{showFilter && (
<TextField
hiddenLabel
value={filterText}
size="small"
variant="outlined"
placeholder="Filter conditions"
onChange={(e) => setFilterText(e.target.value)}
sx={{ ml: 0.5, flex: "1 1 auto", input: { py: 0.65, px: 1 } }}
/>
)}
</Box>
{!filterProxies.length && (
{!sortedProxies.length && (
<Box
sx={{
py: 3,
@@ -208,16 +150,16 @@ const ProxyGroup = ({ group }: Props) => {
</Box>
)}
{filterProxies.length >= 10 ? (
{sortedProxies.length >= 10 ? (
<Virtuoso
ref={virtuosoRef}
style={{ height: "320px", marginBottom: "4px" }}
totalCount={filterProxies.length}
totalCount={sortedProxies.length}
itemContent={(index) => (
<ProxyItem
groupName={group.name}
proxy={filterProxies[index]}
selected={filterProxies[index].name === now}
proxy={sortedProxies[index]}
selected={sortedProxies[index].name === now}
showType={showType}
sx={{ py: 0, pl: 4 }}
onClick={onChangeProxy}
@@ -230,7 +172,7 @@ const ProxyGroup = ({ group }: Props) => {
disablePadding
sx={{ maxHeight: "320px", overflow: "auto", mb: "4px" }}
>
{filterProxies.map((proxy) => (
{sortedProxies.map((proxy) => (
<ProxyItem
key={proxy.name}
groupName={group.name}

View File

@@ -0,0 +1,147 @@
import { useState } from "react";
import { Box, IconButton, TextField, SxProps } from "@mui/material";
import {
AccessTimeRounded,
MyLocationRounded,
NetworkCheckRounded,
FilterAltRounded,
FilterAltOffRounded,
VisibilityRounded,
VisibilityOffRounded,
WifiTetheringRounded,
WifiTetheringOffRounded,
SortByAlphaRounded,
SortRounded,
} from "@mui/icons-material";
import delayManager from "../../services/delay";
import type { ProxySortType } from "./use-sort-proxy";
interface Props {
sx?: SxProps;
groupName: string;
showType: boolean;
sortType: ProxySortType;
filterText: string;
onLocation: () => void;
onCheckDelay: () => void;
onShowType: (val: boolean) => void;
onSortType: (val: ProxySortType) => void;
onFilterText: (val: string) => void;
}
const ProxyHead = (props: Props) => {
const { sx = {}, groupName, showType, sortType, filterText } = props;
const [textState, setTextState] = useState<"url" | "filter" | null>(null);
const [testUrl, setTestUrl] = useState(delayManager.getUrl(groupName) || "");
return (
<Box sx={{ display: "flex", alignItems: "center", ...sx }}>
<IconButton
size="small"
title="location"
color="inherit"
onClick={props.onLocation}
>
<MyLocationRounded />
</IconButton>
<IconButton
size="small"
color="inherit"
title="delay check"
onClick={() => {
// Remind the user that it is custom test url
if (testUrl?.trim() && textState !== "filter") {
setTextState("url");
}
props.onCheckDelay();
}}
>
<NetworkCheckRounded />
</IconButton>
<IconButton
size="small"
color="inherit"
title={["sort by default", "sort by delay", "sort by name"][sortType]}
onClick={() => props.onSortType(((sortType + 1) % 3) as ProxySortType)}
>
{sortType === 0 && <SortRounded />}
{sortType === 1 && <AccessTimeRounded />}
{sortType === 2 && <SortByAlphaRounded />}
</IconButton>
<IconButton
size="small"
color="inherit"
title="edit test url"
onClick={() => setTextState((ts) => (ts === "url" ? null : "url"))}
>
{textState === "url" ? (
<WifiTetheringRounded />
) : (
<WifiTetheringOffRounded />
)}
</IconButton>
<IconButton
size="small"
color="inherit"
title="proxy detail"
onClick={() => props.onShowType(!showType)}
>
{showType ? <VisibilityRounded /> : <VisibilityOffRounded />}
</IconButton>
<IconButton
size="small"
color="inherit"
title="filter"
onClick={() =>
setTextState((ts) => (ts === "filter" ? null : "filter"))
}
>
{textState === "filter" ? (
<FilterAltRounded />
) : (
<FilterAltOffRounded />
)}
</IconButton>
{textState === "filter" && (
<TextField
autoFocus
hiddenLabel
value={filterText}
size="small"
variant="outlined"
placeholder="Filter conditions"
onChange={(e) => props.onFilterText(e.target.value)}
sx={{ ml: 0.5, flex: "1 1 auto", input: { py: 0.65, px: 1 } }}
/>
)}
{textState === "url" && (
<TextField
autoFocus
hiddenLabel
autoSave="off"
autoComplete="off"
value={testUrl}
size="small"
variant="outlined"
placeholder="Test url"
onChange={(e) => {
setTestUrl(e.target.value);
delayManager.setUrl(groupName, e.target.value);
}}
sx={{ ml: 0.5, flex: "1 1 auto", input: { py: 0.65, px: 1 } }}
/>
)}
</Box>
);
};
export default ProxyHead;

View File

@@ -1,4 +1,5 @@
import { useEffect, useRef, useState } from "react";
import { useEffect, useState } from "react";
import { useLockFn } from "ahooks";
import { CheckCircleOutlineRounded } from "@mui/icons-material";
import {
alpha,
@@ -24,8 +25,9 @@ interface Props {
}
const Widget = styled(Box)(() => ({
padding: "4px 6px",
padding: "3px 6px",
fontSize: 14,
borderRadius: "4px",
}));
const TypeBox = styled(Box)(({ theme }) => ({
@@ -50,20 +52,12 @@ const ProxyItem = (props: Props) => {
}
}, [proxy]);
const delayRef = useRef(false);
const onDelay = (e: any) => {
e.preventDefault();
e.stopPropagation();
if (delayRef.current) return;
delayRef.current = true;
delayManager
const onDelay = useLockFn(async () => {
return delayManager
.checkDelay(proxy.name, groupName)
.then((result) => setDelay(result))
.catch(() => setDelay(1e6))
.finally(() => (delayRef.current = false));
};
.catch(() => setDelay(1e6));
});
return (
<ListItem sx={sx}>
@@ -111,13 +105,27 @@ const ProxyItem = (props: Props) => {
<ListItemIcon
sx={{ justifyContent: "flex-end", color: "primary.main" }}
>
<Widget className="the-check" onClick={onDelay}>
<Widget
className="the-check"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
onDelay();
}}
sx={(theme) => ({
":hover": { bgcolor: alpha(theme.palette.primary.main, 0.15) },
})}
>
Check
</Widget>
<Widget
className="the-delay"
onClick={onDelay}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
onDelay();
}}
color={
delay > 500
? "error.main"
@@ -125,6 +133,9 @@ const ProxyItem = (props: Props) => {
? "success.main"
: "text.secondary"
}
sx={(theme) => ({
":hover": { bgcolor: alpha(theme.palette.primary.main, 0.15) },
})}
>
{delay > 1e5 ? "Error" : delay > 3000 ? "Timeout" : `${delay}ms`}
</Widget>

View File

@@ -15,6 +15,7 @@ export default function useFilterProxy(
filterText: string
) {
return useMemo(() => {
if (!proxies) return [];
if (!filterText) return proxies;
const res1 = regex1.exec(filterText);

View File

@@ -0,0 +1,38 @@
import { useMemo } from "react";
import { ApiType } from "../../services/types";
import delayManager from "../../services/delay";
// default | delay | alpha
export type ProxySortType = 0 | 1 | 2;
/**
* sort the proxy
*/
export default function useSortProxy(
proxies: ApiType.ProxyItem[],
groupName: string,
sortType: ProxySortType
) {
return useMemo(() => {
if (!proxies) return [];
if (sortType === 0) return proxies;
const list = proxies.slice();
if (sortType === 1) {
list.sort((a, b) => {
const ad = delayManager.getDelay(a.name, groupName);
const bd = delayManager.getDelay(b.name, groupName);
if (ad === -1) return 1;
if (bd === -1) return -1;
return ad - bd;
});
} else {
list.sort((a, b) => a.name.localeCompare(b.name));
}
return list;
}, [proxies, groupName, sortType]);
}

View File

@@ -1,6 +1,6 @@
import { useEffect, useState } from "react";
import { useEffect, useMemo, useState } from "react";
import { useLockFn } from "ahooks";
import { Button, Paper } from "@mui/material";
import { Box, Button, Paper, TextField } from "@mui/material";
import { Virtuoso } from "react-virtuoso";
import { useTranslation } from "react-i18next";
import { ApiType } from "../services/types";
@@ -8,12 +8,20 @@ import { closeAllConnections, getInfomation } from "../services/api";
import BasePage from "../components/base/base-page";
import ConnectionItem from "../components/connection/connection-item";
const ConnectionsPage = () => {
const initConn = { uploadTotal: 0, downloadTotal: 0, connections: [] };
const initConn = { uploadTotal: 0, downloadTotal: 0, connections: [] };
const ConnectionsPage = () => {
const { t } = useTranslation();
const [filterText, setFilterText] = useState("");
const [connData, setConnData] = useState<ApiType.Connections>(initConn);
const filterConn = useMemo(() => {
return connData.connections.filter((conn) =>
(conn.metadata.host || conn.metadata.destinationIP)?.includes(filterText)
);
}, [connData, filterText]);
useEffect(() => {
let ws: WebSocket | null = null;
@@ -23,32 +31,35 @@ const ConnectionsPage = () => {
ws.addEventListener("message", (event) => {
const data = JSON.parse(event.data) as ApiType.Connections;
// 与前一次connections的展示顺序尽量保持一致
setConnData((old) => {
const oldConn = old.connections;
const oldList = oldConn.map((each) => each.id);
const maxLen = data.connections.length;
const connections: typeof oldConn = [];
// 与前一次连接的顺序尽量保持一致
data.connections
.filter((each) => {
const index = oldList.indexOf(each.id);
const rest = data.connections.filter((each) => {
const index = oldConn.findIndex((o) => o.id === each.id);
if (index >= 0 && index < maxLen) {
connections[index] = each;
return false;
}
return true;
})
.forEach((each) => {
for (let i = 0; i < maxLen; ++i) {
if (!connections[i]) {
connections[i] = each;
return;
}
}
});
if (index >= 0 && index < maxLen) {
const old = oldConn[index];
each.curUpload = each.upload - old.upload;
each.curDownload = each.download - old.download;
connections[index] = each;
return false;
}
return true;
});
for (let i = 0; i < maxLen; ++i) {
if (!connections[i] && rest.length > 0) {
connections[i] = rest.shift()!;
connections[i].curUpload = 0;
connections[i].curDownload = 0;
}
}
return { ...data, connections };
});
@@ -76,11 +87,48 @@ const ConnectionsPage = () => {
}
>
<Paper sx={{ boxShadow: 2, height: "100%" }}>
<Virtuoso
initialTopMostItemIndex={999}
data={connData.connections}
itemContent={(index, item) => <ConnectionItem value={item} />}
/>
<Box
sx={{
pt: 1,
mb: 0.5,
mx: "12px",
height: "36px",
display: "flex",
alignItems: "center",
}}
>
{/* <Select
size="small"
autoComplete="off"
value={logState}
onChange={(e) => setLogState(e.target.value)}
sx={{ width: 120, mr: 1, '[role="button"]': { py: 0.65 } }}
>
<MenuItem value="all">ALL</MenuItem>
<MenuItem value="info">INFO</MenuItem>
<MenuItem value="warn">WARN</MenuItem>
</Select> */}
<TextField
hiddenLabel
fullWidth
size="small"
autoComplete="off"
variant="outlined"
placeholder="Filter conditions"
value={filterText}
onChange={(e) => setFilterText(e.target.value)}
sx={{ input: { py: 0.65, px: 1.25 } }}
/>
</Box>
<Box height="calc(100% - 50px)">
<Virtuoso
initialTopMostItemIndex={999}
data={filterConn}
itemContent={(index, item) => <ConnectionItem value={item} />}
/>
</Box>
</Paper>
</BasePage>
);

View File

@@ -1,5 +1,6 @@
import { useMemo, useState } from "react";
import { useRecoilState } from "recoil";
import { Button, Paper } from "@mui/material";
import { Box, Button, MenuItem, Paper, Select, TextField } from "@mui/material";
import { Virtuoso } from "react-virtuoso";
import { useTranslation } from "react-i18next";
import { atomLogData } from "../services/states";
@@ -10,6 +11,18 @@ const LogPage = () => {
const { t } = useTranslation();
const [logData, setLogData] = useRecoilState(atomLogData);
const [logState, setLogState] = useState("all");
const [filterText, setFilterText] = useState("");
const filterLogs = useMemo(() => {
return logData.filter((data) => {
return (
data.payload.includes(filterText) &&
(logState === "all" ? true : data.type.includes(logState))
);
});
}, [logData, logState, filterText]);
return (
<BasePage
title={t("Logs")}
@@ -25,13 +38,50 @@ const LogPage = () => {
</Button>
}
>
<Paper sx={{ boxShadow: 2, height: "100%" }}>
<Virtuoso
initialTopMostItemIndex={999}
data={logData}
itemContent={(index, item) => <LogItem value={item} />}
followOutput={"smooth"}
/>
<Paper sx={{ boxSizing: "border-box", boxShadow: 2, height: "100%" }}>
<Box
sx={{
pt: 1,
mb: 0.5,
mx: "12px",
height: "36px",
display: "flex",
alignItems: "center",
}}
>
<Select
size="small"
autoComplete="off"
value={logState}
onChange={(e) => setLogState(e.target.value)}
sx={{ width: 120, mr: 1, '[role="button"]': { py: 0.65 } }}
>
<MenuItem value="all">ALL</MenuItem>
<MenuItem value="info">INFO</MenuItem>
<MenuItem value="warn">WARN</MenuItem>
</Select>
<TextField
hiddenLabel
fullWidth
size="small"
autoComplete="off"
variant="outlined"
placeholder="Filter conditions"
value={filterText}
onChange={(e) => setFilterText(e.target.value)}
sx={{ input: { py: 0.65, px: 1.25 } }}
/>
</Box>
<Box height="calc(100% - 50px)">
<Virtuoso
initialTopMostItemIndex={999}
data={filterLogs}
itemContent={(index, item) => <LogItem value={item} />}
followOutput={"smooth"}
/>
</Box>
</Paper>
</BasePage>
);

View File

@@ -4,6 +4,15 @@ const hashKey = (name: string, group: string) => `${group ?? ""}::${name}`;
class DelayManager {
private cache = new Map<string, [number, number]>();
private urlMap = new Map<string, string>();
setUrl(group: string, url: string) {
this.urlMap.set(group, url);
}
getUrl(group: string) {
return this.urlMap.get(group);
}
setDelay(name: string, group: string, delay: number) {
this.cache.set(hashKey(name, group), [Date.now(), delay]);
@@ -23,7 +32,8 @@ class DelayManager {
let delay = -1;
try {
const result = await getProxyDelay(name);
const url = this.getUrl(group);
const result = await getProxyDelay(name, url);
delay = result.delay;
} catch {
delay = 1e6; // error
@@ -38,32 +48,36 @@ class DelayManager {
names: readonly string[];
groupName: string;
skipNum: number;
maxTimeout: number;
},
callback: Function
) {
let names = [...options.names];
const { groupName, skipNum, maxTimeout } = options;
const { groupName, skipNum } = options;
while (names.length) {
const list = names.slice(0, skipNum);
names = names.slice(skipNum);
const names = [...options.names];
const total = names.length;
let called = false;
setTimeout(() => {
if (!called) {
called = true;
callback();
}
}, maxTimeout);
let count = 0;
let current = 0;
await Promise.all(list.map((n) => this.checkDelay(n, groupName)));
return new Promise((resolve) => {
const help = async (): Promise<void> => {
if (current >= skipNum) return;
if (!called) {
called = true;
callback();
}
}
const task = names.shift();
if (!task) return;
current += 1;
await this.checkDelay(task, groupName);
current -= 1;
if (count++ % skipNum === 0 || count === total) callback();
if (count === total) resolve(null);
return help();
};
for (let i = 0; i < skipNum; ++i) help();
});
}
}

View File

@@ -65,6 +65,8 @@ export namespace ApiType {
chains: string[];
rule: string;
rulePayload: string;
curUpload?: number; // calculate
curDownload?: number; // calculate
}
export interface Connections {

View File

@@ -386,37 +386,37 @@
"@jridgewell/resolve-uri" "^3.0.3"
"@jridgewell/sourcemap-codec" "^1.4.10"
"@mui/base@5.0.0-alpha.74":
version "5.0.0-alpha.74"
resolved "https://registry.yarnpkg.com/@mui/base/-/base-5.0.0-alpha.74.tgz#15509242e7911446d5957375b1b18cbb72b3a750"
integrity sha512-pw3T1xNXpW8pLo9+BvtyazZb0CSjNJsjbzznlbV/aNkBfjNPXQVI3X1NDm3WSI8y6M96WDIVO7XrHAohOwALSQ==
"@mui/base@5.0.0-alpha.76":
version "5.0.0-alpha.76"
resolved "https://registry.yarnpkg.com/@mui/base/-/base-5.0.0-alpha.76.tgz#683d68eff6d52e19e9962f608a5d3b8b6fb6ef55"
integrity sha512-Pd0l4DvjXiGRyipn/CTDlYB2XrJwhpLktVXvbvcmzL2SMDaNprSarZqBkPHIubkulmRDZEEcnFDrpKgeSJDg4A==
dependencies:
"@babel/runtime" "^7.17.2"
"@emotion/is-prop-valid" "^1.1.2"
"@mui/types" "^7.1.3"
"@mui/utils" "^5.5.3"
"@popperjs/core" "^2.11.4"
"@mui/utils" "^5.6.1"
"@popperjs/core" "^2.11.5"
clsx "^1.1.1"
prop-types "^15.7.2"
react-is "^17.0.2"
"@mui/icons-material@^5.5.1":
version "5.5.1"
resolved "https://registry.yarnpkg.com/@mui/icons-material/-/icons-material-5.5.1.tgz#848a57972617411370775980cbc6990588d4aafb"
integrity sha512-40f68p5+Yhq3dCn3QYHqQt5RETPyR3AkDw+fma8PtcjqvZ+d+jF84kFmT6NqwA3he7TlwluEtkyAmPzUE4uPdA==
"@mui/icons-material@^5.6.1":
version "5.6.1"
resolved "https://registry.yarnpkg.com/@mui/icons-material/-/icons-material-5.6.1.tgz#421e2b73992349abb07f8f03074d7e56e20bf7ba"
integrity sha512-I1x8u+FRLOmoJpRJASMx9UG+jZrSkNLyRQmBXivQQwXu3m3iasMoaKYhhI0J18t8+FWktbkNTp63oEUHE9Gw0Q==
dependencies:
"@babel/runtime" "^7.17.2"
"@mui/material@^5.5.3":
version "5.5.3"
resolved "https://registry.yarnpkg.com/@mui/material/-/material-5.5.3.tgz#411e53a69da3f9d6664e99f1bdcdaf2760540fdc"
integrity sha512-eADa3kUYbbr1jNjcufn0a7HeU8cSo0agbrkj720hodxVFNIfzq7a2e58Z+PaZqll55kMGBvlYJ7rTcXU399x5A==
"@mui/material@^5.6.1":
version "5.6.1"
resolved "https://registry.yarnpkg.com/@mui/material/-/material-5.6.1.tgz#b74cfbe4666586e054a28cf3df448369892085e1"
integrity sha512-xg6pPq+1jxWupwmPpnfmsHNjrsOe2xynUQWrRfcH8WHrrr1sQulq0VF4gORq/l8DD8a/jb4s8SsC20e/e6mHKQ==
dependencies:
"@babel/runtime" "^7.17.2"
"@mui/base" "5.0.0-alpha.74"
"@mui/system" "^5.5.3"
"@mui/base" "5.0.0-alpha.76"
"@mui/system" "^5.6.1"
"@mui/types" "^7.1.3"
"@mui/utils" "^5.5.3"
"@mui/utils" "^5.6.1"
"@types/react-transition-group" "^4.4.4"
clsx "^1.1.1"
csstype "^3.0.11"
@@ -425,34 +425,34 @@
react-is "^17.0.2"
react-transition-group "^4.4.2"
"@mui/private-theming@^5.5.3":
version "5.5.3"
resolved "https://registry.yarnpkg.com/@mui/private-theming/-/private-theming-5.5.3.tgz#c232a39dd3c268fdef7e92ccc40d51bda9eec3ab"
integrity sha512-Wf7NurY7lk8SBWelSBY2U02zxLt1773JpIcXTHuEC9/GZdQA4CXCJGl2cVQzheKhee5rZ+8JwGulrRiVl1m+4A==
"@mui/private-theming@^5.6.1":
version "5.6.1"
resolved "https://registry.yarnpkg.com/@mui/private-theming/-/private-theming-5.6.1.tgz#198ccec972375db999c293109b5f26456b9c3a22"
integrity sha512-8lgh+tUt/3ftStfvml3dwAzhW3fe/cUFjLcBViOTnWk7UixWR79me4qehsO4NVj0THpu3d2qclrLzdD8qBAWAQ==
dependencies:
"@babel/runtime" "^7.17.2"
"@mui/utils" "^5.5.3"
"@mui/utils" "^5.6.1"
prop-types "^15.7.2"
"@mui/styled-engine@^5.5.2":
version "5.5.2"
resolved "https://registry.yarnpkg.com/@mui/styled-engine/-/styled-engine-5.5.2.tgz#1f92dd27d76f0b7df7aa52c7c7a710e59b2275a6"
integrity sha512-jkz5AHHbA43akBo5L3y1X1/X0f+RvXvCp3eXKt+iOf3qnKSAausbtlVz7gBbC4xIWDnP1Jb/6T+t/0/7gObRYA==
"@mui/styled-engine@^5.6.1":
version "5.6.1"
resolved "https://registry.yarnpkg.com/@mui/styled-engine/-/styled-engine-5.6.1.tgz#e2c859a4dbdd65af89e77703a0725285aef471fd"
integrity sha512-jEhH6TBY8jc9S8yVncXmoTYTbATjEu44RMFXj6sIYfKr5NArVwTwRo3JexLL0t3BOAiYM4xsFLgfKEIvB9SAeQ==
dependencies:
"@babel/runtime" "^7.17.2"
"@emotion/cache" "^11.7.1"
prop-types "^15.7.2"
"@mui/system@^5.5.3":
version "5.5.3"
resolved "https://registry.yarnpkg.com/@mui/system/-/system-5.5.3.tgz#c78d4c16009430389ffd3495d694945422d72ca5"
integrity sha512-J9JcySJuEqfEoP334K/2gEWm2vOx73Uqjii3qlFVhWRBOAJ0Pjyk0sN5W/eVRbwhUm95DNgh2V5s8dRK3vzyVw==
"@mui/system@^5.6.1":
version "5.6.1"
resolved "https://registry.yarnpkg.com/@mui/system/-/system-5.6.1.tgz#dd47a15b82012f44464a0f25765e3dec6182ba98"
integrity sha512-Y5pDvEOK6VOY+0vgNeyDuEEO5QCinhXbZQDyLOlaGLKuAoRGLXO9pcSsjZoGkewYZitXD44EDfgBQ+BqsAfgUA==
dependencies:
"@babel/runtime" "^7.17.2"
"@mui/private-theming" "^5.5.3"
"@mui/styled-engine" "^5.5.2"
"@mui/private-theming" "^5.6.1"
"@mui/styled-engine" "^5.6.1"
"@mui/types" "^7.1.3"
"@mui/utils" "^5.5.3"
"@mui/utils" "^5.6.1"
clsx "^1.1.1"
csstype "^3.0.11"
prop-types "^15.7.2"
@@ -462,10 +462,10 @@
resolved "https://registry.yarnpkg.com/@mui/types/-/types-7.1.3.tgz#d7636f3046110bcccc63e6acfd100e2ad9ca712a"
integrity sha512-DDF0UhMBo4Uezlk+6QxrlDbchF79XG6Zs0zIewlR4c0Dt6GKVFfUtzPtHCH1tTbcSlq/L2bGEdiaoHBJ9Y1gSA==
"@mui/utils@^5.5.3":
version "5.5.3"
resolved "https://registry.yarnpkg.com/@mui/utils/-/utils-5.5.3.tgz#f6e1f10c0e8f4d0bf750588c2c3a96ad819c5b65"
integrity sha512-t627eVRpl3SlxVya0cIVNs8jPl4KCEiGaTSWY9iKKTcMNaeDbuRML+zv/CFHDPr1zFv+FjJSP02ySB+tZ8xIag==
"@mui/utils@^5.6.1":
version "5.6.1"
resolved "https://registry.yarnpkg.com/@mui/utils/-/utils-5.6.1.tgz#4ab79a21bd481555d9a588f4b18061b3c28ea5db"
integrity sha512-CPrzrkiBusCZBLWu0Sg5MJvR3fKJyK3gKecLVX012LULyqg2U64Oz04BKhfkbtBrPBbSQxM+DWW9B1c9hmV9nQ==
dependencies:
"@babel/runtime" "^7.17.2"
"@types/prop-types" "^15.7.4"
@@ -559,10 +559,10 @@
dependencies:
"@octokit/openapi-types" "^11.2.0"
"@popperjs/core@^2.11.4":
version "2.11.4"
resolved "https://registry.yarnpkg.com/@popperjs/core/-/core-2.11.4.tgz#d8c7b8db9226d2d7664553a0741ad7d0397ee503"
integrity sha512-q/ytXxO5NKvyT37pmisQAItCFqA7FD/vNb8dgaJy3/630Fsc+Mz9/9f2SziBoIZ30TJooXyTwZmhi1zjXmObYg==
"@popperjs/core@^2.11.5":
version "2.11.5"
resolved "https://registry.yarnpkg.com/@popperjs/core/-/core-2.11.5.tgz#db5a11bf66bdab39569719555b0f76e138d7bd64"
integrity sha512-9X2obfABZuDVLCgPK9aX0a/x4jaOEweTTWE2+9sr0Qqqevj2Uv5XorvusThmc9XGYpS9yI+fhh8RTafBtGposw==
"@rollup/pluginutils@^4.1.2":
version "4.2.0"