mod.rs 10 KB

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