use minijinja::Environment;
use parking_lot::RwLock;
use rand::Rng;
use std::collections::HashMap;
use std::sync::Arc;
use super::cache::FileCache;
use super::context::TemplateContext;
pub type ParsedTemplate = Arc<String>;
pub struct TemplateEngine {
file_cache: Arc<FileCache>,
templates: RwLock<HashMap<String, ParsedTemplate>>,
}
impl TemplateEngine {
pub fn new() -> Self {
let file_cache = Arc::new(FileCache::new());
Self {
file_cache,
templates: RwLock::new(HashMap::new()),
}
}
pub fn parse(&self, name: &str, text: &str) -> anyhow::Result<ParsedTemplate> {
let processed = Self::preprocess(text);
let mut env = Environment::new();
self.add_functions_to_env(&mut env);
env.add_template(name, &processed)
.map_err(|e| anyhow::anyhow!("failed to parse template '{}': {}", name, e))?;
let tpl = Arc::new(processed);
self.templates
.write()
.insert(name.to_string(), Arc::clone(&tpl));
Ok(tpl)
}
pub fn execute(
&self,
template: &ParsedTemplate,
ctx: &TemplateContext,
) -> anyhow::Result<String> {
let mut env = Environment::new();
self.add_functions_to_env(&mut env);
env.add_template("__exec__", template.as_str())
.map_err(|e| anyhow::anyhow!("failed to add template: {}", e))?;
let tmpl = env
.get_template("__exec__")
.map_err(|e| anyhow::anyhow!("failed to get template: {}", e))?;
let result = tmpl
.render(minijinja::context! {
user_id => &ctx.user_id,
})
.map_err(|e| anyhow::anyhow!("failed to render template: {}", e))?;
Ok(result)
}
pub fn execute_str(&self, text: &str, ctx: &TemplateContext) -> anyhow::Result<String> {
let processed = Self::preprocess(text);
let mut env = Environment::new();
self.add_functions_to_env(&mut env);
env.add_template("__exec__", &processed)
.map_err(|e| anyhow::anyhow!("failed to parse template: {}", e))?;
let tmpl = env
.get_template("__exec__")
.map_err(|e| anyhow::anyhow!("failed to get template: {}", e))?;
let result = tmpl
.render(minijinja::context! {
user_id => &ctx.user_id,
})
.map_err(|e| anyhow::anyhow!("failed to render template: {}", e))?;
Ok(result)
}
pub fn file_cache(&self) -> &Arc<FileCache> {
&self.file_cache
}
fn add_functions_to_env(&self, env: &mut Environment<'_>) {
let file_cache = Arc::clone(&self.file_cache);
env.add_function("random_int", |min: i64, max: i64| -> i64 {
if min >= max {
min
} else {
rand::thread_rng().gen_range(min..max)
}
});
env.add_function("uuid", || -> String { uuid::Uuid::new_v4().to_string() });
env.add_function("random_choice", |values: Vec<String>| -> String {
if values.is_empty() {
String::new()
} else {
let idx = rand::thread_rng().gen_range(0..values.len());
values[idx].clone()
}
});
let fc1 = Arc::clone(&file_cache);
env.add_function("random_line", move |path: String| -> String {
match fc1.get_lines(&path) {
Ok(lines) if !lines.is_empty() => {
let idx = rand::thread_rng().gen_range(0..lines.len());
lines[idx].clone()
}
_ => String::new(),
}
});
let fc2 = Arc::clone(&file_cache);
env.add_function("read_file", move |path: String| -> String {
fc2.get_raw(&path).unwrap_or_default()
});
}
fn preprocess(input: &str) -> String {
let mut output = input.to_string();
output = output.replace("{{userID}}", "{{ user_id }}");
output = output.replace("{{uuid}}", "{{ uuid() }}");
output = output.replace("{{requestID}}", "{{ uuid() }}");
output
}
}
impl Default for TemplateEngine {
fn default() -> Self {
Self::new()
}
}