Skip to content

Commit

Permalink
refactor: done
Browse files Browse the repository at this point in the history
  • Loading branch information
zzzgydi committed Nov 18, 2022
1 parent 34daffb commit 2667ed1
Show file tree
Hide file tree
Showing 24 changed files with 332 additions and 330 deletions.
93 changes: 28 additions & 65 deletions src-tauri/src/cmds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use crate::{
utils::{dirs, help},
};
use crate::{ret_err, wrap_err};
use anyhow::Result;
use anyhow::{Context, Result};
use serde_yaml::Mapping;
use std::collections::{HashMap, VecDeque};
use sysproxy::Sysproxy;
Expand All @@ -19,7 +19,9 @@ pub fn get_profiles() -> CmdResult<IProfiles> {

#[tauri::command]
pub async fn enhance_profiles() -> CmdResult {
wrap_err!(feat::handle_activate().await)
wrap_err!(CoreManager::global().update_config().await)?;
handle::Handle::refresh_clash();
Ok(())
}

#[deprecated]
Expand All @@ -41,48 +43,24 @@ pub async fn update_profile(index: String, option: Option<PrfOption>) -> CmdResu
}

#[tauri::command]
pub async fn select_profile(index: String) -> CmdResult {
wrap_err!({ Config::profiles().draft().put_current(index) })?;

match feat::handle_activate().await {
Ok(_) => {
Config::profiles().apply();
wrap_err!(Config::profiles().data().save_file())?;
Ok(())
}
Err(err) => {
Config::profiles().discard();
log::error!(target: "app", "{err}");
Err(format!("{err}"))
}
pub async fn delete_profile(index: String) -> CmdResult {
let should_update = wrap_err!({ Config::profiles().data().delete_item(index) })?;
if should_update {
wrap_err!(CoreManager::global().update_config().await)?;
handle::Handle::refresh_clash();
}
}

/// change the profile chain
#[tauri::command]
pub async fn change_profile_chain(chain: Option<Vec<String>>) -> CmdResult {
wrap_err!({ Config::profiles().draft().put_chain(chain) })?;

match feat::handle_activate().await {
Ok(_) => {
Config::profiles().apply();
wrap_err!(Config::profiles().data().save_file())?;
Ok(())
}
Err(err) => {
Config::profiles().discard();
log::error!(target: "app", "{err}");
Err(format!("{err}"))
}
}
Ok(())
}

/// 修改profiles的
#[tauri::command]
pub async fn change_profile_valid(valid: Option<Vec<String>>) -> CmdResult {
wrap_err!({ Config::profiles().draft().put_valid(valid) })?;
pub async fn patch_profiles_config(profiles: IProfiles) -> CmdResult {
wrap_err!({ Config::profiles().draft().patch_config(profiles) })?;

match feat::handle_activate().await {
match CoreManager::global().update_config().await {
Ok(_) => {
handle::Handle::refresh_clash();
Config::profiles().apply();
wrap_err!(Config::profiles().data().save_file())?;
Ok(())
Expand All @@ -95,20 +73,10 @@ pub async fn change_profile_valid(valid: Option<Vec<String>>) -> CmdResult {
}
}

#[tauri::command]
pub async fn delete_profile(index: String) -> CmdResult {
let should_update = wrap_err!({ Config::profiles().data().delete_item(index) })?;
if should_update {
wrap_err!(feat::handle_activate().await)?;
}

Ok(())
}

/// 修改某个profile item的
#[tauri::command]
pub fn patch_profile(index: String, profile: PrfItem) -> CmdResult {
wrap_err!(Config::profiles().data().patch_item(index, profile))?;

wrap_err!(timer::Timer::global().refresh())
}

Expand Down Expand Up @@ -157,34 +125,29 @@ pub fn get_clash_info() -> CmdResult<ClashInfoN> {

#[tauri::command]
pub fn get_runtime_config() -> CmdResult<Option<Mapping>> {
Ok(CoreManager::global().runtime_config.lock().config.clone())
Ok(Config::runtime().latest().config.clone())
}

#[tauri::command]
pub fn get_runtime_yaml() -> CmdResult<Option<String>> {
Ok(CoreManager::global()
.runtime_config
.lock()
.config_yaml
.clone())
pub fn get_runtime_yaml() -> CmdResult<String> {
let runtime = Config::runtime();
let runtime = runtime.latest();
let config = runtime.config.as_ref();
wrap_err!(config
.ok_or(anyhow::anyhow!("failed to parse config to yaml file"))
.and_then(
|config| serde_yaml::to_string(config).context("failed to convert config to yaml")
))
}

#[tauri::command]
pub fn get_runtime_exists() -> CmdResult<Vec<String>> {
Ok(CoreManager::global()
.runtime_config
.lock()
.exists_keys
.clone())
Ok(Config::runtime().latest().exists_keys.clone())
}

#[tauri::command]
pub fn get_runtime_logs() -> CmdResult<HashMap<String, Vec<(String, String)>>> {
Ok(CoreManager::global()
.runtime_config
.lock()
.chain_logs
.clone())
Ok(Config::runtime().latest().chain_logs.clone())
}

#[tauri::command]
Expand Down
12 changes: 6 additions & 6 deletions src-tauri/src/config/clash.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::utils::{config, dirs};
use crate::utils::{dirs, help};
use anyhow::Result;
use serde::{Deserialize, Serialize};
use serde_yaml::{Mapping, Value};
Expand All @@ -8,7 +8,7 @@ pub struct IClashTemp(pub Mapping);

impl IClashTemp {
pub fn new() -> Self {
match dirs::clash_path().and_then(|path| config::read_merge_mapping(&path)) {
match dirs::clash_path().and_then(|path| help::read_merge_mapping(&path)) {
Ok(map) => Self(map),
Err(err) => {
log::error!(target: "app", "{err}");
Expand All @@ -20,7 +20,7 @@ impl IClashTemp {
pub fn template() -> Self {
let mut map = Mapping::new();

map.insert("mixed-port".into(), 7892.into());
map.insert("mixed-port".into(), 7890.into());
map.insert("log-level".into(), "info".into());
map.insert("allow-lan".into(), false.into());
map.insert("mode".into(), "rule".into());
Expand All @@ -37,10 +37,10 @@ impl IClashTemp {
}

pub fn save_config(&self) -> Result<()> {
config::save_yaml(
dirs::clash_path()?,
help::save_yaml(
&dirs::clash_path()?,
&self.0,
Some("# Default Config For ClashN Core\n\n"),
Some("# Generated by Clash Verge"),
)
}

Expand Down
81 changes: 80 additions & 1 deletion src-tauri/src/config/config.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,20 @@
use super::{Draft, IClashTemp, IProfiles, IVerge};
use super::{Draft, IClashTemp, IProfiles, IRuntime, IVerge};
use crate::{
enhance,
utils::{dirs, help},
};
use anyhow::{anyhow, Result};
use once_cell::sync::OnceCell;
use std::{env::temp_dir, path::PathBuf};

pub const RUNTIME_CONFIG: &str = "clash-verge.yaml";
pub const CHECK_CONFIG: &str = "clash-verge-check.yaml";

pub struct Config {
clash_config: Draft<IClashTemp>,
verge_config: Draft<IVerge>,
profiles_config: Draft<IProfiles>,
runtime_config: Draft<IRuntime>,
}

impl Config {
Expand All @@ -15,6 +25,7 @@ impl Config {
clash_config: Draft::from(IClashTemp::new()),
verge_config: Draft::from(IVerge::new()),
profiles_config: Draft::from(IProfiles::new()),
runtime_config: Draft::from(IRuntime::new()),
})
}

Expand All @@ -29,4 +40,72 @@ impl Config {
pub fn profiles() -> Draft<IProfiles> {
Self::global().profiles_config.clone()
}

pub fn runtime() -> Draft<IRuntime> {
Self::global().runtime_config.clone()
}

/// 初始化配置
pub fn init_config() -> Result<()> {
crate::log_err!(Self::generate());
if let Err(err) = Self::generate_file(ConfigType::Run) {
log::error!(target: "app", "{err}");

let runtime_path = dirs::app_home_dir()?.join(RUNTIME_CONFIG);
// 如果不存在就将默认的clash文件拿过来
if !runtime_path.exists() {
help::save_yaml(
&runtime_path,
&Config::clash().latest().0,
Some("# Clash Verge Runtime"),
)?;
}
}
Ok(())
}

/// 将配置丢到对应的文件中
pub fn generate_file(typ: ConfigType) -> Result<PathBuf> {
let path = match typ {
ConfigType::Run => dirs::app_home_dir()?.join(RUNTIME_CONFIG),
ConfigType::Check => temp_dir().join(CHECK_CONFIG),
};

let runtime = Config::runtime();
let runtime = runtime.latest();
let config = runtime
.config
.as_ref()
.ok_or(anyhow!("failed to get runtime config"))?;

help::save_yaml(&path, &config, Some("# Generated by Clash Verge"))?;
Ok(path)
}

/// 生成配置存好
pub fn generate() -> Result<()> {
let clash_config = { Config::clash().latest().clone() };

let tun_mode = { Config::verge().latest().enable_tun_mode.clone() };
let tun_mode = tun_mode.unwrap_or(false);

let pa = { Config::profiles().latest().gen_activate()? };

let (config, exists_keys, logs) =
enhance::enhance_config(clash_config.0, pa.current, pa.chain, pa.valid, tun_mode);

*Config::runtime().draft() = IRuntime {
config: Some(config),
exists_keys,
chain_logs: logs,
};

Ok(())
}
}

#[derive(Debug)]
pub enum ConfigType {
Run,
Check,
}
7 changes: 4 additions & 3 deletions src-tauri/src/config/draft.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use super::{IClashTemp, IProfiles, IVerge};
use super::{IClashTemp, IProfiles, IRuntime, IVerge};
use parking_lot::{MappedMutexGuard, Mutex, MutexGuard};
use std::sync::Arc;

Expand All @@ -10,6 +10,7 @@ pub struct Draft<T: Clone + ToOwned> {
macro_rules! draft_define {
($id: ident) => {
impl Draft<$id> {
#[allow(unused)]
pub fn data(&self) -> MappedMutexGuard<$id> {
MutexGuard::map(self.inner.lock(), |guard| &mut guard.0)
}
Expand Down Expand Up @@ -65,9 +66,9 @@ macro_rules! draft_define {

// draft_define!(IClash);
draft_define!(IClashTemp);
draft_define!(IVerge);
// draft_define!(Mapping);
draft_define!(IProfiles);
draft_define!(IRuntime);
draft_define!(IVerge);

#[test]
fn test_draft() {
Expand Down
2 changes: 2 additions & 0 deletions src-tauri/src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@ mod config;
mod draft;
mod prfitem;
mod profiles;
mod runtime;
mod verge;

pub use self::clash::*;
pub use self::config::*;
pub use self::draft::*;
pub use self::prfitem::*;
pub use self::profiles::*;
pub use self::runtime::*;
pub use self::verge::*;
4 changes: 2 additions & 2 deletions src-tauri/src/config/prfitem.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::utils::{config, dirs, help, tmpl};
use crate::utils::{dirs, help, tmpl};
use anyhow::{bail, Context, Result};
use reqwest::StatusCode;
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -388,7 +388,7 @@ impl PrfItem {
}),
"merge" => Some(ChainItem {
uid,
data: ChainType::Merge(config::read_merge_mapping(&path).ok()?),
data: ChainType::Merge(help::read_merge_mapping(&path).ok()?),
}),
_ => None,
}
Expand Down
Loading

0 comments on commit 2667ed1

Please sign in to comment.