Skip to main content

rustango_cms/starter/
media.rs

1//! A theme's sample pictures: the `media` entries of `theme.json`, stored
2//! in the site's media library when the theme is applied, and the
3//! `"@media:<key>"` references in page content that point at them.
4//!
5//! ```json
6//! "media": [ { "key": "hills", "file": "hills.jpg", "title": "Rolling hills",
7//!              "alt": "Layered hills at dawn" } ],
8//! "pages": [ { …, "data": { "cover": "@media:hills" } } ]
9//! ```
10//!
11//! The files come with the call ([`super::apply_with_media`]), usually
12//! embedded in the site's binary. Each goes through the same path as an
13//! upload in the admin. A reference whose picture was not supplied becomes
14//! empty, so the page shows no picture rather than a broken one.
15
16use std::collections::HashMap;
17
18use rustango::sql::Pool;
19use serde::Deserialize;
20use serde_json::Value;
21
22use super::{StarterError, StarterSeed};
23
24/// How page content points at a theme picture.
25pub const REF_PREFIX: &str = "@media:";
26
27/// One `media` entry.
28#[derive(Debug, Deserialize)]
29#[serde(deny_unknown_fields)]
30pub struct MediaSeed {
31    /// Name page content uses: `"@media:<key>"`.
32    pub key: String,
33    /// File name, as supplied to [`super::apply_with_media`].
34    pub file: String,
35    #[serde(default)]
36    pub title: String,
37    /// What the picture shows, for people who can't see it.
38    #[serde(default)]
39    pub alt: String,
40}
41
42/// Every string in `value` that references a picture, as its key.
43fn refs<'a>(value: &'a Value, out: &mut Vec<&'a str>) {
44    match value {
45        Value::String(s) => {
46            if let Some(key) = s.strip_prefix(REF_PREFIX) {
47                out.push(key);
48            }
49        }
50        Value::Array(items) => items.iter().for_each(|v| refs(v, out)),
51        Value::Object(map) => map.values().for_each(|v| refs(v, out)),
52        _ => {}
53    }
54}
55
56fn page_refs<'a>(pages: &'a [super::PageSeed], out: &mut Vec<&'a str>) {
57    for page in pages {
58        refs(&page.data, out);
59        page_refs(&page.children, out);
60    }
61}
62
63/// Problems with the `media` entries and the references to them.
64pub(super) fn problems(seed: &StarterSeed) -> Vec<String> {
65    let mut problems = Vec::new();
66    let mut keys: Vec<&str> = Vec::new();
67    for m in &seed.media {
68        if keys.contains(&m.key.as_str()) {
69            problems.push(format!("media `{}` is listed twice", m.key));
70        }
71        keys.push(&m.key);
72        let simple = !m.file.is_empty() && !m.file.contains(['/', '\\']) && !m.file.starts_with('.');
73        if !simple {
74            problems.push(format!("media `{}`: `file` must be a plain file name", m.key));
75        }
76    }
77    let mut used = Vec::new();
78    page_refs(&seed.pages, &mut used);
79    seed.error_pages.iter().for_each(|e| refs(&e.body, &mut used));
80    seed.site.values().for_each(|v| refs(v, &mut used));
81    seed.branding.values().for_each(|v| refs(v, &mut used));
82    for key in used {
83        if !keys.contains(&key) {
84            problems.push(format!("`{REF_PREFIX}{key}` names no `media` entry"));
85        }
86    }
87    problems
88}
89
90/// Store the supplied pictures; returns key → media id (as the editor
91/// stores it: a string).
92pub(super) async fn store(
93    pool: &Pool,
94    org_slug: &str,
95    seeds: &[MediaSeed],
96    files: &[(&str, &[u8])],
97) -> Result<HashMap<String, String>, StarterError> {
98    let mut ids = HashMap::new();
99    for seed in seeds {
100        let Some((_, bytes)) = files.iter().find(|(name, _)| *name == seed.file) else {
101            tracing::warn!(target: "rustango_cms::starter", file = %seed.file, "theme picture not supplied; skipped");
102            continue;
103        };
104        let title = (!seed.title.is_empty()).then_some(seed.title.as_str());
105        let media = crate::admin::store_media(
106            pool,
107            org_slug,
108            bytes.to_vec(),
109            &seed.file,
110            title,
111            &seed.alt,
112            None,
113            None,
114            true,
115        )
116        .await
117        .map_err(|e| StarterError::Invalid(format!("media `{}`: {e}", seed.key)))?;
118        if let Some(id) = media.id.get() {
119            ids.insert(seed.key.clone(), id.to_string());
120        }
121    }
122    Ok(ids)
123}
124
125/// Replace every picture reference in `value` with its media id, or an
126/// empty string when the picture was not stored.
127pub(super) fn resolve(value: &mut Value, ids: &HashMap<String, String>) {
128    match value {
129        Value::String(s) => {
130            if let Some(key) = s.strip_prefix(REF_PREFIX) {
131                *s = ids.get(key).cloned().unwrap_or_default();
132            }
133        }
134        Value::Array(items) => items.iter_mut().for_each(|v| resolve(v, ids)),
135        Value::Object(map) => map.values_mut().for_each(|v| resolve(v, ids)),
136        _ => {}
137    }
138}
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143    use serde_json::json;
144
145    #[test]
146    fn references_become_ids_or_empty() {
147        let ids = HashMap::from([("hills".to_owned(), "7".to_owned())]);
148        let mut data = json!({
149            "cover": "@media:hills",
150            "body": [{ "type": "gallery", "value": { "images": [{ "value": { "image": "@media:sea" } }] } }],
151            "title": "media: not a reference",
152        });
153        resolve(&mut data, &ids);
154        assert_eq!(data["cover"], "7");
155        assert_eq!(data["body"][0]["value"]["images"][0]["value"]["image"], "");
156        assert_eq!(data["title"], "media: not a reference");
157    }
158
159    #[test]
160    fn unknown_references_and_odd_files_are_reported() {
161        let seed: StarterSeed = serde_json::from_value(json!({
162            "name": "t",
163            "media": [
164                { "key": "a", "file": "a.jpg" },
165                { "key": "a", "file": "../b.jpg" }
166            ],
167            "pages": [{ "key": "home", "type": "Home", "title": "Home", "data": { "cover": "@media:missing" } }]
168        }))
169        .unwrap();
170        let found = problems(&seed).join("; ");
171        for expected in ["listed twice", "plain file name", "`@media:missing` names no `media` entry"] {
172            assert!(found.contains(expected), "{expected}: {found}");
173        }
174    }
175}