use std::collections::{BTreeMap, HashMap, HashSet};
use std::time::{SystemTime, UNIX_EPOCH};
use jmap_chat_types::{
BodyType, BroadcastScope, Chat, ChatContact, ChatKind, ChatMessageEntry, ChatMessagePush,
ChatPushCapability, ChatPushConfig, Message, ReadPosition, RichBody, Space, SpaceMember,
UrgencyLevel,
};
use jmap_server::state_change_for;
use jmap_types::{Id, PushSubscription, State, StateChange, UTCDate, Urgency};
use serde_json::{Map, Value};
use crate::ChatBackend;
use crate::chat::unread_count;
use jmap_server::{SetError, SetErrorType};
pub(crate) const CHAT_PUSH: &str = "chatPush";
const ENTRY_PROPERTIES: [&str; 13] = [
"messageId",
"chatId",
"chatKind",
"chatName",
"spaceId",
"spaceName",
"senderId",
"senderDisplayName",
"sentAt",
"hasMention",
"mentionScopes",
"encrypted",
"bodySnippet",
];
const DEFAULT_ENTRY_PROPERTIES: [&str; 10] = [
"messageId",
"chatId",
"chatKind",
"senderId",
"senderDisplayName",
"sentAt",
"hasMention",
"mentionScopes",
"encrypted",
"bodySnippet",
];
pub fn validate_chat_push(
extra: &Map<String, Value>,
caps: &HashMap<Id, ChatPushCapability>,
) -> Result<(), Box<SetError>> {
let entries = match extra.get(CHAT_PUSH) {
None | Some(Value::Null) => return Ok(()),
Some(Value::Object(entries)) => entries,
Some(_) => return Err(Box::new(invalid(CHAT_PUSH.to_owned()))),
};
for (account, entry) in entries.iter().filter(|(_, e)| !e.is_null()) {
let path = format!("{CHAT_PUSH}/{account}");
let Some(cap) = caps.get(account.as_str()) else {
return Err(Box::new(invalid(path)));
};
let cfg: ChatPushConfig =
serde_json::from_value(entry.clone()).map_err(|_| invalid(path.clone()))?;
if cfg
.kinds
.iter()
.flatten()
.any(|k| matches!(k, ChatKind::Other(_)))
{
return Err(Box::new(invalid(format!("{path}/kinds"))));
}
if cfg
.properties
.iter()
.flatten()
.any(|p| !ENTRY_PROPERTIES.contains(&p.as_str()))
{
return Err(Box::new(invalid(format!("{path}/properties"))));
}
let unsupported = |u: &Option<UrgencyLevel>| {
u.as_ref().is_some_and(|u| {
u.to_urgency()
.is_none_or(|u| !cap.supported_urgency_values.contains(&u))
})
};
if unsupported(&cfg.urgency) {
return Err(Box::new(invalid(format!("{path}/urgency"))));
}
if unsupported(&cfg.mention_urgency) {
return Err(Box::new(invalid(format!("{path}/mentionUrgency"))));
}
}
Ok(())
}
pub fn strip_unsupported_chat_push(
extra: &mut Map<String, Value>,
caps: &HashMap<Id, ChatPushCapability>,
) {
if let Some(Value::Object(entries)) = extra.get_mut(CHAT_PUSH) {
entries.retain(|account, _| caps.contains_key(account.as_str()));
}
}
pub fn chat_state_change_for(
sub: &PushSubscription,
changed: &BTreeMap<Id, BTreeMap<String, State>>,
carried: &HashSet<Id>,
) -> Option<StateChange> {
let filtered: BTreeMap<Id, BTreeMap<String, State>> = changed
.iter()
.map(|(account, types)| {
let mut types = types.clone();
if carried.contains(account) {
types.remove("Message");
}
(account.clone(), types)
})
.collect();
state_change_for(sub, &filtered)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct OwnerFlags {
pub active: bool,
pub admin: bool,
}
impl OwnerFlags {
pub const fn new(active: bool, admin: bool) -> Self {
Self { active, admin }
}
}
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct PushItem<'a> {
pub message: &'a Message,
pub chat: &'a Chat,
pub sender: &'a ChatContact,
pub sender_member: Option<&'a SpaceMember>,
pub space: Option<&'a Space>,
}
impl<'a> PushItem<'a> {
pub const fn new(message: &'a Message, chat: &'a Chat, sender: &'a ChatContact) -> Self {
Self {
message,
chat,
sender,
sender_member: None,
space: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct BuiltPush {
pub payload: ChatMessagePush,
pub urgency: Urgency,
}
pub fn build_chat_message_push(
account_id: &Id,
state: State,
cfg: &ChatPushConfig,
cap: &ChatPushCapability,
owner: OwnerFlags,
item: PushItem<'_>,
unread_count: Option<u64>,
) -> BuiltPush {
let msg = item.message;
let kind = item.chat.kind.clone();
let body_type = msg.body_type.as_str();
let plaintext = is_plaintext(body_type);
let mut mentioned = false;
let mut entry = if plaintext {
let has_mention = msg.mentions.iter().any(|m| m.id == *account_id);
let scopes = mention_scopes(msg, owner);
mentioned = has_mention || !scopes.is_empty();
let snippet = if body_type == BodyType::Rich.as_str() {
rich_text(&msg.body).map(|text| snippet(&text, cap.max_snippet_bytes))
} else {
Some(snippet(&msg.body, cap.max_snippet_bytes))
};
ChatMessageEntry::plaintext(
msg.id.clone(),
msg.chat_id.clone(),
kind.clone(),
msg.sender_id.clone(),
msg.sent_at.clone(),
has_mention,
scopes,
snippet,
)
} else {
ChatMessageEntry::encrypted(
msg.id.clone(),
msg.chat_id.clone(),
kind.clone(),
msg.sender_id.clone(),
msg.sent_at.clone(),
)
};
if kind != ChatKind::Direct {
entry.chat_name = item.chat.name.clone();
}
if kind == ChatKind::Channel {
entry.space_id = item.chat.space_id.clone();
entry.space_name = item.space.map(|s| s.name.clone());
}
entry.sender_display_name = Some(sender_display_name(&kind, &item));
let wanted = |name: &str| match &cfg.properties {
Some(properties) => properties.iter().any(|p| p == name),
None => DEFAULT_ENTRY_PROPERTIES.contains(&name),
};
entry.message_id = entry.message_id.take().filter(|_| wanted("messageId"));
entry.chat_id = entry.chat_id.take().filter(|_| wanted("chatId"));
entry.chat_kind = entry.chat_kind.take().filter(|_| wanted("chatKind"));
entry.chat_name = entry.chat_name.take().filter(|_| wanted("chatName"));
entry.space_id = entry.space_id.take().filter(|_| wanted("spaceId"));
entry.space_name = entry.space_name.take().filter(|_| wanted("spaceName"));
entry.sender_id = entry.sender_id.take().filter(|_| wanted("senderId"));
entry.sender_display_name = entry
.sender_display_name
.take()
.filter(|_| wanted("senderDisplayName"));
entry.sent_at = entry.sent_at.take().filter(|_| wanted("sentAt"));
entry.has_mention = entry.has_mention.take().filter(|_| wanted("hasMention"));
entry.mention_scopes = entry
.mention_scopes
.take()
.filter(|_| wanted("mentionScopes"));
entry.encrypted = entry.encrypted.take().filter(|_| wanted("encrypted"));
entry.body_snippet = entry.body_snippet.take().filter(|_| wanted("bodySnippet"));
let urgency = cfg
.mention_urgency
.as_ref()
.filter(|_| mentioned)
.or(cfg.urgency.as_ref())
.and_then(UrgencyLevel::to_urgency)
.unwrap_or(Urgency::Normal);
let mut payload = ChatMessagePush::new(account_id.clone(), state, vec![entry]);
payload.unread_count = unread_count;
BuiltPush { payload, urgency }
}
pub async fn owner_unread_count<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
account_id: &Id,
) -> Result<u64, B::Error> {
let (chats, _) = backend
.get_objects::<Chat>(caller, account_id, None, None)
.await?;
let derived = if backend.maintains_unread_count() {
None
} else {
let (messages, _) = backend
.get_objects::<Message>(caller, account_id, None, None)
.await?;
let (positions, _) = backend
.get_objects::<ReadPosition>(caller, account_id, None, None)
.await?;
Some((messages, positions))
};
Ok(chats
.iter()
.filter(|chat| !chat_muted(chat))
.map(|chat| match &derived {
Some((messages, positions)) => {
unread_count(messages, positions, account_id, chat.id.as_ref())
}
None => chat.unread_count,
})
.fold(0, u64::saturating_add))
}
fn chat_muted(chat: &Chat) -> bool {
match &chat.mute_until {
Some(until) => mute_active(until),
None => chat.muted,
}
}
pub fn fit_chat_message_push(
mut push: ChatMessagePush,
max_bytes: usize,
) -> Vec<Option<ChatMessagePush>> {
let fits = |p: &ChatMessagePush| serde_json::to_vec(p).is_ok_and(|v| v.len() <= max_bytes);
if fits(&push) {
return vec![Some(push)];
}
std::mem::take(&mut push.messages)
.into_iter()
.map(|entry| {
let mut single = push.clone();
single.messages = vec![entry];
if !fits(&single) {
single.messages[0].body_snippet = None;
}
fits(&single).then_some(single)
})
.collect()
}
pub async fn should_push<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
account_id: &Id,
cfg: &ChatPushConfig,
caps: &HashMap<Id, ChatPushCapability>,
msg: &Message,
owner: OwnerFlags,
) -> Result<bool, B::Error> {
if !caps.contains_key(account_id) || msg.sender_id == *account_id {
return Ok(false);
}
if cfg
.chat_ids
.as_ref()
.is_some_and(|ids| !ids.contains(&msg.chat_id))
{
return Ok(false);
}
let (chats, _) = backend
.get_objects::<Chat>(
caller,
account_id,
Some(std::slice::from_ref(&msg.chat_id)),
None,
)
.await?;
let Some(chat) = chats.into_iter().next() else {
return Ok(false);
};
if cfg
.kinds
.as_ref()
.is_some_and(|kinds| !kinds.contains(&chat.kind))
{
return Ok(false);
}
if !owner_is_member(backend, caller, account_id, &chat).await? {
return Ok(false);
}
let bypass = is_plaintext(msg.body_type.as_str()) && !mention_scopes(msg, owner).is_empty();
if chat_muted(&chat) && !bypass {
return Ok(false);
}
Ok(!backend
.is_contact_blocked(caller, account_id, &msg.sender_id)
.await?)
}
pub(crate) async fn owner_is_member<B: ChatBackend>(
backend: &B,
caller: &B::CallerCtx,
account_id: &Id,
chat: &Chat,
) -> Result<bool, B::Error> {
let is_owner = |id: &Id| id == account_id;
Ok(match chat.kind {
ChatKind::Group => chat.members.iter().flatten().any(|m| is_owner(&m.id)),
ChatKind::Channel => match &chat.space_id {
Some(space_id) => backend
.get_objects::<Space>(
caller,
account_id,
Some(std::slice::from_ref(space_id)),
None,
)
.await?
.0
.iter()
.any(|space| space.members.iter().any(|m| is_owner(&m.id))),
None => false,
},
_ => true,
})
}
fn mute_active(until: &UTCDate) -> bool {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.ok()
.and_then(|d| i64::try_from(d.as_secs()).ok());
match (until.to_epoch_seconds(), now) {
(Ok(until), Some(now)) => now < until,
_ => true,
}
}
fn is_plaintext(body_type: &str) -> bool {
[BodyType::Plain, BodyType::Markdown, BodyType::Rich]
.iter()
.any(|t| t.as_str() == body_type)
}
fn mention_scopes(msg: &Message, owner: OwnerFlags) -> Vec<BroadcastScope> {
let mut scopes: Vec<BroadcastScope> = Vec::new();
for scope in msg.broadcast_mentions.iter().map(|b| &b.scope) {
let targets_owner = match scope {
BroadcastScope::Everyone => true,
BroadcastScope::Here => owner.active,
BroadcastScope::Admins => owner.admin,
_ => false,
};
if targets_owner && !scopes.contains(scope) {
scopes.push(scope.clone());
}
}
scopes
}
fn rich_text(body: &str) -> Option<String> {
let rich: RichBody = serde_json::from_str(body).ok()?;
Some(rich.spans.into_iter().map(|s| s.text).collect())
}
fn snippet(body: &str, max_bytes: u64) -> String {
let mut text: String = body.chars().filter(|c| !c.is_control()).collect();
let mut end = usize::try_from(max_bytes).map_or(text.len(), |max| max.min(text.len()));
while !text.is_char_boundary(end) {
end -= 1;
}
text.truncate(end);
text
}
fn sender_display_name(kind: &ChatKind, item: &PushItem<'_>) -> String {
let nick = item
.sender_member
.filter(|_| *kind == ChatKind::Channel)
.and_then(|m| m.nick.clone());
let login = Some(&item.sender.login).filter(|l| !l.is_empty()).cloned();
nick.or_else(|| item.sender.display_name.clone())
.or(login)
.unwrap_or_else(|| item.sender.identity.clone())
}
fn invalid(property: String) -> SetError {
SetError::new(SetErrorType::InvalidProperties).with_properties([property])
}