use std::cell::RefCell;
use std::collections::HashMap;
use std::future::Future;
use std::path::Path;
use std::sync::RwLock;
use crate::context::Context;
use crate::error::Error;
use crate::handler::BoxFuture;
use crate::middleware::{Middleware, Next};
use crate::response::{IntoResponse, Response};
pub const DEFAULT: &str = "en";
tokio::task_local! {
static LOCALE: RefCell<String>;
}
pub fn locale() -> String {
LOCALE
.try_with(|locale| locale.borrow().clone())
.unwrap_or_else(|_| DEFAULT.to_owned())
}
pub(crate) fn chosen() -> Option<String> {
LOCALE.try_with(|locale| locale.borrow().clone()).ok()
}
pub async fn with_locale<F: Future>(locale: impl Into<String>, fut: F) -> F::Output {
LOCALE.scope(RefCell::new(locale.into()), fut).await
}
pub fn set_locale(locale: impl Into<String>) {
let locale = locale.into();
let _ = LOCALE.try_with(|current| *current.borrow_mut() = locale);
}
static TRANSLATIONS: RwLock<Option<HashMap<String, String>>> = RwLock::new(None);
pub fn load(dir: impl AsRef<Path>) -> crate::Result<()> {
let dir = dir.as_ref();
let mut files: Vec<_> = std::fs::read_dir(dir)
.map_err(|e| Error::internal(format!("reading {}: {e}", dir.display())))?
.filter_map(|entry| entry.ok().map(|e| e.path()))
.filter(|path| {
path.extension()
.is_some_and(|ext| ext == "yml" || ext == "yaml")
})
.collect();
files.sort();
let mut sources = Vec::new();
for file in files {
let text = std::fs::read_to_string(&file)
.map_err(|e| Error::internal(format!("reading {}: {e}", file.display())))?;
sources.push((file.display().to_string(), text));
}
let sources: Vec<(&str, &str)> = sources
.iter()
.map(|(name, text)| (name.as_str(), text.as_str()))
.collect();
load_sources(&sources)
}
pub fn load_sources(sources: &[(&str, &str)]) -> crate::Result<()> {
let mut translations = HashMap::new();
for (name, text) in sources {
let yaml: serde_yaml::Value =
serde_yaml::from_str(text).map_err(|e| Error::internal(format!("{name}: {e}")))?;
flatten(String::new(), &yaml, &mut translations);
}
*TRANSLATIONS.write().unwrap_or_else(|e| e.into_inner()) = Some(translations);
Ok(())
}
fn flatten(prefix: String, value: &serde_yaml::Value, out: &mut HashMap<String, String>) {
use serde_yaml::Value as Y;
let text = match value {
Y::Mapping(map) => {
for (key, value) in map {
let key = match key {
Y::String(s) => s.clone(),
Y::Bool(b) => b.to_string(),
Y::Number(n) => n.to_string(),
_ => continue,
};
let path = if prefix.is_empty() {
key
} else {
format!("{prefix}.{key}")
};
flatten(path, value, out);
}
return;
}
Y::String(s) => s.clone(),
Y::Bool(b) => b.to_string(),
Y::Number(n) => n.to_string(),
_ => return,
};
out.insert(prefix, text);
}
fn lookup(full: &str) -> Option<String> {
TRANSLATIONS
.read()
.unwrap_or_else(|e| e.into_inner())
.as_ref()
.and_then(|translations| translations.get(full).cloned())
}
pub fn t(key: impl AsRef<str>) -> String {
let full = format!("{}.{}", locale(), key.as_ref());
lookup(&full).unwrap_or_else(|| format!("Translation missing: {full}"))
}
pub fn t_count(key: impl AsRef<str>, count: i64) -> String {
t_args(key, &[("count", count.to_string())])
}
pub fn t_args(key: impl AsRef<str>, args: &[(&str, String)]) -> String {
let key = key.as_ref();
let locale = locale();
let count = args
.iter()
.find(|(name, _)| *name == "count")
.and_then(|(_, value)| value.parse::<i64>().ok());
let full = format!("{locale}.{key}");
let text = match count {
Some(count) => {
let forms = [
(count == 0).then_some("zero"),
Some(plural(&locale, count)),
Some("other"),
];
forms
.into_iter()
.flatten()
.find_map(|form| lookup(&format!("{full}.{form}")))
.or_else(|| lookup(&full))
}
None => lookup(&full),
};
let text = text.unwrap_or_else(|| format!("Translation missing: {full}"));
args.iter().fold(text, |text, (name, value)| {
text.replace(&format!("%{{{name}}}"), value)
})
}
pub fn plural(locale: &str, n: i64) -> &'static str {
let language = locale
.split(['-', '_'])
.next()
.unwrap_or(locale)
.to_ascii_lowercase();
let n = n.unsigned_abs();
let (ten, hundred) = (n % 10, n % 100);
match language.as_str() {
"ja" | "zh" | "ko" | "vi" | "th" | "id" | "ms" => "other",
"fr" | "pt" | "hi" | "fa" => {
if n <= 1 {
"one"
} else {
"other"
}
}
"ru" | "uk" | "be" | "sr" | "hr" | "bs" => {
if ten == 1 && hundred != 11 {
"one"
} else if (2..=4).contains(&ten) && !(12..=14).contains(&hundred) {
"few"
} else {
"many"
}
}
"pl" => {
if n == 1 {
"one"
} else if (2..=4).contains(&ten) && !(12..=14).contains(&hundred) {
"few"
} else {
"many"
}
}
"cs" | "sk" => match n {
1 => "one",
2..=4 => "few",
_ => "other",
},
"he" => match n {
1 => "one",
2 => "two",
_ => "other",
},
"ar" => match (n, hundred) {
(0, _) => "zero",
(1, _) => "one",
(2, _) => "two",
(_, 3..=10) => "few",
(_, 11..=99) => "many",
_ => "other",
},
_ => {
if n == 1 {
"one"
} else {
"other"
}
}
}
}
pub fn t_with(key: impl AsRef<str>, values: &[(&str, &str)]) -> String {
values.iter().fold(t(key), |text, (name, value)| {
text.replace(&format!("%{{{name}}}"), value)
})
}
pub struct Locales {
available: Vec<String>,
}
impl Locales {
pub fn new<S: Into<String>>(available: impl IntoIterator<Item = S>) -> Self {
let available: Vec<String> = available.into_iter().map(Into::into).collect();
assert!(
!available.is_empty(),
"Locales::new needs at least one locale"
);
Self { available }
}
}
impl Locales {
fn matching(&self, tag: &str) -> Option<String> {
let tag = tag.trim();
self.available
.iter()
.find(|l| l.eq_ignore_ascii_case(tag))
.or_else(|| {
let language = tag.split(['-', '_']).next()?;
self.available
.iter()
.find(|l| l.eq_ignore_ascii_case(language))
})
.cloned()
}
fn best_accepted(&self, header: &str) -> Option<String> {
let mut tags: Vec<(f32, &str)> = header
.split(',')
.filter_map(|part| {
let mut pieces = part.split(';');
let tag = pieces.next()?.trim();
let q = pieces
.find_map(|p| p.trim().strip_prefix("q="))
.and_then(|q| q.parse::<f32>().ok())
.unwrap_or(1.0);
(!tag.is_empty() && tag != "*" && q > 0.0).then_some((q, tag))
})
.collect();
tags.sort_by(|a, b| b.0.total_cmp(&a.0));
tags.into_iter().find_map(|(_, tag)| self.matching(tag))
}
}
impl Middleware for Locales {
fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
let requested = ctx.params().get("locale").map(str::to_owned);
let locale = match requested {
Some(locale) if self.available.contains(&locale) => {
ctx.cookies().add(
crate::cookies::Cookie::build(("locale", locale.clone()))
.path("/")
.max_age(cookie::time::Duration::days(365))
.same_site(crate::cookies::SameSite::Lax),
);
locale
}
Some(locale) => {
let error = Error::bad_request(format!("\"{locale}\" is not a valid locale"));
return Box::pin(async move { error.into_response() });
}
None => ctx
.cookies()
.get("locale")
.filter(|locale| self.available.contains(locale))
.or_else(|| {
ctx.header(http::header::ACCEPT_LANGUAGE)
.and_then(|header| self.best_accepted(header))
})
.unwrap_or_else(|| self.available[0].clone()),
};
Box::pin(LOCALE.scope(RefCell::new(locale), next.run(ctx)))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::app::App;
use crate::testing::TestClient;
#[tokio::test]
async fn sets_the_locale_from_the_param() {
let app = App::new()
.middleware(Locales::new(["en", "he"]))
.routes(|r| {
r.get("/", |_ctx| async { locale() });
});
let client = TestClient::new(app);
assert_eq!(client.get("/").await.body_text(), "en");
assert_eq!(client.get("/?locale=he").await.body_text(), "he");
let unknown = client.get("/?locale=xx").await;
assert_eq!(unknown.status(), 400);
assert_eq!(locale(), DEFAULT, "outside a request");
assert_eq!(with_locale("he", async { locale() }).await, "he");
}
static LOADING: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
#[tokio::test]
async fn translates_from_rails_locale_files() {
let _loading = LOADING.lock().await;
let dir = std::env::temp_dir().join(format!("glacier-i18n-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("en.yml"),
"en:\n versions:\n ios:\n warning: Update soon\n errors:\n not_found: Not found\n busy: \"In use on %{device} (%{device})\"\n",
)
.unwrap();
std::fs::write(
dir.join("he.yml"),
"he:\n errors:\n not_found: \"לא נמצא\"\n",
)
.unwrap();
load(&dir).unwrap();
assert_eq!(t("versions.ios.warning"), "Update soon");
assert_eq!(
t_with("errors.busy", &[("device", "iPad")]),
"In use on iPad (iPad)"
);
assert_eq!(
with_locale("he", async { t("errors.not_found") }).await,
"לא נמצא"
);
assert_eq!(
with_locale("he", async { t("versions.ios.warning") }).await,
"Translation missing: he.versions.ios.warning"
);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn plural_forms_follow_each_language() {
assert_eq!(plural("en", 1), "one");
assert_eq!(plural("en-GB", 2), "other");
assert_eq!(plural("fr", 0), "one");
assert_eq!(plural("ja", 1), "other");
assert_eq!(plural("ru", 21), "one");
assert_eq!(plural("ru", 3), "few");
assert_eq!(plural("ru", 12), "many");
assert_eq!(plural("pl", 22), "few");
assert_eq!(plural("pl", 5), "many");
assert_eq!(plural("ar", 0), "zero");
assert_eq!(plural("ar", 105), "few");
}
#[tokio::test]
async fn counts_pick_plural_forms() {
let _loading = LOADING.lock().await;
load_sources(&[(
"en.yml",
"en:\n inbox:\n zero: No messages\n one: \"%{count} message\"\n other: \"%{count} messages for %{name}\"\n plain: \"%{count} things\"\nru:\n files:\n one: \"%{count} файл\"\n few: \"%{count} файла\"\n many: \"%{count} файлов\"\n",
)])
.unwrap();
assert_eq!(t_count("inbox", 0), "No messages");
assert_eq!(t_count("inbox", 1), "1 message");
assert_eq!(
t_args("inbox", &[("count", "3".into()), ("name", "Ada".into())]),
"3 messages for Ada"
);
assert_eq!(t_count("plain", 2), "2 things", "a key without forms");
assert_eq!(
with_locale("ru", async { t_count("files", 3) }).await,
"3 файла"
);
assert_eq!(
with_locale("ru", async { t_count("files", 11) }).await,
"11 файлов"
);
}
#[tokio::test]
async fn picks_the_locale_from_cookie_header_or_user() {
let app = App::new()
.middleware(Locales::new(["en", "he", "fr"]))
.routes(|r| {
r.get("/", |_ctx| async { locale() })
.get("/mine", |_ctx| async {
set_locale("he");
locale()
});
});
let client = TestClient::new(app);
client.header("accept-language", "de-DE, fr-CA;q=0.8, en;q=0.5");
assert_eq!(client.get("/").await.body_text(), "fr", "the best match");
assert_eq!(client.get("/?locale=he").await.body_text(), "he");
assert_eq!(client.get("/").await.body_text(), "he");
assert_eq!(client.get("/mine").await.body_text(), "he");
assert_eq!(client.get("/?locale=en").await.body_text(), "en");
assert_eq!(client.get("/mine").await.body_text(), "he");
}
}