rustpbx 0.4.9

A SIP PBX implementation in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::RwLock;

/// Flat translation map: "nav.dashboard" -> "Dashboard"
pub type Translations = HashMap<String, String>;

/// Info about a single locale exposed to templates
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LocaleInfo {
    pub code: String,
    pub name: String,
    pub native_name: String,
}

impl From<(&String, &crate::config::LocaleInfo)> for LocaleInfo {
    fn from((code, info): (&String, &crate::config::LocaleInfo)) -> Self {
        Self {
            code: code.clone(),
            name: info.name.clone(),
            native_name: info.native_name.clone(),
        }
    }
}

/// i18n configuration
#[derive(Debug, Clone)]
pub struct LocaleConfig {
    pub default: String,
    pub available: Vec<LocaleInfo>,
}

impl From<&crate::config::ConsoleConfig> for LocaleConfig {
    fn from(config: &crate::config::ConsoleConfig) -> Self {
        Self {
            default: config.locale_default.clone(),
            available: config.locales.iter().map(LocaleInfo::from).collect(),
        }
    }
}

/// Central i18n manager.
///
/// Loads TOML translation files from a base `locales/` directory and from
/// additional addon-provided directories.  All translations are kept in
/// memory as flat `"section.key" -> "value"` maps so lookups are O(1).
pub struct I18n {
    /// lang code -> flat translation map
    translations: RwLock<HashMap<String, Translations>>,
    config: LocaleConfig,
    core_locales_dir: String,
    /// Extra locale directories registered by addons
    addon_locales_dirs: RwLock<Vec<String>>,
}

impl I18n {
    /// Create a new I18n instance and eagerly load translations from disk.
    pub fn new(config: LocaleConfig) -> Self {
        Self::new_with_core_dir(config, "locales".to_string())
    }

    fn new_with_core_dir(config: LocaleConfig, core_locales_dir: String) -> Self {
        let i18n = Self {
            translations: RwLock::new(HashMap::new()),
            config,
            core_locales_dir,
            addon_locales_dirs: RwLock::new(vec![]),
        };
        i18n.reload();
        i18n
    }

    // ------------------------------------------------------------------
    // Loading
    // ------------------------------------------------------------------

    /// (Re)load all translations from disk, replacing the current cache.
    pub fn reload(&self) {
        let mut cache = match self.translations.write() {
            Ok(g) => g,
            Err(e) => {
                tracing::error!("i18n: failed to acquire write lock: {}", e);
                return;
            }
        };
        cache.clear();

        // Load core locales
        let addon_dirs = self
            .addon_locales_dirs
            .read()
            .unwrap_or_else(|e| e.into_inner());
        for info in &self.config.available {
            let mut flat = Self::load_or_empty(&self.core_locales_dir, &info.code, false);
            // Merge enabled addon locales on top
            for dir in addon_dirs.iter() {
                Self::merge_locale_dir(&mut flat, dir, &info.code);
            }
            cache.insert(info.code.clone(), flat);
        }
    }

    fn load_or_empty(base_dir: &str, locale: &str, addon: bool) -> Translations {
        match Self::load_file(base_dir, locale) {
            Ok(flat) => flat,
            Err(e) => {
                if addon {
                    tracing::debug!(
                        "i18n: failed to load addon locale {}/{}.toml: {}",
                        base_dir,
                        locale,
                        e
                    );
                } else {
                    tracing::warn!("i18n: failed to load {}/{}.toml: {}", base_dir, locale, e);
                }
                Translations::new()
            }
        }
    }

    fn merge_locale_dir(flat: &mut Translations, dir: &str, locale: &str) {
        flat.extend(Self::load_or_empty(dir, locale, true));
    }

    /// Load a single `{base_dir}/{locale}.toml` file and flatten it.
    fn load_file(base_dir: &str, locale: &str) -> anyhow::Result<Translations> {
        let path = format!("{}/{}.toml", base_dir, locale);
        let content = std::fs::read_to_string(&path)
            .map_err(|e| anyhow::anyhow!("i18n: cannot read {}: {}", path, e))?;
        let value: toml::Value = toml::from_str(&content)
            .map_err(|e| anyhow::anyhow!("i18n: cannot parse {}: {}", path, e))?;
        let mut flat = Translations::new();
        Self::flatten_value(&value, String::new(), &mut flat);
        Ok(flat)
    }

