1use rustango::core::Column as _;
16use rustango::sql::Pool;
17use rustango::tenancy::Org;
18use serde_json::Value;
19
20use crate::media::Media;
21
22pub const SCOPE: &str = "branding";
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum Picture {
28 Logo,
29 Favicon,
30}
31
32impl Picture {
33 #[must_use]
35 pub fn key(self) -> &'static str {
36 match self {
37 Self::Logo => "logo",
38 Self::Favicon => "favicon",
39 }
40 }
41
42 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 #[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
71pub 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#[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#[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
100pub 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 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
119pub 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}