use crate::{JmapObject, SetError, SetErrorType};
use jmap_types::i18n::{
JMAP_I18N_URI, LanguageRange, LocalizableProperty, check_localizations, localized_view,
parse_locale, prune_stale_localizations,
};
use jmap_types::{JmapError, PatchObject};
use serde_json::{Map, Value};
#[non_exhaustive]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct I18nInfo {
pub max_localizations: Option<usize>,
}
impl I18nInfo {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_max_localizations(mut self, max: Option<usize>) -> Self {
self.max_localizations = max;
self
}
}
pub fn uses_i18n(using: &[String]) -> bool {
using.iter().any(|u| u == JMAP_I18N_URI)
}
#[derive(Debug, Clone, Default, PartialEq)]
enum Mode {
#[default]
Off,
Strip,
Stored,
View(Vec<LanguageRange>),
}
#[derive(Debug, Clone, Default)]
pub struct I18nProjection {
mode: Mode,
properties: &'static [LocalizableProperty],
}
impl I18nProjection {
pub fn from_args<O: JmapObject>(
args: &mut Map<String, Value>,
using: &[String],
info: Option<&I18nInfo>,
) -> Result<Self, JmapError> {
let language = args.remove("language");
let ranges = match language {
None | Some(Value::Null) => None,
Some(v) => {
if O::LOCALIZABLE.is_empty() {
return Err(JmapError::invalid_arguments(format!(
"language: {} has no localizable properties",
O::TYPE_NAME
)));
}
if !uses_i18n(using) {
return Err(JmapError::invalid_arguments(
"language requires urn:ietf:params:jmap:i18n in using",
));
}
if info.is_none() {
return Err(JmapError::invalid_arguments(
"language: the account does not support urn:ietf:params:jmap:i18n",
));
}
Some(parse_ranges(&v)?)
}
};
Ok(Self::with_ranges::<O>(ranges, using, info))
}
#[must_use]
pub fn without_language<O: JmapObject>(using: &[String], info: Option<&I18nInfo>) -> Self {
Self::with_ranges::<O>(None, using, info)
}
fn with_ranges<O: JmapObject>(
ranges: Option<Vec<LanguageRange>>,
using: &[String],
info: Option<&I18nInfo>,
) -> Self {
let mode = if O::LOCALIZABLE.is_empty() {
Mode::Off
} else if !uses_i18n(using) || info.is_none() {
Mode::Strip
} else if let Some(r) = ranges {
Mode::View(r)
} else {
Mode::Stored
};
Self {
mode,
properties: O::LOCALIZABLE,
}
}
pub fn language(&self) -> Option<&[LanguageRange]> {
match &self.mode {
Mode::View(r) => Some(r),
_ => None,
}
}
pub fn backend_properties(&self, requested: Option<&[String]>) -> Option<Vec<String>> {
let mut props = requested?.to_vec();
if matches!(self.mode, Mode::View(_)) {
for p in ["locale", "localizations"] {
if !props.iter().any(|q| q == p) {
props.push(p.to_owned());
}
}
}
Some(props)
}
pub fn apply(&self, item: &mut Map<String, Value>) {
match &self.mode {
Mode::Off => {}
Mode::Strip => {
item.remove("locale");
item.remove("localizations");
}
Mode::Stored => {
for p in ["locale", "localizations"] {
item.entry(p).or_insert(Value::Null);
}
}
Mode::View(ranges) => localized_view(item, self.properties, ranges),
}
}
}
fn parse_ranges(v: &Value) -> Result<Vec<LanguageRange>, JmapError> {
let bad = || JmapError::invalid_arguments("language must be an array of language ranges");
let Value::Array(items) = v else {
return Err(bad());
};
items
.iter()
.map(|i| {
i.as_str().ok_or_else(bad).and_then(|s| {
LanguageRange::parse(s)
.map_err(|e| JmapError::invalid_arguments(format!("language {s:?}: {e}")))
})
})
.collect()
}
fn invalid(property: &str, description: impl Into<String>) -> Box<SetError> {
Box::new(
SetError::new(SetErrorType::InvalidProperties)
.with_properties([property])
.with_description(description),
)
}
fn localized_root(key: &str) -> Option<&'static str> {
match key.split('/').next() {
Some("locale") => Some("locale"),
Some("localizations") => Some("localizations"),
_ => None,
}
}
#[derive(Debug, Clone, Default)]
pub struct I18nSet {
properties: Option<&'static [LocalizableProperty]>,
allowed: bool,
max_localizations: Option<usize>,
}
impl I18nSet {
pub fn new<O: JmapObject>(using: &[String], info: Option<&I18nInfo>) -> Self {
Self {
properties: (!O::LOCALIZABLE.is_empty()).then_some(O::LOCALIZABLE),
allowed: uses_i18n(using) && info.is_some(),
max_localizations: info.and_then(|i| i.max_localizations),
}
}
fn gate(&self, key: &str) -> Result<(), Box<SetError>> {
match localized_root(key) {
Some(root) if self.properties.is_some() && !self.allowed => Err(invalid(
root,
format!(
"{root} requires urn:ietf:params:jmap:i18n in using and an account that \
supports it"
),
)),
_ => Ok(()),
}
}
pub fn check_create(&self, create: &mut Map<String, Value>) -> Result<(), Box<SetError>> {
let Some(properties) = self.properties else {
return Ok(());
};
for key in create.keys() {
self.gate(key)?;
}
if !self.allowed {
return Ok(());
}
check_and_fold(create, properties, self.max_localizations)
}
pub fn check_patch(&self, patch: &Map<String, Value>) -> Result<(), Box<SetError>> {
if self.properties.is_none() {
return Ok(());
}
patch.keys().try_for_each(|k| self.gate(k))
}
pub fn echo(&self, entry: &mut Value) {
if self.properties.is_some()
&& !self.allowed
&& let Value::Object(m) = entry
{
m.remove("locale");
m.remove("localizations");
}
}
}
fn check_and_fold(
obj: &mut Map<String, Value>,
properties: &[LocalizableProperty],
max: Option<usize>,
) -> Result<(), Box<SetError>> {
let locale = match obj.get("locale") {
Some(v) => parse_locale(v)?,
None => None,
};
if let Some(tag) = &locale {
obj.insert("locale".to_owned(), Value::String(tag.as_str().to_owned()));
}
let Some(value) = obj.get("localizations") else {
return Ok(());
};
let locs = check_localizations(locale.as_ref(), value, properties)?;
if let (Some(locs), Some(max)) = (&locs, max)
&& locs.len() > max
{
return Err(invalid(
"localizations",
format!("at most {max} localizations per object"),
));
}
let folded = match locs {
Some(l) => serde_json::to_value(&l)
.map_err(|_| invalid("localizations", "localizations could not be serialized"))?,
None => Value::Null,
};
obj.insert("localizations".to_owned(), folded);
Ok(())
}
pub fn localized_update<O: JmapObject>(
old: &Map<String, Value>,
new: &mut Map<String, Value>,
patch: &PatchObject,
max_localizations: Option<usize>,
) -> Result<bool, Box<SetError>> {
if O::LOCALIZABLE.is_empty() {
return Ok(false);
}
check_and_fold(new, O::LOCALIZABLE, max_localizations)?;
Ok(prune_stale_localizations(old, new, patch, O::LOCALIZABLE))
}
const LANG_MARK: &str = "|lang=";
fn join_ranges(language: &[LanguageRange]) -> String {
language
.iter()
.map(LanguageRange::as_str)
.collect::<Vec<_>>()
.join(",")
}
pub fn localized_query_state(
state: &jmap_types::State,
language: Option<&[LanguageRange]>,
) -> jmap_types::State {
match language {
None => state.clone(),
Some(l) => {
jmap_types::State::from(format!("{}{LANG_MARK}{}", state.as_ref(), join_ranges(l)))
}
}
}
pub fn unwrap_query_state(
since: &jmap_types::State,
language: Option<&[LanguageRange]>,
) -> Result<jmap_types::State, JmapError> {
let s = since.as_ref();
let (inner, was) = match s.rfind(LANG_MARK) {
Some(i) => (&s[..i], Some(&s[i + LANG_MARK.len()..])),
None => (s, None),
};
let now = language.map(join_ranges);
if was != now.as_deref() {
return Err(JmapError::cannot_calculate_changes());
}
Ok(jmap_types::State::from(inner))
}