    /// Recursively flatten a TOML value into dot-separated keys.
    ///
    /// `{"nav": {"dashboard": "Dashboard"}}` → `"nav.dashboard" = "Dashboard"`
    fn flatten_value(value: &toml::Value, prefix: String, out: &mut Translations) {
        match value {
            toml::Value::Table(table) => {
                for (k, v) in table {
                    let new_prefix = if prefix.is_empty() {
                        k.clone()
                    } else {
                        format!("{}.{}", prefix, k)
                    };
                    Self::flatten_value(v, new_prefix, out);
                }
            }
            toml::Value::String(s) => {
                out.insert(prefix, s.clone());
            }
            other => {
                // Convert non-string leaves (booleans, integers, …) to strings
                out.insert(prefix, other.to_string());
            }
        }
    }

    // ------------------------------------------------------------------
    // Addon support
    // ------------------------------------------------------------------

    /// Register an additional locale directory (provided by an addon) and
    /// immediately reload all translations so the new strings are available.
    pub fn register_addon_locales(&self, addon_id: &str, locales_dir: String) {
        {
            let mut dirs = self
                .addon_locales_dirs
                .write()
                .unwrap_or_else(|e| e.into_inner());
            tracing::debug!(
                "i18n: registering addon '{}' locales at '{}'",
                addon_id,
                locales_dir
            );
            dirs.push(locales_dir);
        }
        self.reload();
    }

    /// Register multiple addon locale directories and reload once.
    pub fn register_addon_locales_bulk(&self, locale_dirs: Vec<(String, String)>) {
        {
            let mut dirs = self
                .addon_locales_dirs
                .write()
                .unwrap_or_else(|e| e.into_inner());
            for (addon_id, locales_dir) in locale_dirs {
                tracing::debug!(
                    "i18n: registering addon '{}' locales at '{}'",
                    addon_id,
                    locales_dir
                );
                dirs.push(locales_dir);
            }
        }
        self.reload();
    }

    // ------------------------------------------------------------------
    // Translation lookups
    // ------------------------------------------------------------------

    /// Look up a translation key for the given locale.
    ///
    /// Falls back to `self.config.default` if the key is missing in the
    /// requested locale, and finally returns the key itself as a last resort.
    pub fn t(&self, locale: &str, key: &str) -> String {
        let cache = self.translations.read().unwrap_or_else(|e| e.into_inner());

        // 1. Requested locale
        if let Some(flat) = cache.get(locale)
            && let Some(v) = flat.get(key)
        {
            return v.clone();
        }

        // 2. Default locale fallback
        if locale != self.config.default
            && let Some(flat) = cache.get(&self.config.default)
            && let Some(v) = flat.get(key)
        {
            return v.clone();
        }

        // 3. Return the key itself so templates always render something
        key.to_string()
    }

    /// Look up a key and replace `{{var}}` placeholders with values from `vars`.
    pub fn t_with_vars(&self, locale: &str, key: &str, vars: &HashMap<String, String>) -> String {
        let mut text = self.t(locale, key);
        for (k, v) in vars {
            text = text.replace(&format!("{{{{{}}}}}", k), v);
        }
        text
    }

    /// Return the full translation map for a locale as a nested
    /// `serde_json::Value` object suitable for injection into template context.
    ///
    /// The flat `"nav.dashboard"` key is re-hydrated into
    /// `{"nav": {"dashboard": "…"}}`.
    pub fn get_translations_json(&self, locale: &str) -> serde_json::Value {
        let cache = self.translations.read().unwrap_or_else(|e| e.into_inner());

        let flat = cache
            .get(locale)
            .or_else(|| cache.get(&self.config.default));

        let mut root = serde_json::Map::new();
        if let Some(flat) = flat {
            for (dotted_key, value) in flat {
                Self::set_nested(
                    &mut root,
                    dotted_key,
                    serde_json::Value::String(value.clone()),
                );
            }
        }
        serde_json::Value::Object(root)
    }

