mod.rs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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::OnceCell;
  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. #[derive(Clone)]
  21. pub struct Core {
  22. pub service: Arc<Mutex<Service>>,
  23. pub sysopt: Arc<Mutex<Sysopt>>,
  24. pub timer: Arc<Mutex<Timer>>,
  25. pub hotkey: Arc<Mutex<Hotkey>>,
  26. pub runtime: Arc<Mutex<RuntimeResult>>,
  27. pub handle: Arc<Mutex<Handle>>,
  28. }
  29. impl Core {
  30. pub fn global() -> &'static Core {
  31. static CORE: OnceCell<Core> = OnceCell::new();
  32. CORE.get_or_init(|| Core {
  33. service: Arc::new(Mutex::new(Service::new())),
  34. sysopt: Arc::new(Mutex::new(Sysopt::new())),
  35. timer: Arc::new(Mutex::new(Timer::new())),
  36. hotkey: Arc::new(Mutex::new(Hotkey::new())),
  37. runtime: Arc::new(Mutex::new(RuntimeResult::default())),
  38. handle: Arc::new(Mutex::new(Handle::default())),
  39. })
  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 patch_cloned = patch.clone();
  96. let clash_mode = patch.get("mode");
  97. let mixed_port = patch.get("mixed-port");
  98. let external = patch.get("external-controller");
  99. let secret = patch.get("secret");
  100. let valid_port = {
  101. let global = Data::global();
  102. let mut clash = global.clash.lock();
  103. clash.patch_config(patch_cloned)?;
  104. clash.info.port.is_some()
  105. };
  106. // todo: port check
  107. if (mixed_port.is_some() && valid_port) || external.is_some() || secret.is_some() {
  108. let mut service = self.service.lock();
  109. service.restart()?;
  110. drop(service);
  111. self.activate()?;
  112. let mut sysopt = self.sysopt.lock();
  113. sysopt.init_sysproxy()?;
  114. }
  115. if clash_mode.is_some() {
  116. let handle = self.handle.lock();
  117. handle.update_systray_part()?;
  118. }
  119. Ok(())
  120. }
  121. /// Patch Verge
  122. pub fn patch_verge(&self, patch: Verge) -> Result<()> {
  123. // save the patch
  124. let global = Data::global();
  125. let mut verge = global.verge.lock();
  126. verge.patch_config(patch.clone())?;
  127. drop(verge);
  128. let tun_mode = patch.enable_tun_mode;
  129. let auto_launch = patch.enable_auto_launch;
  130. let system_proxy = patch.enable_system_proxy;
  131. let proxy_bypass = patch.system_proxy_bypass;
  132. let proxy_guard = patch.enable_proxy_guard;
  133. let language = patch.language;
  134. #[cfg(target_os = "windows")]
  135. {
  136. let service_mode = patch.enable_service_mode;
  137. // 重启服务
  138. if service_mode.is_some() {
  139. let mut service = self.service.lock();
  140. service.restart()?;
  141. drop(service);
  142. }
  143. if tun_mode.is_some() && *tun_mode.as_ref().unwrap_or(&false) {
  144. let wintun_dll = crate::utils::dirs::app_home_dir().join("wintun.dll");
  145. if !wintun_dll.exists() {
  146. bail!("failed to enable TUN for missing `wintun.dll`");
  147. }
  148. }
  149. if service_mode.is_some() || tun_mode.is_some() {
  150. self.activate()?;
  151. }
  152. }
  153. #[cfg(not(target_os = "windows"))]
  154. if tun_mode.is_some() {
  155. self.activate()?;
  156. }
  157. let mut sysopt = self.sysopt.lock();
  158. if auto_launch.is_some() {
  159. sysopt.update_launch()?;
  160. }
  161. if system_proxy.is_some() || proxy_bypass.is_some() {
  162. sysopt.update_sysproxy()?;
  163. sysopt.guard_proxy();
  164. }
  165. if proxy_guard.unwrap_or(false) {
  166. sysopt.guard_proxy();
  167. }
  168. // 更新tray
  169. if language.is_some() {
  170. let handle = self.handle.lock();
  171. handle.update_systray()?;
  172. } else if system_proxy.is_some() || tun_mode.is_some() {
  173. let handle = self.handle.lock();
  174. handle.update_systray_part()?;
  175. }
  176. if patch.hotkeys.is_some() {
  177. let mut hotkey = self.hotkey.lock();
  178. hotkey.update(patch.hotkeys.unwrap())?;
  179. }
  180. Ok(())
  181. }
  182. // update rule/global/direct/script mode
  183. pub fn update_mode(&self, mode: &str) -> Result<()> {
  184. // save config to file
  185. let info = {
  186. let global = Data::global();
  187. let mut clash = global.clash.lock();
  188. clash.config.insert(Value::from("mode"), Value::from(mode));
  189. clash.save_config()?;
  190. clash.info.clone()
  191. };
  192. let mut mapping = Mapping::new();
  193. mapping.insert(Value::from("mode"), Value::from(mode));
  194. let handle = self.handle.clone();
  195. tauri::async_runtime::spawn(async move {
  196. log_if_err!(Service::patch_config(info, mapping.to_owned()).await);
  197. // update tray
  198. let handle = handle.lock();
  199. handle.refresh_clash();
  200. log_if_err!(handle.update_systray_part());
  201. });
  202. Ok(())
  203. }
  204. /// activate the profile
  205. /// auto activate enhanced profile
  206. /// 触发clash配置更新
  207. pub fn activate(&self) -> Result<()> {
  208. let global = Data::global();
  209. let verge = global.verge.lock();
  210. let clash = global.clash.lock();
  211. let profiles = global.profiles.lock();
  212. let tun_mode = verge.enable_tun_mode.clone().unwrap_or(false);
  213. let profile_activate = profiles.gen_activate()?;
  214. let clash_config = clash.config.clone();
  215. let clash_info = clash.info.clone();
  216. drop(clash);
  217. drop(verge);
  218. drop(profiles);
  219. let (config, exists_keys, logs) = enhance_config(
  220. clash_config,
  221. profile_activate.current,
  222. profile_activate.chain,
  223. profile_activate.valid,
  224. tun_mode,
  225. );
  226. let mut runtime = self.runtime.lock();
  227. *runtime = RuntimeResult {
  228. config: Some(config.clone()),
  229. config_yaml: Some(serde_yaml::to_string(&config).unwrap_or("".into())),
  230. exists_keys,
  231. chain_logs: logs,
  232. };
  233. drop(runtime);
  234. let mut service = self.service.lock();
  235. service.check_start()?;
  236. drop(service);
  237. let handle = self.handle.clone();
  238. tauri::async_runtime::spawn(async move {
  239. match Service::set_config(clash_info, config).await {
  240. Ok(_) => {
  241. let handle = handle.lock();
  242. handle.refresh_clash();
  243. handle.notice_message("set_config::ok".into(), "ok".into());
  244. }
  245. Err(err) => {
  246. let handle = handle.lock();
  247. handle.notice_message("set_config::error".into(), format!("{err}"));
  248. log::error!(target: "app", "last {err}")
  249. }
  250. }
  251. });
  252. Ok(())
  253. }
  254. /// Static function
  255. /// update profile item
  256. pub async fn update_profile_item(&self, uid: String, option: Option<PrfOption>) -> Result<()> {
  257. let global = Data::global();
  258. let (url, opt) = {
  259. let profiles = global.profiles.lock();
  260. let item = profiles.get_item(&uid)?;
  261. if let Some(typ) = item.itype.as_ref() {
  262. // maybe only valid for `local` profile
  263. if *typ != "remote" {
  264. // reactivate the config
  265. if Some(uid) == profiles.get_current() {
  266. drop(profiles);
  267. self.activate()?;
  268. }
  269. return Ok(());
  270. }
  271. }
  272. if item.url.is_none() {
  273. bail!("failed to get the profile item url");
  274. }
  275. (item.url.clone().unwrap(), item.option.clone())
  276. };
  277. let merged_opt = PrfOption::merge(opt, option);
  278. let item = PrfItem::from_url(&url, None, None, merged_opt).await?;
  279. let mut profiles = global.profiles.lock();
  280. profiles.update_item(uid.clone(), item)?;
  281. // reactivate the profile
  282. if Some(uid) == profiles.get_current() {
  283. drop(profiles);
  284. self.activate()?;
  285. }
  286. Ok(())
  287. }
  288. }