Skip to main content

rustango_cms/
branding.rs

1//! A site's branding: its name, logo and browser icon, kept in one place
2//! (the `branding` site setting, edited under **Settings → Branding**)
3//! and used everywhere: the admin sidebar and sign-in screens, and the
4//! public site's layout.
5//!
6//! The logo and icon are pictures in the media library, stored as media
7//! ids (`logo`, `favicon`). Sites set up before that kept uploaded files
8//! instead (`logo_storage_key`, `favicon_storage_key`, under the tenant's
9//! `branding/` folder); those still serve, and [`migrate_uploads`] moves
10//! them into the media library.
11//!
12//! Both pictures are served from stable addresses, `/__cms-branding/logo`
13//! and `/__cms-branding/favicon`, so pages never need the media id.
14
15use rustango::core::Column as _;
16use rustango::sql::Pool;
17use rustango::tenancy::Org;
18use serde_json::Value;
19
20use crate::media::Media;
21
22/// Site-setting scope holding the branding.
23pub const SCOPE: &str = "branding";
24
25/// One of the two branding pictures.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum Picture {
28    Logo,
29    Favicon,
30}
31
32impl Picture {
33    /// The setting key holding the media id.
34    #[must_use]
35    pub fn key(self) -> &'static str {
36        match self {
37            Self::Logo => "logo",
38            Self::Favicon => "favicon",
39        }
40    }
41
42    /// The older key holding an uploaded file's name.
43    fn upload_key(self) -> &'static str {
44        match self {
45            Self::Logo => "logo_storage_key",
46            Self::Favicon => "favicon_storage_key",
47        }
48    }
49
50    fn title(self) -> &'static str {
51        match self {
52            Self::Logo => "Logo",
53            Self::Favicon => "Site icon",
54        }
55    }
56
57    /// The address the picture is served from.
58    #[must_use]
59    pub fn url(self) -> &'static str {
60        match self {
61            Self::Logo => "/__cms-branding/logo",
62            Self::Favicon => "/__cms-branding/favicon",
63        }
64    }
65}
66
67fn text<'a>(value: &'a Value, key: &str) -> Option<&'a str> {
68    value.get(key).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty())
69}
70
71/// The branding setting's value (`{}` when unset).
72pub async fn get(pool: &Pool) -> Value {
73    crate::site_setting::get(pool, SCOPE)
74        .await
75        .ok()
76        .flatten()
77        .map_or_else(|| Value::Object(serde_json::Map::new()), |r| r.value_json)
78}
79
80/// Whether `branding` has this picture, as a media id or an uploaded file.
81#[must_use]
82pub fn has(branding: &Value, picture: Picture) -> bool {
83    text(branding, picture.key()).is_some() || text(branding, picture.upload_key()).is_some()
84}
85
86/// The site's name: the Branding site name, else the operator's brand
87/// name for the tenant, else its display name.
88#[must_use]
89pub fn site_name(branding: &Value, org: &Org) -> String {
90    name_from(branding, org.brand_name.as_deref(), &org.display_name)
91}
92
93fn name_from(branding: &Value, brand_name: Option<&str>, display_name: &str) -> String {
94    text(branding, "site_name")
95        .or_else(|| brand_name.map(str::trim).filter(|n| !n.is_empty()))
96        .unwrap_or(display_name)
97        .to_owned()
98}
99
100/// The picture's bytes and mime type, if set and stored.
101pub async fn load(pool: &Pool, org_slug: &str, branding: &Value, picture: Picture) -> Option<(String, Vec<u8>)> {
102    let disk = crate::media_storage::disk_for(org_slug);
103    if let Some(id) = text(branding, picture.key()).and_then(|s| s.parse::<i64>().ok()) {
104        let media = Media::objects().where_(Media::id.eq(id)).first(pool).await.ok().flatten()?;
105        let bytes = disk.load(&crate::media_storage::key(org_slug, &media.storage_key)).await.ok()?;
106        return Some((media.mime, bytes));
107    }
108    let name = text(branding, picture.upload_key())?;
109    // The name comes from a setting the CMS wrote; still never let it
110    // leave the branding folder.
111    if name.contains('/') || name.contains("..") {
112        return None;
113    }
114    let bytes = disk.load(&crate::media_storage::key(org_slug, &format!("branding/{name}"))).await.ok()?;
115    let mime = mime_guess::from_path(name).first_or_octet_stream().essence_str().to_owned();
116    Some((mime, bytes))
117}
118
119/// Move pictures uploaded before branding used the media library into it,
120/// so the Branding form can show and change them. Idempotent; a picture
121/// that can't be read is left as it is.
122pub async fn migrate_uploads(pool: &Pool, org_slug: &str) {
123    let mut branding = get(pool).await;
124    let mut changed = false;
125    for picture in [Picture::Logo, Picture::Favicon] {
126        if text(&branding, picture.key()).is_some() {
127            continue;
128        }
129        let Some(name) = text(&branding, picture.upload_key()).map(str::to_owned) else { continue };
130        let Some((_, bytes)) = load(pool, org_slug, &branding, picture).await else { continue };
131        match crate::admin::store_media(pool, org_slug, bytes, &name, Some(picture.title()), "", None, None, true).await {
132            Ok(media) => {
133                if let (Some(id), Some(map)) = (media.id.get(), branding.as_object_mut()) {
134                    map.insert(picture.key().to_owned(), Value::String(id.to_string()));
135                    map.remove(picture.upload_key());
136                    changed = true;
137                }
138            }
139            Err(e) => tracing::warn!(target: "rustango_cms::branding", error = %e, "could not move a branding upload into the media library"),
140        }
141    }
142    if changed {
143        if let Err(e) = crate::site_setting::upsert(pool, SCOPE, branding).await {
144            tracing::warn!(target: "rustango_cms::branding", error = %e, "could not save branding");
145        }
146    }
147}
148
149#[cfg(test)]
150mod tests {
151    use super::*;
152    use serde_json::json;
153
154    #[test]
155    fn the_site_name_comes_from_branding_first() {
156        assert_eq!(name_from(&json!({ "site_name": " Studio " }), Some("Acme"), "demo"), "Studio");
157        assert_eq!(name_from(&json!({ "site_name": "" }), Some("Acme"), "demo"), "Acme");
158        assert_eq!(name_from(&json!({}), None, "demo"), "demo");
159    }
160
161    #[test]
162    fn a_picture_counts_as_a_media_id_or_an_old_upload() {
163        assert!(has(&json!({ "logo": "7" }), Picture::Logo));
164        assert!(has(&json!({ "logo_storage_key": "logo.png" }), Picture::Logo));
165        assert!(!has(&json!({ "logo": "" }), Picture::Logo));
166        assert!(!has(&json!({ "logo": "7" }), Picture::Favicon));
167    }
168}