feat: refactor system proxy config

This commit is contained in:
GyDi 2021-12-12 18:02:41 +08:00
parent 0f99addca7
commit 1e176c4316

View File

@ -1,46 +1,71 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::io; use std::io;
#[cfg(target_os = "windows")]
use winreg::enums::*;
#[cfg(target_os = "windows")]
use winreg::RegKey;
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]
pub struct ProxyConfig { pub struct SysProxyConfig {
enable: u32, enable: bool,
server: String, server: String,
bypass: String, bypass: String,
} }
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
mod win {
use super::*;
use winreg::enums::*;
use winreg::RegKey;
/// Get the windows system proxy config /// Get the windows system proxy config
pub fn get_proxy_config() -> io::Result<ProxyConfig> { pub fn get_proxy_config() -> io::Result<SysProxyConfig> {
let hkcu = RegKey::predef(HKEY_CURRENT_USER); let hkcu = RegKey::predef(HKEY_CURRENT_USER);
let cur_var = hkcu.open_subkey_with_flags( let cur_var = hkcu.open_subkey_with_flags(
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",
KEY_READ, KEY_READ,
)?; )?;
Ok(ProxyConfig { Ok(SysProxyConfig {
enable: cur_var.get_value("ProxyEnable")?, enable: cur_var.get_value::<u32, _>("ProxyEnable")? == 1u32,
server: cur_var.get_value("ProxyServer")?, server: cur_var.get_value("ProxyServer")?,
bypass: cur_var.get_value("ProxyOverride")?, bypass: cur_var.get_value("ProxyOverride")?,
}) })
} }
#[cfg(target_os = "windows")]
/// Set the windows system proxy config /// Set the windows system proxy config
pub fn set_proxy_config(config: &ProxyConfig) -> io::Result<()> { pub fn set_proxy_config(config: &SysProxyConfig) -> io::Result<()> {
let hkcu = RegKey::predef(HKEY_CURRENT_USER); let hkcu = RegKey::predef(HKEY_CURRENT_USER);
let cur_var = hkcu.open_subkey_with_flags( let cur_var = hkcu.open_subkey_with_flags(
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",
KEY_SET_VALUE, KEY_SET_VALUE,
)?; )?;
cur_var.set_value("ProxyEnable", &config.enable)?; let enable: u32 = if config.enable { 1u32 } else { 0u32 };
cur_var.set_value("ProxyEnable", &enable)?;
cur_var.set_value("ProxyServer", &config.server)?; cur_var.set_value("ProxyServer", &config.server)?;
cur_var.set_value("ProxyOverride", &config.bypass)?; cur_var.set_value("ProxyOverride", &config.bypass)?;
Ok(()) Ok(())
} }
}
#[cfg(target_os = "macos")]
mod macos {
use super::*;
pub fn get_proxy_config() -> io::Result<SysProxyConfig> {
Ok(SysProxyConfig {
enable: false,
server: "server".into(),
bypass: "bypass".into(),
})
}
pub fn set_proxy_config(config: &SysProxyConfig) -> io::Result<()> {
Ok(())
}
}
#[cfg(target_os = "windows")]
pub use win::*;
#[cfg(target_os = "macos")]
pub use macos::*;