parse_book_source/analyzer/
mod.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
use crate::Result;
use regex::Regex;
use std::fmt::Debug;
pub mod analyzer_manager;
pub mod default;
pub mod html;
pub mod json;
pub use analyzer_manager::AnalyzerManager;
pub use default::DefaultAnalyzer;
pub use html::HtmlAnalyzer;
pub use json::JsonPathAnalyzer;

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AnalyzerType {
    JsonPath,
    Html,
    Default,
}

impl AnalyzerType {
    pub fn parse_to_analyzer(&self, date: &str) -> Result<Box<dyn Analyzer>> {
        match self {
            AnalyzerType::JsonPath => Ok(Box::new(JsonPathAnalyzer::parse(date)?)),
            AnalyzerType::Html => Ok(Box::new(HtmlAnalyzer::parse(date)?)),
            AnalyzerType::Default => Ok(Box::new(DefaultAnalyzer::parse(date)?)),
        }
    }
}

#[derive(Debug, Clone)]
pub struct Analyzers {
    pub pattern: Regex,
    pub replace: Option<Regex>,
    pub analyzer: AnalyzerType,
}

impl Analyzers {
    pub fn new(pattern: &str, replace: Option<&str>, analyzer: AnalyzerType) -> Result<Self> {
        Ok(Self {
            pattern: Regex::new(pattern)?,
            replace: replace.map(Regex::new).transpose()?,
            analyzer,
        })
    }
}

#[derive(Debug, Clone)]
pub struct SingleRule {
    pub rule: String,
    // 替换内容(## 后面的内容)
    pub replace: String,
    pub analyzer: AnalyzerType,
}

impl SingleRule {
    pub fn new(rule: &str, replace: Option<&str>, analyzer: AnalyzerType) -> Result<Self> {
        Ok(Self {
            rule: rule.to_string(),
            replace: replace.unwrap_or("").to_string(),
            analyzer,
        })
    }

    pub fn replace_content(&self, content: &str) -> Result<String> {
        if self.replace.is_empty() {
            return Ok(content.to_string());
        }

        if let Some((regex, replace_content)) = self.replace.split_once("##") {
            let regex = Regex::new(regex)?;
            Ok(regex.replace_all(content, replace_content).to_string())
        } else {
            let regex = Regex::new(&self.replace)?;
            Ok(regex.replace_all(content, "").to_string())
        }
    }
}

pub trait Analyzer {
    fn parse(content: &str) -> Result<Self>
    where
        Self: Sized;

    fn get_string(&self, rule: &str) -> Result<String> {
        let _ = rule;
        unimplemented!()
    }

    fn get_string_list(&self, rule: &str) -> Result<Vec<String>> {
        let _ = rule;
        unimplemented!()
    }

    fn get_elements(&self, rule: &str) -> Result<Vec<String>> {
        let _ = rule;
        unimplemented!()
    }
}