Skip to content

Commit

Permalink
Merge pull request #172 from greenhat616/fix-issues
Browse files Browse the repository at this point in the history
fix: issues
  • Loading branch information
keiko233 authored Dec 20, 2023
2 parents f77bf01 + e0430e1 commit 380a638
Show file tree
Hide file tree
Showing 13 changed files with 161 additions and 31 deletions.
6 changes: 5 additions & 1 deletion .stylelintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ module.exports = {
// 'stylelint-config-prettier'
],
rules: {
"selector-pseudo-class-no-unknown": [
true,
{ ignorePseudoClasses: ["global"] },
],
"font-family-name-quotes": null,
"font-family-no-missing-generic-family-keyword": null,
"max-nesting-depth": [
Expand All @@ -24,7 +28,7 @@ module.exports = {
"declaration-block-no-duplicate-properties": true,
"no-duplicate-selectors": true,
"no-descending-specificity": null,
"selector-class-pattern": "^([a-z][a-z0-9]*)((-|__)[a-z0-9]+)*$",
"selector-class-pattern": null,
"value-no-vendor-prefix": [true, { ignoreValues: ["box"] }],
"at-rule-no-unknown": [
true,
Expand Down
32 changes: 15 additions & 17 deletions backend/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion backend/tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ thiserror = { workspace = true, version = "1.0" }
simd-json = "0.13.4"

[target.'cfg(windows)'.dependencies]
runas = "=1.1.0"
runas = "=1.0.0" # blocked by https://github.com/mitsuhiko/rust-runas/issues/13
deelevate = "0.2.0"
winreg = { version = "0.50", features = ["transactions"] }
windows-sys = { version = "0.48", features = [
Expand Down
11 changes: 11 additions & 0 deletions backend/tauri/src/cmds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,17 @@ pub async fn update_core(core_type: ClashCore) -> CmdResult {
)
}

#[tauri::command]
pub async fn clash_api_get_proxy_delay(
name: String,
url: Option<String>,
) -> CmdResult<clash_api::DelayRes> {
match clash_api::get_proxy_delay(name, url).await {
Ok(res) => Ok(res),
Err(err) => Err(format!("{}", err.to_string())),
}
}

#[cfg(windows)]
pub mod uwp {
use super::*;
Expand Down
20 changes: 20 additions & 0 deletions backend/tauri/src/config/clash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,26 @@ impl IClashTemp {
Err(_) => "127.0.0.1:9090".into(),
}
}

pub fn get_tun_device_ip(&self) -> String {
let config = &self.0;

let ip = config
.get("dns")
.and_then(|value| match value {
Value::Mapping(val_map) => Some(val_map.get("fake-ip-range").and_then(
|fake_ip_range| match fake_ip_range {
Value::String(ip_range_val) => Some(ip_range_val.replace("1/16", "2")),
_ => None,
},
)),
_ => None,
})
// 默认IP
.unwrap_or(Some("198.18.0.2".to_string()));

ip.unwrap()
}
}

#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
Expand Down
38 changes: 32 additions & 6 deletions backend/tauri/src/core/clash_api.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::config::Config;
use anyhow::{bail, Result};
use reqwest::header::HeaderMap;
use serde::{Deserialize, Serialize};
use serde_yaml::Mapping;
use std::collections::HashMap;

Expand All @@ -19,7 +20,7 @@ pub async fn put_configs(path: &str) -> Result<()> {

match response.status().as_u16() {
204 => Ok(()),
status @ _ => {
status => {
bail!("failed to put configs with status \"{status}\"")
}
}
Expand All @@ -36,6 +37,31 @@ pub async fn patch_configs(config: &Mapping) -> Result<()> {
Ok(())
}

#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct DelayRes {
delay: u64,
}

/// GET /proxies/{name}/delay
/// 获取代理延迟
pub async fn get_proxy_delay(name: String, test_url: Option<String>) -> Result<DelayRes> {
let (url, headers) = clash_client_info()?;
let url = format!("{url}/proxies/{name}/delay");
let default_url = "http://www.gstatic.com/generate_204";
let test_url = test_url
.map(|s| if s.is_empty() { default_url.into() } else { s })
.unwrap_or(default_url.into());

let client = reqwest::ClientBuilder::new().no_proxy().build()?;
let builder = client
.get(&url)
.headers(headers)
.query(&[("timeout", "10000"), ("url", &test_url)]);
let response = builder.send().await?;

Ok(response.json::<DelayRes>().await?)
}

/// 根据clash info获取clash服务地址和请求头
fn clash_client_info() -> Result<(String, HeaderMap)> {
let client = { Config::clash().data().get_client_info() };
Expand All @@ -56,12 +82,12 @@ fn clash_client_info() -> Result<(String, HeaderMap)> {
/// 缩短clash的日志
pub fn parse_log(log: String) -> String {
if log.starts_with("time=") && log.len() > 33 {
return (&log[33..]).to_owned();
return log[33..].to_owned();
}
if log.len() > 9 {
return (&log[9..]).to_owned();
return log[9..].to_owned();
}
return log;
log
}

/// 缩短clash -t的错误输出
Expand All @@ -78,15 +104,15 @@ pub fn parse_check_output(log: String) -> String {
};

if mr > m {
return (&log[e..mr]).to_owned();
return log[e..mr].to_owned();
}
}

let l = log.find("error=");
let r = log.find("path=").or(Some(log.len()));

if let (Some(l), Some(r)) = (l, r) {
return (&log[(l + 6)..(r - 1)]).to_owned();
return log[(l + 6)..(r - 1)].to_owned();
}

log
Expand Down
47 changes: 47 additions & 0 deletions backend/tauri/src/core/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,31 @@ impl CoreManager {
if should_kill {
sleep(Duration::from_millis(500)).await;
}
#[cfg(target_os = "macos")]
{
let enable_tun = Config::verge().latest().enable_tun_mode.clone();
let enable_tun = enable_tun.unwrap_or(false);

if enable_tun {
log::debug!(target: "app", "try to set system dns");

match (|| async {
let tun_device_ip = Config::clash().clone().latest().get_tun_device_ip();
// 执行 networksetup -setdnsservers Wi-Fi $tun_device_ip
Command::new("networksetup")
.args(["-setdnsservers", "Wi-Fi", tun_device_ip.as_str()])
.output()
})()
.await
{
Ok(_) => return Ok(()),
Err(err) => {
// 修改这个值,免得stop出错
log::error!(target: "app", "{err}");
}
}
}
}
#[cfg(target_os = "windows")]
{
use super::win_service;
Expand Down Expand Up @@ -253,6 +277,29 @@ impl CoreManager {
return Ok(());
}

#[cfg(target_os = "macos")]
{
let enable_tun = Config::verge().latest().enable_tun_mode.clone();
let enable_tun = enable_tun.unwrap_or(false);

if enable_tun {
log::debug!(target: "app", "try to set system dns");

match (|| {
// 执行 networksetup -setdnsservers Wi-Fi "Empty"
Command::new("networksetup")
.args(["-setdnsservers", "Wi-Fi", "Empty"])
.output()
})() {
Ok(_) => return Ok(()),
Err(err) => {
// 修改这个值,免得stop出错
*self.use_service_mode.lock() = false;
log::error!(target: "app", "{err}");
}
}
}
}
let mut sidecar = self.sidecar.lock();
if let Some(child) = sidecar.take() {
log::debug!(target: "app", "stop the core by sidecar");
Expand Down
1 change: 1 addition & 0 deletions backend/tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ fn main() -> std::io::Result<()> {
cmds::get_runtime_yaml,
cmds::get_runtime_exists,
cmds::get_runtime_logs,
cmds::clash_api_get_proxy_delay,
cmds::uwp::invoke_uwp_tool,
// updater
cmds::fetch_latest_core_versions,
Expand Down
5 changes: 5 additions & 0 deletions src/components/base/base-dialog.module.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.basePageTransition {
:global(.MuiDialog-paper) {
max-height: calc(100vh - 64px);
}
}
18 changes: 15 additions & 3 deletions src/components/base/base-dialog.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { classNames } from "@/utils";
import { LoadingButton } from "@mui/lab";
import {
Button,
Expand All @@ -11,6 +12,8 @@ import {
import { TransitionProps } from "@mui/material/transitions";
import { AnimatePresence, motion } from "framer-motion";
import React, { ReactNode } from "react";
import styles from "./base-dialog.module.scss";

interface Props {
title: ReactNode;
open: boolean;
Expand Down Expand Up @@ -50,7 +53,6 @@ export function BaseDialog(props: Props) {

return (
<Dialog
className="123"
open={open}
onClose={props.onClose}
keepMounted
Expand Down Expand Up @@ -93,12 +95,22 @@ const BaseDialogTransition = React.forwardRef(function BaseDialogTransition(
<AnimatePresence>
{inProp && (
<motion.div
className={classNames(styles.basePageTransition)}
style={{
width: "fit-content",
height: "fit-content",
margin: "auto",
// margin: "auto",
maxHeight: "100vh",
position: "fixed",
}}
initial={{
opacity: 0,
scale: 0,
top: "50%",
left: "50%",
translateX: "-50%",
translateY: "-50%",
}}
initial={{ opacity: 0, scale: 0 }}
animate={{
opacity: 1,
scale: 1,
Expand Down
2 changes: 1 addition & 1 deletion src/services/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export const getRules = async () => {
/// Get Proxy delay
export const getProxyDelay = async (name: string, url?: string) => {
const params = {
timeout: 5000,
timeout: 10000,
url: url || "http://www.gstatic.com/generate_204",
};
const instance = await getAxios();
Expand Down
5 changes: 5 additions & 0 deletions src/services/cmds.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,3 +212,8 @@ export async function updateCore(
export async function collectLogs() {
return invoke<void>("collect_logs");
}

export async function cmdGetProxyDelay(name: string, url?: string) {
name = encodeURIComponent(name);
return invoke<{ delay: number }>("clash_api_get_proxy_delay", { name, url });
}
Loading

0 comments on commit 380a638

Please sign in to comment.