Files
clash-proxy/src-tauri/src/data/profiles.rs

329 lines
8.3 KiB
Rust
Raw Normal View History

2022-04-19 01:41:20 +08:00
use super::prfitem::PrfItem;
2022-08-12 03:20:55 +08:00
use super::ChainItem;
2022-04-19 01:41:20 +08:00
use crate::utils::{config, dirs, help};
2022-03-01 08:58:47 +08:00
use anyhow::{bail, Context, Result};
2021-12-13 02:29:02 +08:00
use serde::{Deserialize, Serialize};
use serde_yaml::Mapping;
2022-08-12 03:20:55 +08:00
use std::collections::HashMap;
2022-03-01 08:58:47 +08:00
use std::{fs, io::Write};
2021-12-13 02:29:02 +08:00
2022-03-01 08:58:47 +08:00
///
/// ## Profiles Config
///
/// Define the `profiles.yaml` schema
///
2021-12-14 22:33:42 +08:00
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
2022-03-01 08:58:47 +08:00
pub struct Profiles {
/// same as PrfConfig.current
current: Option<String>,
/// same as PrfConfig.chain
chain: Option<Vec<String>>,
/// record valid fields for clash
valid: Option<Vec<String>>,
2022-03-01 08:58:47 +08:00
/// profile list
items: Option<Vec<PrfItem>>,
}
macro_rules! patch {
($lv: expr, $rv: expr, $key: tt) => {
if ($rv.$key).is_some() {
$lv.$key = $rv.$key;
}
};
2021-12-14 22:33:42 +08:00
}
2022-01-05 02:00:59 +08:00
impl Profiles {
2022-04-19 01:41:20 +08:00
pub fn new() -> Self {
Profiles::read_file()
}
2022-01-05 02:00:59 +08:00
/// read the config from the file
pub fn read_file() -> Self {
2022-03-01 11:05:33 +08:00
let mut profiles = config::read_yaml::<Self>(dirs::profiles_path());
if profiles.items.is_none() {
profiles.items = Some(vec![]);
}
2022-04-20 01:44:47 +08:00
// compatiable with the old old old version
2022-03-01 11:05:33 +08:00
profiles.items.as_mut().map(|items| {
for mut item in items.iter_mut() {
if item.uid.is_none() {
item.uid = Some(help::get_uid("d"));
}
}
});
profiles
2022-01-05 02:00:59 +08:00
}
/// save the config to the file
2022-02-28 01:34:25 +08:00
pub fn save_file(&self) -> Result<()> {
2022-01-05 02:00:59 +08:00
config::save_yaml(
2022-02-28 01:34:25 +08:00
dirs::profiles_path(),
2022-01-05 02:00:59 +08:00
self,
Some("# Profiles Config for Clash Verge\n\n"),
)
}
2022-03-01 08:58:47 +08:00
/// get the current uid
pub fn get_current(&self) -> Option<String> {
self.current.clone()
}
2022-01-05 02:00:59 +08:00
2022-03-01 08:58:47 +08:00
/// only change the main to the target id
pub fn put_current(&mut self, uid: String) -> Result<()> {
if self.items.is_none() {
self.items = Some(vec![]);
2022-01-05 02:00:59 +08:00
}
2022-03-01 08:58:47 +08:00
let items = self.items.as_ref().unwrap();
let some_uid = Some(uid.clone());
2022-04-20 01:44:47 +08:00
if items.iter().find(|&each| each.uid == some_uid).is_some() {
self.current = some_uid;
return self.save_file();
2022-03-01 08:58:47 +08:00
}
bail!("invalid uid \"{uid}\"");
2022-01-05 02:00:59 +08:00
}
2022-03-06 14:59:25 +08:00
/// just change the `chain`
2022-08-08 23:17:22 +08:00
pub fn put_chain(&mut self, chain: Option<Vec<String>>) -> Result<()> {
2022-03-06 14:59:25 +08:00
self.chain = chain;
2022-08-08 23:17:22 +08:00
self.save_file()
2022-03-06 14:59:25 +08:00
}
/// just change the `field`
2022-08-08 23:17:22 +08:00
pub fn put_valid(&mut self, valid: Option<Vec<String>>) -> Result<()> {
self.valid = valid;
2022-08-08 23:17:22 +08:00
self.save_file()
}
2022-04-20 20:37:16 +08:00
/// get items ref
pub fn get_items(&self) -> Option<&Vec<PrfItem>> {
self.items.as_ref()
}
2022-03-01 08:58:47 +08:00
/// find the item by the uid
pub fn get_item(&self, uid: &String) -> Result<&PrfItem> {
if self.items.is_some() {
let items = self.items.as_ref().unwrap();
let some_uid = Some(uid.clone());
2022-01-05 02:00:59 +08:00
2022-03-01 08:58:47 +08:00
for each in items.iter() {
if each.uid == some_uid {
return Ok(each);
}
}
2022-01-05 02:00:59 +08:00
}
2022-08-19 17:11:59 +08:00
bail!("failed to get the profile item \"uid:{uid}\"");
2022-01-05 02:00:59 +08:00
}
2022-02-07 17:26:05 +08:00
/// append new item
2022-03-01 08:58:47 +08:00
/// if the file_data is some
/// then should save the data to file
pub fn append_item(&mut self, mut item: PrfItem) -> Result<()> {
if item.uid.is_none() {
bail!("the uid should not be null");
}
2022-02-07 17:26:05 +08:00
2022-03-01 08:58:47 +08:00
// save the file data
// move the field value after save
if let Some(file_data) = item.file_data.take() {
if item.file.is_none() {
bail!("the file should not be null");
2022-02-07 17:26:05 +08:00
}
2022-03-01 08:58:47 +08:00
let file = item.file.clone().unwrap();
let path = dirs::app_profiles_dir().join(&file);
fs::File::create(path)
.context(format!("failed to create file \"{}\"", file))?
.write(file_data.as_bytes())
.context(format!("failed to write to file \"{}\"", file))?;
}
if self.items.is_none() {
self.items = Some(vec![]);
2022-02-07 17:26:05 +08:00
}
2022-03-01 08:58:47 +08:00
self.items.as_mut().map(|items| items.push(item));
self.save_file()
2022-02-07 17:26:05 +08:00
}
2022-04-20 01:44:47 +08:00
/// update the item value
2022-03-01 08:58:47 +08:00
pub fn patch_item(&mut self, uid: String, item: PrfItem) -> Result<()> {
2022-01-05 02:00:59 +08:00
let mut items = self.items.take().unwrap_or(vec![]);
2022-03-01 08:58:47 +08:00
for mut each in items.iter_mut() {
if each.uid == Some(uid.clone()) {
patch!(each, item, itype);
patch!(each, item, name);
patch!(each, item, desc);
patch!(each, item, file);
patch!(each, item, url);
patch!(each, item, selected);
patch!(each, item, extra);
2022-03-07 01:41:42 +08:00
patch!(each, item, updated);
2022-03-11 19:50:51 +08:00
patch!(each, item, option);
2022-03-01 08:58:47 +08:00
self.items = Some(items);
return self.save_file();
}
}
2022-01-05 02:00:59 +08:00
self.items = Some(items);
2022-08-19 17:11:59 +08:00
bail!("failed to find the profile item \"uid:{uid}\"")
2022-01-05 02:00:59 +08:00
}
2022-03-01 08:58:47 +08:00
/// be used to update the remote item
/// only patch `updated` `extra` `file_data`
pub fn update_item(&mut self, uid: String, mut item: PrfItem) -> Result<()> {
if self.items.is_none() {
self.items = Some(vec![]);
2022-01-05 02:00:59 +08:00
}
2022-03-01 08:58:47 +08:00
// find the item
let _ = self.get_item(&uid)?;
2022-01-05 02:00:59 +08:00
2022-04-20 01:44:47 +08:00
if let Some(items) = self.items.as_mut() {
2022-03-01 08:58:47 +08:00
let some_uid = Some(uid.clone());
2022-01-05 02:00:59 +08:00
2022-03-01 08:58:47 +08:00
for mut each in items.iter_mut() {
if each.uid == some_uid {
2022-03-02 01:45:00 +08:00
each.extra = item.extra;
each.updated = item.updated;
2022-01-05 02:00:59 +08:00
2022-03-01 08:58:47 +08:00
// save the file data
// move the field value after save
if let Some(file_data) = item.file_data.take() {
let file = each.file.take();
let file = file.unwrap_or(item.file.take().unwrap_or(format!("{}.yaml", &uid)));
2022-01-05 02:00:59 +08:00
2022-03-01 08:58:47 +08:00
// the file must exists
each.file = Some(file.clone());
2022-02-17 01:58:12 +08:00
2022-03-01 08:58:47 +08:00
let path = dirs::app_profiles_dir().join(&file);
2022-02-17 01:58:12 +08:00
2022-03-01 08:58:47 +08:00
fs::File::create(path)
2022-04-20 01:44:47 +08:00
.context(format!("failed to create file \"{}\"", file))?
2022-03-01 08:58:47 +08:00
.write(file_data.as_bytes())
2022-04-20 01:44:47 +08:00
.context(format!("failed to write to file \"{}\"", file))?;
2022-03-01 08:58:47 +08:00
}
break;
2022-02-17 01:58:12 +08:00
}
}
2022-04-20 01:44:47 +08:00
}
2022-01-05 02:00:59 +08:00
2022-03-01 08:58:47 +08:00
self.save_file()
}
2022-01-08 14:21:12 +08:00
2022-03-01 08:58:47 +08:00
/// delete item
/// if delete the current then return true
pub fn delete_item(&mut self, uid: String) -> Result<bool> {
let current = self.current.as_ref().unwrap_or(&uid);
let current = current.clone();
2022-01-08 14:21:12 +08:00
2022-03-01 08:58:47 +08:00
let mut items = self.items.take().unwrap_or(vec![]);
let mut index = None;
2022-01-08 14:21:12 +08:00
2022-03-01 08:58:47 +08:00
// get the index
for i in 0..items.len() {
if items[i].uid == Some(uid.clone()) {
index = Some(i);
break;
}
2022-01-08 14:21:12 +08:00
}
2022-01-07 23:29:20 +08:00
2022-03-01 08:58:47 +08:00
if let Some(index) = index {
items.remove(index).file.map(|file| {
let path = dirs::app_profiles_dir().join(file);
if path.exists() {
let _ = fs::remove_file(path);
2022-01-07 23:29:20 +08:00
}
2022-03-01 08:58:47 +08:00
});
}
2022-01-07 23:29:20 +08:00
2022-03-01 08:58:47 +08:00
// delete the original uid
if current == uid {
self.current = match items.len() > 0 {
true => items[0].uid.clone(),
false => None,
};
2022-01-07 23:29:20 +08:00
}
2022-03-01 08:58:47 +08:00
self.items = Some(items);
self.save_file()?;
Ok(current == uid)
2022-01-07 23:29:20 +08:00
}
2022-08-12 03:20:55 +08:00
/// generate the current Mapping data
fn gen_current(&self) -> Result<Mapping> {
2022-03-01 08:58:47 +08:00
let config = Mapping::new();
2022-01-07 23:29:20 +08:00
2022-03-01 08:58:47 +08:00
if self.current.is_none() || self.items.is_none() {
return Ok(config);
2022-01-07 23:29:20 +08:00
}
2022-03-01 08:58:47 +08:00
let current = self.current.clone().unwrap();
for item in self.items.as_ref().unwrap().iter() {
if item.uid == Some(current.clone()) {
let file_path = match item.file.clone() {
Some(file) => dirs::app_profiles_dir().join(file),
None => bail!("failed to get the file field"),
};
2022-01-07 23:29:20 +08:00
2022-03-01 08:58:47 +08:00
if !file_path.exists() {
bail!("failed to read the file \"{}\"", file_path.display());
}
2022-01-07 23:29:20 +08:00
return Ok(config::read_yaml::<Mapping>(file_path.clone()));
2022-03-01 08:58:47 +08:00
}
}
2022-08-19 17:11:59 +08:00
bail!("failed to find current profile \"uid:{current}\"");
2022-03-01 08:58:47 +08:00
}
2022-03-03 01:52:02 +08:00
2022-08-12 03:20:55 +08:00
/// generate the data for activate clash config
pub fn gen_activate(&self) -> Result<PrfActivate> {
let current = self.gen_current()?;
2022-03-03 01:52:02 +08:00
let chain = match self.chain.as_ref() {
Some(chain) => chain
.iter()
2022-08-12 03:20:55 +08:00
.filter_map(|uid| self.get_item(uid).ok())
.filter_map(|item| item.to_enhance())
.collect::<Vec<ChainItem>>(),
2022-03-03 01:52:02 +08:00
None => vec![],
};
let valid = self.valid.clone().unwrap_or(vec![]);
2022-08-12 03:20:55 +08:00
Ok(PrfActivate {
2022-03-06 14:59:25 +08:00
current,
chain,
valid,
2022-03-06 14:59:25 +08:00
})
2022-03-03 01:52:02 +08:00
}
}
2022-08-12 03:20:55 +08:00
#[derive(Default, Clone)]
pub struct PrfActivate {
pub current: Mapping,
pub chain: Vec<ChainItem>,
pub valid: Vec<String>,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct RuntimeResult {
pub config: Option<Mapping>,
pub config_yaml: Option<String>,
// 记录在配置中包括merge和script生成的出现过的keys
// 这些keys不一定都生效
pub exists_keys: Vec<String>,
pub chain_logs: HashMap<String, Vec<(String, String)>>,
}