feat: refactor

This commit is contained in:
GyDi
2022-08-12 03:20:55 +08:00
parent ff6abf08b7
commit 142a62e371
22 changed files with 320 additions and 778 deletions

View File

@@ -87,9 +87,6 @@ pub struct Clash {
/// some info
pub info: ClashInfo,
/// save the running config
pub running_config: Option<String>,
}
impl Clash {
@@ -97,11 +94,7 @@ impl Clash {
let config = Clash::read_config();
let info = ClashInfo::from(&config);
Clash {
config,
info,
running_config: None,
}
Clash { config, info }
}
/// get clash config
@@ -118,14 +111,6 @@ impl Clash {
)
}
/// save running config
pub fn set_running_config(&mut self, config: &Mapping) {
self.running_config = match serde_yaml::to_string(config) {
Ok(config_str) => Some(config_str),
Err(_) => None,
};
}
/// patch update the clash config
/// if the port is changed then return true
pub fn patch_config(&mut self, patch: Mapping) -> Result<(bool, bool)> {

View File

@@ -1,66 +0,0 @@
use super::prfitem::PrfItem;
use crate::utils::{config, dirs};
use serde::{Deserialize, Serialize};
use serde_yaml::Mapping;
use std::fs;
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct PrfEnhanced {
pub current: Mapping,
pub chain: Vec<PrfData>,
pub valid: Vec<String>,
pub callback: String,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct PrfEnhancedResult {
pub data: Option<Mapping>,
pub status: String,
pub error: Option<String>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct PrfData {
pub item: PrfItem,
#[serde(skip_serializing_if = "Option::is_none")]
pub merge: Option<Mapping>,
#[serde(skip_serializing_if = "Option::is_none")]
pub script: Option<String>,
}
impl PrfData {
pub fn from_item(item: &PrfItem) -> Option<PrfData> {
match item.itype.as_ref() {
Some(itype) => {
let file = item.file.clone()?;
let path = dirs::app_profiles_dir().join(file);
if !path.exists() {
return None;
}
match itype.as_str() {
"script" => Some(PrfData {
item: item.clone(),
script: Some(fs::read_to_string(path).unwrap_or("".into())),
merge: None,
}),
"merge" => Some(PrfData {
item: item.clone(),
merge: Some(config::read_yaml::<Mapping>(path)),
script: None,
}),
_ => None,
}
}
None => None,
}
}
}

View File

@@ -1,21 +1,16 @@
use self::notice::Notice;
use self::sysopt::Sysopt;
use self::timer::Timer;
use crate::config::runtime_config;
use crate::core::enhance::PrfEnhancedResult;
use crate::config::enhance_config;
use crate::log_if_err;
use crate::utils::help;
use anyhow::{bail, Result};
use parking_lot::Mutex;
use serde_yaml::Mapping;
use serde_yaml::Value;
use std::sync::Arc;
use std::time::Duration;
use tauri::{AppHandle, Manager, Window};
use tokio::time::sleep;
mod clash;
mod enhance;
mod notice;
mod prfitem;
mod profiles;
@@ -25,47 +20,33 @@ mod timer;
mod verge;
pub use self::clash::*;
pub use self::enhance::*;
pub use self::prfitem::*;
pub use self::profiles::*;
pub use self::service::*;
pub use self::verge::*;
/// close the window for slient start
/// after enhance mode
static mut WINDOW_CLOSABLE: bool = true;
#[derive(Clone)]
pub struct Core {
pub clash: Arc<Mutex<Clash>>,
pub verge: Arc<Mutex<Verge>>,
pub profiles: Arc<Mutex<Profiles>>,
pub service: Arc<Mutex<Service>>,
pub sysopt: Arc<Mutex<Sysopt>>,
pub timer: Arc<Mutex<Timer>>,
pub runtime: Arc<Mutex<RuntimeResult>>,
pub window: Arc<Mutex<Option<Window>>>,
}
impl Core {
pub fn new() -> Core {
let clash = Clash::new();
let verge = Verge::new();
let profiles = Profiles::new();
let service = Service::new();
Core {
clash: Arc::new(Mutex::new(clash)),
verge: Arc::new(Mutex::new(verge)),
profiles: Arc::new(Mutex::new(profiles)),
service: Arc::new(Mutex::new(service)),
clash: Arc::new(Mutex::new(Clash::new())),
verge: Arc::new(Mutex::new(Verge::new())),
profiles: Arc::new(Mutex::new(Profiles::new())),
service: Arc::new(Mutex::new(Service::new())),
sysopt: Arc::new(Mutex::new(Sysopt::new())),
timer: Arc::new(Mutex::new(Timer::new())),
runtime: Arc::new(Mutex::new(RuntimeResult::default())),
window: Arc::new(Mutex::new(None)),
}
}
@@ -95,15 +76,6 @@ impl Core {
// let silent_start = verge.enable_silent_start.clone();
let auto_launch = verge.enable_auto_launch.clone();
// silent start
// if silent_start.unwrap_or(false) {
// let window = self.window.lock();
// window.as_ref().map(|win| {
// win.hide().unwrap();
// });
// }
let mut sysopt = self.sysopt.lock();
sysopt.init_sysproxy(clash.info.port.clone(), &verge);
@@ -116,13 +88,6 @@ impl Core {
log_if_err!(self.update_systray(&app_handle));
log_if_err!(self.update_systray_clash(&app_handle));
// // wait the window setup during resolve app
// let core = self.clone();
// tauri::async_runtime::spawn(async move {
// sleep(Duration::from_secs(2)).await;
// log_if_err!(core.activate_enhanced(true));
// });
// timer initialize
let mut timer = self.timer.lock();
timer.set_core(self.clone());
@@ -140,9 +105,7 @@ impl Core {
let mut service = self.service.lock();
service.restart()?;
drop(service);
self.activate()
// self.activate_enhanced(true)
}
/// change the clash core
@@ -167,7 +130,6 @@ impl Core {
drop(service);
self.activate()
// self.activate_enhanced(true)
}
/// Patch Clash
@@ -186,7 +148,6 @@ impl Core {
drop(service);
self.activate()?;
// self.activate_enhanced(true)?;
let mut sysopt = self.sysopt.lock();
let verge = self.verge.lock();
@@ -260,7 +221,6 @@ impl Core {
}
if tun_mode.is_some() {
// self.activate_enhanced(false)?;
self.activate()?;
}
@@ -345,33 +305,34 @@ impl Core {
/// activate the profile
/// auto activate enhanced profile
pub fn activate(&self) -> Result<()> {
let profiles = self.profiles.lock();
let profile_config = profiles.gen_activate()?;
let profile_enhanced = profiles.gen_enhanced("".into())?;
drop(profiles);
let profile_activate = {
let profiles = self.profiles.lock();
profiles.gen_activate()?
};
let (clash_config, clash_info) = {
let clash = self.clash.lock();
(clash.config.clone(), clash.info.clone())
};
let tun_mode = {
let verge = self.verge.lock();
verge.enable_tun_mode.unwrap_or(false)
};
let mut clash = self.clash.lock();
let clash_config = clash.config.clone();
let (config, result) = runtime_config(
let (config, exists_keys, logs) = enhance_config(
clash_config,
profile_config,
profile_enhanced.chain,
profile_enhanced.valid,
profile_activate.current,
profile_activate.chain,
profile_activate.valid,
tun_mode,
);
dbg!(result);
let info = clash.info.clone();
clash.set_running_config(&config);
drop(clash);
let mut runtime = self.runtime.lock();
runtime.config = Some(config.clone());
runtime.config_yaml = Some(serde_yaml::to_string(&config).unwrap_or("".into()));
runtime.exists_keys = exists_keys;
runtime.chain_logs = logs;
let notice = {
let window = self.window.lock();
@@ -379,109 +340,14 @@ impl Core {
};
let service = self.service.lock();
service.set_config(info, config, notice)
service.set_config(clash_info, config, notice)
}
// /// Enhanced
// /// enhanced profiles mode
// pub fn activate_enhanced(&self, skip: bool) -> Result<()> {
// let window = self.window.lock();
// if window.is_none() {
// bail!("failed to get the main window");
// }
// let event_name = help::get_uid("e");
// let event_name = format!("enhanced-cb-{event_name}");
// // generate the payload
// let payload = {
// let profiles = self.profiles.lock();
// profiles.gen_enhanced(event_name.clone())?
// };
// // do not run enhanced
// if payload.chain.len() == 0 {
// if skip {
// return Ok(());
// }
// drop(window);
// return self.activate();
// }
// let tun_mode = {
// let verge = self.verge.lock();
// verge.enable_tun_mode.unwrap_or(false)
// };
// let info = {
// let clash = self.clash.lock();
// clash.info.clone()
// };
// let notice = Notice::from(window.clone());
// let service = self.service.clone();
// let window = window.clone().unwrap();
// window.once(&event_name, move |event| {
// let result = event.payload();
// if result.is_none() {
// log::warn!(target: "app", "event payload result is none");
// return;
// }
// let result = result.unwrap();
// let result: PrfEnhancedResult = serde_json::from_str(result).unwrap();
// if let Some(data) = result.data {
// let mut config = Clash::read_config();
// let filter_data = Clash::loose_filter(data); // loose filter
// for (key, value) in filter_data.into_iter() {
// config.insert(key, value);
// }
// let config = Clash::_tun_mode(config, tun_mode);
// let service = service.lock();
// log_if_err!(service.set_config(info, config, notice));
// log::info!(target: "app", "profile enhanced status {}", result.status);
// }
// result.error.map(|err| log::error!(target: "app", "{err}"));
// });
// let verge = self.verge.lock();
// let silent_start = verge.enable_silent_start.clone();
// let closable = unsafe { WINDOW_CLOSABLE };
// if silent_start.unwrap_or(false) && closable {
// unsafe {
// WINDOW_CLOSABLE = false;
// }
// window.emit("script-handler-close", payload).unwrap();
// } else {
// window.emit("script-handler", payload).unwrap();
// }
// Ok(())
// }
}
impl Core {
/// Static function
/// update profile item
pub async fn update_profile_item(
core: Core,
uid: String,
option: Option<PrfOption>,
) -> Result<()> {
pub async fn update_profile_item(&self, uid: String, option: Option<PrfOption>) -> Result<()> {
let (url, opt) = {
let profiles = core.profiles.lock();
let profiles = self.profiles.lock();
let item = profiles.get_item(&uid)?;
if let Some(typ) = item.itype.as_ref() {
@@ -490,32 +356,27 @@ impl Core {
// reactivate the config
if Some(uid) == profiles.get_current() {
drop(profiles);
// return core.activate_enhanced(false);
return core.activate();
return self.activate();
}
return Ok(());
}
}
if item.url.is_none() {
bail!("failed to get the profile item url");
}
(item.url.clone().unwrap(), item.option.clone())
};
let merged_opt = PrfOption::merge(opt, option);
let item = PrfItem::from_url(&url, None, None, merged_opt).await?;
let mut profiles = core.profiles.lock();
let mut profiles = self.profiles.lock();
profiles.update_item(uid.clone(), item)?;
// reactivate the profile
if Some(uid) == profiles.get_current() {
drop(profiles);
// core.activate_enhanced(false)?;
core.activate()?;
self.activate()?;
}
Ok(())

View File

@@ -11,6 +11,7 @@ impl Notice {
Notice { win }
}
#[allow(unused)]
pub fn set_win(&mut self, win: Option<Window>) {
self.win = win;
}
@@ -27,6 +28,7 @@ impl Notice {
}
}
#[allow(unused)]
pub fn refresh_profiles(&self) {
if let Some(window) = self.win.as_ref() {
log_if_err!(window.emit("verge://refresh-profiles-config", "yes"));

View File

@@ -1,4 +1,4 @@
use crate::utils::{dirs, help, tmpl};
use crate::utils::{config, dirs, help, tmpl};
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use serde_yaml::Mapping;
@@ -333,4 +333,40 @@ impl PrfItem {
let path = dirs::app_profiles_dir().join(file);
fs::write(path, data.as_bytes()).context("failed to save the file")
}
/// get the data for enhanced mode
pub fn to_enhance(&self) -> Option<ChainItem> {
let itype = self.itype.as_ref()?.as_str();
let file = self.file.clone()?;
let uid = self.uid.clone().unwrap_or("".into());
let path = dirs::app_profiles_dir().join(file);
if !path.exists() {
return None;
}
match itype {
"script" => Some(ChainItem {
uid,
data: ChainType::Script(fs::read_to_string(path).unwrap_or("".into())),
}),
"merge" => Some(ChainItem {
uid,
data: ChainType::Merge(config::read_yaml::<Mapping>(path)),
}),
_ => None,
}
}
}
#[derive(Debug, Clone)]
pub struct ChainItem {
pub uid: String,
pub data: ChainType,
}
#[derive(Debug, Clone)]
pub enum ChainType {
Merge(Mapping),
Script(String),
}

View File

@@ -1,9 +1,10 @@
use super::enhance::{PrfData, PrfEnhanced};
use super::prfitem::PrfItem;
use super::ChainItem;
use crate::utils::{config, dirs, help};
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use serde_yaml::Mapping;
use std::collections::HashMap;
use std::{fs, io::Write};
///
@@ -262,8 +263,8 @@ impl Profiles {
Ok(current == uid)
}
/// only generate config mapping
pub fn gen_activate(&self) -> Result<Mapping> {
/// generate the current Mapping data
fn gen_current(&self) -> Result<Mapping> {
let config = Mapping::new();
if self.current.is_none() || self.items.is_none() {
@@ -271,7 +272,6 @@ impl Profiles {
}
let current = self.current.clone().unwrap();
for item in self.items.as_ref().unwrap().iter() {
if item.uid == Some(current.clone()) {
let file_path = match item.file.clone() {
@@ -286,34 +286,43 @@ impl Profiles {
return Ok(config::read_yaml::<Mapping>(file_path.clone()));
}
}
bail!("failed to found the uid \"{current}\"");
}
/// gen the enhanced profiles
pub fn gen_enhanced(&self, callback: String) -> Result<PrfEnhanced> {
let current = self.gen_activate()?;
/// generate the data for activate clash config
pub fn gen_activate(&self) -> Result<PrfActivate> {
let current = self.gen_current()?;
let chain = match self.chain.as_ref() {
Some(chain) => chain
.iter()
.map(|uid| self.get_item(uid))
.filter(|item| item.is_ok())
.map(|item| item.unwrap())
.map(|item| PrfData::from_item(item))
.filter(|o| o.is_some())
.map(|o| o.unwrap())
.collect::<Vec<PrfData>>(),
.filter_map(|uid| self.get_item(uid).ok())
.filter_map(|item| item.to_enhance())
.collect::<Vec<ChainItem>>(),
None => vec![],
};
let valid = self.valid.clone().unwrap_or(vec![]);
Ok(PrfEnhanced {
Ok(PrfActivate {
current,
chain,
valid,
callback,
})
}
}
#[derive(Default, Clone)]
pub struct PrfActivate {
pub current: Mapping,
pub chain: Vec<ChainItem>,
pub valid: Vec<String>,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct RuntimeResult {
pub config: Option<Mapping>,
pub config_yaml: Option<String>,
// 记录在配置中包括merge和script生成的出现过的keys
// 这些keys不一定都生效
pub exists_keys: Vec<String>,
pub chain_logs: HashMap<String, Vec<(String, String)>>,
}

View File

@@ -140,7 +140,7 @@ impl Timer {
/// the task runner
async fn async_task(core: Core, uid: String) {
log::info!(target: "app", "running timer task `{uid}`");
log_if_err!(Core::update_profile_item(core, uid, None).await);
log_if_err!(core.update_profile_item(uid, None).await);
}
}