mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-01-29 17:15:38 +08:00
refactor: impl structs methods
This commit is contained in:
@@ -1,30 +1,147 @@
|
||||
use crate::utils::{config, dirs};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// ### `config.yaml` schema
|
||||
/// here should contain all configuration options.
|
||||
/// See: https://github.com/Dreamacro/clash/wiki/configuration for details
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct ClashConfig {
|
||||
pub port: Option<u32>,
|
||||
|
||||
/// alias to `mixed-port`
|
||||
pub mixed_port: Option<u32>,
|
||||
|
||||
/// alias to `allow-lan`
|
||||
pub allow_lan: Option<bool>,
|
||||
|
||||
/// alias to `external-controller`
|
||||
pub external_ctrl: Option<String>,
|
||||
|
||||
pub secret: Option<String>,
|
||||
}
|
||||
use serde_yaml::{Mapping, Value};
|
||||
use tauri::api::process::{Command, CommandChild, CommandEvent};
|
||||
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct ClashController {
|
||||
pub struct ClashInfo {
|
||||
/// clash sidecar status
|
||||
pub status: String,
|
||||
|
||||
/// clash core port
|
||||
pub port: Option<String>,
|
||||
|
||||
/// same as `external-controller`
|
||||
pub server: Option<String>,
|
||||
|
||||
/// clash secret
|
||||
pub secret: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Clash {
|
||||
/// some info
|
||||
pub info: ClashInfo,
|
||||
|
||||
/// clash sidecar
|
||||
pub sidecar: Option<CommandChild>,
|
||||
}
|
||||
|
||||
static CLASH_CONFIG: &str = "config.yaml";
|
||||
|
||||
// todo: be able to change config field
|
||||
impl Clash {
|
||||
pub fn new() -> Clash {
|
||||
let clash_config = config::read_yaml::<Mapping>(dirs::app_home_dir().join(CLASH_CONFIG));
|
||||
|
||||
let key_port_1 = Value::String("port".to_string());
|
||||
let key_port_2 = Value::String("mixed-port".to_string());
|
||||
let key_server = Value::String("external-controller".to_string());
|
||||
let key_secret = Value::String("secret".to_string());
|
||||
|
||||
let port = match clash_config.get(&key_port_1) {
|
||||
Some(value) => match value {
|
||||
Value::String(val_str) => Some(val_str.clone()),
|
||||
Value::Number(val_num) => Some(val_num.to_string()),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
let port = match port {
|
||||
Some(_) => port,
|
||||
None => match clash_config.get(&key_port_2) {
|
||||
Some(value) => match value {
|
||||
Value::String(val_str) => Some(val_str.clone()),
|
||||
Value::Number(val_num) => Some(val_num.to_string()),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
},
|
||||
};
|
||||
|
||||
let server = match clash_config.get(&key_server) {
|
||||
Some(value) => match value {
|
||||
Value::String(val_str) => Some(val_str.clone()),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
let secret = match clash_config.get(&key_secret) {
|
||||
Some(value) => match value {
|
||||
Value::String(val_str) => Some(val_str.clone()),
|
||||
Value::Bool(val_bool) => Some(val_bool.to_string()),
|
||||
Value::Number(val_num) => Some(val_num.to_string()),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
|
||||
Clash {
|
||||
info: ClashInfo {
|
||||
status: "init".into(),
|
||||
port,
|
||||
server,
|
||||
secret,
|
||||
},
|
||||
sidecar: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// run clash sidecar
|
||||
pub fn run_sidecar(&mut self) -> Result<(), String> {
|
||||
let app_dir = dirs::app_home_dir();
|
||||
let app_dir = app_dir.as_os_str().to_str().unwrap();
|
||||
|
||||
match Command::new_sidecar("clash") {
|
||||
Ok(cmd) => match cmd.args(["-d", app_dir]).spawn() {
|
||||
Ok((mut rx, cmd_child)) => {
|
||||
self.sidecar = Some(cmd_child);
|
||||
|
||||
// clash log
|
||||
tauri::async_runtime::spawn(async move {
|
||||
while let Some(event) = rx.recv().await {
|
||||
match event {
|
||||
CommandEvent::Stdout(line) => log::info!("[stdout]: {}", line),
|
||||
CommandEvent::Stderr(err) => log::error!("[stderr]: {}", err),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
Err(err) => Err(err.to_string()),
|
||||
},
|
||||
Err(err) => Err(err.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// drop clash sidecar
|
||||
pub fn drop_sidecar(&mut self) -> Result<(), String> {
|
||||
if let Some(sidecar) = self.sidecar.take() {
|
||||
if let Err(err) = sidecar.kill() {
|
||||
return Err(format!("failed to drop clash for \"{}\"", err));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// restart clash sidecar
|
||||
pub fn restart_sidecar(&mut self) -> Result<(), String> {
|
||||
self.drop_sidecar()?;
|
||||
self.run_sidecar()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Clash {
|
||||
fn default() -> Self {
|
||||
Clash::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Clash {
|
||||
fn drop(&mut self) {
|
||||
if let Err(err) = self.drop_sidecar() {
|
||||
log::error!("{}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
use crate::utils::{app_home_dir, config};
|
||||
use crate::utils::{config, dirs};
|
||||
use reqwest::header::HeaderMap;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_yaml::{Mapping, Value};
|
||||
use std::collections::HashMap;
|
||||
use std::env::temp_dir;
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use super::ClashInfo;
|
||||
|
||||
/// Define the `profiles.yaml` schema
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct ProfilesConfig {
|
||||
@@ -56,17 +62,18 @@ pub struct ProfileResponse {
|
||||
}
|
||||
|
||||
static PROFILE_YAML: &str = "profiles.yaml";
|
||||
static PROFILE_TEMP: &str = "clash-verge-runtime.yaml";
|
||||
|
||||
impl ProfilesConfig {
|
||||
/// read the config from the file
|
||||
pub fn read_file() -> Self {
|
||||
config::read_yaml::<ProfilesConfig>(app_home_dir().join(PROFILE_YAML))
|
||||
config::read_yaml::<ProfilesConfig>(dirs::app_home_dir().join(PROFILE_YAML))
|
||||
}
|
||||
|
||||
/// save the config to the file
|
||||
pub fn save_file(&self) -> Result<(), String> {
|
||||
config::save_yaml(
|
||||
app_home_dir().join(PROFILE_YAML),
|
||||
dirs::app_home_dir().join(PROFILE_YAML),
|
||||
self,
|
||||
Some("# Profiles Config for Clash Verge\n\n"),
|
||||
)
|
||||
@@ -74,7 +81,7 @@ impl ProfilesConfig {
|
||||
|
||||
/// sync the config between file and memory
|
||||
pub fn sync_file(&mut self) -> Result<(), String> {
|
||||
let data = config::read_yaml::<Self>(app_home_dir().join(PROFILE_YAML));
|
||||
let data = config::read_yaml::<Self>(dirs::app_home_dir().join(PROFILE_YAML));
|
||||
if data.current.is_none() {
|
||||
Err("failed to read profiles.yaml".into())
|
||||
} else {
|
||||
@@ -88,7 +95,7 @@ impl ProfilesConfig {
|
||||
/// and update the config file
|
||||
pub fn import_from_url(&mut self, url: String, result: ProfileResponse) -> Result<(), String> {
|
||||
// save the profile file
|
||||
let path = app_home_dir().join("profiles").join(&result.file);
|
||||
let path = dirs::app_home_dir().join("profiles").join(&result.file);
|
||||
let file_data = result.data.as_bytes();
|
||||
File::create(path).unwrap().write(file_data).unwrap();
|
||||
|
||||
@@ -145,7 +152,7 @@ impl ProfilesConfig {
|
||||
|
||||
// update file
|
||||
let file_path = &items[index].file.as_ref().unwrap();
|
||||
let file_path = app_home_dir().join("profiles").join(file_path);
|
||||
let file_path = dirs::app_home_dir().join("profiles").join(file_path);
|
||||
let file_data = result.data.as_bytes();
|
||||
File::create(file_path).unwrap().write(file_data).unwrap();
|
||||
|
||||
@@ -206,4 +213,99 @@ impl ProfilesConfig {
|
||||
self.current = Some(current);
|
||||
self.save_file()
|
||||
}
|
||||
|
||||
/// activate current profile
|
||||
pub fn activate(&self, clash_config: ClashInfo) -> Result<(), String> {
|
||||
let current = self.current.unwrap_or(0);
|
||||
match self.items.clone() {
|
||||
Some(items) => {
|
||||
if current >= items.len() {
|
||||
return Err("the index out of bound".into());
|
||||
}
|
||||
|
||||
let profile = items[current].clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let mut count = 5; // retry times
|
||||
let mut err = String::from("");
|
||||
while count > 0 {
|
||||
match activate_profile(&profile, &clash_config).await {
|
||||
Ok(_) => return,
|
||||
Err(e) => err = e,
|
||||
}
|
||||
count -= 1;
|
||||
}
|
||||
log::error!("failed to activate for `{}`", err);
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
None => Err("empty profiles".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// put the profile to clash
|
||||
pub async fn activate_profile(profile_item: &ProfileItem, info: &ClashInfo) -> Result<(), String> {
|
||||
// temp profile's path
|
||||
let temp_path = temp_dir().join(PROFILE_TEMP);
|
||||
|
||||
// generate temp profile
|
||||
{
|
||||
let file_name = match profile_item.file.clone() {
|
||||
Some(file_name) => file_name,
|
||||
None => return Err("profile item should have `file` field".into()),
|
||||
};
|
||||
|
||||
let file_path = dirs::app_home_dir().join("profiles").join(file_name);
|
||||
if !file_path.exists() {
|
||||
return Err(format!("profile `{:?}` not exists", file_path));
|
||||
}
|
||||
|
||||
// Only the following fields are allowed:
|
||||
// proxies/proxy-providers/proxy-groups/rule-providers/rules
|
||||
let config = config::read_yaml::<Mapping>(file_path.clone());
|
||||
let mut new_config = Mapping::new();
|
||||
vec![
|
||||
"proxies",
|
||||
"proxy-providers",
|
||||
"proxy-groups",
|
||||
"rule-providers",
|
||||
"rules",
|
||||
]
|
||||
.iter()
|
||||
.map(|item| Value::String(item.to_string()))
|
||||
.for_each(|key| {
|
||||
if config.contains_key(&key) {
|
||||
let value = config[&key].clone();
|
||||
new_config.insert(key, value);
|
||||
}
|
||||
});
|
||||
|
||||
config::save_yaml(
|
||||
temp_path.clone(),
|
||||
&new_config,
|
||||
Some("# Clash Verge Temp File"),
|
||||
)?
|
||||
};
|
||||
|
||||
let server = format!("http://{}/configs", info.server.clone().unwrap());
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("Content-Type", "application/json".parse().unwrap());
|
||||
|
||||
if let Some(secret) = info.secret.clone() {
|
||||
headers.insert(
|
||||
"Authorization",
|
||||
format!("Bearer {}", secret).parse().unwrap(),
|
||||
);
|
||||
}
|
||||
|
||||
let mut data = HashMap::new();
|
||||
data.insert("path", temp_path.as_os_str().to_str().unwrap());
|
||||
|
||||
let client = reqwest::Client::new();
|
||||
match client.put(server).headers(headers).json(&data).send().await {
|
||||
Ok(_) => Ok(()),
|
||||
Err(err) => Err(format!("request failed `{}`", err.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use crate::utils::{config, dirs, sysopt::SysProxyConfig};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// ### `verge.yaml` schema
|
||||
@@ -15,3 +16,78 @@ pub struct VergeConfig {
|
||||
/// set system proxy bypass
|
||||
pub system_proxy_bypass: Option<String>,
|
||||
}
|
||||
|
||||
static VERGE_CONFIG: &str = "verge.yaml";
|
||||
|
||||
impl VergeConfig {
|
||||
pub fn new() -> Self {
|
||||
config::read_yaml::<VergeConfig>(dirs::app_home_dir().join(VERGE_CONFIG))
|
||||
}
|
||||
|
||||
/// Save Verge App Config
|
||||
pub fn save_file(&self) -> Result<(), String> {
|
||||
config::save_yaml(
|
||||
dirs::app_home_dir().join(VERGE_CONFIG),
|
||||
self,
|
||||
Some("# The Config for Clash Verge App\n\n"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Verge {
|
||||
pub config: VergeConfig,
|
||||
|
||||
pub old_sysproxy: Option<SysProxyConfig>,
|
||||
|
||||
pub cur_sysproxy: Option<SysProxyConfig>,
|
||||
}
|
||||
|
||||
impl Default for Verge {
|
||||
fn default() -> Self {
|
||||
Verge::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Verge {
|
||||
pub fn new() -> Self {
|
||||
Verge {
|
||||
config: VergeConfig::new(),
|
||||
old_sysproxy: None,
|
||||
cur_sysproxy: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// init the sysproxy
|
||||
pub fn init_sysproxy(&mut self, port: Option<String>) {
|
||||
if let Some(port) = port {
|
||||
let enable = self.config.enable_system_proxy.clone().unwrap_or(false);
|
||||
|
||||
self.old_sysproxy = match SysProxyConfig::get_sys() {
|
||||
Ok(proxy) => Some(proxy),
|
||||
Err(_) => None,
|
||||
};
|
||||
|
||||
let bypass = self.config.system_proxy_bypass.clone();
|
||||
let sysproxy = SysProxyConfig::new(enable, port, bypass);
|
||||
|
||||
if enable {
|
||||
if sysproxy.set_sys().is_err() {
|
||||
log::error!("failed to set system proxy");
|
||||
}
|
||||
}
|
||||
|
||||
self.cur_sysproxy = Some(sysproxy);
|
||||
}
|
||||
}
|
||||
|
||||
/// reset the sysproxy
|
||||
pub fn reset_sysproxy(&mut self) {
|
||||
if let Some(sysproxy) = self.old_sysproxy.take() {
|
||||
match sysproxy.set_sys() {
|
||||
Ok(_) => self.cur_sysproxy = None,
|
||||
Err(_) => log::error!("failed to reset proxy for"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user