Skip to main content

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)) => {
452                unread_count(messages, positions, account_id, chat.id.as_ref())
453            }
454            None => chat.unread_count,
455        })
456        .fold(0, u64::saturating_add))
457}
458
459/// Whether the owner has muted `chat` right now: until `muteUntil` when
460/// it is set, otherwise when `muted` is `true`.
461fn chat_muted(chat: &Chat) -> bool {
462    match &chat.mute_until {
463        Some(until) => mute_active(until),
464        None => chat.muted,
465    }
466}
467
468/// Fit `push` to a platform payload limit of `max_bytes` serialized JSON
469/// bytes, returning the payloads to deliver in order. A `None` element
470/// stands for one message whose entry cannot fit; the caller delivers a
471/// `StateChange` for the `Message` data type in its place.
472///
473/// The limit is the delivery platform's; for Web Push,
474/// jmap-push-platform-guide §Payload size: "Servers MUST keep plaintext
475/// under **3993 bytes**", so pass 3992 there.
476///
477/// draft-atwood-jmap-chat-push-00 §Delivery: "If a single
478/// `ChatMessageEntry` does not fit, the server SHOULD shorten or omit that
479/// entry's `bodySnippet`; if the entry still does not fit, the server
480/// delivers a `StateChange` for the `Message` data type in place of a
481/// `ChatMessagePush` for that message." A `push` that fits is returned
482/// unchanged. Otherwise each entry goes in a payload of its own, with the
483/// same `accountId`, `state`, `unreadCount` and extension fields, so no message is lost
484/// (§Delivery: "the server MUST deliver additional `ChatMessagePush`
485/// payloads to cover the remainder"). An entry that does not fit alone
486/// loses `bodySnippet`; no other field is ever removed.
487// ponytail: the snippet is omitted, not shortened, since JSON escaping
488// makes the fitting length a search. Upgrade path: trim it on a UTF-8
489// boundary until the payload fits.
490pub fn fit_chat_message_push(
491    mut push: ChatMessagePush,
492    max_bytes: usize,
493) -> Vec<Option<ChatMessagePush>> {
494    let fits = |p: &ChatMessagePush| serde_json::to_vec(p).is_ok_and(|v| v.len() <= max_bytes);
495    if fits(&push) {
496        return vec![Some(push)];
497    }
498    std::mem::take(&mut push.messages)
499        .into_iter()
500        .map(|entry| {
501            let mut single = push.clone();
502            single.messages = vec![entry];
503            if !fits(&single) {
504                single.messages[0].body_snippet = None;
505            }
506            fits(&single).then_some(single)
507        })
508        .collect()
509}
510
511/// Whether a `ChatMessagePush` for the new inbound message `msg` goes to
512/// a subscription whose `chatPush` entry for `account_id` is `cfg`.
513///
514/// `caps` maps each account that advertises
515/// `urn:ietf:params:jmap:chat:push` to its capability object; a `cfg` for
516/// an account not in `caps` counts as absent and gets `false`
517/// (draft-atwood-jmap-chat-push-00 §PushSubscription Extension). `owner`
518/// is the owner's standing at delivery time, as for
519/// [`build_chat_message_push`].
520///
521/// Returns `true` only when the Chat matches `cfg` and none of the
522/// §Delivery exclusions applies:
523///
524/// - `cfg.kinds` and `cfg.chatIds` both match when present. §ChatPushConfig:
525///   "If both `kinds` and `chatIds` are present, a Chat matches only if its
526///   id appears in `chatIds` and its kind appears in `kinds`."
527/// - The sender is not the owner: `senderId` is not `account_id`.
528/// - The owner is still a member of the Chat. The account must hold the
529///   Chat; for a group Chat its `members` must have an entry whose id is
530///   `account_id`, and for a channel Chat its Space's `members` must.
531/// - The Chat is not muted, unless the owner is targeted by one of the message's broadcast
532///   mentions. Direct mentions never bypass a mute, and neither does an
533///   encrypted message (§End-to-End Encrypted Deployments: "never bypasses
534///   mute suppression"). When `muteUntil` is set, the Chat is muted until
535///   that time whatever `muted` says, because draft-atwood-jmap-chat-00
536///   §Chat `muteUntil` says "Muting expires at this time" and clearing
537///   `muted` afterwards is only a SHOULD. Otherwise the Chat is muted when
538///   `muted` is `true`. A `muteUntil` that is not a seconds-precision
539///   UTCDate, or a system clock before 1970, counts as an active mute.
540/// - The sender's `ChatContact` is not blocked, per
541///   [`ChatBackend::is_contact_blocked`].
542///
543/// # Messages stored before the subscription
544///
545/// §Delivery: "The server MUST NOT deliver a `ChatMessagePush` in any of
546/// the following cases: The message was stored before the
547/// `PushSubscription` was created." This function cannot see creation
548/// order. The caller MUST read the set of subscriptions under the same lock
549/// or transaction as the message write, and call this function only for
550/// subscriptions in that set, including when delivery fans out
551/// asynchronously afterwards.
552///
553/// # Errors
554///
555/// Returns the backend's error if reading the Chat, its Space or the
556/// sender's blocked status fails.
557pub async fn should_push<B: ChatBackend>(
558    backend: &B,
559    caller: &B::CallerCtx,
560    account_id: &Id,
561    cfg: &ChatPushConfig,
562    caps: &HashMap<Id, ChatPushCapability>,
563    msg: &Message,
564    owner: OwnerFlags,
565) -> Result<bool, B::Error> {
566    if !caps.contains_key(account_id) || msg.sender_id == *account_id {
567        return Ok(false);
568    }
569    if cfg
570        .chat_ids
571        .as_ref()
572        .is_some_and(|ids| !ids.contains(&msg.chat_id))
573    {
574        return Ok(false);
575    }
576    let (chats, _) = backend
577        .get_objects::<Chat>(
578            caller,
579            account_id,
580            Some(std::slice::from_ref(&msg.chat_id)),
581            None,
582        )
583        .await?;
584    let Some(chat) = chats.into_iter().next() else {
585        return Ok(false);
586    };
587    if cfg
588        .kinds
589        .as_ref()
590        .is_some_and(|kinds| !kinds.contains(&chat.kind))
591    {
592        return Ok(false);
593    }
594    if !owner_is_member(backend, caller, account_id, &chat).await? {
595        return Ok(false);
596    }
597    let bypass = is_plaintext(msg.body_type.as_str()) && !mention_scopes(msg, owner).is_empty();
598    if chat_muted(&chat) && !bypass {
599        return Ok(false);
600    }
601    Ok(!backend
602        .is_contact_blocked(caller, account_id, &msg.sender_id)
603        .await?)
604}
605
606/// Whether the owner of `account_id` is a current member of `chat`, its
607/// own Chat record: a group lists the owner in `members`, a channel's
608/// Space lists the owner, and a direct Chat always has its owner
609/// (draft-atwood-jmap-chat-00 §Terminology: the owner's member entry is
610/// the accountId).
611pub(crate) async fn owner_is_member<B: ChatBackend>(
612    backend: &B,
613    caller: &B::CallerCtx,
614    account_id: &Id,
615    chat: &Chat,
616) -> Result<bool, B::Error> {
617    let is_owner = |id: &Id| id == account_id;
618    Ok(match chat.kind {
619        ChatKind::Group => chat.members.iter().flatten().any(|m| is_owner(&m.id)),
620        ChatKind::Channel => match &chat.space_id {
621            Some(space_id) => backend
622                .get_objects::<Space>(
623                    caller,
624                    account_id,
625                    Some(std::slice::from_ref(space_id)),
626                    None,
627                )
628                .await?
629                .0
630                .iter()
631                .any(|space| space.members.iter().any(|m| is_owner(&m.id))),
632            None => false,
633        },
634        _ => true,
635    })
636}
637
638/// Whether a mute ending at `until` is still in effect: `until` is later
639/// than now. draft-atwood-jmap-chat-00 §Chat `muteUntil`: "Muting expires
640/// at this time." An unparseable `until` or clock counts as in effect.
641fn mute_active(until: &UTCDate) -> bool {
642    let now = SystemTime::now()
643        .duration_since(UNIX_EPOCH)
644        .ok()
645        .and_then(|d| i64::try_from(d.as_secs()).ok());
646    match (until.to_epoch_seconds(), now) {
647        (Ok(until), Some(now)) => now < until,
648        _ => true,
649    }
650}
651
652/// Whether `body_type` is one of the plaintext body types that
653/// draft-atwood-jmap-chat-push-00 §End-to-End Encrypted Deployments says
654/// "MUST set `encrypted` to `false`"; every other type is encrypted.
655fn is_plaintext(body_type: &str) -> bool {
656    [BodyType::Plain, BodyType::Markdown, BodyType::Rich]
657        .iter()
658        .any(|t| t.as_str() == body_type)
659}
660
661/// The deduplicated `Message.broadcastMentions[]` scopes that target the
662/// owner, in first-seen order. `"everyone"` always targets a Chat member;
663/// unknown scopes never do.
664fn mention_scopes(msg: &Message, owner: OwnerFlags) -> Vec<BroadcastScope> {
665    let mut scopes: Vec<BroadcastScope> = Vec::new();
666    for scope in msg.broadcast_mentions.iter().map(|b| &b.scope) {
667        let targets_owner = match scope {
668            BroadcastScope::Everyone => true,
669            BroadcastScope::Here => owner.active,
670            BroadcastScope::Admins => owner.admin,
671            _ => false,
672        };
673        if targets_owner && !scopes.contains(scope) {
674            scopes.push(scope.clone());
675        }
676    }
677    scopes
678}
679
680/// The plaintext of an `application/jmap-chat-rich` body: its span `text`
681/// values joined in order, or `None` when `body` is not a rich body. The
682/// spans only render the preview; servers must not validate the body or
683/// decide anything from span content (draft-atwood-jmap-chat-00 §Rich Body
684/// Format).
685fn rich_text(body: &str) -> Option<String> {
686    let rich: RichBody = serde_json::from_str(body).ok()?;
687    Some(rich.spans.into_iter().map(|s| s.text).collect())
688}
689
690/// `body` without control characters, cut to at most `max_bytes` bytes on
691/// a UTF-8 character boundary.
692fn snippet(body: &str, max_bytes: u64) -> String {
693    let mut text: String = body.chars().filter(|c| !c.is_control()).collect();
694    let mut end = usize::try_from(max_bytes).map_or(text.len(), |max| max.min(text.len()));
695    while !text.is_char_boundary(end) {
696        end -= 1;
697    }
698    text.truncate(end);
699    text
700}
701
702/// The `senderDisplayName` chain from draft-atwood-jmap-chat-push-00
703/// §ChatMessageEntry: the `SpaceMember.nick` (channels only), then
704/// `ChatContact.displayName`, then a non-empty `ChatContact.login`, then
705/// `ChatContact.identity`.
706fn sender_display_name(kind: &ChatKind, item: &PushItem<'_>) -> String {
707    let nick = item
708        .sender_member
709        .filter(|_| *kind == ChatKind::Channel)
710        .and_then(|m| m.nick.clone());
711    let login = Some(&item.sender.login).filter(|l| !l.is_empty()).cloned();
712    nick.or_else(|| item.sender.display_name.clone())
713        .or(login)
714        .unwrap_or_else(|| item.sender.identity.clone())
715}
716
717/// An `invalidProperties` SetError naming `property`.
718fn invalid(property: String) -> SetError {
719    SetError::new(SetErrorType::InvalidProperties).with_properties([property])
720}