mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-01-29 08:45:41 +08:00
chore: format rust code
This commit is contained in:
@@ -5,62 +5,61 @@ use tauri::{AppHandle, Manager, Window};
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct Handle {
|
||||
pub app_handle: Option<AppHandle>,
|
||||
pub app_handle: Option<AppHandle>,
|
||||
}
|
||||
|
||||
impl Handle {
|
||||
pub fn set_inner(&mut self, app_handle: AppHandle) {
|
||||
self.app_handle = Some(app_handle);
|
||||
}
|
||||
|
||||
pub fn get_window(&self) -> Option<Window> {
|
||||
self
|
||||
.app_handle
|
||||
.as_ref()
|
||||
.map_or(None, |a| a.get_window("main"))
|
||||
}
|
||||
|
||||
pub fn refresh_clash(&self) {
|
||||
if let Some(window) = self.get_window() {
|
||||
log_if_err!(window.emit("verge://refresh-clash-config", "yes"));
|
||||
pub fn set_inner(&mut self, app_handle: AppHandle) {
|
||||
self.app_handle = Some(app_handle);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn refresh_verge(&self) {
|
||||
if let Some(window) = self.get_window() {
|
||||
log_if_err!(window.emit("verge://refresh-verge-config", "yes"));
|
||||
pub fn get_window(&self) -> Option<Window> {
|
||||
self.app_handle
|
||||
.as_ref()
|
||||
.map_or(None, |a| a.get_window("main"))
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
pub fn refresh_profiles(&self) {
|
||||
if let Some(window) = self.get_window() {
|
||||
log_if_err!(window.emit("verge://refresh-profiles-config", "yes"));
|
||||
pub fn refresh_clash(&self) {
|
||||
if let Some(window) = self.get_window() {
|
||||
log_if_err!(window.emit("verge://refresh-clash-config", "yes"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn notice_message(&self, status: String, msg: String) {
|
||||
if let Some(window) = self.get_window() {
|
||||
log_if_err!(window.emit("verge://notice-message", (status, msg)));
|
||||
pub fn refresh_verge(&self) {
|
||||
if let Some(window) = self.get_window() {
|
||||
log_if_err!(window.emit("verge://refresh-verge-config", "yes"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_systray(&self) -> Result<()> {
|
||||
if self.app_handle.is_none() {
|
||||
bail!("update_systray unhandle error");
|
||||
#[allow(unused)]
|
||||
pub fn refresh_profiles(&self) {
|
||||
if let Some(window) = self.get_window() {
|
||||
log_if_err!(window.emit("verge://refresh-profiles-config", "yes"));
|
||||
}
|
||||
}
|
||||
let app_handle = self.app_handle.as_ref().unwrap();
|
||||
Tray::update_systray(app_handle)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// update the system tray state
|
||||
pub fn update_systray_part(&self) -> Result<()> {
|
||||
if self.app_handle.is_none() {
|
||||
bail!("update_systray unhandle error");
|
||||
pub fn notice_message(&self, status: String, msg: String) {
|
||||
if let Some(window) = self.get_window() {
|
||||
log_if_err!(window.emit("verge://notice-message", (status, msg)));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_systray(&self) -> Result<()> {
|
||||
if self.app_handle.is_none() {
|
||||
bail!("update_systray unhandle error");
|
||||
}
|
||||
let app_handle = self.app_handle.as_ref().unwrap();
|
||||
Tray::update_systray(app_handle)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// update the system tray state
|
||||
pub fn update_systray_part(&self) -> Result<()> {
|
||||
if self.app_handle.is_none() {
|
||||
bail!("update_systray unhandle error");
|
||||
}
|
||||
let app_handle = self.app_handle.as_ref().unwrap();
|
||||
Tray::update_part(app_handle)?;
|
||||
Ok(())
|
||||
}
|
||||
let app_handle = self.app_handle.as_ref().unwrap();
|
||||
Tray::update_part(app_handle)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,150 +4,150 @@ use std::collections::HashMap;
|
||||
use tauri::{AppHandle, GlobalShortcutManager};
|
||||
|
||||
pub struct Hotkey {
|
||||
current: Vec<String>, // 保存当前的热键设置
|
||||
manager: Option<AppHandle>,
|
||||
current: Vec<String>, // 保存当前的热键设置
|
||||
manager: Option<AppHandle>,
|
||||
}
|
||||
|
||||
impl Hotkey {
|
||||
pub fn new() -> Hotkey {
|
||||
Hotkey {
|
||||
current: Vec::new(),
|
||||
manager: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init(&mut self, app_handle: AppHandle) -> Result<()> {
|
||||
self.manager = Some(app_handle);
|
||||
let data = Data::global();
|
||||
let verge = data.verge.lock();
|
||||
|
||||
if let Some(hotkeys) = verge.hotkeys.as_ref() {
|
||||
for hotkey in hotkeys.iter() {
|
||||
let mut iter = hotkey.split(',');
|
||||
let func = iter.next();
|
||||
let key = iter.next();
|
||||
|
||||
if func.is_some() && key.is_some() {
|
||||
log_if_err!(self.register(key.unwrap(), func.unwrap()));
|
||||
} else {
|
||||
log::error!(target: "app", "invalid hotkey \"{}\":\"{}\"", key.unwrap_or("None"), func.unwrap_or("None"));
|
||||
pub fn new() -> Hotkey {
|
||||
Hotkey {
|
||||
current: Vec::new(),
|
||||
manager: None,
|
||||
}
|
||||
}
|
||||
self.current = hotkeys.clone();
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
pub fn init(&mut self, app_handle: AppHandle) -> Result<()> {
|
||||
self.manager = Some(app_handle);
|
||||
let data = Data::global();
|
||||
let verge = data.verge.lock();
|
||||
|
||||
fn get_manager(&self) -> Result<impl GlobalShortcutManager> {
|
||||
if self.manager.is_none() {
|
||||
bail!("failed to get hotkey manager");
|
||||
}
|
||||
Ok(self.manager.as_ref().unwrap().global_shortcut_manager())
|
||||
}
|
||||
if let Some(hotkeys) = verge.hotkeys.as_ref() {
|
||||
for hotkey in hotkeys.iter() {
|
||||
let mut iter = hotkey.split(',');
|
||||
let func = iter.next();
|
||||
let key = iter.next();
|
||||
|
||||
fn register(&mut self, hotkey: &str, func: &str) -> Result<()> {
|
||||
let mut manager = self.get_manager()?;
|
||||
|
||||
if manager.is_registered(hotkey)? {
|
||||
manager.unregister(hotkey)?;
|
||||
}
|
||||
|
||||
let f = match func.trim() {
|
||||
"clash_mode_rule" => || feat::change_clash_mode("rule"),
|
||||
"clash_mode_global" => || feat::change_clash_mode("global"),
|
||||
"clash_mode_direct" => || feat::change_clash_mode("direct"),
|
||||
"clash_mode_script" => || feat::change_clash_mode("script"),
|
||||
"toggle_system_proxy" => || feat::toggle_system_proxy(),
|
||||
"enable_system_proxy" => || feat::enable_system_proxy(),
|
||||
"disable_system_proxy" => || feat::disable_system_proxy(),
|
||||
"toggle_tun_mode" => || feat::toggle_tun_mode(),
|
||||
"enable_tun_mode" => || feat::enable_tun_mode(),
|
||||
"disable_tun_mode" => || feat::disable_tun_mode(),
|
||||
|
||||
_ => bail!("invalid function \"{func}\""),
|
||||
};
|
||||
|
||||
manager.register(hotkey, f)?;
|
||||
log::info!(target: "app", "register hotkey {hotkey} {func}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn unregister(&mut self, hotkey: &str) -> Result<()> {
|
||||
self.get_manager()?.unregister(&hotkey)?;
|
||||
log::info!(target: "app", "unregister hotkey {hotkey}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn update(&mut self, new_hotkeys: Vec<String>) -> Result<()> {
|
||||
let current = self.current.to_owned();
|
||||
let old_map = Self::get_map_from_vec(¤t);
|
||||
let new_map = Self::get_map_from_vec(&new_hotkeys);
|
||||
|
||||
let (del, add) = Self::get_diff(old_map, new_map);
|
||||
|
||||
del.iter().for_each(|key| {
|
||||
let _ = self.unregister(key);
|
||||
});
|
||||
|
||||
add.iter().for_each(|(key, func)| {
|
||||
log_if_err!(self.register(key, func));
|
||||
});
|
||||
|
||||
self.current = new_hotkeys;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_map_from_vec<'a>(hotkeys: &'a Vec<String>) -> HashMap<&'a str, &'a str> {
|
||||
let mut map = HashMap::new();
|
||||
|
||||
hotkeys.iter().for_each(|hotkey| {
|
||||
let mut iter = hotkey.split(',');
|
||||
let func = iter.next();
|
||||
let key = iter.next();
|
||||
|
||||
if func.is_some() && key.is_some() {
|
||||
let func = func.unwrap().trim();
|
||||
let key = key.unwrap().trim();
|
||||
map.insert(key, func);
|
||||
}
|
||||
});
|
||||
map
|
||||
}
|
||||
|
||||
fn get_diff<'a>(
|
||||
old_map: HashMap<&'a str, &'a str>,
|
||||
new_map: HashMap<&'a str, &'a str>,
|
||||
) -> (Vec<&'a str>, Vec<(&'a str, &'a str)>) {
|
||||
let mut del_list = vec![];
|
||||
let mut add_list = vec![];
|
||||
|
||||
old_map.iter().for_each(|(&key, func)| {
|
||||
match new_map.get(key) {
|
||||
Some(new_func) => {
|
||||
if new_func != func {
|
||||
del_list.push(key);
|
||||
add_list.push((key, *new_func));
|
||||
}
|
||||
if func.is_some() && key.is_some() {
|
||||
log_if_err!(self.register(key.unwrap(), func.unwrap()));
|
||||
} else {
|
||||
log::error!(target: "app", "invalid hotkey \"{}\":\"{}\"", key.unwrap_or("None"), func.unwrap_or("None"));
|
||||
}
|
||||
}
|
||||
self.current = hotkeys.clone();
|
||||
}
|
||||
None => del_list.push(key),
|
||||
};
|
||||
});
|
||||
|
||||
new_map.iter().for_each(|(&key, &func)| {
|
||||
if old_map.get(key).is_none() {
|
||||
add_list.push((key, func));
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
(del_list, add_list)
|
||||
}
|
||||
fn get_manager(&self) -> Result<impl GlobalShortcutManager> {
|
||||
if self.manager.is_none() {
|
||||
bail!("failed to get hotkey manager");
|
||||
}
|
||||
Ok(self.manager.as_ref().unwrap().global_shortcut_manager())
|
||||
}
|
||||
|
||||
fn register(&mut self, hotkey: &str, func: &str) -> Result<()> {
|
||||
let mut manager = self.get_manager()?;
|
||||
|
||||
if manager.is_registered(hotkey)? {
|
||||
manager.unregister(hotkey)?;
|
||||
}
|
||||
|
||||
let f = match func.trim() {
|
||||
"clash_mode_rule" => || feat::change_clash_mode("rule"),
|
||||
"clash_mode_global" => || feat::change_clash_mode("global"),
|
||||
"clash_mode_direct" => || feat::change_clash_mode("direct"),
|
||||
"clash_mode_script" => || feat::change_clash_mode("script"),
|
||||
"toggle_system_proxy" => || feat::toggle_system_proxy(),
|
||||
"enable_system_proxy" => || feat::enable_system_proxy(),
|
||||
"disable_system_proxy" => || feat::disable_system_proxy(),
|
||||
"toggle_tun_mode" => || feat::toggle_tun_mode(),
|
||||
"enable_tun_mode" => || feat::enable_tun_mode(),
|
||||
"disable_tun_mode" => || feat::disable_tun_mode(),
|
||||
|
||||
_ => bail!("invalid function \"{func}\""),
|
||||
};
|
||||
|
||||
manager.register(hotkey, f)?;
|
||||
log::info!(target: "app", "register hotkey {hotkey} {func}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn unregister(&mut self, hotkey: &str) -> Result<()> {
|
||||
self.get_manager()?.unregister(&hotkey)?;
|
||||
log::info!(target: "app", "unregister hotkey {hotkey}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn update(&mut self, new_hotkeys: Vec<String>) -> Result<()> {
|
||||
let current = self.current.to_owned();
|
||||
let old_map = Self::get_map_from_vec(¤t);
|
||||
let new_map = Self::get_map_from_vec(&new_hotkeys);
|
||||
|
||||
let (del, add) = Self::get_diff(old_map, new_map);
|
||||
|
||||
del.iter().for_each(|key| {
|
||||
let _ = self.unregister(key);
|
||||
});
|
||||
|
||||
add.iter().for_each(|(key, func)| {
|
||||
log_if_err!(self.register(key, func));
|
||||
});
|
||||
|
||||
self.current = new_hotkeys;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_map_from_vec<'a>(hotkeys: &'a Vec<String>) -> HashMap<&'a str, &'a str> {
|
||||
let mut map = HashMap::new();
|
||||
|
||||
hotkeys.iter().for_each(|hotkey| {
|
||||
let mut iter = hotkey.split(',');
|
||||
let func = iter.next();
|
||||
let key = iter.next();
|
||||
|
||||
if func.is_some() && key.is_some() {
|
||||
let func = func.unwrap().trim();
|
||||
let key = key.unwrap().trim();
|
||||
map.insert(key, func);
|
||||
}
|
||||
});
|
||||
map
|
||||
}
|
||||
|
||||
fn get_diff<'a>(
|
||||
old_map: HashMap<&'a str, &'a str>,
|
||||
new_map: HashMap<&'a str, &'a str>,
|
||||
) -> (Vec<&'a str>, Vec<(&'a str, &'a str)>) {
|
||||
let mut del_list = vec![];
|
||||
let mut add_list = vec![];
|
||||
|
||||
old_map.iter().for_each(|(&key, func)| {
|
||||
match new_map.get(key) {
|
||||
Some(new_func) => {
|
||||
if new_func != func {
|
||||
del_list.push(key);
|
||||
add_list.push((key, *new_func));
|
||||
}
|
||||
}
|
||||
None => del_list.push(key),
|
||||
};
|
||||
});
|
||||
|
||||
new_map.iter().for_each(|(&key, &func)| {
|
||||
if old_map.get(key).is_none() {
|
||||
add_list.push((key, func));
|
||||
}
|
||||
});
|
||||
|
||||
(del_list, add_list)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Hotkey {
|
||||
fn drop(&mut self) {
|
||||
if let Ok(mut manager) = self.get_manager() {
|
||||
let _ = manager.unregister_all();
|
||||
fn drop(&mut self) {
|
||||
if let Ok(mut manager) = self.get_manager() {
|
||||
let _ = manager.unregister_all();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,328 +22,328 @@ pub use self::service::*;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Core {
|
||||
pub service: Arc<Mutex<Service>>,
|
||||
pub sysopt: Arc<Mutex<Sysopt>>,
|
||||
pub timer: Arc<Mutex<Timer>>,
|
||||
pub hotkey: Arc<Mutex<Hotkey>>,
|
||||
pub runtime: Arc<Mutex<RuntimeResult>>,
|
||||
pub handle: Arc<Mutex<Handle>>,
|
||||
pub service: Arc<Mutex<Service>>,
|
||||
pub sysopt: Arc<Mutex<Sysopt>>,
|
||||
pub timer: Arc<Mutex<Timer>>,
|
||||
pub hotkey: Arc<Mutex<Hotkey>>,
|
||||
pub runtime: Arc<Mutex<RuntimeResult>>,
|
||||
pub handle: Arc<Mutex<Handle>>,
|
||||
}
|
||||
|
||||
impl Core {
|
||||
pub fn global() -> &'static Core {
|
||||
static CORE: OnceCell<Core> = OnceCell::new();
|
||||
pub fn global() -> &'static Core {
|
||||
static CORE: OnceCell<Core> = OnceCell::new();
|
||||
|
||||
CORE.get_or_init(|| Core {
|
||||
service: Arc::new(Mutex::new(Service::new())),
|
||||
sysopt: Arc::new(Mutex::new(Sysopt::new())),
|
||||
timer: Arc::new(Mutex::new(Timer::new())),
|
||||
hotkey: Arc::new(Mutex::new(Hotkey::new())),
|
||||
runtime: Arc::new(Mutex::new(RuntimeResult::default())),
|
||||
handle: Arc::new(Mutex::new(Handle::default())),
|
||||
})
|
||||
}
|
||||
|
||||
/// initialize the core state
|
||||
pub fn init(&self, app_handle: tauri::AppHandle) {
|
||||
// kill old clash process
|
||||
Service::kill_old_clash();
|
||||
|
||||
let mut handle = self.handle.lock();
|
||||
handle.set_inner(app_handle.clone());
|
||||
drop(handle);
|
||||
|
||||
let mut service = self.service.lock();
|
||||
log_if_err!(service.start());
|
||||
drop(service);
|
||||
|
||||
log_if_err!(self.activate());
|
||||
|
||||
let mut sysopt = self.sysopt.lock();
|
||||
log_if_err!(sysopt.init_launch());
|
||||
log_if_err!(sysopt.init_sysproxy());
|
||||
drop(sysopt);
|
||||
|
||||
let handle = self.handle.lock();
|
||||
log_if_err!(handle.update_systray_part());
|
||||
drop(handle);
|
||||
|
||||
let mut hotkey = self.hotkey.lock();
|
||||
log_if_err!(hotkey.init(app_handle));
|
||||
drop(hotkey);
|
||||
|
||||
// timer initialize
|
||||
let mut timer = self.timer.lock();
|
||||
log_if_err!(timer.restore());
|
||||
}
|
||||
|
||||
/// restart the clash sidecar
|
||||
pub fn restart_clash(&self) -> Result<()> {
|
||||
let mut service = self.service.lock();
|
||||
service.restart()?;
|
||||
drop(service);
|
||||
self.activate()
|
||||
}
|
||||
|
||||
/// change the clash core
|
||||
pub fn change_core(&self, clash_core: Option<String>) -> Result<()> {
|
||||
let clash_core = clash_core.unwrap_or("clash".into());
|
||||
|
||||
if &clash_core != "clash" && &clash_core != "clash-meta" {
|
||||
bail!("invalid clash core name \"{clash_core}\"");
|
||||
CORE.get_or_init(|| Core {
|
||||
service: Arc::new(Mutex::new(Service::new())),
|
||||
sysopt: Arc::new(Mutex::new(Sysopt::new())),
|
||||
timer: Arc::new(Mutex::new(Timer::new())),
|
||||
hotkey: Arc::new(Mutex::new(Hotkey::new())),
|
||||
runtime: Arc::new(Mutex::new(RuntimeResult::default())),
|
||||
handle: Arc::new(Mutex::new(Handle::default())),
|
||||
})
|
||||
}
|
||||
|
||||
let global = Data::global();
|
||||
let mut verge = global.verge.lock();
|
||||
verge.patch_config(Verge {
|
||||
clash_core: Some(clash_core.clone()),
|
||||
..Verge::default()
|
||||
})?;
|
||||
drop(verge);
|
||||
/// initialize the core state
|
||||
pub fn init(&self, app_handle: tauri::AppHandle) {
|
||||
// kill old clash process
|
||||
Service::kill_old_clash();
|
||||
|
||||
let mut service = self.service.lock();
|
||||
service.clear_logs();
|
||||
service.restart()?;
|
||||
drop(service);
|
||||
let mut handle = self.handle.lock();
|
||||
handle.set_inner(app_handle.clone());
|
||||
drop(handle);
|
||||
|
||||
self.activate()
|
||||
}
|
||||
let mut service = self.service.lock();
|
||||
log_if_err!(service.start());
|
||||
drop(service);
|
||||
|
||||
/// Patch Clash
|
||||
/// handle the clash config changed
|
||||
pub fn patch_clash(&self, patch: Mapping) -> Result<()> {
|
||||
let patch_cloned = patch.clone();
|
||||
let clash_mode = patch.get("mode");
|
||||
let mixed_port = patch.get("mixed-port");
|
||||
let external = patch.get("external-controller");
|
||||
let secret = patch.get("secret");
|
||||
log_if_err!(self.activate());
|
||||
|
||||
let valid_port = {
|
||||
let global = Data::global();
|
||||
let mut clash = global.clash.lock();
|
||||
clash.patch_config(patch_cloned)?;
|
||||
clash.info.port.is_some()
|
||||
};
|
||||
let mut sysopt = self.sysopt.lock();
|
||||
log_if_err!(sysopt.init_launch());
|
||||
log_if_err!(sysopt.init_sysproxy());
|
||||
drop(sysopt);
|
||||
|
||||
// todo: port check
|
||||
if (mixed_port.is_some() && valid_port) || external.is_some() || secret.is_some() {
|
||||
let mut service = self.service.lock();
|
||||
service.restart()?;
|
||||
drop(service);
|
||||
let handle = self.handle.lock();
|
||||
log_if_err!(handle.update_systray_part());
|
||||
drop(handle);
|
||||
|
||||
self.activate()?;
|
||||
let mut hotkey = self.hotkey.lock();
|
||||
log_if_err!(hotkey.init(app_handle));
|
||||
drop(hotkey);
|
||||
|
||||
let mut sysopt = self.sysopt.lock();
|
||||
sysopt.init_sysproxy()?;
|
||||
// timer initialize
|
||||
let mut timer = self.timer.lock();
|
||||
log_if_err!(timer.restore());
|
||||
}
|
||||
|
||||
if clash_mode.is_some() {
|
||||
let handle = self.handle.lock();
|
||||
handle.update_systray_part()?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Patch Verge
|
||||
pub fn patch_verge(&self, patch: Verge) -> Result<()> {
|
||||
// save the patch
|
||||
let global = Data::global();
|
||||
let mut verge = global.verge.lock();
|
||||
verge.patch_config(patch.clone())?;
|
||||
drop(verge);
|
||||
|
||||
let tun_mode = patch.enable_tun_mode;
|
||||
let auto_launch = patch.enable_auto_launch;
|
||||
let system_proxy = patch.enable_system_proxy;
|
||||
let proxy_bypass = patch.system_proxy_bypass;
|
||||
let proxy_guard = patch.enable_proxy_guard;
|
||||
let language = patch.language;
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let service_mode = patch.enable_service_mode;
|
||||
|
||||
// 重启服务
|
||||
if service_mode.is_some() {
|
||||
/// restart the clash sidecar
|
||||
pub fn restart_clash(&self) -> Result<()> {
|
||||
let mut service = self.service.lock();
|
||||
service.restart()?;
|
||||
drop(service);
|
||||
}
|
||||
self.activate()
|
||||
}
|
||||
|
||||
if tun_mode.is_some() && *tun_mode.as_ref().unwrap_or(&false) {
|
||||
let wintun_dll = crate::utils::dirs::app_home_dir().join("wintun.dll");
|
||||
if !wintun_dll.exists() {
|
||||
bail!("failed to enable TUN for missing `wintun.dll`");
|
||||
/// change the clash core
|
||||
pub fn change_core(&self, clash_core: Option<String>) -> Result<()> {
|
||||
let clash_core = clash_core.unwrap_or("clash".into());
|
||||
|
||||
if &clash_core != "clash" && &clash_core != "clash-meta" {
|
||||
bail!("invalid clash core name \"{clash_core}\"");
|
||||
}
|
||||
}
|
||||
|
||||
if service_mode.is_some() || tun_mode.is_some() {
|
||||
self.activate()?;
|
||||
}
|
||||
let global = Data::global();
|
||||
let mut verge = global.verge.lock();
|
||||
verge.patch_config(Verge {
|
||||
clash_core: Some(clash_core.clone()),
|
||||
..Verge::default()
|
||||
})?;
|
||||
drop(verge);
|
||||
|
||||
let mut service = self.service.lock();
|
||||
service.clear_logs();
|
||||
service.restart()?;
|
||||
drop(service);
|
||||
|
||||
self.activate()
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
if tun_mode.is_some() {
|
||||
self.activate()?;
|
||||
}
|
||||
/// Patch Clash
|
||||
/// handle the clash config changed
|
||||
pub fn patch_clash(&self, patch: Mapping) -> Result<()> {
|
||||
let patch_cloned = patch.clone();
|
||||
let clash_mode = patch.get("mode");
|
||||
let mixed_port = patch.get("mixed-port");
|
||||
let external = patch.get("external-controller");
|
||||
let secret = patch.get("secret");
|
||||
|
||||
let mut sysopt = self.sysopt.lock();
|
||||
let valid_port = {
|
||||
let global = Data::global();
|
||||
let mut clash = global.clash.lock();
|
||||
clash.patch_config(patch_cloned)?;
|
||||
clash.info.port.is_some()
|
||||
};
|
||||
|
||||
if auto_launch.is_some() {
|
||||
sysopt.update_launch()?;
|
||||
}
|
||||
if system_proxy.is_some() || proxy_bypass.is_some() {
|
||||
sysopt.update_sysproxy()?;
|
||||
sysopt.guard_proxy();
|
||||
}
|
||||
if proxy_guard.unwrap_or(false) {
|
||||
sysopt.guard_proxy();
|
||||
}
|
||||
// todo: port check
|
||||
if (mixed_port.is_some() && valid_port) || external.is_some() || secret.is_some() {
|
||||
let mut service = self.service.lock();
|
||||
service.restart()?;
|
||||
drop(service);
|
||||
|
||||
// 更新tray
|
||||
if language.is_some() {
|
||||
let handle = self.handle.lock();
|
||||
handle.update_systray()?;
|
||||
} else if system_proxy.is_some() || tun_mode.is_some() {
|
||||
let handle = self.handle.lock();
|
||||
handle.update_systray_part()?;
|
||||
}
|
||||
self.activate()?;
|
||||
|
||||
if patch.hotkeys.is_some() {
|
||||
let mut hotkey = self.hotkey.lock();
|
||||
hotkey.update(patch.hotkeys.unwrap())?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// update rule/global/direct/script mode
|
||||
pub fn update_mode(&self, mode: &str) -> Result<()> {
|
||||
// save config to file
|
||||
let info = {
|
||||
let global = Data::global();
|
||||
let mut clash = global.clash.lock();
|
||||
clash.config.insert(Value::from("mode"), Value::from(mode));
|
||||
clash.save_config()?;
|
||||
clash.info.clone()
|
||||
};
|
||||
|
||||
let mut mapping = Mapping::new();
|
||||
mapping.insert(Value::from("mode"), Value::from(mode));
|
||||
|
||||
let handle = self.handle.clone();
|
||||
|
||||
tauri::async_runtime::spawn(async move {
|
||||
log_if_err!(Service::patch_config(info, mapping.to_owned()).await);
|
||||
|
||||
// update tray
|
||||
let handle = handle.lock();
|
||||
handle.refresh_clash();
|
||||
log_if_err!(handle.update_systray_part());
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// activate the profile
|
||||
/// auto activate enhanced profile
|
||||
/// 触发clash配置更新
|
||||
pub fn activate(&self) -> Result<()> {
|
||||
let global = Data::global();
|
||||
|
||||
let verge = global.verge.lock();
|
||||
let clash = global.clash.lock();
|
||||
let profiles = global.profiles.lock();
|
||||
|
||||
let tun_mode = verge.enable_tun_mode.clone().unwrap_or(false);
|
||||
let profile_activate = profiles.gen_activate()?;
|
||||
|
||||
let clash_config = clash.config.clone();
|
||||
let clash_info = clash.info.clone();
|
||||
|
||||
drop(clash);
|
||||
drop(verge);
|
||||
drop(profiles);
|
||||
|
||||
let (config, exists_keys, logs) = enhance_config(
|
||||
clash_config,
|
||||
profile_activate.current,
|
||||
profile_activate.chain,
|
||||
profile_activate.valid,
|
||||
tun_mode,
|
||||
);
|
||||
|
||||
let mut runtime = self.runtime.lock();
|
||||
*runtime = RuntimeResult {
|
||||
config: Some(config.clone()),
|
||||
config_yaml: Some(serde_yaml::to_string(&config).unwrap_or("".into())),
|
||||
exists_keys,
|
||||
chain_logs: logs,
|
||||
};
|
||||
drop(runtime);
|
||||
|
||||
let mut service = self.service.lock();
|
||||
service.check_start()?;
|
||||
drop(service);
|
||||
|
||||
let handle = self.handle.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
match Service::set_config(clash_info, config).await {
|
||||
Ok(_) => {
|
||||
let handle = handle.lock();
|
||||
handle.refresh_clash();
|
||||
handle.notice_message("set_config::ok".into(), "ok".into());
|
||||
let mut sysopt = self.sysopt.lock();
|
||||
sysopt.init_sysproxy()?;
|
||||
}
|
||||
Err(err) => {
|
||||
let handle = handle.lock();
|
||||
handle.notice_message("set_config::error".into(), format!("{err}"));
|
||||
log::error!(target: "app", "{err}")
|
||||
|
||||
if clash_mode.is_some() {
|
||||
let handle = self.handle.lock();
|
||||
handle.update_systray_part()?;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Static function
|
||||
/// update profile item
|
||||
pub async fn update_profile_item(&self, uid: String, option: Option<PrfOption>) -> Result<()> {
|
||||
let global = Data::global();
|
||||
/// Patch Verge
|
||||
pub fn patch_verge(&self, patch: Verge) -> Result<()> {
|
||||
// save the patch
|
||||
let global = Data::global();
|
||||
let mut verge = global.verge.lock();
|
||||
verge.patch_config(patch.clone())?;
|
||||
drop(verge);
|
||||
|
||||
let (url, opt) = {
|
||||
let profiles = global.profiles.lock();
|
||||
let item = profiles.get_item(&uid)?;
|
||||
let tun_mode = patch.enable_tun_mode;
|
||||
let auto_launch = patch.enable_auto_launch;
|
||||
let system_proxy = patch.enable_system_proxy;
|
||||
let proxy_bypass = patch.system_proxy_bypass;
|
||||
let proxy_guard = patch.enable_proxy_guard;
|
||||
let language = patch.language;
|
||||
|
||||
if let Some(typ) = item.itype.as_ref() {
|
||||
// maybe only valid for `local` profile
|
||||
if *typ != "remote" {
|
||||
// reactivate the config
|
||||
if Some(uid) == profiles.get_current() {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let service_mode = patch.enable_service_mode;
|
||||
|
||||
// 重启服务
|
||||
if service_mode.is_some() {
|
||||
let mut service = self.service.lock();
|
||||
service.restart()?;
|
||||
drop(service);
|
||||
}
|
||||
|
||||
if tun_mode.is_some() && *tun_mode.as_ref().unwrap_or(&false) {
|
||||
let wintun_dll = crate::utils::dirs::app_home_dir().join("wintun.dll");
|
||||
if !wintun_dll.exists() {
|
||||
bail!("failed to enable TUN for missing `wintun.dll`");
|
||||
}
|
||||
}
|
||||
|
||||
if service_mode.is_some() || tun_mode.is_some() {
|
||||
self.activate()?;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
if tun_mode.is_some() {
|
||||
self.activate()?;
|
||||
}
|
||||
|
||||
let mut sysopt = self.sysopt.lock();
|
||||
|
||||
if auto_launch.is_some() {
|
||||
sysopt.update_launch()?;
|
||||
}
|
||||
if system_proxy.is_some() || proxy_bypass.is_some() {
|
||||
sysopt.update_sysproxy()?;
|
||||
sysopt.guard_proxy();
|
||||
}
|
||||
if proxy_guard.unwrap_or(false) {
|
||||
sysopt.guard_proxy();
|
||||
}
|
||||
|
||||
// 更新tray
|
||||
if language.is_some() {
|
||||
let handle = self.handle.lock();
|
||||
handle.update_systray()?;
|
||||
} else if system_proxy.is_some() || tun_mode.is_some() {
|
||||
let handle = self.handle.lock();
|
||||
handle.update_systray_part()?;
|
||||
}
|
||||
|
||||
if patch.hotkeys.is_some() {
|
||||
let mut hotkey = self.hotkey.lock();
|
||||
hotkey.update(patch.hotkeys.unwrap())?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// update rule/global/direct/script mode
|
||||
pub fn update_mode(&self, mode: &str) -> Result<()> {
|
||||
// save config to file
|
||||
let info = {
|
||||
let global = Data::global();
|
||||
let mut clash = global.clash.lock();
|
||||
clash.config.insert(Value::from("mode"), Value::from(mode));
|
||||
clash.save_config()?;
|
||||
clash.info.clone()
|
||||
};
|
||||
|
||||
let mut mapping = Mapping::new();
|
||||
mapping.insert(Value::from("mode"), Value::from(mode));
|
||||
|
||||
let handle = self.handle.clone();
|
||||
|
||||
tauri::async_runtime::spawn(async move {
|
||||
log_if_err!(Service::patch_config(info, mapping.to_owned()).await);
|
||||
|
||||
// update tray
|
||||
let handle = handle.lock();
|
||||
handle.refresh_clash();
|
||||
log_if_err!(handle.update_systray_part());
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// activate the profile
|
||||
/// auto activate enhanced profile
|
||||
/// 触发clash配置更新
|
||||
pub fn activate(&self) -> Result<()> {
|
||||
let global = Data::global();
|
||||
|
||||
let verge = global.verge.lock();
|
||||
let clash = global.clash.lock();
|
||||
let profiles = global.profiles.lock();
|
||||
|
||||
let tun_mode = verge.enable_tun_mode.clone().unwrap_or(false);
|
||||
let profile_activate = profiles.gen_activate()?;
|
||||
|
||||
let clash_config = clash.config.clone();
|
||||
let clash_info = clash.info.clone();
|
||||
|
||||
drop(clash);
|
||||
drop(verge);
|
||||
drop(profiles);
|
||||
|
||||
let (config, exists_keys, logs) = enhance_config(
|
||||
clash_config,
|
||||
profile_activate.current,
|
||||
profile_activate.chain,
|
||||
profile_activate.valid,
|
||||
tun_mode,
|
||||
);
|
||||
|
||||
let mut runtime = self.runtime.lock();
|
||||
*runtime = RuntimeResult {
|
||||
config: Some(config.clone()),
|
||||
config_yaml: Some(serde_yaml::to_string(&config).unwrap_or("".into())),
|
||||
exists_keys,
|
||||
chain_logs: logs,
|
||||
};
|
||||
drop(runtime);
|
||||
|
||||
let mut service = self.service.lock();
|
||||
service.check_start()?;
|
||||
drop(service);
|
||||
|
||||
let handle = self.handle.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
match Service::set_config(clash_info, config).await {
|
||||
Ok(_) => {
|
||||
let handle = handle.lock();
|
||||
handle.refresh_clash();
|
||||
handle.notice_message("set_config::ok".into(), "ok".into());
|
||||
}
|
||||
Err(err) => {
|
||||
let handle = handle.lock();
|
||||
handle.notice_message("set_config::error".into(), format!("{err}"));
|
||||
log::error!(target: "app", "{err}")
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Static function
|
||||
/// update profile item
|
||||
pub async fn update_profile_item(&self, uid: String, option: Option<PrfOption>) -> Result<()> {
|
||||
let global = Data::global();
|
||||
|
||||
let (url, opt) = {
|
||||
let profiles = global.profiles.lock();
|
||||
let item = profiles.get_item(&uid)?;
|
||||
|
||||
if let Some(typ) = item.itype.as_ref() {
|
||||
// maybe only valid for `local` profile
|
||||
if *typ != "remote" {
|
||||
// reactivate the config
|
||||
if Some(uid) == profiles.get_current() {
|
||||
drop(profiles);
|
||||
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 = global.profiles.lock();
|
||||
profiles.update_item(uid.clone(), item)?;
|
||||
|
||||
// reactivate the profile
|
||||
if Some(uid) == profiles.get_current() {
|
||||
drop(profiles);
|
||||
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 = global.profiles.lock();
|
||||
profiles.update_item(uid.clone(), item)?;
|
||||
|
||||
// reactivate the profile
|
||||
if Some(uid) == profiles.get_current() {
|
||||
drop(profiles);
|
||||
self.activate()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,8 +9,8 @@ use std::fs;
|
||||
use std::io::Write;
|
||||
use std::sync::Arc;
|
||||
use std::{
|
||||
collections::{HashMap, VecDeque},
|
||||
time::Duration,
|
||||
collections::{HashMap, VecDeque},
|
||||
time::Duration,
|
||||
};
|
||||
use tauri::api::process::{Command, CommandChild, CommandEvent};
|
||||
use tokio::time::sleep;
|
||||
@@ -19,209 +19,209 @@ const LOGS_QUEUE_LEN: usize = 100;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Service {
|
||||
sidecar: Option<CommandChild>,
|
||||
sidecar: Option<CommandChild>,
|
||||
|
||||
logs: Arc<RwLock<VecDeque<String>>>,
|
||||
logs: Arc<RwLock<VecDeque<String>>>,
|
||||
|
||||
#[allow(unused)]
|
||||
use_service_mode: bool,
|
||||
#[allow(unused)]
|
||||
use_service_mode: bool,
|
||||
}
|
||||
|
||||
impl Service {
|
||||
pub fn new() -> Service {
|
||||
let queue = VecDeque::with_capacity(LOGS_QUEUE_LEN + 10);
|
||||
pub fn new() -> Service {
|
||||
let queue = VecDeque::with_capacity(LOGS_QUEUE_LEN + 10);
|
||||
|
||||
Service {
|
||||
sidecar: None,
|
||||
logs: Arc::new(RwLock::new(queue)),
|
||||
use_service_mode: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start(&mut self) -> Result<()> {
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
self.start_clash_by_sidecar()?;
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let enable = {
|
||||
let data = Data::global();
|
||||
let verge = data.verge.lock();
|
||||
verge.enable_service_mode.clone().unwrap_or(false)
|
||||
};
|
||||
|
||||
self.use_service_mode = enable;
|
||||
|
||||
if !enable {
|
||||
return self.start_clash_by_sidecar();
|
||||
}
|
||||
|
||||
tauri::async_runtime::spawn(async move {
|
||||
match Self::check_service().await {
|
||||
Ok(status) => {
|
||||
// 未启动clash
|
||||
if status.code != 0 {
|
||||
log_if_err!(Self::start_clash_by_service().await);
|
||||
}
|
||||
}
|
||||
Err(err) => log::error!(target: "app", "{err}"),
|
||||
Service {
|
||||
sidecar: None,
|
||||
logs: Arc::new(RwLock::new(queue)),
|
||||
use_service_mode: false,
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
pub fn start(&mut self) -> Result<()> {
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
self.start_clash_by_sidecar()?;
|
||||
|
||||
pub fn stop(&mut self) -> Result<()> {
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
self.stop_clash_by_sidecar()?;
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let enable = {
|
||||
let data = Data::global();
|
||||
let verge = data.verge.lock();
|
||||
verge.enable_service_mode.clone().unwrap_or(false)
|
||||
};
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let _ = self.stop_clash_by_sidecar();
|
||||
self.use_service_mode = enable;
|
||||
|
||||
if self.use_service_mode {
|
||||
tauri::async_runtime::block_on(async move {
|
||||
log_if_err!(Self::stop_clash_by_service().await);
|
||||
});
|
||||
}
|
||||
if !enable {
|
||||
return self.start_clash_by_sidecar();
|
||||
}
|
||||
|
||||
tauri::async_runtime::spawn(async move {
|
||||
match Self::check_service().await {
|
||||
Ok(status) => {
|
||||
// 未启动clash
|
||||
if status.code != 0 {
|
||||
log_if_err!(Self::start_clash_by_service().await);
|
||||
}
|
||||
}
|
||||
Err(err) => log::error!(target: "app", "{err}"),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
pub fn stop(&mut self) -> Result<()> {
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
self.stop_clash_by_sidecar()?;
|
||||
|
||||
pub fn restart(&mut self) -> Result<()> {
|
||||
self.stop()?;
|
||||
self.start()
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let _ = self.stop_clash_by_sidecar();
|
||||
|
||||
pub fn get_logs(&self) -> VecDeque<String> {
|
||||
self.logs.read().clone()
|
||||
}
|
||||
if self.use_service_mode {
|
||||
tauri::async_runtime::block_on(async move {
|
||||
log_if_err!(Self::stop_clash_by_service().await);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
pub fn set_logs(&self, text: String) {
|
||||
let mut logs = self.logs.write();
|
||||
if logs.len() > LOGS_QUEUE_LEN {
|
||||
(*logs).pop_front();
|
||||
}
|
||||
(*logs).push_back(text);
|
||||
}
|
||||
|
||||
pub fn clear_logs(&self) {
|
||||
let mut logs = self.logs.write();
|
||||
(*logs).clear();
|
||||
}
|
||||
|
||||
/// start the clash sidecar
|
||||
fn start_clash_by_sidecar(&mut self) -> Result<()> {
|
||||
if self.sidecar.is_some() {
|
||||
let sidecar = self.sidecar.take().unwrap();
|
||||
let _ = sidecar.kill();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
let clash_core: String = {
|
||||
let global = Data::global();
|
||||
let verge = global.verge.lock();
|
||||
verge.clash_core.clone().unwrap_or("clash".into())
|
||||
};
|
||||
pub fn restart(&mut self) -> Result<()> {
|
||||
self.stop()?;
|
||||
self.start()
|
||||
}
|
||||
|
||||
let app_dir = dirs::app_home_dir();
|
||||
let app_dir = app_dir.as_os_str().to_str().unwrap();
|
||||
pub fn get_logs(&self) -> VecDeque<String> {
|
||||
self.logs.read().clone()
|
||||
}
|
||||
|
||||
// fix #212
|
||||
let args = match clash_core.as_str() {
|
||||
"clash-meta" => vec!["-m", "-d", app_dir],
|
||||
_ => vec!["-d", app_dir],
|
||||
};
|
||||
|
||||
let cmd = Command::new_sidecar(clash_core)?;
|
||||
|
||||
let (mut rx, cmd_child) = cmd.args(args).spawn()?;
|
||||
|
||||
// 将pid写入文件中
|
||||
let pid = cmd_child.pid();
|
||||
log_if_err!(|| -> Result<()> {
|
||||
let path = dirs::clash_pid_path();
|
||||
fs::File::create(path)?.write(format!("{pid}").as_bytes())?;
|
||||
Ok(())
|
||||
}());
|
||||
|
||||
self.sidecar = Some(cmd_child);
|
||||
|
||||
// clash log
|
||||
let logs = self.logs.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let write_log = |text: String| {
|
||||
let mut logs = logs.write();
|
||||
if logs.len() >= LOGS_QUEUE_LEN {
|
||||
(*logs).pop_front();
|
||||
#[allow(unused)]
|
||||
pub fn set_logs(&self, text: String) {
|
||||
let mut logs = self.logs.write();
|
||||
if logs.len() > LOGS_QUEUE_LEN {
|
||||
(*logs).pop_front();
|
||||
}
|
||||
(*logs).push_back(text);
|
||||
};
|
||||
}
|
||||
|
||||
while let Some(event) = rx.recv().await {
|
||||
match event {
|
||||
CommandEvent::Stdout(line) => {
|
||||
let can_short = line.starts_with("time=") && line.len() > 33;
|
||||
let stdout = if can_short { &line[33..] } else { &line };
|
||||
log::info!(target: "app" ,"[clash]: {}", stdout);
|
||||
write_log(line);
|
||||
}
|
||||
CommandEvent::Stderr(err) => {
|
||||
log::error!(target: "app" ,"[clash error]: {}", err);
|
||||
write_log(err);
|
||||
}
|
||||
CommandEvent::Error(err) => log::error!(target: "app" ,"{err}"),
|
||||
CommandEvent::Terminated(_) => break,
|
||||
_ => {}
|
||||
pub fn clear_logs(&self) {
|
||||
let mut logs = self.logs.write();
|
||||
(*logs).clear();
|
||||
}
|
||||
|
||||
/// start the clash sidecar
|
||||
fn start_clash_by_sidecar(&mut self) -> Result<()> {
|
||||
if self.sidecar.is_some() {
|
||||
let sidecar = self.sidecar.take().unwrap();
|
||||
let _ = sidecar.kill();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
let clash_core: String = {
|
||||
let global = Data::global();
|
||||
let verge = global.verge.lock();
|
||||
verge.clash_core.clone().unwrap_or("clash".into())
|
||||
};
|
||||
|
||||
/// stop the clash sidecar
|
||||
fn stop_clash_by_sidecar(&mut self) -> Result<()> {
|
||||
if let Some(sidecar) = self.sidecar.take() {
|
||||
sidecar.kill()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
let app_dir = dirs::app_home_dir();
|
||||
let app_dir = app_dir.as_os_str().to_str().unwrap();
|
||||
|
||||
pub fn check_start(&mut self) -> Result<()> {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let global = Data::global();
|
||||
let verge = global.verge.lock();
|
||||
let service_mode = verge.enable_service_mode.unwrap_or(false);
|
||||
// fix #212
|
||||
let args = match clash_core.as_str() {
|
||||
"clash-meta" => vec!["-m", "-d", app_dir],
|
||||
_ => vec!["-d", app_dir],
|
||||
};
|
||||
|
||||
if !service_mode && self.sidecar.is_none() {
|
||||
self.start()?;
|
||||
}
|
||||
let cmd = Command::new_sidecar(clash_core)?;
|
||||
|
||||
let (mut rx, cmd_child) = cmd.args(args).spawn()?;
|
||||
|
||||
// 将pid写入文件中
|
||||
let pid = cmd_child.pid();
|
||||
log_if_err!(|| -> Result<()> {
|
||||
let path = dirs::clash_pid_path();
|
||||
fs::File::create(path)?.write(format!("{pid}").as_bytes())?;
|
||||
Ok(())
|
||||
}());
|
||||
|
||||
self.sidecar = Some(cmd_child);
|
||||
|
||||
// clash log
|
||||
let logs = self.logs.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let write_log = |text: String| {
|
||||
let mut logs = logs.write();
|
||||
if logs.len() >= LOGS_QUEUE_LEN {
|
||||
(*logs).pop_front();
|
||||
}
|
||||
(*logs).push_back(text);
|
||||
};
|
||||
|
||||
while let Some(event) = rx.recv().await {
|
||||
match event {
|
||||
CommandEvent::Stdout(line) => {
|
||||
let can_short = line.starts_with("time=") && line.len() > 33;
|
||||
let stdout = if can_short { &line[33..] } else { &line };
|
||||
log::info!(target: "app" ,"[clash]: {}", stdout);
|
||||
write_log(line);
|
||||
}
|
||||
CommandEvent::Stderr(err) => {
|
||||
log::error!(target: "app" ,"[clash error]: {}", err);
|
||||
write_log(err);
|
||||
}
|
||||
CommandEvent::Error(err) => log::error!(target: "app" ,"{err}"),
|
||||
CommandEvent::Terminated(_) => break,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
if self.sidecar.is_none() {
|
||||
self.start()?;
|
||||
/// stop the clash sidecar
|
||||
fn stop_clash_by_sidecar(&mut self) -> Result<()> {
|
||||
if let Some(sidecar) = self.sidecar.take() {
|
||||
sidecar.kill()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
pub fn check_start(&mut self) -> Result<()> {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let global = Data::global();
|
||||
let verge = global.verge.lock();
|
||||
let service_mode = verge.enable_service_mode.unwrap_or(false);
|
||||
|
||||
/// update clash config
|
||||
/// using PUT methods
|
||||
pub async fn set_config(info: ClashInfo, config: Mapping) -> Result<()> {
|
||||
let temp_path = dirs::profiles_temp_path();
|
||||
config::save_yaml(temp_path.clone(), &config, Some("# Clash Verge Temp File"))?;
|
||||
if !service_mode && self.sidecar.is_none() {
|
||||
self.start()?;
|
||||
}
|
||||
}
|
||||
|
||||
let (server, headers) = Self::clash_client_info(info)?;
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
if self.sidecar.is_none() {
|
||||
self.start()?;
|
||||
}
|
||||
|
||||
let mut data = HashMap::new();
|
||||
data.insert("path", temp_path.as_os_str().to_str().unwrap());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
macro_rules! report_err {
|
||||
/// update clash config
|
||||
/// using PUT methods
|
||||
pub async fn set_config(info: ClashInfo, config: Mapping) -> Result<()> {
|
||||
let temp_path = dirs::profiles_temp_path();
|
||||
config::save_yaml(temp_path.clone(), &config, Some("# Clash Verge Temp File"))?;
|
||||
|
||||
let (server, headers) = Self::clash_client_info(info)?;
|
||||
|
||||
let mut data = HashMap::new();
|
||||
data.insert("path", temp_path.as_os_str().to_str().unwrap());
|
||||
|
||||
macro_rules! report_err {
|
||||
($i: expr, $e: expr) => {
|
||||
match $i {
|
||||
4 => bail!($e),
|
||||
@@ -230,306 +230,308 @@ impl Service {
|
||||
};
|
||||
}
|
||||
|
||||
// retry 5 times
|
||||
for i in 0..5 {
|
||||
let headers = headers.clone();
|
||||
match reqwest::ClientBuilder::new().no_proxy().build() {
|
||||
Ok(client) => {
|
||||
let builder = client.put(&server).headers(headers).json(&data);
|
||||
match builder.send().await {
|
||||
Ok(resp) => match resp.status().as_u16() {
|
||||
204 => break,
|
||||
// 配置有问题不重试
|
||||
400 => bail!("failed to update clash config with status 400"),
|
||||
status @ _ => report_err!(i, "failed to activate clash with status \"{status}\""),
|
||||
},
|
||||
Err(err) => report_err!(i, "{err}"),
|
||||
}
|
||||
// retry 5 times
|
||||
for i in 0..5 {
|
||||
let headers = headers.clone();
|
||||
match reqwest::ClientBuilder::new().no_proxy().build() {
|
||||
Ok(client) => {
|
||||
let builder = client.put(&server).headers(headers).json(&data);
|
||||
match builder.send().await {
|
||||
Ok(resp) => match resp.status().as_u16() {
|
||||
204 => break,
|
||||
// 配置有问题不重试
|
||||
400 => bail!("failed to update clash config with status 400"),
|
||||
status @ _ => {
|
||||
report_err!(i, "failed to activate clash with status \"{status}\"")
|
||||
}
|
||||
},
|
||||
Err(err) => report_err!(i, "{err}"),
|
||||
}
|
||||
}
|
||||
Err(err) => report_err!(i, "{err}"),
|
||||
}
|
||||
sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
Err(err) => report_err!(i, "{err}"),
|
||||
}
|
||||
sleep(Duration::from_millis(500)).await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
/// patch clash config
|
||||
pub async fn patch_config(info: ClashInfo, config: Mapping) -> Result<()> {
|
||||
let (server, headers) = Self::clash_client_info(info)?;
|
||||
|
||||
/// patch clash config
|
||||
pub async fn patch_config(info: ClashInfo, config: Mapping) -> Result<()> {
|
||||
let (server, headers) = Self::clash_client_info(info)?;
|
||||
|
||||
let client = reqwest::ClientBuilder::new().no_proxy().build()?;
|
||||
let builder = client.patch(&server).headers(headers.clone()).json(&config);
|
||||
builder.send().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// get clash client url and headers from clash info
|
||||
fn clash_client_info(info: ClashInfo) -> Result<(String, HeaderMap)> {
|
||||
if info.server.is_none() {
|
||||
let status = &info.status;
|
||||
if info.port.is_none() {
|
||||
bail!("failed to parse config.yaml file with status {status}");
|
||||
} else {
|
||||
bail!("failed to parse the server with status {status}");
|
||||
}
|
||||
let client = reqwest::ClientBuilder::new().no_proxy().build()?;
|
||||
let builder = client.patch(&server).headers(headers.clone()).json(&config);
|
||||
builder.send().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
let server = info.server.unwrap();
|
||||
let server = format!("http://{server}/configs");
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("Content-Type", "application/json".parse().unwrap());
|
||||
|
||||
if let Some(secret) = info.secret.as_ref() {
|
||||
let secret = format!("Bearer {}", secret.clone()).parse().unwrap();
|
||||
headers.insert("Authorization", secret);
|
||||
}
|
||||
|
||||
Ok((server, headers))
|
||||
}
|
||||
|
||||
/// kill old clash process
|
||||
pub fn kill_old_clash() {
|
||||
use sysinfo::{Pid, PidExt, ProcessExt, System, SystemExt};
|
||||
|
||||
if let Ok(pid) = fs::read(dirs::clash_pid_path()) {
|
||||
if let Ok(pid) = String::from_utf8_lossy(&pid).parse() {
|
||||
let mut system = System::new();
|
||||
system.refresh_all();
|
||||
|
||||
let proc = system.process(Pid::from_u32(pid));
|
||||
if let Some(proc) = proc {
|
||||
proc.kill();
|
||||
/// get clash client url and headers from clash info
|
||||
fn clash_client_info(info: ClashInfo) -> Result<(String, HeaderMap)> {
|
||||
if info.server.is_none() {
|
||||
let status = &info.status;
|
||||
if info.port.is_none() {
|
||||
bail!("failed to parse config.yaml file with status {status}");
|
||||
} else {
|
||||
bail!("failed to parse the server with status {status}");
|
||||
}
|
||||
}
|
||||
|
||||
let server = info.server.unwrap();
|
||||
let server = format!("http://{server}/configs");
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("Content-Type", "application/json".parse().unwrap());
|
||||
|
||||
if let Some(secret) = info.secret.as_ref() {
|
||||
let secret = format!("Bearer {}", secret.clone()).parse().unwrap();
|
||||
headers.insert("Authorization", secret);
|
||||
}
|
||||
|
||||
Ok((server, headers))
|
||||
}
|
||||
|
||||
/// kill old clash process
|
||||
pub fn kill_old_clash() {
|
||||
use sysinfo::{Pid, PidExt, ProcessExt, System, SystemExt};
|
||||
|
||||
if let Ok(pid) = fs::read(dirs::clash_pid_path()) {
|
||||
if let Ok(pid) = String::from_utf8_lossy(&pid).parse() {
|
||||
let mut system = System::new();
|
||||
system.refresh_all();
|
||||
|
||||
let proc = system.process(Pid::from_u32(pid));
|
||||
if let Some(proc) = proc {
|
||||
proc.kill();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Service {
|
||||
fn drop(&mut self) {
|
||||
log_if_err!(self.stop());
|
||||
}
|
||||
fn drop(&mut self) {
|
||||
log_if_err!(self.stop());
|
||||
}
|
||||
}
|
||||
|
||||
/// ### Service Mode
|
||||
///
|
||||
#[cfg(target_os = "windows")]
|
||||
pub mod win_service {
|
||||
use super::*;
|
||||
use anyhow::Context;
|
||||
use deelevate::{PrivilegeLevel, Token};
|
||||
use runas::Command as RunasCommand;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::os::windows::process::CommandExt;
|
||||
use std::{env::current_exe, process::Command as StdCommand};
|
||||
use super::*;
|
||||
use anyhow::Context;
|
||||
use deelevate::{PrivilegeLevel, Token};
|
||||
use runas::Command as RunasCommand;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::os::windows::process::CommandExt;
|
||||
use std::{env::current_exe, process::Command as StdCommand};
|
||||
|
||||
const SERVICE_NAME: &str = "clash_verge_service";
|
||||
const SERVICE_NAME: &str = "clash_verge_service";
|
||||
|
||||
const SERVICE_URL: &str = "http://127.0.0.1:33211";
|
||||
const SERVICE_URL: &str = "http://127.0.0.1:33211";
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||
pub struct ResponseBody {
|
||||
pub bin_path: String,
|
||||
pub config_dir: String,
|
||||
pub log_file: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||
pub struct JsonResponse {
|
||||
pub code: u64,
|
||||
pub msg: String,
|
||||
pub data: Option<ResponseBody>,
|
||||
}
|
||||
|
||||
impl Service {
|
||||
/// Install the Clash Verge Service
|
||||
/// 该函数应该在协程或者线程中执行,避免UAC弹窗阻塞主线程
|
||||
pub async fn install_service() -> Result<()> {
|
||||
let binary_path = dirs::service_path();
|
||||
let install_path = binary_path.with_file_name("install-service.exe");
|
||||
|
||||
if !install_path.exists() {
|
||||
bail!("installer exe not found");
|
||||
}
|
||||
|
||||
let token = Token::with_current_process()?;
|
||||
let level = token.privilege_level()?;
|
||||
|
||||
let status = match level {
|
||||
PrivilegeLevel::NotPrivileged => RunasCommand::new(install_path).status()?,
|
||||
_ => StdCommand::new(install_path)
|
||||
.creation_flags(0x08000000)
|
||||
.status()?,
|
||||
};
|
||||
|
||||
if !status.success() {
|
||||
bail!(
|
||||
"failed to install service with status {}",
|
||||
status.code().unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||
pub struct ResponseBody {
|
||||
pub bin_path: String,
|
||||
pub config_dir: String,
|
||||
pub log_file: String,
|
||||
}
|
||||
|
||||
/// Uninstall the Clash Verge Service
|
||||
/// 该函数应该在协程或者线程中执行,避免UAC弹窗阻塞主线程
|
||||
pub async fn uninstall_service() -> Result<()> {
|
||||
let binary_path = dirs::service_path();
|
||||
let uninstall_path = binary_path.with_file_name("uninstall-service.exe");
|
||||
|
||||
if !uninstall_path.exists() {
|
||||
bail!("uninstaller exe not found");
|
||||
}
|
||||
|
||||
let token = Token::with_current_process()?;
|
||||
let level = token.privilege_level()?;
|
||||
|
||||
let status = match level {
|
||||
PrivilegeLevel::NotPrivileged => RunasCommand::new(uninstall_path).status()?,
|
||||
_ => StdCommand::new(uninstall_path)
|
||||
.creation_flags(0x08000000)
|
||||
.status()?,
|
||||
};
|
||||
|
||||
if !status.success() {
|
||||
bail!(
|
||||
"failed to uninstall service with status {}",
|
||||
status.code().unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||
pub struct JsonResponse {
|
||||
pub code: u64,
|
||||
pub msg: String,
|
||||
pub data: Option<ResponseBody>,
|
||||
}
|
||||
|
||||
/// [deprecated]
|
||||
/// start service
|
||||
/// 该函数应该在协程或者线程中执行,避免UAC弹窗阻塞主线程
|
||||
pub async fn start_service() -> Result<()> {
|
||||
let token = Token::with_current_process()?;
|
||||
let level = token.privilege_level()?;
|
||||
impl Service {
|
||||
/// Install the Clash Verge Service
|
||||
/// 该函数应该在协程或者线程中执行,避免UAC弹窗阻塞主线程
|
||||
pub async fn install_service() -> Result<()> {
|
||||
let binary_path = dirs::service_path();
|
||||
let install_path = binary_path.with_file_name("install-service.exe");
|
||||
|
||||
let args = ["start", SERVICE_NAME];
|
||||
if !install_path.exists() {
|
||||
bail!("installer exe not found");
|
||||
}
|
||||
|
||||
let status = match level {
|
||||
PrivilegeLevel::NotPrivileged => RunasCommand::new("sc").args(&args).status()?,
|
||||
_ => StdCommand::new("sc").args(&args).status()?,
|
||||
};
|
||||
let token = Token::with_current_process()?;
|
||||
let level = token.privilege_level()?;
|
||||
|
||||
match status.success() {
|
||||
true => Ok(()),
|
||||
false => bail!(
|
||||
"failed to start service with status {}",
|
||||
status.code().unwrap()
|
||||
),
|
||||
}
|
||||
let status = match level {
|
||||
PrivilegeLevel::NotPrivileged => RunasCommand::new(install_path).status()?,
|
||||
_ => StdCommand::new(install_path)
|
||||
.creation_flags(0x08000000)
|
||||
.status()?,
|
||||
};
|
||||
|
||||
if !status.success() {
|
||||
bail!(
|
||||
"failed to install service with status {}",
|
||||
status.code().unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Uninstall the Clash Verge Service
|
||||
/// 该函数应该在协程或者线程中执行,避免UAC弹窗阻塞主线程
|
||||
pub async fn uninstall_service() -> Result<()> {
|
||||
let binary_path = dirs::service_path();
|
||||
let uninstall_path = binary_path.with_file_name("uninstall-service.exe");
|
||||
|
||||
if !uninstall_path.exists() {
|
||||
bail!("uninstaller exe not found");
|
||||
}
|
||||
|
||||
let token = Token::with_current_process()?;
|
||||
let level = token.privilege_level()?;
|
||||
|
||||
let status = match level {
|
||||
PrivilegeLevel::NotPrivileged => RunasCommand::new(uninstall_path).status()?,
|
||||
_ => StdCommand::new(uninstall_path)
|
||||
.creation_flags(0x08000000)
|
||||
.status()?,
|
||||
};
|
||||
|
||||
if !status.success() {
|
||||
bail!(
|
||||
"failed to uninstall service with status {}",
|
||||
status.code().unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [deprecated]
|
||||
/// start service
|
||||
/// 该函数应该在协程或者线程中执行,避免UAC弹窗阻塞主线程
|
||||
pub async fn start_service() -> Result<()> {
|
||||
let token = Token::with_current_process()?;
|
||||
let level = token.privilege_level()?;
|
||||
|
||||
let args = ["start", SERVICE_NAME];
|
||||
|
||||
let status = match level {
|
||||
PrivilegeLevel::NotPrivileged => RunasCommand::new("sc").args(&args).status()?,
|
||||
_ => StdCommand::new("sc").args(&args).status()?,
|
||||
};
|
||||
|
||||
match status.success() {
|
||||
true => Ok(()),
|
||||
false => bail!(
|
||||
"failed to start service with status {}",
|
||||
status.code().unwrap()
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// stop service
|
||||
pub async fn stop_service() -> Result<()> {
|
||||
let url = format!("{SERVICE_URL}/stop_service");
|
||||
let res = reqwest::ClientBuilder::new()
|
||||
.no_proxy()
|
||||
.build()?
|
||||
.post(url)
|
||||
.send()
|
||||
.await?
|
||||
.json::<JsonResponse>()
|
||||
.await
|
||||
.context("failed to connect to the Clash Verge Service")?;
|
||||
|
||||
if res.code != 0 {
|
||||
bail!(res.msg);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// check the windows service status
|
||||
pub async fn check_service() -> Result<JsonResponse> {
|
||||
let url = format!("{SERVICE_URL}/get_clash");
|
||||
let response = reqwest::ClientBuilder::new()
|
||||
.no_proxy()
|
||||
.build()?
|
||||
.get(url)
|
||||
.send()
|
||||
.await?
|
||||
.json::<JsonResponse>()
|
||||
.await
|
||||
.context("failed to connect to the Clash Verge Service")?;
|
||||
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
/// start the clash by service
|
||||
pub(super) async fn start_clash_by_service() -> Result<()> {
|
||||
let status = Self::check_service().await?;
|
||||
|
||||
if status.code == 0 {
|
||||
Self::stop_clash_by_service().await?;
|
||||
sleep(Duration::from_secs(1)).await;
|
||||
}
|
||||
|
||||
let clash_core = {
|
||||
let global = Data::global();
|
||||
let verge = global.verge.lock();
|
||||
verge.clash_core.clone().unwrap_or("clash".into())
|
||||
};
|
||||
|
||||
let clash_bin = format!("{clash_core}.exe");
|
||||
let bin_path = current_exe().unwrap().with_file_name(clash_bin);
|
||||
let bin_path = bin_path.as_os_str().to_str().unwrap();
|
||||
|
||||
let config_dir = dirs::app_home_dir();
|
||||
let config_dir = config_dir.as_os_str().to_str().unwrap();
|
||||
|
||||
let log_path = dirs::service_log_file();
|
||||
let log_path = log_path.as_os_str().to_str().unwrap();
|
||||
|
||||
let mut map = HashMap::new();
|
||||
map.insert("bin_path", bin_path);
|
||||
map.insert("config_dir", config_dir);
|
||||
map.insert("log_file", log_path);
|
||||
|
||||
let url = format!("{SERVICE_URL}/start_clash");
|
||||
let res = reqwest::ClientBuilder::new()
|
||||
.no_proxy()
|
||||
.build()?
|
||||
.post(url)
|
||||
.json(&map)
|
||||
.send()
|
||||
.await?
|
||||
.json::<JsonResponse>()
|
||||
.await
|
||||
.context("failed to connect to the Clash Verge Service")?;
|
||||
|
||||
if res.code != 0 {
|
||||
bail!(res.msg);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// stop the clash by service
|
||||
pub(super) async fn stop_clash_by_service() -> Result<()> {
|
||||
let url = format!("{SERVICE_URL}/stop_clash");
|
||||
let res = reqwest::ClientBuilder::new()
|
||||
.no_proxy()
|
||||
.build()?
|
||||
.post(url)
|
||||
.send()
|
||||
.await?
|
||||
.json::<JsonResponse>()
|
||||
.await
|
||||
.context("failed to connect to the Clash Verge Service")?;
|
||||
|
||||
if res.code != 0 {
|
||||
bail!(res.msg);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// stop service
|
||||
pub async fn stop_service() -> Result<()> {
|
||||
let url = format!("{SERVICE_URL}/stop_service");
|
||||
let res = reqwest::ClientBuilder::new()
|
||||
.no_proxy()
|
||||
.build()?
|
||||
.post(url)
|
||||
.send()
|
||||
.await?
|
||||
.json::<JsonResponse>()
|
||||
.await
|
||||
.context("failed to connect to the Clash Verge Service")?;
|
||||
|
||||
if res.code != 0 {
|
||||
bail!(res.msg);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// check the windows service status
|
||||
pub async fn check_service() -> Result<JsonResponse> {
|
||||
let url = format!("{SERVICE_URL}/get_clash");
|
||||
let response = reqwest::ClientBuilder::new()
|
||||
.no_proxy()
|
||||
.build()?
|
||||
.get(url)
|
||||
.send()
|
||||
.await?
|
||||
.json::<JsonResponse>()
|
||||
.await
|
||||
.context("failed to connect to the Clash Verge Service")?;
|
||||
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
/// start the clash by service
|
||||
pub(super) async fn start_clash_by_service() -> Result<()> {
|
||||
let status = Self::check_service().await?;
|
||||
|
||||
if status.code == 0 {
|
||||
Self::stop_clash_by_service().await?;
|
||||
sleep(Duration::from_secs(1)).await;
|
||||
}
|
||||
|
||||
let clash_core = {
|
||||
let global = Data::global();
|
||||
let verge = global.verge.lock();
|
||||
verge.clash_core.clone().unwrap_or("clash".into())
|
||||
};
|
||||
|
||||
let clash_bin = format!("{clash_core}.exe");
|
||||
let bin_path = current_exe().unwrap().with_file_name(clash_bin);
|
||||
let bin_path = bin_path.as_os_str().to_str().unwrap();
|
||||
|
||||
let config_dir = dirs::app_home_dir();
|
||||
let config_dir = config_dir.as_os_str().to_str().unwrap();
|
||||
|
||||
let log_path = dirs::service_log_file();
|
||||
let log_path = log_path.as_os_str().to_str().unwrap();
|
||||
|
||||
let mut map = HashMap::new();
|
||||
map.insert("bin_path", bin_path);
|
||||
map.insert("config_dir", config_dir);
|
||||
map.insert("log_file", log_path);
|
||||
|
||||
let url = format!("{SERVICE_URL}/start_clash");
|
||||
let res = reqwest::ClientBuilder::new()
|
||||
.no_proxy()
|
||||
.build()?
|
||||
.post(url)
|
||||
.json(&map)
|
||||
.send()
|
||||
.await?
|
||||
.json::<JsonResponse>()
|
||||
.await
|
||||
.context("failed to connect to the Clash Verge Service")?;
|
||||
|
||||
if res.code != 0 {
|
||||
bail!(res.msg);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// stop the clash by service
|
||||
pub(super) async fn stop_clash_by_service() -> Result<()> {
|
||||
let url = format!("{SERVICE_URL}/stop_clash");
|
||||
let res = reqwest::ClientBuilder::new()
|
||||
.no_proxy()
|
||||
.build()?
|
||||
.post(url)
|
||||
.send()
|
||||
.await?
|
||||
.json::<JsonResponse>()
|
||||
.await
|
||||
.context("failed to connect to the Clash Verge Service")?;
|
||||
|
||||
if res.code != 0 {
|
||||
bail!(res.msg);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,18 +6,18 @@ use sysproxy::Sysproxy;
|
||||
use tauri::{async_runtime::Mutex, utils::platform::current_exe};
|
||||
|
||||
pub struct Sysopt {
|
||||
/// current system proxy setting
|
||||
cur_sysproxy: Option<Sysproxy>,
|
||||
/// current system proxy setting
|
||||
cur_sysproxy: Option<Sysproxy>,
|
||||
|
||||
/// record the original system proxy
|
||||
/// recover it when exit
|
||||
old_sysproxy: Option<Sysproxy>,
|
||||
/// record the original system proxy
|
||||
/// recover it when exit
|
||||
old_sysproxy: Option<Sysproxy>,
|
||||
|
||||
/// helps to auto launch the app
|
||||
auto_launch: Option<AutoLaunch>,
|
||||
/// helps to auto launch the app
|
||||
auto_launch: Option<AutoLaunch>,
|
||||
|
||||
/// record whether the guard async is running or not
|
||||
guard_state: Arc<Mutex<bool>>,
|
||||
/// record whether the guard async is running or not
|
||||
guard_state: Arc<Mutex<bool>>,
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
@@ -28,258 +28,258 @@ static DEFAULT_BYPASS: &str = "localhost,127.0.0.1/8,::1";
|
||||
static DEFAULT_BYPASS: &str = "127.0.0.1,localhost,<local>";
|
||||
|
||||
impl Sysopt {
|
||||
pub fn new() -> Sysopt {
|
||||
Sysopt {
|
||||
cur_sysproxy: None,
|
||||
old_sysproxy: None,
|
||||
auto_launch: None,
|
||||
guard_state: Arc::new(Mutex::new(false)),
|
||||
}
|
||||
}
|
||||
|
||||
/// init the sysproxy
|
||||
pub fn init_sysproxy(&mut self) -> Result<()> {
|
||||
let data = Data::global();
|
||||
let clash = data.clash.lock();
|
||||
let port = clash.info.port.clone();
|
||||
|
||||
if port.is_none() {
|
||||
bail!("clash port is none");
|
||||
pub fn new() -> Sysopt {
|
||||
Sysopt {
|
||||
cur_sysproxy: None,
|
||||
old_sysproxy: None,
|
||||
auto_launch: None,
|
||||
guard_state: Arc::new(Mutex::new(false)),
|
||||
}
|
||||
}
|
||||
|
||||
let verge = data.verge.lock();
|
||||
/// init the sysproxy
|
||||
pub fn init_sysproxy(&mut self) -> Result<()> {
|
||||
let data = Data::global();
|
||||
let clash = data.clash.lock();
|
||||
let port = clash.info.port.clone();
|
||||
|
||||
let enable = verge.enable_system_proxy.clone().unwrap_or(false);
|
||||
let bypass = verge.system_proxy_bypass.clone();
|
||||
let bypass = bypass.unwrap_or(DEFAULT_BYPASS.into());
|
||||
if port.is_none() {
|
||||
bail!("clash port is none");
|
||||
}
|
||||
|
||||
let port = port.unwrap().parse::<u16>()?;
|
||||
let host = String::from("127.0.0.1");
|
||||
|
||||
self.cur_sysproxy = Some(Sysproxy {
|
||||
enable,
|
||||
host,
|
||||
port,
|
||||
bypass,
|
||||
});
|
||||
|
||||
if enable {
|
||||
self.old_sysproxy = Sysproxy::get_system_proxy().map_or(None, |p| Some(p));
|
||||
self.cur_sysproxy.as_ref().unwrap().set_system_proxy()?;
|
||||
}
|
||||
|
||||
// run the system proxy guard
|
||||
self.guard_proxy();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// update the system proxy
|
||||
pub fn update_sysproxy(&mut self) -> Result<()> {
|
||||
if self.cur_sysproxy.is_none() || self.old_sysproxy.is_none() {
|
||||
return self.init_sysproxy();
|
||||
}
|
||||
|
||||
let data = Data::global();
|
||||
let verge = data.verge.lock();
|
||||
|
||||
let enable = verge.enable_system_proxy.clone().unwrap_or(false);
|
||||
let bypass = verge.system_proxy_bypass.clone();
|
||||
let bypass = bypass.unwrap_or(DEFAULT_BYPASS.into());
|
||||
|
||||
let mut sysproxy = self.cur_sysproxy.take().unwrap();
|
||||
|
||||
sysproxy.enable = enable;
|
||||
sysproxy.bypass = bypass;
|
||||
|
||||
self.cur_sysproxy = Some(sysproxy);
|
||||
self.cur_sysproxy.as_ref().unwrap().set_system_proxy()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// reset the sysproxy
|
||||
pub fn reset_sysproxy(&mut self) -> Result<()> {
|
||||
let cur = self.cur_sysproxy.take();
|
||||
|
||||
if let Some(mut old) = self.old_sysproxy.take() {
|
||||
// 如果原代理和当前代理 端口一致,就disable关闭,否则就恢复原代理设置
|
||||
// 当前没有设置代理的时候,不确定旧设置是否和当前一致,全关了
|
||||
let port_same = cur.map_or(true, |cur| old.port == cur.port);
|
||||
|
||||
if old.enable && port_same {
|
||||
old.enable = false;
|
||||
log::info!(target: "app", "reset proxy by disabling the original proxy");
|
||||
} else {
|
||||
log::info!(target: "app", "reset proxy to the original proxy");
|
||||
}
|
||||
|
||||
old.set_system_proxy()?;
|
||||
} else if let Some(mut cur @ Sysproxy { enable: true, .. }) = cur {
|
||||
// 没有原代理,就按现在的代理设置disable即可
|
||||
log::info!(target: "app", "reset proxy by disabling the current proxy");
|
||||
cur.enable = false;
|
||||
cur.set_system_proxy()?;
|
||||
} else {
|
||||
log::info!(target: "app", "reset proxy with no action");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// init the auto launch
|
||||
pub fn init_launch(&mut self) -> Result<()> {
|
||||
let data = Data::global();
|
||||
let verge = data.verge.lock();
|
||||
let enable = verge.enable_auto_launch.clone().unwrap_or(false);
|
||||
|
||||
let app_exe = current_exe()?;
|
||||
let app_exe = dunce::canonicalize(app_exe)?;
|
||||
let app_name = app_exe
|
||||
.file_stem()
|
||||
.and_then(|f| f.to_str())
|
||||
.ok_or(anyhow!("failed to get file stem"))?;
|
||||
|
||||
let app_path = app_exe
|
||||
.as_os_str()
|
||||
.to_str()
|
||||
.ok_or(anyhow!("failed to get app_path"))?
|
||||
.to_string();
|
||||
|
||||
// fix issue #26
|
||||
#[cfg(target_os = "windows")]
|
||||
let app_path = format!("\"{app_path}\"");
|
||||
|
||||
// use the /Applications/Clash Verge.app path
|
||||
#[cfg(target_os = "macos")]
|
||||
let app_path = (|| -> Option<String> {
|
||||
let path = std::path::PathBuf::from(&app_path);
|
||||
let path = path.parent()?.parent()?.parent()?;
|
||||
let extension = path.extension()?.to_str()?;
|
||||
match extension == "app" {
|
||||
true => Some(path.as_os_str().to_str()?.to_string()),
|
||||
false => None,
|
||||
}
|
||||
})()
|
||||
.unwrap_or(app_path);
|
||||
|
||||
let auto = AutoLaunchBuilder::new()
|
||||
.set_app_name(app_name)
|
||||
.set_app_path(&app_path)
|
||||
.build()?;
|
||||
|
||||
self.auto_launch = Some(auto);
|
||||
|
||||
// 避免在开发时将自启动关了
|
||||
#[cfg(feature = "verge-dev")]
|
||||
if !enable {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let auto = self.auto_launch.as_ref().unwrap();
|
||||
|
||||
// macos每次启动都更新登录项,避免重复设置登录项
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let _ = auto.disable();
|
||||
if enable {
|
||||
auto.enable()?;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
match enable {
|
||||
true => auto.enable()?,
|
||||
false => auto.disable()?,
|
||||
};
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// update the startup
|
||||
pub fn update_launch(&mut self) -> Result<()> {
|
||||
if self.auto_launch.is_none() {
|
||||
return self.init_launch();
|
||||
}
|
||||
|
||||
let data = Data::global();
|
||||
let verge = data.verge.lock();
|
||||
let enable = verge.enable_auto_launch.clone().unwrap_or(false);
|
||||
|
||||
let auto_launch = self.auto_launch.as_ref().unwrap();
|
||||
|
||||
match enable {
|
||||
true => auto_launch.enable()?,
|
||||
false => crate::log_if_err!(auto_launch.disable()), // 忽略关闭的错误
|
||||
};
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// launch a system proxy guard
|
||||
/// read config from file directly
|
||||
pub fn guard_proxy(&self) {
|
||||
use tokio::time::{sleep, Duration};
|
||||
|
||||
let guard_state = self.guard_state.clone();
|
||||
|
||||
tauri::async_runtime::spawn(async move {
|
||||
// if it is running, exit
|
||||
let mut state = guard_state.lock().await;
|
||||
if *state {
|
||||
return;
|
||||
}
|
||||
*state = true;
|
||||
drop(state);
|
||||
|
||||
// default duration is 10s
|
||||
let mut wait_secs = 10u64;
|
||||
|
||||
loop {
|
||||
sleep(Duration::from_secs(wait_secs)).await;
|
||||
|
||||
let global = Data::global();
|
||||
let verge = global.verge.lock();
|
||||
let verge = data.verge.lock();
|
||||
|
||||
let enable = verge.enable_system_proxy.clone().unwrap_or(false);
|
||||
let guard = verge.enable_proxy_guard.clone().unwrap_or(false);
|
||||
let guard_duration = verge.proxy_guard_duration.clone().unwrap_or(10);
|
||||
let bypass = verge.system_proxy_bypass.clone();
|
||||
drop(verge);
|
||||
let bypass = bypass.unwrap_or(DEFAULT_BYPASS.into());
|
||||
|
||||
// stop loop
|
||||
if !enable || !guard {
|
||||
break;
|
||||
let port = port.unwrap().parse::<u16>()?;
|
||||
let host = String::from("127.0.0.1");
|
||||
|
||||
self.cur_sysproxy = Some(Sysproxy {
|
||||
enable,
|
||||
host,
|
||||
port,
|
||||
bypass,
|
||||
});
|
||||
|
||||
if enable {
|
||||
self.old_sysproxy = Sysproxy::get_system_proxy().map_or(None, |p| Some(p));
|
||||
self.cur_sysproxy.as_ref().unwrap().set_system_proxy()?;
|
||||
}
|
||||
|
||||
// update duration
|
||||
wait_secs = guard_duration;
|
||||
// run the system proxy guard
|
||||
self.guard_proxy();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
let clash = global.clash.lock();
|
||||
let port = clash.info.port.clone();
|
||||
let port = port.unwrap_or("".into()).parse::<u16>();
|
||||
drop(clash);
|
||||
/// update the system proxy
|
||||
pub fn update_sysproxy(&mut self) -> Result<()> {
|
||||
if self.cur_sysproxy.is_none() || self.old_sysproxy.is_none() {
|
||||
return self.init_sysproxy();
|
||||
}
|
||||
|
||||
log::debug!(target: "app", "try to guard the system proxy");
|
||||
let data = Data::global();
|
||||
let verge = data.verge.lock();
|
||||
|
||||
match port {
|
||||
Ok(port) => {
|
||||
let sysproxy = Sysproxy {
|
||||
enable: true,
|
||||
host: "127.0.0.1".into(),
|
||||
port,
|
||||
bypass: bypass.unwrap_or(DEFAULT_BYPASS.into()),
|
||||
let enable = verge.enable_system_proxy.clone().unwrap_or(false);
|
||||
let bypass = verge.system_proxy_bypass.clone();
|
||||
let bypass = bypass.unwrap_or(DEFAULT_BYPASS.into());
|
||||
|
||||
let mut sysproxy = self.cur_sysproxy.take().unwrap();
|
||||
|
||||
sysproxy.enable = enable;
|
||||
sysproxy.bypass = bypass;
|
||||
|
||||
self.cur_sysproxy = Some(sysproxy);
|
||||
self.cur_sysproxy.as_ref().unwrap().set_system_proxy()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// reset the sysproxy
|
||||
pub fn reset_sysproxy(&mut self) -> Result<()> {
|
||||
let cur = self.cur_sysproxy.take();
|
||||
|
||||
if let Some(mut old) = self.old_sysproxy.take() {
|
||||
// 如果原代理和当前代理 端口一致,就disable关闭,否则就恢复原代理设置
|
||||
// 当前没有设置代理的时候,不确定旧设置是否和当前一致,全关了
|
||||
let port_same = cur.map_or(true, |cur| old.port == cur.port);
|
||||
|
||||
if old.enable && port_same {
|
||||
old.enable = false;
|
||||
log::info!(target: "app", "reset proxy by disabling the original proxy");
|
||||
} else {
|
||||
log::info!(target: "app", "reset proxy to the original proxy");
|
||||
}
|
||||
|
||||
old.set_system_proxy()?;
|
||||
} else if let Some(mut cur @ Sysproxy { enable: true, .. }) = cur {
|
||||
// 没有原代理,就按现在的代理设置disable即可
|
||||
log::info!(target: "app", "reset proxy by disabling the current proxy");
|
||||
cur.enable = false;
|
||||
cur.set_system_proxy()?;
|
||||
} else {
|
||||
log::info!(target: "app", "reset proxy with no action");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// init the auto launch
|
||||
pub fn init_launch(&mut self) -> Result<()> {
|
||||
let data = Data::global();
|
||||
let verge = data.verge.lock();
|
||||
let enable = verge.enable_auto_launch.clone().unwrap_or(false);
|
||||
|
||||
let app_exe = current_exe()?;
|
||||
let app_exe = dunce::canonicalize(app_exe)?;
|
||||
let app_name = app_exe
|
||||
.file_stem()
|
||||
.and_then(|f| f.to_str())
|
||||
.ok_or(anyhow!("failed to get file stem"))?;
|
||||
|
||||
let app_path = app_exe
|
||||
.as_os_str()
|
||||
.to_str()
|
||||
.ok_or(anyhow!("failed to get app_path"))?
|
||||
.to_string();
|
||||
|
||||
// fix issue #26
|
||||
#[cfg(target_os = "windows")]
|
||||
let app_path = format!("\"{app_path}\"");
|
||||
|
||||
// use the /Applications/Clash Verge.app path
|
||||
#[cfg(target_os = "macos")]
|
||||
let app_path = (|| -> Option<String> {
|
||||
let path = std::path::PathBuf::from(&app_path);
|
||||
let path = path.parent()?.parent()?.parent()?;
|
||||
let extension = path.extension()?.to_str()?;
|
||||
match extension == "app" {
|
||||
true => Some(path.as_os_str().to_str()?.to_string()),
|
||||
false => None,
|
||||
}
|
||||
})()
|
||||
.unwrap_or(app_path);
|
||||
|
||||
let auto = AutoLaunchBuilder::new()
|
||||
.set_app_name(app_name)
|
||||
.set_app_path(&app_path)
|
||||
.build()?;
|
||||
|
||||
self.auto_launch = Some(auto);
|
||||
|
||||
// 避免在开发时将自启动关了
|
||||
#[cfg(feature = "verge-dev")]
|
||||
if !enable {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let auto = self.auto_launch.as_ref().unwrap();
|
||||
|
||||
// macos每次启动都更新登录项,避免重复设置登录项
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let _ = auto.disable();
|
||||
if enable {
|
||||
auto.enable()?;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
match enable {
|
||||
true => auto.enable()?,
|
||||
false => auto.disable()?,
|
||||
};
|
||||
|
||||
log_if_err!(sysproxy.set_system_proxy());
|
||||
}
|
||||
Err(_) => log::error!(target: "app", "failed to parse clash port"),
|
||||
}
|
||||
}
|
||||
|
||||
let mut state = guard_state.lock().await;
|
||||
*state = false;
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// update the startup
|
||||
pub fn update_launch(&mut self) -> Result<()> {
|
||||
if self.auto_launch.is_none() {
|
||||
return self.init_launch();
|
||||
}
|
||||
|
||||
let data = Data::global();
|
||||
let verge = data.verge.lock();
|
||||
let enable = verge.enable_auto_launch.clone().unwrap_or(false);
|
||||
|
||||
let auto_launch = self.auto_launch.as_ref().unwrap();
|
||||
|
||||
match enable {
|
||||
true => auto_launch.enable()?,
|
||||
false => crate::log_if_err!(auto_launch.disable()), // 忽略关闭的错误
|
||||
};
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// launch a system proxy guard
|
||||
/// read config from file directly
|
||||
pub fn guard_proxy(&self) {
|
||||
use tokio::time::{sleep, Duration};
|
||||
|
||||
let guard_state = self.guard_state.clone();
|
||||
|
||||
tauri::async_runtime::spawn(async move {
|
||||
// if it is running, exit
|
||||
let mut state = guard_state.lock().await;
|
||||
if *state {
|
||||
return;
|
||||
}
|
||||
*state = true;
|
||||
drop(state);
|
||||
|
||||
// default duration is 10s
|
||||
let mut wait_secs = 10u64;
|
||||
|
||||
loop {
|
||||
sleep(Duration::from_secs(wait_secs)).await;
|
||||
|
||||
let global = Data::global();
|
||||
let verge = global.verge.lock();
|
||||
|
||||
let enable = verge.enable_system_proxy.clone().unwrap_or(false);
|
||||
let guard = verge.enable_proxy_guard.clone().unwrap_or(false);
|
||||
let guard_duration = verge.proxy_guard_duration.clone().unwrap_or(10);
|
||||
let bypass = verge.system_proxy_bypass.clone();
|
||||
drop(verge);
|
||||
|
||||
// stop loop
|
||||
if !enable || !guard {
|
||||
break;
|
||||
}
|
||||
|
||||
// update duration
|
||||
wait_secs = guard_duration;
|
||||
|
||||
let clash = global.clash.lock();
|
||||
let port = clash.info.port.clone();
|
||||
let port = port.unwrap_or("".into()).parse::<u16>();
|
||||
drop(clash);
|
||||
|
||||
log::debug!(target: "app", "try to guard the system proxy");
|
||||
|
||||
match port {
|
||||
Ok(port) => {
|
||||
let sysproxy = Sysproxy {
|
||||
enable: true,
|
||||
host: "127.0.0.1".into(),
|
||||
port,
|
||||
bypass: bypass.unwrap_or(DEFAULT_BYPASS.into()),
|
||||
};
|
||||
|
||||
log_if_err!(sysproxy.set_system_proxy());
|
||||
}
|
||||
Err(_) => log::error!(target: "app", "failed to parse clash port"),
|
||||
}
|
||||
}
|
||||
|
||||
let mut state = guard_state.lock().await;
|
||||
*state = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,165 +8,165 @@ use std::collections::HashMap;
|
||||
type TaskID = u64;
|
||||
|
||||
pub struct Timer {
|
||||
/// cron manager
|
||||
delay_timer: DelayTimer,
|
||||
/// cron manager
|
||||
delay_timer: DelayTimer,
|
||||
|
||||
/// save the current state
|
||||
timer_map: HashMap<String, (TaskID, u64)>,
|
||||
/// save the current state
|
||||
timer_map: HashMap<String, (TaskID, u64)>,
|
||||
|
||||
/// increment id
|
||||
timer_count: TaskID,
|
||||
/// increment id
|
||||
timer_count: TaskID,
|
||||
}
|
||||
|
||||
impl Timer {
|
||||
pub fn new() -> Self {
|
||||
Timer {
|
||||
delay_timer: DelayTimerBuilder::default().build(),
|
||||
timer_map: HashMap::new(),
|
||||
timer_count: 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Correctly update all cron tasks
|
||||
pub fn refresh(&mut self) -> Result<()> {
|
||||
let diff_map = self.gen_diff();
|
||||
|
||||
for (uid, diff) in diff_map.into_iter() {
|
||||
match diff {
|
||||
DiffFlag::Del(tid) => {
|
||||
let _ = self.timer_map.remove(&uid);
|
||||
log_if_err!(self.delay_timer.remove_task(tid));
|
||||
pub fn new() -> Self {
|
||||
Timer {
|
||||
delay_timer: DelayTimerBuilder::default().build(),
|
||||
timer_map: HashMap::new(),
|
||||
timer_count: 1,
|
||||
}
|
||||
DiffFlag::Add(tid, val) => {
|
||||
let _ = self.timer_map.insert(uid.clone(), (tid, val));
|
||||
log_if_err!(self.add_task(uid, tid, val));
|
||||
}
|
||||
DiffFlag::Mod(tid, val) => {
|
||||
let _ = self.timer_map.insert(uid.clone(), (tid, val));
|
||||
log_if_err!(self.delay_timer.remove_task(tid));
|
||||
log_if_err!(self.add_task(uid, tid, val));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
/// Correctly update all cron tasks
|
||||
pub fn refresh(&mut self) -> Result<()> {
|
||||
let diff_map = self.gen_diff();
|
||||
|
||||
/// restore timer
|
||||
pub fn restore(&mut self) -> Result<()> {
|
||||
self.refresh()?;
|
||||
|
||||
let cur_timestamp = get_now(); // seconds
|
||||
|
||||
let global = Data::global();
|
||||
let profiles = global.profiles.lock();
|
||||
|
||||
profiles
|
||||
.get_items()
|
||||
.unwrap_or(&vec![])
|
||||
.iter()
|
||||
.filter(|item| item.uid.is_some() && item.updated.is_some() && item.option.is_some())
|
||||
.filter(|item| {
|
||||
// mins to seconds
|
||||
let interval = item.option.as_ref().unwrap().update_interval.unwrap_or(0) as usize * 60;
|
||||
let updated = item.updated.unwrap();
|
||||
return interval > 0 && cur_timestamp - updated >= interval;
|
||||
})
|
||||
.for_each(|item| {
|
||||
let uid = item.uid.as_ref().unwrap();
|
||||
if let Some((task_id, _)) = self.timer_map.get(uid) {
|
||||
log_if_err!(self.delay_timer.advance_task(*task_id));
|
||||
for (uid, diff) in diff_map.into_iter() {
|
||||
match diff {
|
||||
DiffFlag::Del(tid) => {
|
||||
let _ = self.timer_map.remove(&uid);
|
||||
log_if_err!(self.delay_timer.remove_task(tid));
|
||||
}
|
||||
DiffFlag::Add(tid, val) => {
|
||||
let _ = self.timer_map.insert(uid.clone(), (tid, val));
|
||||
log_if_err!(self.add_task(uid, tid, val));
|
||||
}
|
||||
DiffFlag::Mod(tid, val) => {
|
||||
let _ = self.timer_map.insert(uid.clone(), (tid, val));
|
||||
log_if_err!(self.delay_timer.remove_task(tid));
|
||||
log_if_err!(self.add_task(uid, tid, val));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// generate a uid -> update_interval map
|
||||
fn gen_map(&self) -> HashMap<String, u64> {
|
||||
let global = Data::global();
|
||||
let profiles = global.profiles.lock();
|
||||
|
||||
let mut new_map = HashMap::new();
|
||||
|
||||
if let Some(items) = profiles.get_items() {
|
||||
for item in items.iter() {
|
||||
if item.option.is_some() {
|
||||
let option = item.option.as_ref().unwrap();
|
||||
let interval = option.update_interval.unwrap_or(0);
|
||||
|
||||
if interval > 0 {
|
||||
new_map.insert(item.uid.clone().unwrap(), interval);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
new_map
|
||||
}
|
||||
/// restore timer
|
||||
pub fn restore(&mut self) -> Result<()> {
|
||||
self.refresh()?;
|
||||
|
||||
/// generate the diff map for refresh
|
||||
fn gen_diff(&mut self) -> HashMap<String, DiffFlag> {
|
||||
let mut diff_map = HashMap::new();
|
||||
let cur_timestamp = get_now(); // seconds
|
||||
|
||||
let new_map = self.gen_map();
|
||||
let cur_map = &self.timer_map;
|
||||
let global = Data::global();
|
||||
let profiles = global.profiles.lock();
|
||||
|
||||
cur_map.iter().for_each(|(uid, (tid, val))| {
|
||||
let new_val = new_map.get(uid).unwrap_or(&0);
|
||||
profiles
|
||||
.get_items()
|
||||
.unwrap_or(&vec![])
|
||||
.iter()
|
||||
.filter(|item| item.uid.is_some() && item.updated.is_some() && item.option.is_some())
|
||||
.filter(|item| {
|
||||
// mins to seconds
|
||||
let interval =
|
||||
item.option.as_ref().unwrap().update_interval.unwrap_or(0) as usize * 60;
|
||||
let updated = item.updated.unwrap();
|
||||
return interval > 0 && cur_timestamp - updated >= interval;
|
||||
})
|
||||
.for_each(|item| {
|
||||
let uid = item.uid.as_ref().unwrap();
|
||||
if let Some((task_id, _)) = self.timer_map.get(uid) {
|
||||
log_if_err!(self.delay_timer.advance_task(*task_id));
|
||||
}
|
||||
});
|
||||
|
||||
if *new_val == 0 {
|
||||
diff_map.insert(uid.clone(), DiffFlag::Del(*tid));
|
||||
} else if new_val != val {
|
||||
diff_map.insert(uid.clone(), DiffFlag::Mod(*tid, *new_val));
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
let mut count = self.timer_count;
|
||||
/// generate a uid -> update_interval map
|
||||
fn gen_map(&self) -> HashMap<String, u64> {
|
||||
let global = Data::global();
|
||||
let profiles = global.profiles.lock();
|
||||
|
||||
new_map.iter().for_each(|(uid, val)| {
|
||||
if cur_map.get(uid).is_none() {
|
||||
diff_map.insert(uid.clone(), DiffFlag::Add(count, *val));
|
||||
let mut new_map = HashMap::new();
|
||||
|
||||
count += 1;
|
||||
}
|
||||
});
|
||||
if let Some(items) = profiles.get_items() {
|
||||
for item in items.iter() {
|
||||
if item.option.is_some() {
|
||||
let option = item.option.as_ref().unwrap();
|
||||
let interval = option.update_interval.unwrap_or(0);
|
||||
|
||||
self.timer_count = count;
|
||||
if interval > 0 {
|
||||
new_map.insert(item.uid.clone().unwrap(), interval);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
diff_map
|
||||
}
|
||||
new_map
|
||||
}
|
||||
|
||||
/// add a cron task
|
||||
fn add_task(&self, uid: String, tid: TaskID, minutes: u64) -> Result<()> {
|
||||
let core = Core::global();
|
||||
/// generate the diff map for refresh
|
||||
fn gen_diff(&mut self) -> HashMap<String, DiffFlag> {
|
||||
let mut diff_map = HashMap::new();
|
||||
|
||||
let task = TaskBuilder::default()
|
||||
.set_task_id(tid)
|
||||
.set_maximum_parallel_runnable_num(1)
|
||||
.set_frequency_repeated_by_minutes(minutes)
|
||||
// .set_frequency_repeated_by_seconds(minutes) // for test
|
||||
.spawn_async_routine(move || Self::async_task(core.to_owned(), uid.to_owned()))
|
||||
.context("failed to create timer task")?;
|
||||
let new_map = self.gen_map();
|
||||
let cur_map = &self.timer_map;
|
||||
|
||||
self
|
||||
.delay_timer
|
||||
.add_task(task)
|
||||
.context("failed to add timer task")?;
|
||||
cur_map.iter().for_each(|(uid, (tid, val))| {
|
||||
let new_val = new_map.get(uid).unwrap_or(&0);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
if *new_val == 0 {
|
||||
diff_map.insert(uid.clone(), DiffFlag::Del(*tid));
|
||||
} else if new_val != val {
|
||||
diff_map.insert(uid.clone(), DiffFlag::Mod(*tid, *new_val));
|
||||
}
|
||||
});
|
||||
|
||||
/// 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(uid, None).await);
|
||||
}
|
||||
let mut count = self.timer_count;
|
||||
|
||||
new_map.iter().for_each(|(uid, val)| {
|
||||
if cur_map.get(uid).is_none() {
|
||||
diff_map.insert(uid.clone(), DiffFlag::Add(count, *val));
|
||||
|
||||
count += 1;
|
||||
}
|
||||
});
|
||||
|
||||
self.timer_count = count;
|
||||
|
||||
diff_map
|
||||
}
|
||||
|
||||
/// add a cron task
|
||||
fn add_task(&self, uid: String, tid: TaskID, minutes: u64) -> Result<()> {
|
||||
let core = Core::global();
|
||||
|
||||
let task = TaskBuilder::default()
|
||||
.set_task_id(tid)
|
||||
.set_maximum_parallel_runnable_num(1)
|
||||
.set_frequency_repeated_by_minutes(minutes)
|
||||
// .set_frequency_repeated_by_seconds(minutes) // for test
|
||||
.spawn_async_routine(move || Self::async_task(core.to_owned(), uid.to_owned()))
|
||||
.context("failed to create timer task")?;
|
||||
|
||||
self.delay_timer
|
||||
.add_task(task)
|
||||
.context("failed to add timer task")?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 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(uid, None).await);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum DiffFlag {
|
||||
Del(TaskID),
|
||||
Add(TaskID, u64),
|
||||
Mod(TaskID, u64),
|
||||
Del(TaskID),
|
||||
Add(TaskID, u64),
|
||||
Mod(TaskID, u64),
|
||||
}
|
||||
|
||||
@@ -1,124 +1,130 @@
|
||||
use crate::{data::Data, feat, utils::resolve};
|
||||
use anyhow::{Ok, Result};
|
||||
use tauri::{
|
||||
api, AppHandle, CustomMenuItem, Manager, SystemTrayEvent, SystemTrayMenu, SystemTrayMenuItem,
|
||||
SystemTraySubmenu,
|
||||
api, AppHandle, CustomMenuItem, Manager, SystemTrayEvent, SystemTrayMenu, SystemTrayMenuItem,
|
||||
SystemTraySubmenu,
|
||||
};
|
||||
|
||||
pub struct Tray {}
|
||||
|
||||
impl Tray {
|
||||
pub fn tray_menu(app_handle: &AppHandle) -> SystemTrayMenu {
|
||||
let data = Data::global();
|
||||
let zh = {
|
||||
let verge = data.verge.lock();
|
||||
verge.language == Some("zh".into())
|
||||
};
|
||||
pub fn tray_menu(app_handle: &AppHandle) -> SystemTrayMenu {
|
||||
let data = Data::global();
|
||||
let zh = {
|
||||
let verge = data.verge.lock();
|
||||
verge.language == Some("zh".into())
|
||||
};
|
||||
|
||||
let version = app_handle.package_info().version.to_string();
|
||||
let version = app_handle.package_info().version.to_string();
|
||||
|
||||
if zh {
|
||||
SystemTrayMenu::new()
|
||||
.add_item(CustomMenuItem::new("open_window", "打开面板"))
|
||||
.add_native_item(SystemTrayMenuItem::Separator)
|
||||
.add_item(CustomMenuItem::new("rule_mode", "规则模式"))
|
||||
.add_item(CustomMenuItem::new("global_mode", "全局模式"))
|
||||
.add_item(CustomMenuItem::new("direct_mode", "直连模式"))
|
||||
.add_item(CustomMenuItem::new("script_mode", "脚本模式"))
|
||||
.add_native_item(SystemTrayMenuItem::Separator)
|
||||
.add_item(CustomMenuItem::new("system_proxy", "系统代理"))
|
||||
.add_item(CustomMenuItem::new("tun_mode", "TUN 模式"))
|
||||
.add_submenu(SystemTraySubmenu::new(
|
||||
"更多",
|
||||
SystemTrayMenu::new()
|
||||
.add_item(CustomMenuItem::new("restart_clash", "重启 Clash"))
|
||||
.add_item(CustomMenuItem::new("restart_app", "重启应用"))
|
||||
.add_item(CustomMenuItem::new("app_version", format!("Version {version}")).disabled()),
|
||||
))
|
||||
.add_native_item(SystemTrayMenuItem::Separator)
|
||||
.add_item(CustomMenuItem::new("quit", "退出").accelerator("CmdOrControl+Q"))
|
||||
} else {
|
||||
SystemTrayMenu::new()
|
||||
.add_item(CustomMenuItem::new("open_window", "Dashboard"))
|
||||
.add_native_item(SystemTrayMenuItem::Separator)
|
||||
.add_item(CustomMenuItem::new("rule_mode", "Rule Mode"))
|
||||
.add_item(CustomMenuItem::new("global_mode", "Global Mode"))
|
||||
.add_item(CustomMenuItem::new("direct_mode", "Direct Mode"))
|
||||
.add_item(CustomMenuItem::new("script_mode", "Script Mode"))
|
||||
.add_native_item(SystemTrayMenuItem::Separator)
|
||||
.add_item(CustomMenuItem::new("system_proxy", "System Proxy"))
|
||||
.add_item(CustomMenuItem::new("tun_mode", "Tun Mode"))
|
||||
.add_submenu(SystemTraySubmenu::new(
|
||||
"More",
|
||||
SystemTrayMenu::new()
|
||||
.add_item(CustomMenuItem::new("restart_clash", "Restart Clash"))
|
||||
.add_item(CustomMenuItem::new("restart_app", "Restart App"))
|
||||
.add_item(CustomMenuItem::new("app_version", format!("Version {version}")).disabled()),
|
||||
))
|
||||
.add_native_item(SystemTrayMenuItem::Separator)
|
||||
.add_item(CustomMenuItem::new("quit", "Quit").accelerator("CmdOrControl+Q"))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_systray(app_handle: &AppHandle) -> Result<()> {
|
||||
app_handle
|
||||
.tray_handle()
|
||||
.set_menu(Tray::tray_menu(app_handle))?;
|
||||
Tray::update_part(app_handle)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn update_part(app_handle: &AppHandle) -> Result<()> {
|
||||
let global = Data::global();
|
||||
let clash = global.clash.lock();
|
||||
let mode = clash
|
||||
.config
|
||||
.get(&serde_yaml::Value::from("mode"))
|
||||
.map(|val| val.as_str().unwrap_or("rule"))
|
||||
.unwrap_or("rule");
|
||||
|
||||
let tray = app_handle.tray_handle();
|
||||
|
||||
let _ = tray.get_item("rule_mode").set_selected(mode == "rule");
|
||||
let _ = tray.get_item("global_mode").set_selected(mode == "global");
|
||||
let _ = tray.get_item("direct_mode").set_selected(mode == "direct");
|
||||
let _ = tray.get_item("script_mode").set_selected(mode == "script");
|
||||
|
||||
let verge = global.verge.lock();
|
||||
let system_proxy = verge.enable_system_proxy.as_ref().unwrap_or(&false);
|
||||
let tun_mode = verge.enable_tun_mode.as_ref().unwrap_or(&false);
|
||||
|
||||
let _ = tray.get_item("system_proxy").set_selected(*system_proxy);
|
||||
let _ = tray.get_item("tun_mode").set_selected(*tun_mode);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn on_system_tray_event(app_handle: &AppHandle, event: SystemTrayEvent) {
|
||||
match event {
|
||||
SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() {
|
||||
mode @ ("rule_mode" | "global_mode" | "direct_mode" | "script_mode") => {
|
||||
let mode = &mode[0..mode.len() - 5];
|
||||
feat::change_clash_mode(mode);
|
||||
if zh {
|
||||
SystemTrayMenu::new()
|
||||
.add_item(CustomMenuItem::new("open_window", "打开面板"))
|
||||
.add_native_item(SystemTrayMenuItem::Separator)
|
||||
.add_item(CustomMenuItem::new("rule_mode", "规则模式"))
|
||||
.add_item(CustomMenuItem::new("global_mode", "全局模式"))
|
||||
.add_item(CustomMenuItem::new("direct_mode", "直连模式"))
|
||||
.add_item(CustomMenuItem::new("script_mode", "脚本模式"))
|
||||
.add_native_item(SystemTrayMenuItem::Separator)
|
||||
.add_item(CustomMenuItem::new("system_proxy", "系统代理"))
|
||||
.add_item(CustomMenuItem::new("tun_mode", "TUN 模式"))
|
||||
.add_submenu(SystemTraySubmenu::new(
|
||||
"更多",
|
||||
SystemTrayMenu::new()
|
||||
.add_item(CustomMenuItem::new("restart_clash", "重启 Clash"))
|
||||
.add_item(CustomMenuItem::new("restart_app", "重启应用"))
|
||||
.add_item(
|
||||
CustomMenuItem::new("app_version", format!("Version {version}"))
|
||||
.disabled(),
|
||||
),
|
||||
))
|
||||
.add_native_item(SystemTrayMenuItem::Separator)
|
||||
.add_item(CustomMenuItem::new("quit", "退出").accelerator("CmdOrControl+Q"))
|
||||
} else {
|
||||
SystemTrayMenu::new()
|
||||
.add_item(CustomMenuItem::new("open_window", "Dashboard"))
|
||||
.add_native_item(SystemTrayMenuItem::Separator)
|
||||
.add_item(CustomMenuItem::new("rule_mode", "Rule Mode"))
|
||||
.add_item(CustomMenuItem::new("global_mode", "Global Mode"))
|
||||
.add_item(CustomMenuItem::new("direct_mode", "Direct Mode"))
|
||||
.add_item(CustomMenuItem::new("script_mode", "Script Mode"))
|
||||
.add_native_item(SystemTrayMenuItem::Separator)
|
||||
.add_item(CustomMenuItem::new("system_proxy", "System Proxy"))
|
||||
.add_item(CustomMenuItem::new("tun_mode", "Tun Mode"))
|
||||
.add_submenu(SystemTraySubmenu::new(
|
||||
"More",
|
||||
SystemTrayMenu::new()
|
||||
.add_item(CustomMenuItem::new("restart_clash", "Restart Clash"))
|
||||
.add_item(CustomMenuItem::new("restart_app", "Restart App"))
|
||||
.add_item(
|
||||
CustomMenuItem::new("app_version", format!("Version {version}"))
|
||||
.disabled(),
|
||||
),
|
||||
))
|
||||
.add_native_item(SystemTrayMenuItem::Separator)
|
||||
.add_item(CustomMenuItem::new("quit", "Quit").accelerator("CmdOrControl+Q"))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_systray(app_handle: &AppHandle) -> Result<()> {
|
||||
app_handle
|
||||
.tray_handle()
|
||||
.set_menu(Tray::tray_menu(app_handle))?;
|
||||
Tray::update_part(app_handle)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn update_part(app_handle: &AppHandle) -> Result<()> {
|
||||
let global = Data::global();
|
||||
let clash = global.clash.lock();
|
||||
let mode = clash
|
||||
.config
|
||||
.get(&serde_yaml::Value::from("mode"))
|
||||
.map(|val| val.as_str().unwrap_or("rule"))
|
||||
.unwrap_or("rule");
|
||||
|
||||
let tray = app_handle.tray_handle();
|
||||
|
||||
let _ = tray.get_item("rule_mode").set_selected(mode == "rule");
|
||||
let _ = tray.get_item("global_mode").set_selected(mode == "global");
|
||||
let _ = tray.get_item("direct_mode").set_selected(mode == "direct");
|
||||
let _ = tray.get_item("script_mode").set_selected(mode == "script");
|
||||
|
||||
let verge = global.verge.lock();
|
||||
let system_proxy = verge.enable_system_proxy.as_ref().unwrap_or(&false);
|
||||
let tun_mode = verge.enable_tun_mode.as_ref().unwrap_or(&false);
|
||||
|
||||
let _ = tray.get_item("system_proxy").set_selected(*system_proxy);
|
||||
let _ = tray.get_item("tun_mode").set_selected(*tun_mode);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn on_system_tray_event(app_handle: &AppHandle, event: SystemTrayEvent) {
|
||||
match event {
|
||||
SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() {
|
||||
mode @ ("rule_mode" | "global_mode" | "direct_mode" | "script_mode") => {
|
||||
let mode = &mode[0..mode.len() - 5];
|
||||
feat::change_clash_mode(mode);
|
||||
}
|
||||
|
||||
"open_window" => resolve::create_window(app_handle),
|
||||
"system_proxy" => feat::toggle_system_proxy(),
|
||||
"tun_mode" => feat::toggle_tun_mode(),
|
||||
"restart_clash" => feat::restart_clash_core(),
|
||||
"restart_app" => api::process::restart(&app_handle.env()),
|
||||
"quit" => {
|
||||
resolve::resolve_reset();
|
||||
api::process::kill_children();
|
||||
app_handle.exit(0);
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
#[cfg(target_os = "windows")]
|
||||
SystemTrayEvent::LeftClick { .. } => {
|
||||
resolve::create_window(app_handle);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
"open_window" => resolve::create_window(app_handle),
|
||||
"system_proxy" => feat::toggle_system_proxy(),
|
||||
"tun_mode" => feat::toggle_tun_mode(),
|
||||
"restart_clash" => feat::restart_clash_core(),
|
||||
"restart_app" => api::process::restart(&app_handle.env()),
|
||||
"quit" => {
|
||||
resolve::resolve_reset();
|
||||
api::process::kill_children();
|
||||
app_handle.exit(0);
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
#[cfg(target_os = "windows")]
|
||||
SystemTrayEvent::LeftClick { .. } => {
|
||||
resolve::create_window(app_handle);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user