    pub fn available_locales_json(&self) -> serde_json::Value {
        serde_json::to_value(self.available_locales()).unwrap_or(serde_json::Value::Array(vec![]))
    }

    /// Insert a value at a dot-separated path inside a JSON map.
    fn set_nested(
        map: &mut serde_json::Map<String, serde_json::Value>,
        key: &str,
        value: serde_json::Value,
    ) {
        let mut parts = key.splitn(2, '.');
        let head = match parts.next() {
            Some(h) => h,
            None => return,
        };

        if let Some(tail) = parts.next() {
            // Recurse into (or create) the nested object
            let child = map
                .entry(head.to_string())
                .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
            if let serde_json::Value::Object(ref mut m) = *child {
                Self::set_nested(m, tail, value);
            }
        } else {
            map.insert(head.to_string(), value);
        }
    }

    // ------------------------------------------------------------------
    // Accessors
    // ------------------------------------------------------------------

    pub fn available_locales(&self) -> &[LocaleInfo] {
        &self.config.available
    }

    pub fn default_locale(&self) -> &str {
        &self.config.default
    }
}

// ------------------------------------------------------------------
// Request-level locale detection
// ------------------------------------------------------------------

/// Detect the user's preferred locale from (in order of priority):
/// 1. A `locale` cookie
/// 2. The `Accept-Language` HTTP header
/// 3. The configured default
pub fn detect_locale(
    headers: &axum::http::HeaderMap,
    available: &[LocaleInfo],
    default: &str,
) -> String {
    // 1. Cookie takes highest priority
    if let Some(val) = get_cookie(headers, "locale")
        && is_available(&val, available)
    {
        return val;
    }

    // 2. Accept-Language header
    if let Some(accept) = headers.get(axum::http::header::ACCEPT_LANGUAGE)
        && let Ok(s) = accept.to_str()
    {
        // Parse "zh-CN,zh;q=0.9,en;q=0.8" style values
        let mut candidates: Vec<(&str, f32)> = s
            .split(',')
            .filter_map(|item| {
                let mut parts = item.trim().splitn(2, ';');
                let tag = parts.next()?.trim();
                let q: f32 = parts
                    .next()
                    .and_then(|p| p.trim().strip_prefix("q="))
                    .and_then(|q| q.parse().ok())
                    .unwrap_or(1.0);
                Some((tag, q))
            })
            .collect();
        candidates.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
        for (tag, _) in candidates {
            // Match full tag first ("zh-CN"), then base language ("zh")
            if is_available(tag, available) {
                return tag.to_string();
            }
            let base = tag.split('-').next().unwrap_or(tag);
            if is_available(base, available) {
                return base.to_string();
            }
        }
    }

    // 3. Default
    default.to_string()
}

pub(crate) fn get_cookie(headers: &axum::http::HeaderMap, name: &str) -> Option<String> {
    use axum::http::header::COOKIE;

    for cookie_header in headers.get_all(COOKIE) {
        if let Ok(s) = cookie_header.to_str() {
            let found = s.split(';').find_map(|pair| {
                let mut kv = pair.trim().splitn(2, '=');
                if kv.next().map(str::trim) == Some(name) {
                    Some(kv.next().unwrap_or("").trim().to_string())
                } else {
                    None
                }
            });
            if let Some(found) = found
                && !found.is_empty()
            {
                return Some(found);
            }
        }
    }
    None
}

