mod.rs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. use self::handle::Handle;
  2. use self::hotkey::Hotkey;
  3. use self::sysopt::Sysopt;
  4. use self::timer::Timer;
  5. use crate::config::enhance_config;
  6. use crate::data::*;
  7. use crate::log_if_err;
  8. use anyhow::{bail, Result};
  9. use once_cell::sync::Lazy;
  10. use parking_lot::Mutex;
  11. use serde_yaml::{Mapping, Value};
  12. use std::sync::Arc;
  13. mod handle;
  14. mod hotkey;
  15. mod service;
  16. mod sysopt;
  17. mod timer;
  18. pub mod tray;
  19. pub use self::service::*;
  20. static CORE: Lazy<Core> = Lazy::new(|| Core {
  21. service: Arc::new(Mutex::new(Service::new())),
  22. sysopt: Arc::new(Mutex::new(Sysopt::new())),
  23. timer: Arc::new(Mutex::new(Timer::new())),
  24. hotkey: Arc::new(Mutex::new(Hotkey::new())),
  25. runtime: Arc::new(Mutex::new(RuntimeResult::default())),
  26. handle: Arc::new(Mutex::new(Handle::default())),
  27. });
  28. #[derive(Clone)]
  29. pub struct Core {
  30. pub service: Arc<Mutex<Service>>,
  31. pub sysopt: Arc<Mutex<Sysopt>>,
  32. pub timer: Arc<Mutex<Timer>>,
  33. pub hotkey: Arc<Mutex<Hotkey>>,
  34. pub runtime: Arc<Mutex<RuntimeResult>>,
  35. pub handle: Arc<Mutex<Handle>>,
  36. }
  37. impl Core {
  38. pub fn global() -> Core {
  39. CORE.clone()
  40. }
  41. /// initialize the core state
  42. pub fn init(&self, app_handle: tauri::AppHandle) {
  43. // kill old clash process
  44. Service::kill_old_clash();
  45. let mut handle = self.handle.lock();
  46. handle.set_inner(app_handle.clone());
  47. drop(handle);
  48. let mut service = self.service.lock();
  49. log_if_err!(service.start());
  50. drop(service);
  51. log_if_err!(self.activate());
  52. let mut sysopt = self.sysopt.lock();
  53. log_if_err!(sysopt.init_launch());
  54. log_if_err!(sysopt.init_sysproxy());
  55. drop(sysopt);
  56. let handle = self.handle.lock();
  57. log_if_err!(handle.update_systray_part());
  58. drop(handle);
  59. let mut hotkey = self.hotkey.lock();
  60. log_if_err!(hotkey.init(app_handle));
  61. drop(hotkey);
  62. // timer initialize
  63. let mut timer = self.timer.lock();
  64. log_if_err!(timer.restore());
  65. }
  66. /// restart the clash sidecar
  67. pub fn restart_clash(&self) -> Result<()> {
  68. let mut service = self.service.lock();
  69. service.restart()?;
  70. drop(service);
  71. self.activate()
  72. }
  73. /// change the clash core
  74. pub fn change_core(&self, clash_core: Option<String>) -> Result<()> {
  75. let clash_core = clash_core.unwrap_or("clash".into());
  76. if &clash_core != "clash" && &clash_core != "clash-meta" {
  77. bail!("invalid clash core name \"{clash_core}\"");
  78. }
  79. let global = Data::global();
  80. let mut verge = global.verge.lock();
  81. verge.patch_config(Verge {
  82. clash_core: Some(clash_core.clone()),
  83. ..Verge::default()
  84. })?;
  85. drop(verge);
  86. let mut service = self.service.lock();
  87. service.clear_logs();
  88. service.restart()?;
  89. drop(service);
  90. self.activate()
  91. }
  92. /// Patch Clash
  93. /// handle the clash config changed
  94. pub fn patch_clash(&self, patch: Mapping) -> Result<()> {
  95. let has_port = patch.contains_key(&Value::from("mixed-port"));
  96. let has_mode = patch.contains_key(&Value::from("mode"));
  97. let port = {
  98. let global = Data::global();
  99. let mut clash = global.clash.lock();
  100. clash.patch_config(patch)?;
  101. clash.info.port.clone()
  102. };
  103. // todo: port check
  104. if has_port && port.is_some() {
  105. let mut service = self.service.lock();
  106. service.restart()?;
  107. drop(service);
  108. self.activate()?;
  109. let mut sysopt = self.sysopt.lock();
  110. sysopt.init_sysproxy()?;
  111. }
  112. if has_mode {
  113. let handle = self.handle.lock();
  114. handle.update_systray_part()?;
  115. }
  116. Ok(())
  117. }
  118. /// Patch Verge
  119. pub fn patch_verge(&self, patch: Verge) -> Result<()> {
  120. // save the patch
  121. let global = Data::global();
  122. let mut verge = global.verge.lock();
  123. verge.patch_config(patch.clone())?;
  124. drop(verge);
  125. let tun_mode = patch.enable_tun_mode;
  126. let auto_launch = patch.enable_auto_launch;
  127. let system_proxy = patch.enable_system_proxy;
  128. let proxy_bypass = patch.system_proxy_bypass;
  129. let proxy_guard = patch.enable_proxy_guard;
  130. let language = patch.language;
  131. #[cfg(target_os = "windows")]
  132. {
  133. let service_mode = patch.enable_service_mode;
  134. // 重启服务
  135. if service_mode.is_some() {
  136. let mut service = self.service.lock();
  137. service.restart()?;
  138. drop(service);
  139. }
  140. if tun_mode.is_some() && *tun_mode.as_ref().unwrap_or(&false) {
  141. let wintun_dll = crate::utils::dirs::app_home_dir().join("wintun.dll");
  142. if !wintun_dll.exists() {
  143. bail!("failed to enable TUN for missing `wintun.dll`");
  144. }
  145. }
  146. if service_mode.is_some() || tun_mode.is_some() {
  147. self.activate()?;
  148. }
  149. }
  150. #[cfg(not(target_os = "windows"))]
  151. if tun_mode.is_some() {
  152. self.activate()?;
  153. }
  154. let mut sysopt = self.sysopt.lock();
  155. if auto_launch.is_some() {
  156. sysopt.update_launch()?;
  157. }
  158. if system_proxy.is_some() || proxy_bypass.is_some() {
  159. sysopt.update_sysproxy()?;
  160. sysopt.guard_proxy();
  161. }
  162. if proxy_guard.unwrap_or(false) {
  163. sysopt.guard_proxy();
  164. }
  165. // 更新tray
  166. if language.is_some() {
  167. let handle = self.handle.lock();
  168. handle.update_systray()?;
  169. } else if system_proxy.is_some() || tun_mode.is_some() {
  170. let handle = self.handle.lock();
  171. handle.update_systray_part()?;
  172. }
  173. if patch.hotkeys.is_some() {
  174. let mut hotkey = self.hotkey.lock();
  175. hotkey.update(patch.hotkeys.unwrap())?;
  176. }
  177. Ok(())
  178. }
  179. // update rule/global/direct/script mode
  180. pub fn update_mode(&self, mode: &str) -> Result<()> {
  181. // save config to file
  182. let info = {
  183. let global = Data::global();
  184. let mut clash = global.clash.lock();
  185. clash.config.insert(Value::from("mode"), Value::from(mode));
  186. clash.save_config()?;
  187. clash.info.clone()
  188. };
  189. let mut mapping = Mapping::new();
  190. mapping.insert(Value::from("mode"), Value::from(mode));
  191. let handle = self.handle.clone();
  192. tauri::async_runtime::spawn(async move {
  193. log_if_err!(Service::patch_config(info, mapping.to_owned()).await);
  194. // update tray
  195. let handle = handle.lock();
  196. handle.refresh_clash();
  197. log_if_err!(handle.update_systray_part());
  198. });
  199. Ok(())
  200. }
  201. /// activate the profile
  202. /// auto activate enhanced profile
  203. /// 触发clash配置更新
  204. pub fn activate(&self) -> Result<()> {
  205. let global = Data::global();
  206. let verge = global.verge.lock();
  207. let clash = global.clash.lock();
  208. let profiles = global.profiles.lock();
  209. let tun_mode = verge.enable_tun_mode.clone().unwrap_or(false);
  210. let profile_activate = profiles.gen_activate()?;
  211. let clash_config = clash.config.clone();
  212. let clash_info = clash.info.clone();
  213. drop(clash);
  214. drop(verge);
  215. drop(profiles);
  216. let (config, exists_keys, logs) = enhance_config(
  217. clash_config,
  218. profile_activate.current,
  219. profile_activate.chain,
  220. profile_activate.valid,
  221. tun_mode,
  222. );
  223. let mut runtime = self.runtime.lock();
  224. *runtime = RuntimeResult {
  225. config: Some(config.clone()),
  226. config_yaml: Some(serde_yaml::to_string(&config).unwrap_or("".into())),
  227. exists_keys,
  228. chain_logs: logs,
  229. };
  230. drop(runtime);
  231. let mut service = self.service.lock();
  232. service.check_start()?;
  233. drop(service);
  234. let handle = self.handle.clone();
  235. tauri::async_runtime::spawn(async move {
  236. match Service::set_config(clash_info, config).await {
  237. Ok(_) => {
  238. let handle = handle.lock();
  239. handle.refresh_clash();
  240. handle.notice_message("set_config::ok".into(), "ok".into());
  241. }
  242. Err(err) => {
  243. let handle = handle.lock();
  244. handle.notice_message("set_config::error".into(), format!("{err}"));
  245. log::error!(target: "app", "last {err}")
  246. }
  247. }
  248. });
  249. Ok(())
  250. }
  251. /// Static function
  252. /// update profile item
  253. pub async fn update_profile_item(&self, uid: String, option: Option<PrfOption>) -> Result<()> {
  254. let global = Data::global();
  255. let (url, opt) = {
  256. let profiles = global.profiles.lock();
  257. let item = profiles.get_item(&uid)?;
  258. if let Some(typ) = item.itype.as_ref() {
  259. // maybe only valid for `local` profile
  260. if *typ != "remote" {
  261. // reactivate the config
  262. if Some(uid) == profiles.get_current() {
  263. drop(profiles);
  264. self.activate()?;
  265. }
  266. return Ok(());
  267. }
  268. }
  269. if item.url.is_none() {
  270. bail!("failed to get the profile item url");
  271. }
  272. (item.url.clone().unwrap(), item.option.clone())
  273. };
  274. let merged_opt = PrfOption::merge(opt, option);
  275. let item = PrfItem::from_url(&url, None, None, merged_opt).await?;
  276. let mut profiles = global.profiles.lock();
  277. profiles.update_item(uid.clone(), item)?;
  278. // reactivate the profile
  279. if Some(uid) == profiles.get_current() {
  280. drop(profiles);
  281. self.activate()?;
  282. }
  283. Ok(())
  284. }
  285. }