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