1use std::cell::RefCell;
40use std::collections::HashMap;
41use std::sync::Arc;
42
43use tera::{Function, Tera, Value};
44
45type Key = (String, i64);
47
48thread_local! {
49 static CURRENT_SNIPPETS_HTML: RefCell<Option<Arc<HashMap<Key, String>>>>
50 = const { RefCell::new(None) };
51}
52
53#[must_use = "the guard clears the thread-local on drop; bind it to a local"]
56pub struct SnippetHtmlGuard {
57 _priv: (),
58}
59
60impl Drop for SnippetHtmlGuard {
61 fn drop(&mut self) {
62 CURRENT_SNIPPETS_HTML.with(|cell| {
63 *cell.borrow_mut() = None;
64 });
65 }
66}
67
68pub fn install(map: HashMap<Key, String>) -> SnippetHtmlGuard {
72 CURRENT_SNIPPETS_HTML.with(|cell| {
73 *cell.borrow_mut() = Some(Arc::new(map));
74 });
75 SnippetHtmlGuard { _priv: () }
76}
77
78pub fn register_tera_function(tera: &mut Tera) {
81 tera.register_function("snippet_html", SnippetHtmlFn);
82}
83
84struct SnippetHtmlFn;
89
90impl Function for SnippetHtmlFn {
91 fn call(&self, args: &HashMap<String, Value>) -> tera::Result<Value> {
92 let ty = args.get("type").and_then(Value::as_str).unwrap_or("");
93 let id = args.get("id").and_then(Value::as_i64).unwrap_or(0);
94 if ty.is_empty() || id <= 0 {
95 return Ok(Value::String(String::new()));
96 }
97 let html = CURRENT_SNIPPETS_HTML.with(|cell| {
98 cell.borrow()
99 .as_ref()
100 .and_then(|m| m.get(&(ty.to_owned(), id)).cloned())
101 .unwrap_or_default()
102 });
103 Ok(Value::String(html))
104 }
105 fn is_safe(&self) -> bool {
106 true
107 }
108}
109
110pub async fn prefetch(
124 pool: &rustango::sql::Pool,
125 tera: &Tera,
126 locale_id: Option<i64>,
127) -> HashMap<Key, String> {
128 use rustango::core::Column as _;
129 use rustango::sql::FetcherPool as _;
130 let mut out: HashMap<Key, String> = HashMap::new();
131 for handler in crate::library::registered_handlers() {
135 let type_default = handler.render_template();
136 let per_element = handler.allows_element_template();
137 if type_default.is_none() && !per_element {
140 continue;
141 }
142 let type_name = handler.type_name();
143 let rows = match crate::snippet::Snippet::objects()
144 .where_(crate::snippet::Snippet::type_name.eq(type_name.to_owned()))
145 .fetch(pool)
146 .await
147 {
148 Ok(r) => r,
149 Err(e) => {
150 tracing::warn!(
151 target: "rustango_cms::snippet_render",
152 error = %e,
153 type_name = %type_name,
154 "snippet prefetch failed for type; skipping",
155 );
156 continue;
157 }
158 };
159 let translations = match locale_id {
162 Some(lid) => {
163 let ids: Vec<i64> = rows.iter().filter_map(|r| r.id.get().copied()).collect();
164 crate::snippet_translation::fetch_for_snippets(pool, &ids, lid)
165 .await
166 .unwrap_or_default()
167 }
168 None => HashMap::new(),
169 };
170 for row in rows {
171 let Some(id) = row.id.get().copied() else {
172 continue;
173 };
174 let mut ctx = tera::Context::new();
175 let mut snippet_value = serde_json::to_value(&row).unwrap_or(serde_json::Value::Null);
176 if let Some(overrides) = translations.get(&id) {
177 apply_overrides(&mut snippet_value, overrides);
178 }
179 let template = match per_element
182 .then(|| element_template(&snippet_value))
183 .flatten()
184 {
185 Some(name) => name,
186 None => match type_default {
187 Some(t) => t.to_owned(),
188 None => continue,
191 },
192 };
193 ctx.insert("snippet", &snippet_value);
194 match tera.render(&template, &ctx) {
195 Ok(html) => {
196 out.insert((type_name.to_owned(), id), html);
197 }
198 Err(e) => {
199 tracing::warn!(
200 target: "rustango_cms::snippet_render",
201 error = %e,
202 type_name = %type_name,
203 id,
204 template = %template,
205 "snippet template render failed; leaving slot empty",
206 );
207 }
208 }
209 }
210 }
211 out
212}
213
214fn element_template(snippet_value: &Value) -> Option<String> {
224 let name = snippet_value.get("data")?.get("template")?.as_str()?;
225 crate::tenant_templates::safe_name(name).ok()
226}
227
228fn apply_overrides(value: &mut Value, overrides: &HashMap<String, String>) {
233 let Some(obj) = value.as_object_mut() else {
234 return;
235 };
236 for (path, v) in overrides {
237 if let Some(key) = path.strip_prefix("data.") {
238 let data = obj
239 .entry("data")
240 .or_insert_with(|| Value::Object(serde_json::Map::new()));
241 if let Some(map) = data.as_object_mut() {
242 map.insert(key.to_owned(), Value::String(v.clone()));
243 }
244 } else {
245 obj.insert(path.clone(), Value::String(v.clone()));
246 }
247 }
248}
249
250#[cfg(test)]
251mod tests {
252 use super::*;
253 use tera::{Context, Tera};
254
255 fn fresh_tera() -> Tera {
256 let mut tera = Tera::default();
257 register_tera_function(&mut tera);
258 tera
259 }
260
261 fn render(tera: &Tera, src: &str) -> String {
262 let mut t = tera.clone();
263 t.add_raw_template("t.html", src).unwrap();
264 t.render("t.html", &Context::new()).unwrap()
265 }
266
267 fn with_template(name: &str) -> Value {
268 serde_json::json!({ "data": { "template": name } })
269 }
270
271 #[test]
272 fn element_template_reads_a_plain_relative_name() {
273 assert_eq!(
274 element_template(&with_template("widgets/donations.html")),
275 Some("widgets/donations.html".to_owned())
276 );
277 }
278
279 #[test]
280 fn element_template_trims_surrounding_whitespace() {
281 assert_eq!(
282 element_template(&with_template(" widgets/a.html \n")),
283 Some("widgets/a.html".to_owned())
284 );
285 }
286
287 #[test]
288 fn element_template_absent_when_unset_or_wrong_shape() {
289 assert_eq!(element_template(&serde_json::json!({})), None);
290 assert_eq!(element_template(&serde_json::json!({"data": {}})), None);
291 assert_eq!(
293 element_template(&serde_json::json!({"data": {"template": 7}})),
294 None
295 );
296 }
297
298 #[test]
299 fn element_template_refuses_traversal_and_absolute_names() {
300 for bad in [
301 "",
302 " ",
303 "/etc/passwd",
304 "../../secrets.html",
305 "widgets/../../../x.html",
306 "widgets\\win.html",
307 ".env",
309 "a//b.html",
310 "a/./b.html",
311 "widgets/donations",
312 ] {
313 assert_eq!(
314 element_template(&with_template(bad)),
315 None,
316 "should have refused {bad:?}"
317 );
318 }
319 }
320
321 #[test]
322 fn element_template_allows_dots_inside_a_segment() {
323 assert_eq!(
326 element_template(&with_template("widgets/a..b.html")),
327 Some("widgets/a..b.html".to_owned())
328 );
329 }
330
331 #[test]
332 fn apply_overrides_replaces_top_level_and_data_paths() {
333 let mut v = serde_json::json!({
336 "title": "Hi", "body_markdown": "en body", "data": {"cta": "Click"}
337 });
338 let mut o = HashMap::new();
339 o.insert("title".to_owned(), "Bonjour".to_owned());
340 o.insert("body_markdown".to_owned(), "corps fr".to_owned());
341 o.insert("data.cta".to_owned(), "Cliquez".to_owned());
342 super::apply_overrides(&mut v, &o);
343 assert_eq!(v["title"], serde_json::json!("Bonjour"));
344 assert_eq!(v["body_markdown"], serde_json::json!("corps fr"));
345 assert_eq!(v["data"]["cta"], serde_json::json!("Cliquez"));
346 }
347
348 #[test]
349 fn apply_overrides_creates_missing_data_object() {
350 let mut v = serde_json::json!({ "title": "Hi" });
351 let mut o = HashMap::new();
352 o.insert("data.x".to_owned(), "y".to_owned());
353 super::apply_overrides(&mut v, &o);
354 assert_eq!(v["data"]["x"], serde_json::json!("y"));
355 }
356
357 #[test]
358 fn returns_empty_when_nothing_installed() {
359 let tera = fresh_tera();
360 let out = render(&tera, r#"x{{ snippet_html(type="Category", id=1) }}y"#);
361 assert_eq!(out, "xy");
362 }
363
364 #[test]
365 fn resolves_known_type_and_id() {
366 let mut m = HashMap::new();
367 m.insert(
368 ("Category".to_owned(), 4i64),
369 "<span>rust</span>".to_owned(),
370 );
371 let _g = install(m);
372 let tera = fresh_tera();
373 let out = render(&tera, r#"{{ snippet_html(type="Category", id=4) }}"#);
374 assert_eq!(out, "<span>rust</span>");
375 }
376
377 #[test]
378 fn unknown_type_returns_empty() {
379 let mut m = HashMap::new();
380 m.insert(
381 ("Category".to_owned(), 4i64),
382 "<span>rust</span>".to_owned(),
383 );
384 let _g = install(m);
385 let tera = fresh_tera();
386 let out = render(&tera, r#"x{{ snippet_html(type="Author", id=4) }}y"#);
387 assert_eq!(out, "xy");
388 }
389
390 #[test]
391 fn unknown_id_returns_empty() {
392 let mut m = HashMap::new();
393 m.insert(
394 ("Category".to_owned(), 4i64),
395 "<span>rust</span>".to_owned(),
396 );
397 let _g = install(m);
398 let tera = fresh_tera();
399 let out = render(&tera, r#"x{{ snippet_html(type="Category", id=99) }}y"#);
400 assert_eq!(out, "xy");
401 }
402
403 #[test]
404 fn missing_args_return_empty() {
405 let _g = install(HashMap::new());
406 let tera = fresh_tera();
407 let out = render(&tera, r#"x{{ snippet_html(type="Category") }}y"#);
408 assert_eq!(out, "xy");
409 let out2 = render(&tera, r#"x{{ snippet_html(id=4) }}y"#);
410 assert_eq!(out2, "xy");
411 }
412
413 #[test]
414 fn output_is_marked_safe() {
415 let mut m = HashMap::new();
417 m.insert(("X".to_owned(), 1i64), "<b>ok</b>".to_owned());
418 let _g = install(m);
419 let tera = fresh_tera();
420 let out = render(&tera, r#"{{ snippet_html(type="X", id=1) }}"#);
421 assert!(out.contains("<b>ok</b>"), "got `{out}`");
422 }
423
424 #[test]
425 fn guard_clears_thread_local() {
426 {
427 let mut m = HashMap::new();
428 m.insert(("X".to_owned(), 1i64), "y".to_owned());
429 let _g = install(m);
430 let tera = fresh_tera();
431 assert_eq!(render(&tera, r#"{{ snippet_html(type="X", id=1) }}"#), "y");
432 }
433 let tera = fresh_tera();
434 assert_eq!(
435 render(&tera, r#"x{{ snippet_html(type="X", id=1) }}y"#),
436 "xy"
437 );
438 }
439}