fn is_available(code: &str, available: &[LocaleInfo]) -> bool {
    available.iter().any(|l| l.code == code)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::TempDir;

    /// Build a minimal I18n with two in-memory locale files written to a tmpdir.
    fn make_i18n(tmp: &TempDir) -> I18n {
        let dir = tmp.path().join("locales");
        std::fs::create_dir_all(&dir).unwrap();

        // English
        let mut f = std::fs::File::create(dir.join("en.toml")).unwrap();
        writeln!(
            f,
            r#"
[common]
save = "Save"
cancel = "Cancel"

[messages]
saved = "{{{{name}}}} saved."
"#
        )
        .unwrap();

        // Chinese
        let mut f = std::fs::File::create(dir.join("zh.toml")).unwrap();
        writeln!(
            f,
            r#"
[common]
save = "保存"
"#
        )
        .unwrap();

        let config = LocaleConfig {
            default: "en".to_string(),
            available: vec![
                LocaleInfo {
                    code: "en".into(),
                    name: "English".into(),
                    native_name: "English".into(),
                },
                LocaleInfo {
                    code: "zh".into(),
                    name: "Chinese".into(),
                    native_name: "中文".into(),
                },
            ],
        };

        I18n::new_with_core_dir(config, dir.to_string_lossy().to_string())
    }

    #[test]
    fn lookup_existing_key() {
        let tmp = TempDir::new().unwrap();
        let i18n = make_i18n(&tmp);
        assert_eq!(i18n.t("en", "common.save"), "Save");
        assert_eq!(i18n.t("zh", "common.save"), "保存");
    }

    #[test]
    fn fallback_to_default_locale() {
        let tmp = TempDir::new().unwrap();
        let i18n = make_i18n(&tmp);
        // "common.cancel" is only in English
        assert_eq!(i18n.t("zh", "common.cancel"), "Cancel");
    }

    #[test]
    fn fallback_to_key_when_missing() {
        let tmp = TempDir::new().unwrap();
        let i18n = make_i18n(&tmp);
        assert_eq!(i18n.t("en", "nonexistent.key"), "nonexistent.key");
    }

    #[test]
    fn variable_interpolation() {
        let tmp = TempDir::new().unwrap();
        let i18n = make_i18n(&tmp);
        let mut vars = std::collections::HashMap::new();
        vars.insert("name".to_string(), "Extension 100".to_string());
        assert_eq!(
            i18n.t_with_vars("en", "messages.saved", &vars),
            "Extension 100 saved."
        );
    }

    #[test]
    fn get_translations_json_is_nested() {
        let tmp = TempDir::new().unwrap();
        let i18n = make_i18n(&tmp);
        let json = i18n.get_translations_json("en");
        let save = &json["common"]["save"];
        assert_eq!(save.as_str().unwrap(), "Save");
    }

    #[test]
    fn detect_locale_from_cookie() {
        let mut headers = axum::http::HeaderMap::new();
        headers.insert(
            axum::http::header::COOKIE,
            "locale=zh; rustpbx_session=abc".parse().unwrap(),
        );
        let available = vec![
            LocaleInfo {
                code: "en".into(),
                name: "English".into(),
                native_name: "English".into(),
            },
            LocaleInfo {
                code: "zh".into(),
                name: "Chinese".into(),
                native_name: "中文".into(),
            },
        ];
        assert_eq!(detect_locale(&headers, &available, "en"), "zh");
    }

    #[test]
    fn detect_locale_from_accept_language() {
        let mut headers = axum::http::HeaderMap::new();
        headers.insert(
            axum::http::header::ACCEPT_LANGUAGE,
            "zh-CN,zh;q=0.9,en;q=0.8".parse().unwrap(),
        );
        let available = vec![
            LocaleInfo {
                code: "en".into(),
                name: "English".into(),
                native_name: "English".into(),
            },
            LocaleInfo {
                code: "zh".into(),
                name: "Chinese".into(),
                native_name: "中文".into(),
            },
        ];
        assert_eq!(detect_locale(&headers, &available, "en"), "zh");
    }

    #[test]
    fn detect_locale_defaults_when_unsupported() {
        let headers = axum::http::HeaderMap::new();
        let available = vec![LocaleInfo {
            code: "en".into(),
            name: "English".into(),
            native_name: "English".into(),
        }];
        assert_eq!(detect_locale(&headers, &available, "en"), "en");
    }
}