jmap_chat_server/push.rs
1//! `chatPush` support for RFC 8620 push subscriptions
2//! (draft-atwood-jmap-chat-push-00).
3//!
4//! The `chatPush` property lives in [`PushSubscription::extra`] as a map of
5//! accountId to `ChatPushConfig`. A backend calls [`validate_chat_push`] on
6//! every create and update, [`strip_unsupported_chat_push`] on every
7//! subscription it returns from `list_push_subscriptions`, builds
8//! notifications with [`chat_state_change_for`], and builds the
9//! `ChatMessagePush` for each new inbound message with
10//! [`build_chat_message_push`] after [`should_push`] allows it, with the
11//! badge count from [`owner_unread_count`], fitted to the platform size
12//! limit with [`fit_chat_message_push`].
13
14use std::collections::{BTreeMap, HashMap, HashSet};
15use std::time::{SystemTime, UNIX_EPOCH};
16
17use jmap_chat_types::{
18 BodyType, BroadcastScope, Chat, ChatContact, ChatKind, ChatMessageEntry, ChatMessagePush,
19 ChatPushCapability, ChatPushConfig, Message, ReadPosition, RichBody, Space, SpaceMember,
20 UrgencyLevel,
21};
22use jmap_server::state_change_for;
23use jmap_types::{Id, PushSubscription, State, StateChange, UTCDate, Urgency};
24use serde_json::{Map, Value};
25
26use crate::ChatBackend;
27use crate::chat::unread_count;
28use jmap_server::{SetError, SetErrorType};
29
30/// The `PushSubscription` property this extension adds.
31pub(crate) const CHAT_PUSH: &str = "chatPush";
32
33/// The `ChatMessageEntry` fields a server MUST support in `properties`
34/// (draft-atwood-jmap-chat-push-00 §ChatPushConfig). `unreadCount` is a
35/// `ChatMessagePush` property, not an entry field, so it is rejected like
36/// any unknown name.
37const ENTRY_PROPERTIES: [&str; 13] = [
38 "messageId",
39 "chatId",
40 "chatKind",
41 "chatName",
42 "spaceId",
43 "spaceName",
44 "senderId",
45 "senderDisplayName",
46 "sentAt",
47 "hasMention",
48 "mentionScopes",
49 "encrypted",
50 "bodySnippet",
51];
52
53/// The `ChatMessageEntry` fields sent when `properties` is absent
54/// (draft-atwood-jmap-chat-push-00 §ChatPushConfig).
55const DEFAULT_ENTRY_PROPERTIES: [&str; 10] = [
56 "messageId",
57 "chatId",
58 "chatKind",
59 "senderId",
60 "senderDisplayName",
61 "sentAt",
62 "hasMention",
63 "mentionScopes",
64 "encrypted",
65 "bodySnippet",
66];
67
68/// Check the `chatPush` property in a `PushSubscription`'s `extra` map
69/// before it is stored.
70///
71/// `caps` maps each account that advertises
72/// `urn:ietf:params:jmap:chat:push` to its account-level capability object.
73/// An absent or `null` `chatPush`, and a `null` entry for an account, are
74/// accepted. Otherwise the first offending value gets an
75/// `invalidProperties` SetError naming it:
76///
77/// - `chatPush`: the value is not an object.
78/// - `chatPush/<accountId>`: the account is not in `caps`, or the entry is
79/// not a `ChatPushConfig`. draft-atwood-jmap-chat-push-00
80/// §PushSubscription Extension: "If a `PushSubscription/set` create or
81/// update includes a `chatPush` entry for an account whose
82/// `accountCapabilities` does not include
83/// `urn:ietf:params:jmap:chat:push`, the server MUST return an
84/// `invalidProperties` SetError whose `properties` names the offending
85/// entry (e.g., `chatPush/<id>`) and MUST NOT store the subscription
86/// change."
87/// - `chatPush/<accountId>/kinds`: a value other than `"direct"`,
88/// `"group"` or `"channel"`.
89/// - `chatPush/<accountId>/properties`: a name that is not a
90/// `ChatMessageEntry` field the server supports.
91/// - `chatPush/<accountId>/urgency` and `.../mentionUrgency`: a value not
92/// in the account's `supportedUrgencyValues`, including any value outside
93/// RFC 8030 §5.3, which no capability can list. draft-atwood-jmap-chat-push-00
94/// §ChatPushConfig: "the server MUST return an `invalidProperties`
95/// SetError on `PushSubscription/set` whose `properties` names the
96/// offending path (e.g., `chatPush/<id>/urgency`)".
97pub fn validate_chat_push(
98 extra: &Map<String, Value>,
99 caps: &HashMap<Id, ChatPushCapability>,
100) -> Result<(), Box<SetError>> {
101 let entries = match extra.get(CHAT_PUSH) {
102 None | Some(Value::Null) => return Ok(()),
103 Some(Value::Object(entries)) => entries,
104 Some(_) => return Err(Box::new(invalid(CHAT_PUSH.to_owned()))),
105 };
106 for (account, entry) in entries.iter().filter(|(_, e)| !e.is_null()) {
107 let path = format!("{CHAT_PUSH}/{account}");
108 let Some(cap) = caps.get(account.as_str()) else {
109 return Err(Box::new(invalid(path)));
110 };
111 let cfg: ChatPushConfig =
112 serde_json::from_value(entry.clone()).map_err(|_| invalid(path.clone()))?;
113 if cfg
114 .kinds
115 .iter()
116 .flatten()
117 .any(|k| matches!(k, ChatKind::Other(_)))
118 {
119 return Err(Box::new(invalid(format!("{path}/kinds"))));
120 }
121 if cfg
122 .properties
123 .iter()
124 .flatten()
125 .any(|p| !ENTRY_PROPERTIES.contains(&p.as_str()))
126 {
127 return Err(Box::new(invalid(format!("{path}/properties"))));
128 }
129 let unsupported = |u: &Option<UrgencyLevel>| {
130 u.as_ref().is_some_and(|u| {
131 u.to_urgency()
132 .is_none_or(|u| !cap.supported_urgency_values.contains(&u))
133 })
134 };
135 if unsupported(&cfg.urgency) {
136 return Err(Box::new(invalid(format!("{path}/urgency"))));
137 }
138 if unsupported(&cfg.mention_urgency) {
139 return Err(Box::new(invalid(format!("{path}/mentionUrgency"))));
140 }
141 }
142 Ok(())
143}
144
145/// Remove `chatPush` entries for accounts not in `caps` from a stored
146/// subscription's `extra` map before it is returned.
147///
148/// An entry stored while the account advertised
149/// `urn:ietf:params:jmap:chat:push` stops being returned once it no longer
150/// does. draft-atwood-jmap-chat-push-00 rejects such an entry only on
151/// `/set` (§PushSubscription Extension) and states no rule for one stored
152/// before the capability was withdrawn. This server strips it so that
153/// `/get` matches delivery: [`should_push`] treats the entry as absent, and
154/// the draft says "When `chatPush` is absent or null for an account, the
155/// server delivers standard `StateChange` notifications for that account
156/// without inline message content."
157pub fn strip_unsupported_chat_push(
158 extra: &mut Map<String, Value>,
159 caps: &HashMap<Id, ChatPushCapability>,
160) {
161 if let Some(Value::Object(entries)) = extra.get_mut(CHAT_PUSH) {
162 entries.retain(|account, _| caps.contains_key(account.as_str()));
163 }
164}
165
166/// The `StateChange` to push to `sub` for the types in `changed`, or `None`
167/// when nothing is left to send.
168///
169/// Wraps [`state_change_for`] (which filters by `types`) and drops the
170/// `Message` type for each account in `carried`. The caller puts an
171/// account in `carried` only when every Message change for it in `changed`
172/// arrived in a `ChatMessagePush` delivered to `sub`; an edit, a destroy,
173/// the owner's own message or a message [`should_push`] filtered out keeps
174/// the account out, and `Message` stays in its `StateChange`.
175/// draft-atwood-jmap-chat-push-00 §PushSubscription Extension: "A
176/// `ChatMessagePush` stands in for the `StateChange` that the arrival of
177/// the messages it carries would otherwise cause. Every other change in
178/// the account is still announced by a standard `StateChange`, as
179/// {{RFC8620}} Section 7 describes: this includes Message changes that the
180/// payload does not carry (edits, destroys, the owner's own messages, and
181/// messages excluded by `ChatPushConfig`, mute, or block) and changes to
182/// every other data type."
183///
184/// A consumer falling back to a plain `StateChange` under rate limiting
185/// (§Rate Limiting and Fallback) calls [`state_change_for`] directly.
186pub fn chat_state_change_for(
187 sub: &PushSubscription,
188 changed: &BTreeMap<Id, BTreeMap<String, State>>,
189 carried: &HashSet<Id>,
190) -> Option<StateChange> {
191 let filtered: BTreeMap<Id, BTreeMap<String, State>> = changed
192 .iter()
193 .map(|(account, types)| {
194 let mut types = types.clone();
195 if carried.contains(account) {
196 types.remove("Message");
197 }
198 (account.clone(), types)
199 })
200 .collect();
201 state_change_for(sub, &filtered)
202}
203
204/// The account owner's standing in the Chat at delivery time, which
205/// decides the broadcast scopes that target them.
206///
207/// draft-atwood-jmap-chat-push-00 §ChatMessageEntry `mentionScopes`:
208/// "`"here"` is included only when the owner satisfies the
209/// deployment-defined "active" predicate at delivery time; `"admins"` is
210/// included only when the owner satisfies the deployment-defined
211/// "administrative authority" predicate at delivery time." Both predicates
212/// are deployment-defined, so the caller evaluates them.
213///
214/// Build it with [`OwnerFlags::new`]; more flags may be added.
215#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
216#[non_exhaustive]
217pub struct OwnerFlags {
218 /// The owner satisfies the deployment's "active" predicate.
219 pub active: bool,
220 /// The owner has administrative authority in the Chat.
221 pub admin: bool,
222}
223
224impl OwnerFlags {
225 /// The owner's flags from the two deployment-defined predicates.
226 pub const fn new(active: bool, admin: bool) -> Self {
227 Self { active, admin }
228 }
229}
230
231/// The stored records one `ChatMessageEntry` is built from.
232///
233/// Build it with [`PushItem::new`] and set the optional fields after; more
234/// fields may be added.
235#[derive(Debug, Clone, Copy)]
236#[non_exhaustive]
237pub struct PushItem<'a> {
238 /// The new inbound message.
239 pub message: &'a Message,
240 /// The Chat containing the message.
241 pub chat: &'a Chat,
242 /// The sender's `ChatContact` on the account owner's contact list.
243 pub sender: &'a ChatContact,
244 /// The sender's `SpaceMember` record in the Space containing the
245 /// Chat, when the Chat is a channel and the record exists. Ignored for
246 /// other kinds.
247 pub sender_member: Option<&'a SpaceMember>,
248 /// The Space containing the Chat, when the Chat is a channel. Its
249 /// `name` becomes `spaceName`. Ignored for other kinds.
250 pub space: Option<&'a Space>,
251}
252
253impl<'a> PushItem<'a> {
254 /// The required records, with `sender_member` and `space` unset.
255 pub const fn new(message: &'a Message, chat: &'a Chat, sender: &'a ChatContact) -> Self {
256 Self {
257 message,
258 chat,
259 sender,
260 sender_member: None,
261 space: None,
262 }
263 }
264}
265
266/// A built `ChatMessagePush` and the Web Push urgency to deliver it with.
267#[derive(Debug, Clone, PartialEq, Eq)]
268#[non_exhaustive]
269pub struct BuiltPush {
270 /// The payload to deliver to the push endpoint.
271 pub payload: ChatMessagePush,
272 /// The Web Push urgency for this delivery.
273 pub urgency: Urgency,
274}
275
276/// Build the `ChatMessagePush` for one new inbound message under one
277/// subscription's `ChatPushConfig` for `account_id`.
278///
279/// The caller decides whether to deliver at all (draft-atwood-jmap-chat-push-00
280/// §Delivery) and passes `state`, the account's `Message` state after this
281/// message was stored. §ChatMessagePush: "The server MUST set this field to
282/// the post-delivery state".
283///
284/// `unread_count` becomes the payload's `unreadCount`, normally the
285/// value of [`owner_unread_count`] read after this message was stored.
286/// §ChatMessagePush: "The account owner's total unread message count
287/// across all non-muted Chats at the time this push was generated.
288/// Servers SHOULD include this for platforms that support atomic badge
289/// updates". `None` leaves it out.
290///
291/// The entry holds exactly the fields in `cfg.properties`, or the default
292/// set when it is absent. §ChatPushConfig: "The `properties` list is
293/// authoritative: the server returns exactly the requested fields." Each
294/// field is derived as §ChatMessageEntry says, with these exceptions:
295///
296/// - `encrypted` comes from `bodyType`: `false` for `text/plain`,
297/// `text/markdown` and `application/jmap-chat-rich`, otherwise `true`
298/// (§End-to-End Encrypted Deployments). An encrypted entry never has
299/// `hasMention`, `mentionScopes` or `bodySnippet`.
300/// - `bodySnippet` is the body with control characters removed, cut to at
301/// most `cap.maxSnippetBytes` bytes on a UTF-8 character boundary.
302/// Markdown markup is left in, which misses the §ChatMessageEntry SHOULD
303/// for a plaintext approximation. For `application/jmap-chat-rich` the
304/// snippet is rendered from the span `text` values joined in order
305/// (draft-atwood-jmap-chat-00 §Span Object: "The plaintext content of
306/// this span"), so no markup reaches it; a body that does not parse as a
307/// rich body gets no snippet.
308/// - `senderDisplayName` treats an empty `login` as absent.
309///
310/// The urgency is `cfg.mentionUrgency` when it is set and the owner is
311/// mentioned directly or by a targeting broadcast scope, otherwise
312/// `cfg.urgency`, otherwise `"normal"` (§Urgency). The mention test uses
313/// the computed mention, whether or not `properties` asks for
314/// `hasMention` or `mentionScopes`. A chosen value outside RFC 8030
315/// (`UrgencyLevel::Other`, which [`validate_chat_push`] rejects before a
316/// config is stored) is also sent as `"normal"`, the urgency of a push
317/// without the header (RFC 8030 §5.3).
318pub fn build_chat_message_push(
319 account_id: &Id,
320 state: State,
321 cfg: &ChatPushConfig,
322 cap: &ChatPushCapability,
323 owner: OwnerFlags,
324 item: PushItem<'_>,
325 unread_count: Option<u64>,
326) -> BuiltPush {
327 let msg = item.message;
328 let kind = item.chat.kind.clone();
329 let body_type = msg.body_type.as_str();
330 let plaintext = is_plaintext(body_type);
331
332 let mut mentioned = false;
333 let mut entry = if plaintext {
334 let has_mention = msg.mentions.iter().any(|m| m.id == *account_id);
335 let scopes = mention_scopes(msg, owner);
336 mentioned = has_mention || !scopes.is_empty();
337 let snippet = if body_type == BodyType::Rich.as_str() {
338 rich_text(&msg.body).map(|text| snippet(&text, cap.max_snippet_bytes))
339 } else {
340 Some(snippet(&msg.body, cap.max_snippet_bytes))
341 };
342 ChatMessageEntry::plaintext(
343 msg.id.clone(),
344 msg.chat_id.clone(),
345 kind.clone(),
346 msg.sender_id.clone(),
347 msg.sent_at.clone(),
348 has_mention,
349 scopes,
350 snippet,
351 )
352 } else {
353 ChatMessageEntry::encrypted(
354 msg.id.clone(),
355 msg.chat_id.clone(),
356 kind.clone(),
357 msg.sender_id.clone(),
358 msg.sent_at.clone(),
359 )
360 };
361 if kind != ChatKind::Direct {
362 entry.chat_name = item.chat.name.clone();
363 }
364 if kind == ChatKind::Channel {
365 entry.space_id = item.chat.space_id.clone();
366 entry.space_name = item.space.map(|s| s.name.clone());
367 }
368 entry.sender_display_name = Some(sender_display_name(&kind, &item));
369
370 let wanted = |name: &str| match &cfg.properties {
371 Some(properties) => properties.iter().any(|p| p == name),
372 None => DEFAULT_ENTRY_PROPERTIES.contains(&name),
373 };
374 entry.message_id = entry.message_id.take().filter(|_| wanted("messageId"));
375 entry.chat_id = entry.chat_id.take().filter(|_| wanted("chatId"));
376 entry.chat_kind = entry.chat_kind.take().filter(|_| wanted("chatKind"));
377 entry.chat_name = entry.chat_name.take().filter(|_| wanted("chatName"));
378 entry.space_id = entry.space_id.take().filter(|_| wanted("spaceId"));
379 entry.space_name = entry.space_name.take().filter(|_| wanted("spaceName"));
380 entry.sender_id = entry.sender_id.take().filter(|_| wanted("senderId"));
381 entry.sender_display_name = entry
382 .sender_display_name
383 .take()
384 .filter(|_| wanted("senderDisplayName"));
385 entry.sent_at = entry.sent_at.take().filter(|_| wanted("sentAt"));
386 entry.has_mention = entry.has_mention.take().filter(|_| wanted("hasMention"));
387 entry.mention_scopes = entry
388 .mention_scopes
389 .take()
390 .filter(|_| wanted("mentionScopes"));
391 entry.encrypted = entry.encrypted.take().filter(|_| wanted("encrypted"));
392 entry.body_snippet = entry.body_snippet.take().filter(|_| wanted("bodySnippet"));
393
394 let urgency = cfg
395 .mention_urgency
396 .as_ref()
397 .filter(|_| mentioned)
398 .or(cfg.urgency.as_ref())
399 .and_then(UrgencyLevel::to_urgency)
400 .unwrap_or(Urgency::Normal);
401 // ponytail: one message per payload, which §Delivery allows ("Contains
402 // exactly one entry for a single new message") and §Batching and Retry
403 // prefers ("at most one `ChatMessagePush` per message"). The upgrade
404 // path is batching, chunked by `maxMessagesPerPush`.
405 let mut payload = ChatMessagePush::new(account_id.clone(), state, vec![entry]);
406 payload.unread_count = unread_count;
407 BuiltPush { payload, urgency }
408}
409
410/// The owner of `account_id`'s total unread message count across all
411/// non-muted Chats, for [`build_chat_message_push`].
412///
413/// draft-atwood-jmap-chat-push-00 §ChatMessagePush `unreadCount`: "The
414/// account owner's total unread message count across all non-muted Chats
415/// at the time this push was generated." Each Chat contributes its
416/// `unreadCount` as `Chat/get` reports it: the stored value when
417/// [`ChatBackend::maintains_unread_count`] is `true`, otherwise the count
418/// derived from the owner's ReadPosition (draft-atwood-jmap-chat-00
419/// §Chat `unreadCount`). A Chat is muted as in [`should_push`]: until
420/// `muteUntil` when it is set, otherwise when `muted` is `true`.
421///
422/// # Errors
423///
424/// Returns the backend's error if reading the Chats, Messages or
425/// ReadPositions fails.
426// ponytail: like Chat/get, a backend that does not maintain the count is
427// scanned in full (O(messages)) per call.
428pub async fn owner_unread_count<B: ChatBackend>(
429 backend: &B,
430 caller: &B::CallerCtx,
431 account_id: &Id,
432) -> Result<u64, B::Error> {
433 let (chats, _) = backend
434 .get_objects::<Chat>(caller, account_id, None, None)
435 .await?;
436 let derived = if backend.maintains_unread_count() {
437 None
438 } else {
439 let (messages, _) = backend
440 .get_objects::<Message>(caller, account_id, None, None)
441 .await?;
442 let (positions, _) = backend
443 .get_objects::<ReadPosition>(caller, account_id, None, None)
444 .await?;
445 Some((messages, positions))
446 };
447 Ok(chats
448 .iter()
449 .filter(|chat| !chat_muted(chat))
450 .map(|chat| match &derived {
451 Some((messages, positions)) => unread_count(messages, positions, chat.id.as_ref()),
452 None => chat.unread_count,
453 })
454 .fold(0, u64::saturating_add))
455}
456
457/// Whether the owner has muted `chat` right now: until `muteUntil` when
458/// it is set, otherwise when `muted` is `true`.
459fn chat_muted(chat: &Chat) -> bool {
460 match &chat.mute_until {
461 Some(until) => mute_active(until),
462 None => chat.muted,
463 }
464}
465
466/// Fit `push` to a platform payload limit of `max_bytes` serialized JSON
467/// bytes, returning the payloads to deliver in order. A `None` element
468/// stands for one message whose entry cannot fit; the caller delivers a
469/// `StateChange` for the `Message` data type in its place.
470///
471/// The limit is the delivery platform's; for Web Push,
472/// jmap-push-platform-guide §Payload size: "Servers MUST keep plaintext
473/// under **3993 bytes**", so pass 3992 there.
474///
475/// draft-atwood-jmap-chat-push-00 §Delivery: "If a single
476/// `ChatMessageEntry` does not fit, the server SHOULD shorten or omit that
477/// entry's `bodySnippet`; if the entry still does not fit, the server
478/// delivers a `StateChange` for the `Message` data type in place of a
479/// `ChatMessagePush` for that message." A `push` that fits is returned
480/// unchanged. Otherwise each entry goes in a payload of its own, with the
481/// same `accountId`, `state`, `unreadCount` and extension fields, so no message is lost
482/// (§Delivery: "the server MUST deliver additional `ChatMessagePush`
483/// payloads to cover the remainder"). An entry that does not fit alone
484/// loses `bodySnippet`; no other field is ever removed.
485// ponytail: the snippet is omitted, not shortened, since JSON escaping
486// makes the fitting length a search. Upgrade path: trim it on a UTF-8
487// boundary until the payload fits.
488pub fn fit_chat_message_push(
489 mut push: ChatMessagePush,
490 max_bytes: usize,
491) -> Vec<Option<ChatMessagePush>> {
492 let fits = |p: &ChatMessagePush| serde_json::to_vec(p).is_ok_and(|v| v.len() <= max_bytes);
493 if fits(&push) {
494 return vec![Some(push)];
495 }
496 std::mem::take(&mut push.messages)
497 .into_iter()
498 .map(|entry| {
499 let mut single = push.clone();
500 single.messages = vec![entry];
501 if !fits(&single) {
502 single.messages[0].body_snippet = None;
503 }
504 fits(&single).then_some(single)
505 })
506 .collect()
507}
508
509/// Whether a `ChatMessagePush` for the new inbound message `msg` goes to
510/// a subscription whose `chatPush` entry for `account_id` is `cfg`.
511///
512/// `caps` maps each account that advertises
513/// `urn:ietf:params:jmap:chat:push` to its capability object; a `cfg` for
514/// an account not in `caps` counts as absent and gets `false`
515/// (draft-atwood-jmap-chat-push-00 §PushSubscription Extension). `owner`
516/// is the owner's standing at delivery time, as for
517/// [`build_chat_message_push`].
518///
519/// Returns `true` only when the Chat matches `cfg` and none of the
520/// §Delivery exclusions applies:
521///
522/// - `cfg.kinds` and `cfg.chatIds` both match when present. §ChatPushConfig:
523/// "If both `kinds` and `chatIds` are present, a Chat matches only if its
524/// id appears in `chatIds` and its kind appears in `kinds`."
525/// - The sender is not the owner: `senderId` is not `account_id`.
526/// - The owner is still a member of the Chat. The account must hold the
527/// Chat; for a group Chat its `members` must have an entry whose id is
528/// `account_id`, and for a channel Chat its Space's `members` must.
529/// - The Chat is not muted, unless the owner is targeted by one of the message's broadcast
530/// mentions. Direct mentions never bypass a mute, and neither does an
531/// encrypted message (§End-to-End Encrypted Deployments: "never bypasses
532/// mute suppression"). When `muteUntil` is set, the Chat is muted until
533/// that time whatever `muted` says, because draft-atwood-jmap-chat-00
534/// §Chat `muteUntil` says "Muting expires at this time" and clearing
535/// `muted` afterwards is only a SHOULD. Otherwise the Chat is muted when
536/// `muted` is `true`. A `muteUntil` that is not a seconds-precision
537/// UTCDate, or a system clock before 1970, counts as an active mute.
538/// - The sender's `ChatContact` is not blocked, per
539/// [`ChatBackend::is_contact_blocked`].
540///
541/// # Messages stored before the subscription
542///
543/// §Delivery: "The server MUST NOT deliver a `ChatMessagePush` in any of
544/// the following cases: The message was stored before the
545/// `PushSubscription` was created." This function cannot see creation
546/// order. The caller MUST read the set of subscriptions under the same lock
547/// or transaction as the message write, and call this function only for
548/// subscriptions in that set, including when delivery fans out
549/// asynchronously afterwards.
550///
551/// # Errors
552///
553/// Returns the backend's error if reading the Chat, its Space or the
554/// sender's blocked status fails.
555pub async fn should_push<B: ChatBackend>(
556 backend: &B,
557 caller: &B::CallerCtx,
558 account_id: &Id,
559 cfg: &ChatPushConfig,
560 caps: &HashMap<Id, ChatPushCapability>,
561 msg: &Message,
562 owner: OwnerFlags,
563) -> Result<bool, B::Error> {
564 if !caps.contains_key(account_id) || msg.sender_id == *account_id {
565 return Ok(false);
566 }
567 if cfg
568 .chat_ids
569 .as_ref()
570 .is_some_and(|ids| !ids.contains(&msg.chat_id))
571 {
572 return Ok(false);
573 }
574 let (chats, _) = backend
575 .get_objects::<Chat>(
576 caller,
577 account_id,
578 Some(std::slice::from_ref(&msg.chat_id)),
579 None,
580 )
581 .await?;
582 let Some(chat) = chats.into_iter().next() else {
583 return Ok(false);
584 };
585 if cfg
586 .kinds
587 .as_ref()
588 .is_some_and(|kinds| !kinds.contains(&chat.kind))
589 {
590 return Ok(false);
591 }
592 if !owner_is_member(backend, caller, account_id, &chat).await? {
593 return Ok(false);
594 }
595 let bypass = is_plaintext(msg.body_type.as_str()) && !mention_scopes(msg, owner).is_empty();
596 if chat_muted(&chat) && !bypass {
597 return Ok(false);
598 }
599 Ok(!backend
600 .is_contact_blocked(caller, account_id, &msg.sender_id)
601 .await?)
602}
603
604/// Whether the owner of `account_id` is a current member of `chat`, its
605/// own Chat record: a group lists the owner in `members`, a channel's
606/// Space lists the owner, and a direct Chat always has its owner
607/// (draft-atwood-jmap-chat-00 §Terminology: the owner's member entry is
608/// the accountId).
609pub(crate) async fn owner_is_member<B: ChatBackend>(
610 backend: &B,
611 caller: &B::CallerCtx,
612 account_id: &Id,
613 chat: &Chat,
614) -> Result<bool, B::Error> {
615 let is_owner = |id: &Id| id == account_id;
616 Ok(match chat.kind {
617 ChatKind::Group => chat.members.iter().flatten().any(|m| is_owner(&m.id)),
618 ChatKind::Channel => match &chat.space_id {
619 Some(space_id) => backend
620 .get_objects::<Space>(
621 caller,
622 account_id,
623 Some(std::slice::from_ref(space_id)),
624 None,
625 )
626 .await?
627 .0
628 .iter()
629 .any(|space| space.members.iter().any(|m| is_owner(&m.id))),
630 None => false,
631 },
632 _ => true,
633 })
634}
635
636/// Whether a mute ending at `until` is still in effect: `until` is later
637/// than now. draft-atwood-jmap-chat-00 §Chat `muteUntil`: "Muting expires
638/// at this time." An unparseable `until` or clock counts as in effect.
639fn mute_active(until: &UTCDate) -> bool {
640 let now = SystemTime::now()
641 .duration_since(UNIX_EPOCH)
642 .ok()
643 .and_then(|d| i64::try_from(d.as_secs()).ok());
644 match (until.to_epoch_seconds(), now) {
645 (Ok(until), Some(now)) => now < until,
646 _ => true,
647 }
648}
649
650/// Whether `body_type` is one of the plaintext body types that
651/// draft-atwood-jmap-chat-push-00 §End-to-End Encrypted Deployments says
652/// "MUST set `encrypted` to `false`"; every other type is encrypted.
653fn is_plaintext(body_type: &str) -> bool {
654 [BodyType::Plain, BodyType::Markdown, BodyType::Rich]
655 .iter()
656 .any(|t| t.as_str() == body_type)
657}
658
659/// The deduplicated `Message.broadcastMentions[]` scopes that target the
660/// owner, in first-seen order. `"everyone"` always targets a Chat member;
661/// unknown scopes never do.
662fn mention_scopes(msg: &Message, owner: OwnerFlags) -> Vec<BroadcastScope> {
663 let mut scopes: Vec<BroadcastScope> = Vec::new();
664 for scope in msg.broadcast_mentions.iter().map(|b| &b.scope) {
665 let targets_owner = match scope {
666 BroadcastScope::Everyone => true,
667 BroadcastScope::Here => owner.active,
668 BroadcastScope::Admins => owner.admin,
669 _ => false,
670 };
671 if targets_owner && !scopes.contains(scope) {
672 scopes.push(scope.clone());
673 }
674 }
675 scopes
676}
677
678/// The plaintext of an `application/jmap-chat-rich` body: its span `text`
679/// values joined in order, or `None` when `body` is not a rich body. The
680/// spans only render the preview; servers must not validate the body or
681/// decide anything from span content (draft-atwood-jmap-chat-00 §Rich Body
682/// Format).
683fn rich_text(body: &str) -> Option<String> {
684 let rich: RichBody = serde_json::from_str(body).ok()?;
685 Some(rich.spans.into_iter().map(|s| s.text).collect())
686}
687
688/// `body` without control characters, cut to at most `max_bytes` bytes on
689/// a UTF-8 character boundary.
690fn snippet(body: &str, max_bytes: u64) -> String {
691 let mut text: String = body.chars().filter(|c| !c.is_control()).collect();
692 let mut end = usize::try_from(max_bytes).map_or(text.len(), |max| max.min(text.len()));
693 while !text.is_char_boundary(end) {
694 end -= 1;
695 }
696 text.truncate(end);
697 text
698}
699
700/// The `senderDisplayName` chain from draft-atwood-jmap-chat-push-00
701/// §ChatMessageEntry: the `SpaceMember.nick` (channels only), then
702/// `ChatContact.displayName`, then a non-empty `ChatContact.login`, then
703/// `ChatContact.identity`.
704fn sender_display_name(kind: &ChatKind, item: &PushItem<'_>) -> String {
705 let nick = item
706 .sender_member
707 .filter(|_| *kind == ChatKind::Channel)
708 .and_then(|m| m.nick.clone());
709 let login = Some(&item.sender.login).filter(|l| !l.is_empty()).cloned();
710 nick.or_else(|| item.sender.display_name.clone())
711 .or(login)
712 .unwrap_or_else(|| item.sender.identity.clone())
713}
714
715/// An `invalidProperties` SetError naming `property`.
716fn invalid(property: String) -> SetError {
717 SetError::new(SetErrorType::InvalidProperties).with_properties([property])
718}