use std::collections::{BTreeMap, HashMap};
use std::time::{SystemTime, UNIX_EPOCH};
use jmap_chat_types::{
BodyType, Chat, ChatContact, ChatKind, ChatMessageEntry, ChatMessagePush, ChatPushCapability,
ChatPushConfig, Message, Space, SpaceMember, UrgencyLevel,
};
use jmap_server::state_change_for;
use jmap_types::{Id, PushSubscription, State, StateChange, UTCDate};
use serde_json::{Map, Value};
use crate::{ChatBackend, SetError, SetErrorType};
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",
];
#[allow(clippy::result_large_err)]
pub fn validate_chat_push(
extra: &Map<String, Value>,
caps: &HashMap<Id, ChatPushCapability>,
) -> Result<(), SetError> {
let entries = match extra.get(CHAT_PUSH) {
None | Some(Value::Null) => return Ok(()),
Some(Value::Object(entries)) => entries,
Some(_) => return Err(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(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(invalid(format!("{path}/kinds")));
}
if cfg
.properties
.iter()
.flatten()
.any(|p| !ENTRY_PROPERTIES.contains(&p.as_str()))
{
return Err(invalid(format!("{path}/properties")));
}
let unsupported = |u: &Option<UrgencyLevel>| {
u.as_ref()
.is_some_and(|u| !cap.supported_urgency_values.contains(u))
};
if unsupported(&cfg.urgency) {
return Err(invalid(format!("{path}/urgency")));
}
if unsupported(&cfg.mention_urgency) {
return Err(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>>,
caps: &HashMap<Id, ChatPushCapability>,
) -> Option<StateChange> {
let live = |account: &Id| {
caps.contains_key(account)
&& sub
.extra
.get(CHAT_PUSH)
.and_then(|entries| entries.get(account.as_ref()))
.is_some_and(|entry| !entry.is_null())
};
let filtered: BTreeMap<Id, BTreeMap<String, State>> = changed
.iter()
.map(|(account, types)| {
let mut types = types.clone();
if live(account) {
types.remove("Message");
}
(account.clone(), types)
})
.collect();
state_change_for(sub, &filtered)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct OwnerFlags {
pub active: bool,
pub admin: bool,
}
#[derive(Debug, Clone, Copy)]
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>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BuiltPush {
pub payload: ChatMessagePush,
pub urgency: UrgencyLevel,
}
pub fn build_chat_message_push(
account_id: &Id,
state: State,
cfg: &ChatPushConfig,
cap: &ChatPushCapability,
owner: OwnerFlags,
item: PushItem<'_>,
) -> 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 = (body_type != BodyType::Rich.as_str())
.then(|| 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
.clone()
.filter(|_| mentioned)
.or_else(|| cfg.urgency.clone())
.unwrap_or(UrgencyLevel::Normal);
BuiltPush {
payload: ChatMessagePush::new(account_id.clone(), state, vec![entry]),
urgency,
}
}
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);
}
let is_owner = |id: &Id| id == account_id;
let member = 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,
};
if !member {
return Ok(false);
}
let bypass = is_plaintext(&msg.body_type) && !mention_scopes(msg, owner).is_empty();
let muted = match &chat.mute_until {
Some(until) => mute_active(until),
None => chat.muted,
};
if muted && !bypass {
return Ok(false);
}
Ok(!backend
.is_contact_blocked(caller, account_id, &msg.sender_id)
.await?)
}
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<String> {
let mut scopes: Vec<String> = Vec::new();
for scope in msg.broadcast_mentions.iter().map(|b| b.scope.as_str()) {
let targets_owner = match scope {
"everyone" => true,
"here" => owner.active,
"admins" => owner.admin,
_ => false,
};
if targets_owner && !scopes.iter().any(|s| s == scope) {
scopes.push(scope.to_owned());
}
}
scopes
}
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])
}