clash.rs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. extern crate log;
  2. use crate::{
  3. events::emit::{clash_start, ClashInfoPayload},
  4. utils::{
  5. app_home_dir,
  6. config::{read_clash_controller, read_profiles},
  7. },
  8. };
  9. use reqwest::header::HeaderMap;
  10. use std::{collections::HashMap, env::temp_dir, fs};
  11. use tauri::{
  12. api::process::{Command, CommandEvent},
  13. AppHandle,
  14. };
  15. /// Run the clash bin
  16. pub fn run_clash_bin(app_handle: &AppHandle) -> ClashInfoPayload {
  17. let app_dir = app_home_dir();
  18. let app_dir = app_dir.as_os_str().to_str().unwrap();
  19. let mut payload = ClashInfoPayload {
  20. status: "success".to_string(),
  21. controller: None,
  22. message: None,
  23. };
  24. let result = match Command::new_sidecar("clash") {
  25. Ok(cmd) => match cmd.args(["-d", app_dir]).spawn() {
  26. Ok(res) => Ok(res),
  27. Err(err) => Err(err.to_string()),
  28. },
  29. Err(err) => Err(err.to_string()),
  30. };
  31. match result {
  32. Ok((mut rx, _)) => {
  33. log::info!("Successfully execute clash sidecar");
  34. payload.controller = Some(read_clash_controller());
  35. tauri::async_runtime::spawn(async move {
  36. while let Some(event) = rx.recv().await {
  37. match event {
  38. CommandEvent::Stdout(line) => log::info!("{}", line),
  39. CommandEvent::Stderr(err) => log::error!("{}", err),
  40. _ => {}
  41. }
  42. }
  43. });
  44. }
  45. Err(err) => {
  46. log::error!("Failed to execute clash sidecar for \"{}\"", err);
  47. payload.status = "error".to_string();
  48. payload.message = Some(err.to_string());
  49. }
  50. };
  51. clash_start(app_handle, &payload);
  52. payload
  53. }
  54. /// Update the clash profile firstly
  55. pub async fn put_clash_profile(payload: &ClashInfoPayload) -> Result<(), String> {
  56. let profile = {
  57. let profiles = read_profiles();
  58. let current = profiles.current.unwrap_or(0) as usize;
  59. match profiles.items {
  60. Some(items) => {
  61. if items.len() == 0 {
  62. return Err("can not read profiles".to_string());
  63. }
  64. let idx = if current < items.len() { current } else { 0 };
  65. items[idx].clone()
  66. }
  67. None => {
  68. return Err("can not read profiles".to_string());
  69. }
  70. }
  71. };
  72. // generate temp profile
  73. let file_name = match profile.file {
  74. Some(file_name) => file_name.clone(),
  75. None => {
  76. return Err("the profile item should have `file` field".to_string());
  77. }
  78. };
  79. let file_path = app_home_dir().join("profiles").join(file_name);
  80. let temp_path = temp_dir().join("clash-verge-runtime.yaml");
  81. if !file_path.exists() {
  82. return Err(format!("the profile `{:?}` not exists", file_path));
  83. }
  84. fs::copy(file_path, temp_path.clone()).unwrap();
  85. let ctrl = payload.controller.clone().unwrap();
  86. let server = format!("http://{}/configs", ctrl.server.unwrap());
  87. let mut headers = HeaderMap::new();
  88. headers.insert("Content-Type", "application/json".parse().unwrap());
  89. if let Some(secret) = ctrl.secret {
  90. headers.insert(
  91. "Authorization",
  92. format!("Bearer {}", secret).parse().unwrap(),
  93. );
  94. }
  95. let mut data = HashMap::new();
  96. data.insert("path", temp_path.as_os_str().to_str().unwrap());
  97. let client = reqwest::Client::new();
  98. match client.put(server).headers(headers).json(&data).send().await {
  99. Ok(_) => Ok(()),
  100. Err(err) => Err(format!("request failed with status `{}`", err.to_string())),
  101. }
  102. }