rustango_cms/
translation.rs1use chrono::{DateTime, Utc};
16use rustango::sql::Auto;
17use rustango::Model;
18use serde::{Deserialize, Serialize};
19
20#[derive(Model, Debug, Clone, Serialize, Deserialize)]
24#[rustango(
25 table = "cms_translation",
26 app = "cms",
27 admin(
28 list_display = "page_id, locale_id, field_path, value, updated_at",
29 ordering = "page_id",
30 list_filter = "locale_id, field_path",
31 )
32)]
33pub struct Translation {
34 #[rustango(primary_key)]
35 pub id: Auto<i64>,
36
37 #[rustango(fk = "cms_page", on = "id", index)]
38 pub page_id: i64,
39
40 #[rustango(fk = "cms_locale", on = "id", index)]
41 pub locale_id: i64,
42
43 #[rustango(max_length = 255, index)]
50 pub field_path: String,
51
52 pub value: String,
54
55 #[rustango(auto_now)]
56 pub updated_at: Auto<DateTime<Utc>>,
57}
58
59pub async fn fetch_for(
66 pool: &rustango::sql::Pool,
67 page_id: i64,
68 locale_id: i64,
69) -> Result<std::collections::HashMap<String, String>, rustango::sql::ExecError> {
70 use rustango::core::Column as _;
71 use rustango::sql::FetcherPool as _;
72
73 let rows: Vec<Translation> = Translation::objects()
74 .where_(Translation::page_id.eq(page_id))
75 .where_(Translation::locale_id.eq(locale_id))
76 .fetch(pool)
77 .await?;
78 Ok(rows
79 .into_iter()
80 .filter(|t| !t.value.is_empty())
81 .map(|t| (t.field_path, t.value))
82 .collect())
83}
84
85pub async fn fetch_for_pages(
99 pool: &rustango::sql::Pool,
100 page_ids: &[i64],
101 locale_id: i64,
102) -> Result<
103 std::collections::HashMap<i64, std::collections::HashMap<String, String>>,
104 rustango::sql::ExecError,
105> {
106 use rustango::core::Column as _;
107 use rustango::sql::FetcherPool as _;
108
109 if page_ids.is_empty() {
110 return Ok(std::collections::HashMap::new());
111 }
112 let rows: Vec<Translation> = Translation::objects()
113 .where_(Translation::locale_id.eq(locale_id))
114 .where_(Translation::page_id.is_in(page_ids.iter().copied()))
115 .fetch(pool)
116 .await?;
117 let mut out: std::collections::HashMap<i64, std::collections::HashMap<String, String>> =
118 std::collections::HashMap::new();
119 for row in rows {
120 if row.value.is_empty() {
121 continue;
122 }
123 out.entry(row.page_id)
124 .or_default()
125 .insert(row.field_path, row.value);
126 }
127 Ok(out)
128}
129
130pub fn overlay_translations(
148 value: &mut serde_json::Value,
149 by_page: &std::collections::HashMap<i64, std::collections::HashMap<String, String>>,
150) {
151 match value {
152 serde_json::Value::Object(map) => {
153 let pid = map
154 .get("page_id")
155 .or_else(|| map.get("id"))
156 .and_then(serde_json::Value::as_i64);
157 if let Some(tr) = pid.and_then(|p| by_page.get(&p)) {
158 for (field_path, translated) in tr {
159 if !field_path.contains('.')
160 && !translated.is_empty()
161 && map.contains_key(field_path)
162 {
163 map.insert(
164 field_path.clone(),
165 serde_json::Value::String(translated.clone()),
166 );
167 }
168 }
169 }
170 for v in map.values_mut() {
171 overlay_translations(v, by_page);
172 }
173 }
174 serde_json::Value::Array(arr) => {
175 for v in arr.iter_mut() {
176 overlay_translations(v, by_page);
177 }
178 }
179 _ => {}
180 }
181}
182
183pub fn validate_field_path(raw: &str) -> Result<String, String> {
194 let p = raw.trim();
195 if p.is_empty() {
196 return Err("Field name is required.".to_owned());
197 }
198 if p.chars().count() > 255 {
199 return Err("Field name is too long (max 255 characters).".to_owned());
200 }
201 if !p
202 .chars()
203 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.' || c == '-')
204 {
205 return Err("Field name may only contain letters, digits, '_', '.' and '-'.".to_owned());
206 }
207 Ok(p.to_owned())
208}
209
210pub async fn resolve_locale(
221 pool: &rustango::sql::Pool,
222 explicit_code: Option<&str>,
223) -> Result<Option<crate::locale::Locale>, rustango::sql::ExecError> {
224 use rustango::core::Column as _;
225 use rustango::sql::FetcherPool as _;
226 if let Some(code) = explicit_code {
227 let mut hits: Vec<crate::locale::Locale> = crate::locale::Locale::objects()
228 .where_(crate::locale::Locale::code.eq(code.to_owned()))
229 .where_(crate::locale::Locale::active.eq(true))
230 .fetch(pool)
231 .await?;
232 if let Some(l) = hits.pop() {
233 return Ok(Some(l));
234 }
235 }
239 let mut defaults: Vec<crate::locale::Locale> = crate::locale::Locale::objects()
240 .where_(crate::locale::Locale::is_default.eq(true))
241 .fetch(pool)
242 .await?;
243 Ok(defaults.pop())
244}
245
246pub fn register_tera_filter(tera: &mut tera::Tera) {
257 tera.register_filter("t", t_filter);
258}
259
260fn t_filter(
261 value: &tera::Value,
262 args: &std::collections::HashMap<String, tera::Value>,
263) -> tera::Result<tera::Value> {
264 let field = args
265 .get("field")
266 .and_then(tera::Value::as_str)
267 .ok_or_else(|| tera::Error::msg("t filter: `field` (string) is required"))?;
268
269 if let Some(map) = args.get("translations").and_then(tera::Value::as_object) {
273 if let Some(v) = map.get(field).and_then(tera::Value::as_str) {
274 if !v.is_empty() {
275 return Ok(tera::Value::String(v.to_owned()));
276 }
277 }
278 }
279
280 if let (Some(by_page), Some(page_id)) = (args.get("by_page"), args.get("page_id")) {
284 let key = match page_id {
285 tera::Value::Number(n) => n.to_string(),
286 tera::Value::String(s) => s.clone(),
287 _ => String::new(),
288 };
289 if let Some(per_page) = by_page.as_object().and_then(|m| m.get(&key)) {
290 if let Some(v) = per_page
291 .as_object()
292 .and_then(|m| m.get(field))
293 .and_then(tera::Value::as_str)
294 {
295 if !v.is_empty() {
296 return Ok(tera::Value::String(v.to_owned()));
297 }
298 }
299 }
300 }
301
302 Ok(value.clone())
303}
304
305#[cfg(test)]
306mod tests {
307 use super::validate_field_path;
308
309 #[test]
310 fn validate_field_path_accepts_scalar_dotted_and_block_paths() {
311 assert_eq!(validate_field_path("title").unwrap(), "title");
312 assert_eq!(validate_field_path(" body ").unwrap(), "body");
313 let p = "body.550e8400-e29b-41d4-a716-446655440000.title";
315 assert_eq!(validate_field_path(p).unwrap(), p);
316 let nested = "body.550e8400-e29b-41d4-a716-446655440000.params.\
317 11111111-2222-3333-4444-555555555555.description";
318 assert_eq!(validate_field_path(nested).unwrap(), nested);
319 }
320
321 #[test]
322 fn validate_field_path_rejects_garbage_and_overlong() {
323 assert!(validate_field_path("").is_err());
324 assert!(validate_field_path(" ").is_err());
325 assert!(validate_field_path("has space").is_err());
326 assert!(validate_field_path("semi;colon").is_err());
327 assert!(validate_field_path(&"x".repeat(256)).is_err());
328 assert!(validate_field_path(&"a".repeat(255)).is_ok());
329 }
330}