rss_proxy/plugin/builtin/
keyword.rs1use crate::model::FeedItem;
2use crate::plugin::{FilterDecision, Plugin};
3use async_trait::async_trait;
4
5pub struct KeywordFilterPlugin {
6 pub include_keywords: Vec<String>,
7 pub exclude_keywords: Vec<String>,
8}
9
10impl KeywordFilterPlugin {
11 pub fn new(include: Vec<String>, exclude: Vec<String>) -> Self {
12 Self {
13 include_keywords: include
14 .into_iter()
15 .map(|k| k.trim().to_lowercase())
16 .filter(|k| !k.is_empty())
17 .collect(),
18 exclude_keywords: exclude
19 .into_iter()
20 .map(|k| k.trim().to_lowercase())
21 .filter(|k| !k.is_empty())
22 .collect(),
23 }
24 }
25
26 fn matches_haystack(&self, haystack: &str, keyword: &str) -> bool {
27 haystack.to_lowercase().contains(keyword)
28 }
29
30 fn item_text(&self, item: &FeedItem) -> String {
31 let mut text = format!("{} {} ", item.title, item.description);
32 if let Some(ref c) = item.content {
33 text.push_str(c);
34 text.push(' ');
35 }
36 if let Some(ref a) = item.author {
37 text.push_str(a);
38 text.push(' ');
39 }
40 for cat in &item.categories {
41 text.push_str(cat);
42 text.push(' ');
43 }
44 text
45 }
46}
47
48#[async_trait]
49impl Plugin for KeywordFilterPlugin {
50 fn name(&self) -> &str {
51 "KeywordFilterPlugin"
52 }
53
54 async fn filter_item(&self, item: &FeedItem) -> anyhow::Result<FilterDecision> {
55 let full_text = self.item_text(item);
56
57 for exclude in &self.exclude_keywords {
59 if self.matches_haystack(&full_text, exclude) {
60 return Ok(FilterDecision::Drop);
61 }
62 }
63
64 if !self.include_keywords.is_empty() {
66 let matched = self
67 .include_keywords
68 .iter()
69 .any(|include| self.matches_haystack(&full_text, include));
70
71 if !matched {
72 return Ok(FilterDecision::Drop);
73 }
74 }
75
76 Ok(FilterDecision::Keep)
77 }
78}