libsubconverter/models/
ruleset.rs1use std::{
2 collections::HashMap,
3 sync::{Arc, RwLock},
4};
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum RulesetType {
9 Surge,
10 Quanx,
11 ClashDomain,
12 ClashIpcidr,
13 ClashClassical,
14}
15
16impl Default for RulesetType {
17 fn default() -> Self {
18 RulesetType::Surge
19 }
20}
21
22pub type RulesetMapping = HashMap<String, RulesetType>;
24
25pub static RULESET_TYPES: once_cell::sync::Lazy<RulesetMapping> =
27 once_cell::sync::Lazy::new(|| {
28 let mut types = RulesetMapping::new();
29 types.insert("clash-domain:".to_string(), RulesetType::ClashDomain);
30 types.insert("clash-ipcidr:".to_string(), RulesetType::ClashIpcidr);
31 types.insert("clash-classical:".to_string(), RulesetType::ClashClassical);
32 types.insert("quanx:".to_string(), RulesetType::Quanx);
33 types.insert("surge:".to_string(), RulesetType::Surge);
34 types
35 });
36
37pub fn get_ruleset_type_from_url(url: &str) -> Option<RulesetType> {
42 for (prefix, ruleset_type) in RULESET_TYPES.iter() {
43 if url.starts_with(prefix) {
44 return Some(ruleset_type.clone());
45 }
46 }
47 None
48}
49
50#[derive(Debug, Clone, Default, PartialEq)]
51pub struct RulesetConfig {
52 pub group: String,
53 pub url: String,
54 pub interval: u32,
55}
56
57pub type RulesetConfigs = Vec<RulesetConfig>;
58
59#[derive(Debug, Clone)]
72pub struct RulesetContent {
73 pub group: String, pub rule_path: String, pub rule_path_typed: String, pub rule_type: RulesetType, pub rule_content: Arc<RwLock<Option<String>>>,
82
83 pub update_interval: u32, }
85
86impl RulesetContent {
87 pub fn new(rule_path: &str, group: &str) -> Self {
89 RulesetContent {
90 group: group.to_string(),
91 rule_path: rule_path.to_string(),
92 rule_path_typed: rule_path.to_string(),
93 rule_type: RulesetType::default(),
94 rule_content: Arc::new(RwLock::new(None)),
95 update_interval: 0,
96 }
97 }
98
99 pub fn get_rule_content(&self) -> String {
102 match self.rule_content.read() {
104 Ok(guard) => match &*guard {
105 Some(content) => content.clone(),
106 None => String::new(),
107 },
108 Err(_) => String::new(),
109 }
110 }
111
112 pub fn set_rule_content(&mut self, content: &str) {
115 if let Ok(mut guard) = self.rule_content.write() {
116 *guard = Some(content.to_string());
117 }
118 }
119
120 pub fn has_rule_content(&self) -> bool {
123 match self.rule_content.read() {
124 Ok(guard) => guard.is_some(),
125 Err(_) => false,
126 }
127 }
128}
129
130pub fn parse_ruleset(content: &str, group: &str) -> RulesetContent {
132 let mut ruleset = RulesetContent::new("", group);
133 ruleset.set_rule_content(content);
134 ruleset
135}