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 MAY include this for platforms that support atomic badge
289/// updates" (draft-atwood-jmap-chat-push-00, jmap-chat-spec 77c3474 L150).
290/// `None` leaves it out.
291///
292/// The entry holds exactly the fields in `cfg.properties`, or the default
293/// set when it is absent. §ChatPushConfig: "The `properties` list is
294/// authoritative: the server returns exactly the requested fields." Each
295/// field is derived as §ChatMessageEntry says, with these exceptions:
296///
297/// - `encrypted` comes from `bodyType`: `false` for `text/plain`,
298///   `text/markdown` and `application/jmap-chat-rich`, otherwise `true`
299///   (§End-to-End Encrypted Deployments). An encrypted entry never has
300///   `hasMention`, `mentionScopes` or `bodySnippet`.
301/// - `bodySnippet` is the body with control characters removed, cut to at
302///   most `cap.maxSnippetBytes` bytes on a UTF-8 character boundary.
303///   Markdown markup is left in, which misses the §ChatMessageEntry SHOULD
304///   for a plaintext approximation. For `application/jmap-chat-rich` the
305///   snippet is rendered from the span `text` values joined in order
306///   (draft-atwood-jmap-chat-00 §Span Object: "The plaintext content of
307///   this span"), so no markup reaches it; a body that does not parse as a
308///   rich body gets no snippet.
309/// - `senderDisplayName` treats an empty `login` as absent.
310///
311/// The urgency is `cfg.mentionUrgency` when it is set and the owner is
312/// mentioned directly or by a targeting broadcast scope, otherwise
313/// `cfg.urgency`, otherwise `"normal"` (§Urgency). The mention test uses
314/// the computed mention, whether or not `properties` asks for
315/// `hasMention` or `mentionScopes`. A chosen value outside RFC 8030
316/// (`UrgencyLevel::Other`, which [`validate_chat_push`] rejects before a
317/// config is stored) is also sent as `"normal"`, the urgency of a push
318/// without the header (RFC 8030 §5.3).
319pub fn build_chat_message_push(
320    account_id: &Id,
321    state: State,
322    cfg: &ChatPushConfig,
323    cap: &ChatPushCapability,
324    owner: OwnerFlags,
325    item: PushItem<'_>,
326    unread_count: Option<u64>,
327) -> BuiltPush {
328    let msg = item.message;
329    let kind = item.chat.kind.clone();
330    let body_type = msg.body_type.as_str();
331    let plaintext = is_plaintext(body_type);
332
333    let mut mentioned = false;
334    let mut entry = if plaintext {
335        let has_mention = msg.mentions.iter().any(|m| m.id == *account_id);
336        let scopes = mention_scopes(msg, owner);
337        mentioned = has_mention || !scopes.is_empty();
338        let snippet = if body_type == BodyType::Rich.as_str() {
339            rich_text(&msg.body).map(|text| snippet(&text, cap.max_snippet_bytes))
340        } else {
341            Some(snippet(&msg.body, cap.max_snippet_bytes))
342        };
343        ChatMessageEntry::plaintext(
344            msg.id.clone(),
345            msg.chat_id.clone(),
346            kind.clone(),
347            msg.sender_id.clone(),
348            msg.sent_at.clone(),
349            has_mention,
350            scopes,
351            snippet,
352        )
353    } else {
354        ChatMessageEntry::encrypted(
355            msg.id.clone(),
356            msg.chat_id.clone(),
357            kind.clone(),
358            msg.sender_id.clone(),
359            msg.sent_at.clone(),
360        )
361    };
362    if kind != ChatKind::Direct {
363        entry.chat_name = item.chat.name.clone();
364    }
365    if kind == ChatKind::Channel {
366        entry.space_id = item.chat.space_id.clone();
367        entry.space_name = item.space.map(|s| s.name.clone());
368    }
369    entry.sender_display_name = Some(sender_display_name(&kind, &item));
370
371    let wanted = |name: &str| match &cfg.properties {
372        Some(properties) => properties.iter().any(|p| p == name),
373        None => DEFAULT_ENTRY_PROPERTIES.contains(&name),
374    };
375    entry.message_id = entry.message_id.take().filter(|_| wanted("messageId"));
376    entry.chat_id = entry.chat_id.take().filter(|_| wanted("chatId"));
377    entry.chat_kind = entry.chat_kind.take().filter(|_| wanted("chatKind"));
378    entry.chat_name = entry.chat_name.take().filter(|_| wanted("chatName"));
379    entry.space_id = entry.space_id.take().filter(|_| wanted("spaceId"));
380    entry.space_name = entry.space_name.take().filter(|_| wanted("spaceName"));
381    entry.sender_id = entry.sender_id.take().filter(|_| wanted("senderId"));
382    entry.sender_display_name = entry
383        .sender_display_name
384        .take()
385        .filter(|_| wanted("senderDisplayName"));
386    entry.sent_at = entry.sent_at.take().filter(|_| wanted("sentAt"));
387    entry.has_mention = entry.has_mention.take().filter(|_| wanted("hasMention"));
388    entry.mention_scopes = entry
389        .mention_scopes
390        .take()
391        .filter(|_| wanted("mentionScopes"));
392    entry.encrypted = entry.encrypted.take().filter(|_| wanted("encrypted"));
393    entry.body_snippet = entry.body_snippet.take().filter(|_| wanted("bodySnippet"));
394
395    let urgency = cfg
396        .mention_urgency
397        .as_ref()
398        .filter(|_| mentioned)
399        .or(cfg.urgency.as_ref())
400        .and_then(UrgencyLevel::to_urgency)
401        .unwrap_or(Urgency::Normal);
402    // ponytail: one message per payload, which §Delivery allows ("Contains
403    // exactly one entry for a single new message") and §Batching and Retry
404    // prefers ("at most one `ChatMessagePush` per message"). The upgrade
405    // path is batching, chunked by `maxMessagesPerPush`.
406    let mut payload = ChatMessagePush::new(account_id.clone(), state, vec![entry]);
407    payload.unread_count = unread_count;
408    BuiltPush { payload, urgency }
409}
410
411/// The owner of `account_id`'s total unread message count across all
412/// non-muted Chats, for [`build_chat_message_push`].
413///
414/// draft-atwood-jmap-chat-push-00 §ChatMessagePush `unreadCount`: "The
415/// account owner's total unread message count across all non-muted Chats
416/// at the time this push was generated." Each Chat contributes its
417/// `unreadCount` as `Chat/get` reports it: the stored value when
418/// [`ChatSettings::maintains_unread_count`](crate::ChatSettings::maintains_unread_count) is `true`, otherwise the count
419/// derived from the owner's ReadPosition (draft-atwood-jmap-chat-00
420/// §Chat `unreadCount`). A Chat is muted as in [`should_push`]: until
421/// `muteUntil` when it is set, otherwise when `muted` is `true`.
422///
423/// # Errors
424///
425/// Returns the backend's error if reading the Chats, Messages or
426/// ReadPositions fails.
427// ponytail: like Chat/get, a backend that does not maintain the count is
428// scanned in full (O(messages)) per call.
429pub async fn owner_unread_count<B: ChatBackend>(
430    backend: &B,
431    caller: &B::CallerCtx,
432    account_id: &Id,
433) -> Result<u64, B::Error> {
434    let (chats, _) = backend
435        .get_objects::<Chat>(caller, account_id, None, None)
436        .await?;
437    let derived = if backend.maintains_unread_count() {
438        None
439    } else {
440        let (messages, _) = backend
441            .get_objects::<Message>(caller, account_id, None, None)
442            .await?;
443        let (positions, _) = backend
444            .get_objects::<ReadPosition>(caller, account_id, None, None)
445            .await?;
446        Some((messages, positions))
447    };
448    Ok(chats
449        .iter()
450        .filter(|chat| !chat_muted(chat))
451        .map(|chat| match &derived {
452            Some((messages, positions)) => {
453                unread_count(messages, positions, account_id, chat.id.as_ref())
454            }
455            None => chat.unread_count,
456        })
457        .fold(0, u64::saturating_add))
458}
459
460/// Whether the owner has muted `chat` right now: until `muteUntil` when
461/// it is set, otherwise when `muted` is `true`.
462fn chat_muted(chat: &Chat) -> bool {
463    match &chat.mute_until {
464        Some(until) => mute_active(until),
465        None => chat.muted,
466    }
467}
468
469/// Fit `push` to a platform payload limit of `max_bytes` serialized JSON
470/// bytes, returning the payloads to deliver in order. A `None` element
471/// stands for one message whose entry cannot fit; the caller delivers a
472/// `StateChange` for the `Message` data type in its place.
473///
474/// The limit is the delivery platform's; for Web Push,
475/// jmap-push-platform-guide §Payload size: "Servers MUST keep plaintext
476/// under **3993 bytes**", so pass 3992 there.
477///
478/// draft-atwood-jmap-chat-push-00 §Delivery: "If a single
479/// `ChatMessageEntry` does not fit, the server SHOULD shorten or omit that
480/// entry's `bodySnippet`; if the entry still does not fit, the server
481/// delivers a `StateChange` for the `Message` data type in place of a
482/// `ChatMessagePush` for that message." A `push` that fits is returned
483/// unchanged. Otherwise each entry goes in a payload of its own, with the
484/// same `accountId`, `state`, `unreadCount` and extension fields, so no message is lost
485/// (§Delivery: "the server MUST deliver additional `ChatMessagePush`
486/// payloads to cover the remainder"). An entry that does not fit alone
487/// loses `bodySnippet`; no other field is ever removed.
488// ponytail: the snippet is omitted, not shortened, since JSON escaping
489// makes the fitting length a search. Upgrade path: trim it on a UTF-8
490// boundary until the payload fits.
491pub fn fit_chat_message_push(
492    mut push: ChatMessagePush,
493    max_bytes: usize,
494) -> Vec<Option<ChatMessagePush>> {
495    let fits = |p: &ChatMessagePush| serde_json::to_vec(p).is_ok_and(|v| v.len() <= max_bytes);
496    if fits(&push) {
497        return vec![Some(push)];
498    }
499    std::mem::take(&mut push.messages)
500        .into_iter()
501        .map(|entry| {
502            let mut single = push.clone();
503            single.messages = vec![entry];
504            if !fits(&single) {
505                single.messages[0].body_snippet = None;
506            }
507            fits(&single).then_some(single)
508        })
509        .collect()
510}
511
512/// Whether a `ChatMessagePush` for the new inbound message `msg` goes to
513/// a subscription whose `chatPush` entry for `account_id` is `cfg`.
514///
515/// `caps` maps each account that advertises
516/// `urn:ietf:params:jmap:chat:push` to its capability object; a `cfg` for
517/// an account not in `caps` counts as absent and gets `false`
518/// (draft-atwood-jmap-chat-push-00 §PushSubscription Extension). `owner`
519/// is the owner's standing at delivery time, as for
520/// [`build_chat_message_push`].
521///
522/// Returns `true` only when the Chat matches `cfg` and none of the
523/// §Delivery exclusions applies:
524///
525/// - `cfg.kinds` and `cfg.chatIds` both match when present. §ChatPushConfig:
526///   "If both `kinds` and `chatIds` are present, a Chat matches only if its
527///   id appears in `chatIds` and its kind appears in `kinds`."
528/// - The sender is not the owner: `senderId` is not `account_id`.
529/// - The owner is still a member of the Chat. The account must hold the
530///   Chat; for a group Chat its `members` must have an entry whose id is
531///   `account_id`, and for a channel Chat its Space's `members` must.
532/// - The Chat is not muted, unless the owner is targeted by one of the message's broadcast
533///   mentions. Direct mentions never bypass a mute, and neither does an
534///   encrypted message (§End-to-End Encrypted Deployments: "never bypasses
535///   mute suppression"). When `muteUntil` is set, the Chat is muted until
536///   that time whatever `muted` says, because draft-atwood-jmap-chat-00
537///   §Chat `muteUntil` says "Muting expires at this time" and clearing
538///   `muted` afterwards is only a SHOULD. Otherwise the Chat is muted when
539///   `muted` is `true`. A `muteUntil` that is not a seconds-precision
540///   UTCDate, or a system clock before 1970, counts as an active mute.
541/// - The sender's `ChatContact` is not blocked, per
542///   [`ChatAccessPolicy::is_contact_blocked`](crate::ChatAccessPolicy::is_contact_blocked).
543///
544/// # Messages stored before the subscription
545///
546/// §Delivery (draft-atwood-jmap-chat-push-00, jmap-chat-spec 77c3474
547/// L214): "The server SHOULD NOT deliver a `ChatMessagePush` in any of the
548/// following cases: The message was stored before the `PushSubscription`
549/// was created." This crate follows the recommendation by choice. This
550/// function cannot see creation
551/// order. The caller MUST read the set of subscriptions under the same lock
552/// or transaction as the message write, and call this function only for
553/// subscriptions in that set, including when delivery fans out
554/// asynchronously afterwards.
555///
556/// # Errors
557///
558/// Returns the backend's error if reading the Chat, its Space or the
559/// sender's blocked status fails.
560pub async fn should_push<B: ChatBackend>(
561    backend: &B,
562    caller: &B::CallerCtx,
563    account_id: &Id,
564    cfg: &ChatPushConfig,
565    caps: &HashMap<Id, ChatPushCapability>,
566    msg: &Message,
567    owner: OwnerFlags,
568) -> Result<bool, B::Error> {
569    if !caps.contains_key(account_id) || msg.sender_id == *account_id {
570        return Ok(false);
571    }
572    if cfg
573        .chat_ids
574        .as_ref()
575        .is_some_and(|ids| !ids.contains(&msg.chat_id))
576    {
577        return Ok(false);
578    }
579    let (chats, _) = backend
580        .get_objects::<Chat>(
581            caller,
582            account_id,
583            Some(std::slice::from_ref(&msg.chat_id)),
584            None,
585        )
586        .await?;
587    let Some(chat) = chats.into_iter().next() else {
588        return Ok(false);
589    };
590    if cfg
591        .kinds
592        .as_ref()
593        .is_some_and(|kinds| !kinds.contains(&chat.kind))
594    {
595        return Ok(false);
596    }
597    if !owner_is_member(backend, caller, account_id, &chat).await? {
598        return Ok(false);
599    }
600    let bypass = is_plaintext(msg.body_type.as_str()) && !mention_scopes(msg, owner).is_empty();
601    if chat_muted(&chat) && !bypass {
602        return Ok(false);
603    }
604    Ok(!backend
605        .is_contact_blocked(caller, account_id, &msg.sender_id)
606        .await?)
607}
608
609/// Whether the owner of `account_id` is a current member of `chat`, its
610/// own Chat record: a group lists the owner in `members`, a channel's
611/// Space lists the owner, and a direct Chat always has its owner
612/// (draft-atwood-jmap-chat-00 §Terminology: the owner's member entry is
613/// the accountId).
614pub(crate) async fn owner_is_member<B: ChatBackend>(
615    backend: &B,
616    caller: &B::CallerCtx,
617    account_id: &Id,
618    chat: &Chat,
619) -> Result<bool, B::Error> {
620    let is_owner = |id: &Id| id == account_id;
621    Ok(match chat.kind {
622        ChatKind::Group => chat.members.iter().flatten().any(|m| is_owner(&m.id)),
623        ChatKind::Channel => match &chat.space_id {
624            Some(space_id) => backend
625                .get_objects::<Space>(
626                    caller,
627                    account_id,
628                    Some(std::slice::from_ref(space_id)),
629                    None,
630                )
631                .await?
632                .0
633                .iter()
634                .any(|space| space.members.iter().any(|m| is_owner(&m.id))),
635            None => false,
636        },
637        _ => true,
638    })
639}
640
641/// Whether a mute ending at `until` is still in effect: `until` is later
642/// than now. draft-atwood-jmap-chat-00 §Chat `muteUntil`: "Muting expires
643/// at this time." An unparseable `until` or clock counts as in effect.
644fn mute_active(until: &UTCDate) -> bool {
645    let now = SystemTime::now()
646        .duration_since(UNIX_EPOCH)
647        .ok()
648        .and_then(|d| i64::try_from(d.as_secs()).ok());
649    match (until.to_epoch_seconds(), now) {
650        (Ok(until), Some(now)) => now < until,
651        _ => true,
652    }
653}
654
655/// Whether `body_type` is one of the plaintext body types that
656/// draft-atwood-jmap-chat-push-00 §End-to-End Encrypted Deployments says
657/// "MUST set `encrypted` to `false`"; every other type is encrypted.
658fn is_plaintext(body_type: &str) -> bool {
659    [BodyType::Plain, BodyType::Markdown, BodyType::Rich]
660        .iter()
661        .any(|t| t.as_str() == body_type)
662}
663
664/// The deduplicated `Message.broadcastMentions[]` scopes that target the
665/// owner, in first-seen order. `"everyone"` always targets a Chat member;
666/// unknown scopes never do.
667fn mention_scopes(msg: &Message, owner: OwnerFlags) -> Vec<BroadcastScope> {
668    let mut scopes: Vec<BroadcastScope> = Vec::new();
669    for scope in msg.broadcast_mentions.iter().map(|b| &b.scope) {
670        let targets_owner = match scope {
671            BroadcastScope::Everyone => true,
672            BroadcastScope::Here => owner.active,
673            BroadcastScope::Admins => owner.admin,
674            _ => false,
675        };
676        if targets_owner && !scopes.contains(scope) {
677            scopes.push(scope.clone());
678        }
679    }
680    scopes
681}
682
683/// The plaintext of an `application/jmap-chat-rich` body: its span `text`
684/// values joined in order, or `None` when `body` is not a rich body. The
685/// spans only render the preview; servers must not validate the body or
686/// decide anything from span content (draft-atwood-jmap-chat-00 §Rich Body
687/// Format).
688fn rich_text(body: &str) -> Option<String> {
689    let rich: RichBody = serde_json::from_str(body).ok()?;
690    Some(rich.spans.into_iter().map(|s| s.text).collect())
691}
692
693/// `body` without control characters, cut to at most `max_bytes` bytes at
694/// an extended grapheme cluster boundary (draft-atwood-jmap-updates-00
695/// §6.5), so a push preview never ends in half an emoji or a bare base
696/// letter.
697fn snippet(body: &str, max_bytes: u64) -> String {
698    let text: String = body.chars().filter(|c| !c.is_control()).collect();
699    let max = usize::try_from(max_bytes).unwrap_or(usize::MAX);
700    jmap_types::text::truncate_graphemes(&text, max).to_owned()
701}
702
703/// The `senderDisplayName` chain from draft-atwood-jmap-chat-push-00
704/// §ChatMessageEntry: the `SpaceMember.nick` (channels only), then
705/// `ChatContact.displayName`, then a non-empty `ChatContact.login`, then
706/// `ChatContact.identity`.
707fn sender_display_name(kind: &ChatKind, item: &PushItem<'_>) -> String {
708    let nick = item
709        .sender_member
710        .filter(|_| *kind == ChatKind::Channel)
711        .and_then(|m| m.nick.clone());
712    let login = Some(&item.sender.login).filter(|l| !l.is_empty()).cloned();
713    nick.or_else(|| item.sender.display_name.clone())
714        .or(login)
715        .unwrap_or_else(|| item.sender.identity.clone())
716}
717
718/// An `invalidProperties` SetError naming `property`.
719fn invalid(property: String) -> SetError {
720    SetError::new(SetErrorType::InvalidProperties).with_properties([property])
721}
722
723#[cfg(test)]
724mod snippet_tests {
725    use super::snippet;
726
727    /// draft-atwood-jmap-updates-00 §6.5: a shortened push preview is cut at
728    /// an extended grapheme cluster boundary (UAX #29), within the octet cap.
729    #[test]
730    fn snippet_cuts_at_grapheme_boundaries() {
731        // "e" + U+0301 is one 3-octet cluster: a 2-octet cap must not keep
732        // the bare "e".
733        assert_eq!(snippet("ae\u{301}", 2), "a");
734        // Woman technologist (ZWJ sequence, 11 octets) is all or nothing.
735        let tech = "\u{1F469}\u{200D}\u{1F4BB}";
736        assert_eq!(snippet(&format!("x{tech}"), 11), "x");
737        assert_eq!(snippet(&format!("x{tech}"), 12), format!("x{tech}"));
738        // Control characters are still removed first.
739        assert_eq!(snippet("a\nb", 10), "ab");
740    }
741}