cmds.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. use crate::{
  2. config::*,
  3. core::*,
  4. feat,
  5. utils::{dirs, help, resolve},
  6. };
  7. use crate::{ret_err, wrap_err};
  8. use anyhow::{Context, Result};
  9. use serde_yaml::Mapping;
  10. use std::collections::{HashMap, VecDeque};
  11. use sysproxy::{Autoproxy, Sysproxy};
  12. use tauri::{api, Manager};
  13. type CmdResult<T = ()> = Result<T, String>;
  14. #[tauri::command]
  15. pub fn get_profiles() -> CmdResult<IProfiles> {
  16. Ok(Config::profiles().data().clone())
  17. }
  18. #[tauri::command]
  19. pub async fn enhance_profiles() -> CmdResult {
  20. wrap_err!(CoreManager::global().update_config().await)?;
  21. handle::Handle::refresh_clash();
  22. Ok(())
  23. }
  24. #[tauri::command]
  25. pub async fn import_profile(url: String, option: Option<PrfOption>) -> CmdResult {
  26. let item = wrap_err!(PrfItem::from_url(&url, None, None, option).await)?;
  27. wrap_err!(Config::profiles().data().append_item(item))
  28. }
  29. #[tauri::command]
  30. pub async fn reorder_profile(active_id: String, over_id: String) -> CmdResult {
  31. wrap_err!(Config::profiles().data().reorder(active_id, over_id))
  32. }
  33. #[tauri::command]
  34. pub async fn create_profile(item: PrfItem, file_data: Option<String>) -> CmdResult {
  35. let item = wrap_err!(PrfItem::from(item, file_data).await)?;
  36. wrap_err!(Config::profiles().data().append_item(item))
  37. }
  38. #[tauri::command]
  39. pub async fn update_profile(index: String, option: Option<PrfOption>) -> CmdResult {
  40. wrap_err!(feat::update_profile(index, option).await)
  41. }
  42. #[tauri::command]
  43. pub async fn delete_profile(index: String) -> CmdResult {
  44. let should_update = wrap_err!({ Config::profiles().data().delete_item(index) })?;
  45. if should_update {
  46. wrap_err!(CoreManager::global().update_config().await)?;
  47. handle::Handle::refresh_clash();
  48. }
  49. Ok(())
  50. }
  51. /// 修改profiles的
  52. #[tauri::command]
  53. pub async fn patch_profiles_config(profiles: IProfiles) -> CmdResult {
  54. wrap_err!({ Config::profiles().draft().patch_config(profiles) })?;
  55. match CoreManager::global().update_config().await {
  56. Ok(_) => {
  57. handle::Handle::refresh_clash();
  58. let _ = handle::Handle::update_systray_part();
  59. Config::profiles().apply();
  60. wrap_err!(Config::profiles().data().save_file())?;
  61. Ok(())
  62. }
  63. Err(err) => {
  64. Config::profiles().discard();
  65. log::error!(target: "app", "{err}");
  66. Err(format!("{err}"))
  67. }
  68. }
  69. }
  70. /// 修改某个profile item的
  71. #[tauri::command]
  72. pub fn patch_profile(index: String, profile: PrfItem) -> CmdResult {
  73. wrap_err!(Config::profiles().data().patch_item(index, profile))?;
  74. wrap_err!(timer::Timer::global().refresh())
  75. }
  76. #[tauri::command]
  77. pub fn view_profile(app_handle: tauri::AppHandle, index: String) -> CmdResult {
  78. let file = {
  79. wrap_err!(Config::profiles().latest().get_item(&index))?
  80. .file
  81. .clone()
  82. .ok_or("the file field is null")
  83. }?;
  84. let path = wrap_err!(dirs::app_profiles_dir())?.join(file);
  85. if !path.exists() {
  86. ret_err!("the file not found");
  87. }
  88. wrap_err!(help::open_file(app_handle, path))
  89. }
  90. #[tauri::command]
  91. pub fn read_profile_file(index: String) -> CmdResult<String> {
  92. let profiles = Config::profiles();
  93. let profiles = profiles.latest();
  94. let item = wrap_err!(profiles.get_item(&index))?;
  95. let data = wrap_err!(item.read_file())?;
  96. Ok(data)
  97. }
  98. #[tauri::command]
  99. pub fn save_profile_file(index: String, file_data: Option<String>) -> CmdResult {
  100. if file_data.is_none() {
  101. return Ok(());
  102. }
  103. let profiles = Config::profiles();
  104. let profiles = profiles.latest();
  105. let item = wrap_err!(profiles.get_item(&index))?;
  106. wrap_err!(item.save_file(file_data.unwrap()))
  107. }
  108. #[tauri::command]
  109. pub fn get_clash_info() -> CmdResult<ClashInfo> {
  110. Ok(Config::clash().latest().get_client_info())
  111. }
  112. #[tauri::command]
  113. pub fn get_runtime_config() -> CmdResult<Option<Mapping>> {
  114. Ok(Config::runtime().latest().config.clone())
  115. }
  116. #[tauri::command]
  117. pub fn get_runtime_yaml() -> CmdResult<String> {
  118. let runtime = Config::runtime();
  119. let runtime = runtime.latest();
  120. let config = runtime.config.as_ref();
  121. wrap_err!(config
  122. .ok_or(anyhow::anyhow!("failed to parse config to yaml file"))
  123. .and_then(
  124. |config| serde_yaml::to_string(config).context("failed to convert config to yaml")
  125. ))
  126. }
  127. #[tauri::command]
  128. pub fn get_runtime_exists() -> CmdResult<Vec<String>> {
  129. Ok(Config::runtime().latest().exists_keys.clone())
  130. }
  131. #[tauri::command]
  132. pub fn get_runtime_logs() -> CmdResult<HashMap<String, Vec<(String, String)>>> {
  133. Ok(Config::runtime().latest().chain_logs.clone())
  134. }
  135. #[tauri::command]
  136. pub async fn patch_clash_config(payload: Mapping) -> CmdResult {
  137. wrap_err!(feat::patch_clash(payload).await)
  138. }
  139. #[tauri::command]
  140. pub fn get_verge_config() -> CmdResult<IVerge> {
  141. Ok(Config::verge().data().clone())
  142. }
  143. #[tauri::command]
  144. pub async fn patch_verge_config(payload: IVerge) -> CmdResult {
  145. wrap_err!(feat::patch_verge(payload).await)
  146. }
  147. #[tauri::command]
  148. pub async fn change_clash_core(clash_core: Option<String>) -> CmdResult {
  149. wrap_err!(CoreManager::global().change_core(clash_core).await)
  150. }
  151. /// restart the sidecar
  152. #[tauri::command]
  153. pub async fn restart_sidecar() -> CmdResult {
  154. wrap_err!(CoreManager::global().run_core().await)
  155. }
  156. #[tauri::command]
  157. pub fn grant_permission(_core: String) -> CmdResult {
  158. #[cfg(any(target_os = "macos", target_os = "linux"))]
  159. return wrap_err!(manager::grant_permission(_core));
  160. #[cfg(not(any(target_os = "macos", target_os = "linux")))]
  161. return Err("Unsupported target".into());
  162. }
  163. /// get the system proxy
  164. #[tauri::command]
  165. pub fn get_sys_proxy() -> CmdResult<Mapping> {
  166. let current = wrap_err!(Sysproxy::get_system_proxy())?;
  167. let mut map = Mapping::new();
  168. map.insert("enable".into(), current.enable.into());
  169. map.insert(
  170. "server".into(),
  171. format!("{}:{}", current.host, current.port).into(),
  172. );
  173. map.insert("bypass".into(), current.bypass.into());
  174. Ok(map)
  175. }
  176. /// get the system proxy
  177. #[tauri::command]
  178. pub fn get_auto_proxy() -> CmdResult<Mapping> {
  179. let current = wrap_err!(Autoproxy::get_auto_proxy())?;
  180. let mut map = Mapping::new();
  181. map.insert("enable".into(), current.enable.into());
  182. map.insert("url".into(), current.url.into());
  183. Ok(map)
  184. }
  185. #[tauri::command]
  186. pub fn get_clash_logs() -> CmdResult<VecDeque<String>> {
  187. Ok(logger::Logger::global().get_log())
  188. }
  189. #[tauri::command]
  190. pub fn open_app_dir() -> CmdResult<()> {
  191. let app_dir = wrap_err!(dirs::app_home_dir())?;
  192. wrap_err!(open::that(app_dir))
  193. }
  194. #[tauri::command]
  195. pub fn open_core_dir() -> CmdResult<()> {
  196. let core_dir = wrap_err!(tauri::utils::platform::current_exe())?;
  197. let core_dir = core_dir.parent().ok_or("failed to get core dir")?;
  198. wrap_err!(open::that(core_dir))
  199. }
  200. #[tauri::command]
  201. pub fn open_logs_dir() -> CmdResult<()> {
  202. let log_dir = wrap_err!(dirs::app_logs_dir())?;
  203. wrap_err!(open::that(log_dir))
  204. }
  205. #[tauri::command]
  206. pub fn open_web_url(url: String) -> CmdResult<()> {
  207. wrap_err!(open::that(url))
  208. }
  209. #[cfg(windows)]
  210. pub mod uwp {
  211. use super::*;
  212. use crate::core::win_uwp;
  213. #[tauri::command]
  214. pub async fn invoke_uwp_tool() -> CmdResult {
  215. wrap_err!(win_uwp::invoke_uwptools().await)
  216. }
  217. }
  218. #[tauri::command]
  219. pub async fn clash_api_get_proxy_delay(
  220. name: String,
  221. url: Option<String>,
  222. timeout: i32,
  223. ) -> CmdResult<clash_api::DelayRes> {
  224. match clash_api::get_proxy_delay(name, url, timeout).await {
  225. Ok(res) => Ok(res),
  226. Err(err) => Err(err.to_string()),
  227. }
  228. }
  229. #[tauri::command]
  230. pub fn get_portable_flag() -> CmdResult<bool> {
  231. Ok(*dirs::PORTABLE_FLAG.get().unwrap_or(&false))
  232. }
  233. #[tauri::command]
  234. pub async fn test_delay(url: String) -> CmdResult<u32> {
  235. Ok(feat::test_delay(url).await.unwrap_or(10000u32))
  236. }
  237. #[tauri::command]
  238. pub fn get_app_dir() -> CmdResult<String> {
  239. let app_home_dir = wrap_err!(dirs::app_home_dir())?
  240. .to_string_lossy()
  241. .to_string();
  242. Ok(app_home_dir)
  243. }
  244. #[tauri::command]
  245. pub async fn download_icon_cache(url: String, name: String) -> CmdResult<String> {
  246. let icon_cache_dir = wrap_err!(dirs::app_home_dir())?.join("icons").join("cache");
  247. let icon_path = icon_cache_dir.join(name);
  248. if !icon_cache_dir.exists() {
  249. let _ = std::fs::create_dir_all(&icon_cache_dir);
  250. }
  251. if !icon_path.exists() {
  252. let response = wrap_err!(reqwest::get(url).await)?;
  253. let mut file = wrap_err!(std::fs::File::create(&icon_path))?;
  254. let content = wrap_err!(response.bytes().await)?;
  255. wrap_err!(std::io::copy(&mut content.as_ref(), &mut file))?;
  256. }
  257. Ok(icon_path.to_string_lossy().to_string())
  258. }
  259. #[tauri::command]
  260. pub fn copy_icon_file(path: String, name: String) -> CmdResult<String> {
  261. let file_path = std::path::Path::new(&path);
  262. let icon_dir = wrap_err!(dirs::app_home_dir())?.join("icons");
  263. if !icon_dir.exists() {
  264. let _ = std::fs::create_dir_all(&icon_dir);
  265. }
  266. let ext = match file_path.extension() {
  267. Some(e) => e.to_string_lossy().to_string(),
  268. None => "ico".to_string(),
  269. };
  270. let png_dest_path = icon_dir.join(format!("{name}.png"));
  271. let ico_dest_path = icon_dir.join(format!("{name}.ico"));
  272. let dest_path = icon_dir.join(format!("{name}.{ext}"));
  273. if file_path.exists() {
  274. std::fs::remove_file(png_dest_path).unwrap_or_default();
  275. std::fs::remove_file(ico_dest_path).unwrap_or_default();
  276. match std::fs::copy(file_path, &dest_path) {
  277. Ok(_) => Ok(dest_path.to_string_lossy().to_string()),
  278. Err(err) => Err(err.to_string()),
  279. }
  280. } else {
  281. Err("file not found".to_string())
  282. }
  283. }
  284. #[tauri::command]
  285. pub fn open_devtools(app_handle: tauri::AppHandle) {
  286. if let Some(window) = app_handle.get_window("main") {
  287. if !window.is_devtools_open() {
  288. window.open_devtools();
  289. } else {
  290. window.close_devtools();
  291. }
  292. }
  293. }
  294. #[tauri::command]
  295. pub fn exit_app(app_handle: tauri::AppHandle) {
  296. let _ = resolve::save_window_size_position(&app_handle, true);
  297. resolve::resolve_reset();
  298. api::process::kill_children();
  299. app_handle.exit(0);
  300. std::process::exit(0);
  301. }
  302. pub mod service {
  303. use super::*;
  304. use crate::core::service;
  305. #[tauri::command]
  306. pub async fn check_service() -> CmdResult<service::JsonResponse> {
  307. wrap_err!(service::check_service().await)
  308. }
  309. #[tauri::command]
  310. pub async fn install_service() -> CmdResult {
  311. wrap_err!(service::install_service().await)
  312. }
  313. #[tauri::command]
  314. pub async fn uninstall_service() -> CmdResult {
  315. wrap_err!(service::uninstall_service().await)
  316. }
  317. }
  318. #[cfg(not(windows))]
  319. pub mod uwp {
  320. use super::*;
  321. #[tauri::command]
  322. pub async fn invoke_uwp_tool() -> CmdResult {
  323. Ok(())
  324. }
  325. }