Browse Source

feat: adjust clash info parsing logs

GyDi 2 years ago
parent
commit
7f321c89cb
4 changed files with 56 additions and 182 deletions
  1. 41 174
      src-tauri/src/core/clash.rs
  2. 8 5
      src-tauri/src/core/mod.rs
  3. 3 2
      src-tauri/src/core/service.rs
  4. 4 1
      src-tauri/src/core/sysopt.rs

+ 41 - 174
src-tauri/src/core/clash.rs

@@ -22,18 +22,26 @@ impl ClashInfo {
   /// parse the clash's config.yaml
   /// get some information
   pub fn from(config: &Mapping) -> ClashInfo {
-    let key_port_1 = Value::from("port");
-    let key_port_2 = Value::from("mixed-port");
+    let key_port_1 = Value::from("mixed-port");
+    let key_port_2 = Value::from("port");
     let key_server = Value::from("external-controller");
     let key_secret = Value::from("secret");
 
+    let mut status: u32 = 0;
+
     let port = match config.get(&key_port_1) {
       Some(value) => match value {
         Value::String(val_str) => Some(val_str.clone()),
         Value::Number(val_num) => Some(val_num.to_string()),
-        _ => None,
+        _ => {
+          status |= 0b1;
+          None
+        }
       },
-      _ => None,
+      _ => {
+        status |= 0b10;
+        None
+      }
     };
     let port = match port {
       Some(_) => port,
@@ -41,25 +49,38 @@ impl ClashInfo {
         Some(value) => match value {
           Value::String(val_str) => Some(val_str.clone()),
           Value::Number(val_num) => Some(val_num.to_string()),
-          _ => None,
+          _ => {
+            status |= 0b100;
+            None
+          }
         },
-        _ => None,
+        _ => {
+          status |= 0b1000;
+          None
+        }
       },
     };
 
     // `external-controller` could be
     // "127.0.0.1:9090" or ":9090"
     let server = match config.get(&key_server) {
-      Some(value) => {
-        let val_str = value.as_str().unwrap_or("");
-
-        if val_str.starts_with(":") {
-          Some(format!("127.0.0.1{val_str}"))
-        } else {
-          Some(val_str.into())
+      Some(value) => match value.as_str() {
+        Some(val_str) => {
+          if val_str.starts_with(":") {
+            Some(format!("127.0.0.1{val_str}"))
+          } else {
+            Some(val_str.into())
+          }
+        }
+        None => {
+          status |= 0b10000;
+          None
         }
+      },
+      None => {
+        status |= 0b100000;
+        None
       }
-      _ => None,
     };
 
     let secret = match config.get(&key_secret) {
@@ -73,7 +94,7 @@ impl ClashInfo {
     };
 
     ClashInfo {
-      status: "init".into(),
+      status: format!("{status}"),
       port,
       server,
       secret,
@@ -113,29 +134,16 @@ impl Clash {
 
   /// patch update the clash config
   /// if the port is changed then return true
-  pub fn patch_config(&mut self, patch: Mapping) -> Result<(bool, bool)> {
+  pub fn patch_config(&mut self, patch: Mapping) -> Result<()> {
     let port_key = Value::from("mixed-port");
     let server_key = Value::from("external-controller");
     let secret_key = Value::from("secret");
-    let mode_key = Value::from("mode");
 
-    let mut change_port = false;
-    let mut change_info = false;
-    let mut change_mode = false;
+    let change_info = patch.contains_key(&port_key)
+      || patch.contains_key(&server_key)
+      || patch.contains_key(&secret_key);
 
     for (key, value) in patch.into_iter() {
-      if key == port_key {
-        change_port = true;
-      }
-
-      if key == mode_key {
-        change_mode = true;
-      }
-
-      if key == port_key || key == server_key || key == secret_key || key == mode_key {
-        change_info = true;
-      }
-
       self.config.insert(key, value);
     }
 
@@ -143,149 +151,8 @@ impl Clash {
       self.info = ClashInfo::from(&self.config);
     }
 
-    self.save_config()?;
-
-    Ok((change_port, change_mode))
+    self.save_config()
   }
-
-  // /// revise the `tun` and `dns` config
-  // pub fn _tun_mode(mut config: Mapping, enable: bool) -> Mapping {
-  //   macro_rules! revise {
-  //     ($map: expr, $key: expr, $val: expr) => {
-  //       let ret_key = Value::String($key.into());
-  //       $map.insert(ret_key, Value::from($val));
-  //     };
-  //   }
-
-  //   // if key not exists then append value
-  //   macro_rules! append {
-  //     ($map: expr, $key: expr, $val: expr) => {
-  //       let ret_key = Value::String($key.into());
-  //       if !$map.contains_key(&ret_key) {
-  //         $map.insert(ret_key, Value::from($val));
-  //       }
-  //     };
-  //   }
-
-  //   // tun config
-  //   let tun_val = config.get(&Value::from("tun"));
-  //   let mut new_tun = Mapping::new();
-
-  //   if tun_val.is_some() && tun_val.as_ref().unwrap().is_mapping() {
-  //     new_tun = tun_val.as_ref().unwrap().as_mapping().unwrap().clone();
-  //   }
-
-  //   revise!(new_tun, "enable", enable);
-
-  //   if enable {
-  //     append!(new_tun, "stack", "gvisor");
-  //     append!(new_tun, "dns-hijack", vec!["198.18.0.2:53"]);
-  //     append!(new_tun, "auto-route", true);
-  //     append!(new_tun, "auto-detect-interface", true);
-  //   }
-
-  //   revise!(config, "tun", new_tun);
-
-  //   if enable {
-  //     // dns config
-  //     let dns_val = config.get(&Value::from("dns"));
-  //     let mut new_dns = Mapping::new();
-
-  //     if dns_val.is_some() && dns_val.as_ref().unwrap().is_mapping() {
-  //       new_dns = dns_val.as_ref().unwrap().as_mapping().unwrap().clone();
-  //     }
-  //     revise!(new_dns, "enable", enable);
-
-  //     // 借鉴cfw的默认配置
-  //     append!(new_dns, "enhanced-mode", "fake-ip");
-  //     append!(
-  //       new_dns,
-  //       "nameserver",
-  //       vec!["114.114.114.114", "223.5.5.5", "8.8.8.8"]
-  //     );
-  //     append!(new_dns, "fallback", vec![] as Vec<&str>);
-
-  //     #[cfg(target_os = "windows")]
-  //     append!(
-  //       new_dns,
-  //       "fake-ip-filter",
-  //       vec![
-  //         "dns.msftncsi.com",
-  //         "www.msftncsi.com",
-  //         "www.msftconnecttest.com"
-  //       ]
-  //     );
-
-  //     revise!(config, "dns", new_dns);
-  //   }
-
-  //   config
-  // }
-
-  // /// only 5 default fields available (clash config fields)
-  // /// convert to lowercase
-  // pub fn strict_filter(config: Mapping) -> Mapping {
-  //   // Only the following fields are allowed:
-  //   // proxies/proxy-providers/proxy-groups/rule-providers/rules
-  //   let valid_keys = vec![
-  //     "proxies",
-  //     "proxy-providers",
-  //     "proxy-groups",
-  //     "rules",
-  //     "rule-providers",
-  //   ];
-
-  //   let mut new_config = Mapping::new();
-
-  //   for (key, value) in config.into_iter() {
-  //     key.as_str().map(|key_str| {
-  //       // change to lowercase
-  //       let mut key_str = String::from(key_str);
-  //       key_str.make_ascii_lowercase();
-
-  //       // filter
-  //       if valid_keys.contains(&&*key_str) {
-  //         new_config.insert(Value::String(key_str), value);
-  //       }
-  //     });
-  //   }
-
-  //   new_config
-  // }
-
-  // /// more clash config fields available
-  // /// convert to lowercase
-  // pub fn loose_filter(config: Mapping) -> Mapping {
-  //   // all of these can not be revised by script or merge
-  //   // http/https/socks port should be under control
-  //   let not_allow = vec![
-  //     "port",
-  //     "socks-port",
-  //     "mixed-port",
-  //     "allow-lan",
-  //     "mode",
-  //     "external-controller",
-  //     "secret",
-  //     "log-level",
-  //   ];
-
-  //   let mut new_config = Mapping::new();
-
-  //   for (key, value) in config.into_iter() {
-  //     key.as_str().map(|key_str| {
-  //       // change to lowercase
-  //       let mut key_str = String::from(key_str);
-  //       key_str.make_ascii_lowercase();
-
-  //       // filter
-  //       if !not_allow.contains(&&*key_str) {
-  //         new_config.insert(Value::String(key_str), value);
-  //       }
-  //     });
-  //   }
-
-  //   new_config
-  // }
 }
 
 impl Default for Clash {

+ 8 - 5
src-tauri/src/core/mod.rs

@@ -135,14 +135,17 @@ impl Core {
   /// Patch Clash
   /// handle the clash config changed
   pub fn patch_clash(&self, patch: Mapping, app_handle: &AppHandle) -> Result<()> {
-    let ((changed_port, changed_mode), port) = {
+    let has_port = patch.contains_key(&Value::from("mixed-port"));
+    let has_mode = patch.contains_key(&Value::from("mode"));
+
+    let port = {
       let mut clash = self.clash.lock();
-      (clash.patch_config(patch)?, clash.info.port.clone())
+      clash.patch_config(patch)?;
+      clash.info.port.clone()
     };
 
     // todo: port check
-
-    if changed_port {
+    if has_port && port.is_some() {
       let mut service = self.service.lock();
       service.restart()?;
       drop(service);
@@ -154,7 +157,7 @@ impl Core {
       sysopt.init_sysproxy(port, &verge);
     }
 
-    if changed_mode {
+    if has_mode {
       self.update_systray_clash(app_handle)?;
     }
 

+ 3 - 2
src-tauri/src/core/service.rs

@@ -196,10 +196,11 @@ impl Service {
   /// get clash client url and headers from clash info
   fn clash_client_info(info: ClashInfo) -> Result<(String, HeaderMap)> {
     if info.server.is_none() {
+      let status = &info.status;
       if info.port.is_none() {
-        bail!("failed to parse config.yaml file");
+        bail!("failed to parse config.yaml file with status {status}");
       } else {
-        bail!("failed to parse the server");
+        bail!("failed to parse the server with status {status}");
       }
     }
 

+ 4 - 1
src-tauri/src/core/sysopt.rs

@@ -193,7 +193,10 @@ impl Sysopt {
 
             log_if_err!(sysproxy.set_sys());
           }
-          None => log::error!(target: "app", "failed to parse clash port"),
+          None => {
+            let status = &clash.info.status;
+            log::error!(target: "app", "failed to parse clash port with status {status}")
+          }
         }
       }