rss_proxy/plugin/
rhai_plugin.rs1use crate::model::{Feed, FeedItem};
2use crate::plugin::{FilterDecision, Plugin};
3use async_trait::async_trait;
4use rhai::{Dynamic, Engine, Scope, AST};
5use std::path::{Path, PathBuf};
6use tracing::{debug, warn};
7
8pub struct RhaiPlugin {
9 name: String,
10 path: PathBuf,
11 engine: Engine,
12 ast: AST,
13}
14
15impl RhaiPlugin {
16 pub fn path(&self) -> &Path {
17 &self.path
18 }
19 pub fn from_file<P: AsRef<Path>>(path: P) -> anyhow::Result<Self> {
20 let path = path.as_ref().to_path_buf();
21 let name = path
22 .file_stem()
23 .and_then(|s| s.to_str())
24 .unwrap_or("unnamed_plugin")
25 .to_string();
26
27 let engine = Engine::new();
28 let ast = engine
29 .compile_file(path.clone())
30 .map_err(|e| anyhow::anyhow!("Failed to compile Rhai script {:?}: {}", path, e))?;
31
32 Ok(Self {
33 name,
34 path,
35 engine,
36 ast,
37 })
38 }
39
40 pub fn load_directory<P: AsRef<Path>>(dir: P) -> Vec<Self> {
42 let mut plugins = Vec::new();
43 let dir = dir.as_ref();
44
45 if !dir.exists() || !dir.is_dir() {
46 return plugins;
47 }
48
49 if let Ok(entries) = std::fs::read_dir(dir) {
50 for entry in entries.flatten() {
51 let p = entry.path();
52 if p.is_file() && p.extension().is_some_and(|ext| ext == "rhai") {
53 match Self::from_file(&p) {
54 Ok(plugin) => plugins.push(plugin),
55 Err(e) => warn!("Error loading Rhai plugin at {:?}: {}", p, e),
56 }
57 }
58 }
59 }
60
61 plugins
62 }
63}
64
65#[async_trait]
66impl Plugin for RhaiPlugin {
67 fn name(&self) -> &str {
68 &self.name
69 }
70
71 async fn filter_item(&self, item: &FeedItem) -> anyhow::Result<FilterDecision> {
72 let mut scope = Scope::new();
73 let dynamic_item = rhai::serde::to_dynamic(item)
74 .map_err(|e| anyhow::anyhow!("Failed to serialize FeedItem to Rhai: {}", e))?;
75
76 let result =
78 self.engine
79 .call_fn::<Dynamic>(&mut scope, &self.ast, "filter_item", (dynamic_item,));
80
81 match result {
82 Ok(val) => {
83 if let Some(b) = val.clone().try_cast::<bool>() {
85 return Ok(if b {
86 FilterDecision::Keep
87 } else {
88 FilterDecision::Drop
89 });
90 }
91
92 if let Some(s) = val.clone().try_cast::<String>() {
94 let s = s.trim().to_lowercase();
95 if s == "drop" || s == "reject" {
96 return Ok(FilterDecision::Drop);
97 } else {
98 return Ok(FilterDecision::Keep);
99 }
100 }
101
102 if let Some(s) = val.clone().try_cast::<rhai::ImmutableString>() {
103 let s = s.trim().to_lowercase();
104 if s == "drop" || s == "reject" {
105 return Ok(FilterDecision::Drop);
106 } else {
107 return Ok(FilterDecision::Keep);
108 }
109 }
110
111 Ok(FilterDecision::Keep)
112 }
113 Err(e) => match *e {
114 rhai::EvalAltResult::ErrorFunctionNotFound(ref name, _)
116 if name.starts_with("filter_item") =>
117 {
118 Ok(FilterDecision::Keep)
119 }
120 other => {
121 warn!(
122 "Rhai plugin '{}' error in filter_item: {}",
123 self.name, other
124 );
125 Ok(FilterDecision::Keep)
126 }
127 },
128 }
129 }
130
131 async fn transform_item(&self, item: &mut FeedItem) -> anyhow::Result<()> {
132 let mut scope = Scope::new();
133 let dynamic_item = rhai::serde::to_dynamic(&*item)
134 .map_err(|e| anyhow::anyhow!("Failed to serialize FeedItem to Rhai: {}", e))?;
135
136 let result = self.engine.call_fn::<Dynamic>(
138 &mut scope,
139 &self.ast,
140 "transform_item",
141 (dynamic_item,),
142 );
143
144 match result {
145 Ok(val) => {
146 if let Ok(updated_item) = rhai::serde::from_dynamic::<FeedItem>(&val) {
147 *item = updated_item;
148 debug!("Rhai plugin '{}' updated item '{}'", self.name, item.title);
149 }
150 }
151 Err(e) => match *e {
152 rhai::EvalAltResult::ErrorFunctionNotFound(ref name, _)
153 if name.starts_with("transform_item") =>
154 {
155 }
157 other => {
158 warn!(
159 "Rhai plugin '{}' error in transform_item: {}",
160 self.name, other
161 );
162 }
163 },
164 }
165
166 Ok(())
167 }
168
169 async fn pre_process_feed(&self, feed: &mut Feed) -> anyhow::Result<()> {
170 let mut scope = Scope::new();
171 let dynamic_feed = rhai::serde::to_dynamic(&*feed)
172 .map_err(|e| anyhow::anyhow!("Failed to serialize Feed to Rhai: {}", e))?;
173
174 let result = self.engine.call_fn::<Dynamic>(
175 &mut scope,
176 &self.ast,
177 "pre_process_feed",
178 (dynamic_feed,),
179 );
180
181 match result {
182 Ok(val) => {
183 if let Ok(updated_feed) = rhai::serde::from_dynamic::<Feed>(&val) {
184 *feed = updated_feed;
185 }
186 }
187 Err(e) => match *e {
188 rhai::EvalAltResult::ErrorFunctionNotFound(ref name, _)
189 if name.starts_with("pre_process_feed") => {}
190 other => {
191 warn!(
192 "Rhai plugin '{}' error in pre_process_feed: {}",
193 self.name, other
194 );
195 }
196 },
197 }
198
199 Ok(())
200 }
201
202 async fn post_process_feed(&self, feed: &mut Feed) -> anyhow::Result<()> {
203 let mut scope = Scope::new();
204 let dynamic_feed = rhai::serde::to_dynamic(&*feed)
205 .map_err(|e| anyhow::anyhow!("Failed to serialize Feed to Rhai: {}", e))?;
206
207 let result = self.engine.call_fn::<Dynamic>(
208 &mut scope,
209 &self.ast,
210 "post_process_feed",
211 (dynamic_feed,),
212 );
213
214 match result {
215 Ok(val) => {
216 if let Ok(updated_feed) = rhai::serde::from_dynamic::<Feed>(&val) {
217 *feed = updated_feed;
218 }
219 }
220 Err(e) => match *e {
221 rhai::EvalAltResult::ErrorFunctionNotFound(ref name, _)
222 if name.starts_with("post_process_feed") => {}
223 other => {
224 warn!(
225 "Rhai plugin '{}' error in post_process_feed: {}",
226 self.name, other
227 );
228 }
229 },
230 }
231
232 Ok(())
233 }
234}