ruma_common/push/
condition.rs

1use std::{collections::BTreeMap, ops::RangeBounds, str::FromStr};
2#[cfg(feature = "unstable-msc4306")]
3use std::{future::Future, pin::Pin, sync::Arc};
4
5use js_int::{Int, UInt};
6use regex::bytes::Regex;
7#[cfg(feature = "unstable-msc3931")]
8use ruma_macros::StringEnum;
9use serde::{Deserialize, Serialize};
10use serde_json::value::Value as JsonValue;
11use wildmatch::WildMatch;
12
13#[cfg(feature = "unstable-msc4306")]
14use crate::EventId;
15use crate::{
16    power_levels::{NotificationPowerLevels, NotificationPowerLevelsKey},
17    room_version_rules::RoomPowerLevelsRules,
18    OwnedRoomId, OwnedUserId, UserId,
19};
20#[cfg(feature = "unstable-msc3931")]
21use crate::{PrivOwnedStr, RoomVersionId};
22
23mod flattened_json;
24mod push_condition_serde;
25mod room_member_count_is;
26
27pub use self::{
28    flattened_json::{FlattenedJson, FlattenedJsonValue, ScalarJsonValue},
29    room_member_count_is::{ComparisonOperator, RoomMemberCountIs},
30};
31
32/// Features supported by room versions.
33#[cfg(feature = "unstable-msc3931")]
34#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
35#[derive(Clone, PartialEq, Eq, StringEnum)]
36#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
37pub enum RoomVersionFeature {
38    /// m.extensible_events
39    ///
40    /// The room supports [extensible events].
41    ///
42    /// [extensible events]: https://github.com/matrix-org/matrix-spec-proposals/pull/1767
43    #[cfg(feature = "unstable-msc3932")]
44    #[ruma_enum(rename = "org.matrix.msc3932.extensible_events")]
45    ExtensibleEvents,
46
47    #[doc(hidden)]
48    _Custom(PrivOwnedStr),
49}
50
51#[cfg(feature = "unstable-msc3931")]
52impl RoomVersionFeature {
53    /// Get the default features for the given room version.
54    pub fn list_for_room_version(version: &RoomVersionId) -> Vec<Self> {
55        match version {
56            RoomVersionId::V1
57            | RoomVersionId::V2
58            | RoomVersionId::V3
59            | RoomVersionId::V4
60            | RoomVersionId::V5
61            | RoomVersionId::V6
62            | RoomVersionId::V7
63            | RoomVersionId::V8
64            | RoomVersionId::V9
65            | RoomVersionId::V10
66            | RoomVersionId::V11
67            | RoomVersionId::V12
68            | RoomVersionId::_Custom(_) => vec![],
69            #[cfg(feature = "unstable-hydra")]
70            RoomVersionId::HydraV11 => vec![],
71            #[cfg(feature = "unstable-msc2870")]
72            RoomVersionId::MSC2870 => vec![],
73        }
74    }
75}
76
77/// A condition that must apply for an associated push rule's action to be taken.
78#[derive(Clone, Debug)]
79#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
80pub enum PushCondition {
81    /// A glob pattern match on a field of the event.
82    EventMatch {
83        /// The [dot-separated path] of the property of the event to match.
84        ///
85        /// [dot-separated path]: https://spec.matrix.org/latest/appendices/#dot-separated-property-paths
86        key: String,
87
88        /// The glob-style pattern to match against.
89        ///
90        /// Patterns with no special glob characters should be treated as having asterisks
91        /// prepended and appended when testing the condition.
92        pattern: String,
93    },
94
95    /// Matches unencrypted messages where `content.body` contains the owner's display name in that
96    /// room.
97    ContainsDisplayName,
98
99    /// Matches the current number of members in the room.
100    RoomMemberCount {
101        /// The condition on the current number of members in the room.
102        is: RoomMemberCountIs,
103    },
104
105    /// Takes into account the current power levels in the room, ensuring the sender of the event
106    /// has high enough power to trigger the notification.
107    SenderNotificationPermission {
108        /// The field in the power level event the user needs a minimum power level for.
109        ///
110        /// Fields must be specified under the `notifications` property in the power level event's
111        /// `content`.
112        key: NotificationPowerLevelsKey,
113    },
114
115    /// Apply the rule only to rooms that support a given feature.
116    #[cfg(feature = "unstable-msc3931")]
117    RoomVersionSupports {
118        /// The feature the room must support for the push rule to apply.
119        feature: RoomVersionFeature,
120    },
121
122    /// Exact value match on a property of the event.
123    EventPropertyIs {
124        /// The [dot-separated path] of the property of the event to match.
125        ///
126        /// [dot-separated path]: https://spec.matrix.org/latest/appendices/#dot-separated-property-paths
127        key: String,
128
129        /// The value to match against.
130        value: ScalarJsonValue,
131    },
132
133    /// Exact value match on a value in an array property of the event.
134    EventPropertyContains {
135        /// The [dot-separated path] of the property of the event to match.
136        ///
137        /// [dot-separated path]: https://spec.matrix.org/latest/appendices/#dot-separated-property-paths
138        key: String,
139
140        /// The value to match against.
141        value: ScalarJsonValue,
142    },
143
144    /// Matches a thread event based on the user's thread subscription status, as defined by
145    /// [MSC4306].
146    ///
147    /// [MSC4306]: https://github.com/matrix-org/matrix-spec-proposals/pull/4306
148    #[cfg(feature = "unstable-msc4306")]
149    ThreadSubscription {
150        /// Whether the user must be subscribed (`true`) or unsubscribed (`false`) to the thread
151        /// for the condition to match.
152        subscribed: bool,
153    },
154
155    #[doc(hidden)]
156    _Custom(_CustomPushCondition),
157}
158
159pub(super) fn check_event_match(
160    event: &FlattenedJson,
161    key: &str,
162    pattern: &str,
163    context: &PushConditionRoomCtx,
164) -> bool {
165    let value = match key {
166        "room_id" => context.room_id.as_str(),
167        _ => match event.get_str(key) {
168            Some(v) => v,
169            None => return false,
170        },
171    };
172
173    value.matches_pattern(pattern, key == "content.body")
174}
175
176impl PushCondition {
177    /// Check if this condition applies to the event.
178    ///
179    /// # Arguments
180    ///
181    /// * `event` - The flattened JSON representation of a room message event.
182    /// * `context` - The context of the room at the time of the event. If the power levels context
183    ///   is missing from it, conditions that depend on it will never apply.
184    pub async fn applies(&self, event: &FlattenedJson, context: &PushConditionRoomCtx) -> bool {
185        if event.get_str("sender").is_some_and(|sender| sender == context.user_id) {
186            return false;
187        }
188
189        match self {
190            Self::EventMatch { key, pattern } => check_event_match(event, key, pattern, context),
191            Self::ContainsDisplayName => {
192                let Some(value) = event.get_str("content.body") else { return false };
193                value.matches_pattern(&context.user_display_name, true)
194            }
195            Self::RoomMemberCount { is } => is.contains(&context.member_count),
196            Self::SenderNotificationPermission { key } => {
197                let Some(power_levels) = &context.power_levels else { return false };
198                let Some(sender_id) = event.get_str("sender") else { return false };
199                let Ok(sender_id) = <&UserId>::try_from(sender_id) else { return false };
200
201                power_levels.has_sender_notification_permission(sender_id, key)
202            }
203            #[cfg(feature = "unstable-msc3931")]
204            Self::RoomVersionSupports { feature } => match feature {
205                RoomVersionFeature::ExtensibleEvents => {
206                    context.supported_features.contains(&RoomVersionFeature::ExtensibleEvents)
207                }
208                RoomVersionFeature::_Custom(_) => false,
209            },
210            Self::EventPropertyIs { key, value } => event.get(key).is_some_and(|v| v == value),
211            Self::EventPropertyContains { key, value } => event
212                .get(key)
213                .and_then(FlattenedJsonValue::as_array)
214                .is_some_and(|a| a.contains(value)),
215            #[cfg(feature = "unstable-msc4306")]
216            Self::ThreadSubscription { subscribed: must_be_subscribed } => {
217                let Some(has_thread_subscription_fn) = &context.has_thread_subscription_fn else {
218                    // If we don't have a function to check thread subscriptions, we can't
219                    // determine if the condition applies.
220                    return false;
221                };
222
223                // The event must have a relation of type `m.thread`.
224                if event.get_str("content.m\\.relates_to.rel_type") != Some("m.thread") {
225                    return false;
226                }
227
228                // Retrieve the thread root event ID.
229                let Some(Ok(thread_root)) =
230                    event.get_str("content.m\\.relates_to.event_id").map(<&EventId>::try_from)
231                else {
232                    return false;
233                };
234
235                let is_subscribed = has_thread_subscription_fn(thread_root).await;
236
237                *must_be_subscribed == is_subscribed
238            }
239            Self::_Custom(_) => false,
240        }
241    }
242}
243
244/// An unknown push condition.
245#[doc(hidden)]
246#[derive(Clone, Debug, Deserialize, Serialize)]
247#[allow(clippy::exhaustive_structs)]
248pub struct _CustomPushCondition {
249    /// The kind of the condition.
250    kind: String,
251
252    /// The additional fields that the condition contains.
253    #[serde(flatten)]
254    data: BTreeMap<String, JsonValue>,
255}
256
257/// The context of the room associated to an event to be able to test all push conditions.
258#[derive(Clone)]
259#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
260pub struct PushConditionRoomCtx {
261    /// The ID of the room.
262    pub room_id: OwnedRoomId,
263
264    /// The number of members in the room.
265    pub member_count: UInt,
266
267    /// The user's matrix ID.
268    pub user_id: OwnedUserId,
269
270    /// The display name of the current user in the room.
271    pub user_display_name: String,
272
273    /// The room power levels context for the room.
274    ///
275    /// If this is missing, push rules that require this will never match.
276    pub power_levels: Option<PushConditionPowerLevelsCtx>,
277
278    /// The list of features this room's version or the room itself supports.
279    #[cfg(feature = "unstable-msc3931")]
280    pub supported_features: Vec<RoomVersionFeature>,
281
282    /// A closure that returns a future indicating if the given thread (represented by its thread
283    /// root event id) is subscribed to by the current user, where subscriptions are defined as per
284    /// [MSC4306].
285    ///
286    /// [MSC4306]: https://github.com/matrix-org/matrix-spec-proposals/pull/4306
287    #[cfg(feature = "unstable-msc4306")]
288    has_thread_subscription_fn: Option<Arc<HasThreadSubscriptionFn>>,
289}
290
291#[cfg(all(feature = "unstable-msc4306", not(target_family = "wasm")))]
292type HasThreadSubscriptionFuture<'a> = Pin<Box<dyn Future<Output = bool> + Send + 'a>>;
293
294#[cfg(all(feature = "unstable-msc4306", target_family = "wasm"))]
295type HasThreadSubscriptionFuture<'a> = Pin<Box<dyn Future<Output = bool> + 'a>>;
296
297#[cfg(all(feature = "unstable-msc4306", not(target_family = "wasm")))]
298type HasThreadSubscriptionFn =
299    dyn for<'a> Fn(&'a EventId) -> HasThreadSubscriptionFuture<'a> + Send + Sync;
300
301#[cfg(all(feature = "unstable-msc4306", target_family = "wasm"))]
302type HasThreadSubscriptionFn = dyn for<'a> Fn(&'a EventId) -> HasThreadSubscriptionFuture<'a>;
303
304impl std::fmt::Debug for PushConditionRoomCtx {
305    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
306        let mut debug_struct = f.debug_struct("PushConditionRoomCtx");
307
308        debug_struct
309            .field("room_id", &self.room_id)
310            .field("member_count", &self.member_count)
311            .field("user_id", &self.user_id)
312            .field("user_display_name", &self.user_display_name)
313            .field("power_levels", &self.power_levels);
314
315        #[cfg(feature = "unstable-msc3931")]
316        debug_struct.field("supported_features", &self.supported_features);
317
318        debug_struct.finish_non_exhaustive()
319    }
320}
321
322impl PushConditionRoomCtx {
323    /// Create a new `PushConditionRoomCtx`.
324    pub fn new(
325        room_id: OwnedRoomId,
326        member_count: UInt,
327        user_id: OwnedUserId,
328        user_display_name: String,
329    ) -> Self {
330        Self {
331            room_id,
332            member_count,
333            user_id,
334            user_display_name,
335            power_levels: None,
336            #[cfg(feature = "unstable-msc3931")]
337            supported_features: Vec::new(),
338            #[cfg(feature = "unstable-msc4306")]
339            has_thread_subscription_fn: None,
340        }
341    }
342
343    /// Set a function to check if the user is subscribed to a thread, so as to define the push
344    /// rules defined in [MSC4306].
345    ///
346    /// [MSC4306]: https://github.com/matrix-org/matrix-spec-proposals/pull/4306
347    #[cfg(feature = "unstable-msc4306")]
348    pub fn with_has_thread_subscription_fn(
349        self,
350        #[cfg(not(target_family = "wasm"))]
351        has_thread_subscription_fn: impl for<'a> Fn(&'a EventId) -> HasThreadSubscriptionFuture<'a>
352            + Send
353            + Sync
354            + 'static,
355        #[cfg(target_family = "wasm")]
356        has_thread_subscription_fn: impl for<'a> Fn(&'a EventId) -> HasThreadSubscriptionFuture<'a>
357            + 'static,
358    ) -> Self {
359        Self { has_thread_subscription_fn: Some(Arc::new(has_thread_subscription_fn)), ..self }
360    }
361
362    /// Add the given power levels context to this `PushConditionRoomCtx`.
363    pub fn with_power_levels(self, power_levels: PushConditionPowerLevelsCtx) -> Self {
364        Self { power_levels: Some(power_levels), ..self }
365    }
366}
367
368/// The room power levels context to be able to test the corresponding push conditions.
369///
370/// Should be constructed using `From<RoomPowerLevels>`.
371#[derive(Clone, Debug)]
372#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
373pub struct PushConditionPowerLevelsCtx {
374    /// The power levels of the users of the room.
375    pub users: BTreeMap<OwnedUserId, Int>,
376
377    /// The default power level of the users of the room.
378    pub users_default: Int,
379
380    /// The notification power levels of the room.
381    pub notifications: NotificationPowerLevels,
382
383    /// The tweaks for determining the power level of a user.
384    pub rules: RoomPowerLevelsRules,
385}
386
387impl PushConditionPowerLevelsCtx {
388    /// Create a new `PushConditionPowerLevelsCtx`.
389    pub fn new(
390        users: BTreeMap<OwnedUserId, Int>,
391        users_default: Int,
392        notifications: NotificationPowerLevels,
393        rules: RoomPowerLevelsRules,
394    ) -> Self {
395        Self { users, users_default, notifications, rules }
396    }
397
398    /// Whether the given user has the permission to notify for the given key.
399    pub fn has_sender_notification_permission(
400        &self,
401        user_id: &UserId,
402        key: &NotificationPowerLevelsKey,
403    ) -> bool {
404        let Some(notification_power_level) = self.notifications.get(key) else {
405            // We don't know the required power level for the key.
406            return false;
407        };
408
409        if self
410            .rules
411            .privileged_creators
412            .as_ref()
413            .is_some_and(|creators| creators.contains(user_id))
414        {
415            return true;
416        }
417
418        let user_power_level = self.users.get(user_id).unwrap_or(&self.users_default);
419
420        user_power_level >= notification_power_level
421    }
422}
423
424/// Additional functions for character matching.
425trait CharExt {
426    /// Whether or not this char can be part of a word.
427    fn is_word_char(&self) -> bool;
428}
429
430impl CharExt for char {
431    fn is_word_char(&self) -> bool {
432        self.is_ascii_alphanumeric() || *self == '_'
433    }
434}
435
436/// Additional functions for string matching.
437trait StrExt {
438    /// Get the length of the char at `index`. The byte index must correspond to
439    /// the start of a char boundary.
440    fn char_len(&self, index: usize) -> usize;
441
442    /// Get the char at `index`. The byte index must correspond to the start of
443    /// a char boundary.
444    fn char_at(&self, index: usize) -> char;
445
446    /// Get the index of the char that is before the char at `index`. The byte index
447    /// must correspond to a char boundary.
448    ///
449    /// Returns `None` if there's no previous char. Otherwise, returns the char.
450    fn find_prev_char(&self, index: usize) -> Option<char>;
451
452    /// Matches this string against `pattern`.
453    ///
454    /// The pattern can be a glob with wildcards `*` and `?`.
455    ///
456    /// The match is case insensitive.
457    ///
458    /// If `match_words` is `true`, checks that the pattern is separated from other words.
459    fn matches_pattern(&self, pattern: &str, match_words: bool) -> bool;
460
461    /// Matches this string against `pattern`, with word boundaries.
462    ///
463    /// The pattern can be a glob with wildcards `*` and `?`.
464    ///
465    /// A word boundary is defined as the start or end of the value, or any character not in the
466    /// sets `[A-Z]`, `[a-z]`, `[0-9]` or `_`.
467    ///
468    /// The match is case sensitive.
469    fn matches_word(&self, pattern: &str) -> bool;
470
471    /// Translate the wildcards in `self` to a regex syntax.
472    ///
473    /// `self` must only contain wildcards.
474    fn wildcards_to_regex(&self) -> String;
475}
476
477impl StrExt for str {
478    fn char_len(&self, index: usize) -> usize {
479        let mut len = 1;
480        while !self.is_char_boundary(index + len) {
481            len += 1;
482        }
483        len
484    }
485
486    fn char_at(&self, index: usize) -> char {
487        let end = index + self.char_len(index);
488        let char_str = &self[index..end];
489        char::from_str(char_str)
490            .unwrap_or_else(|_| panic!("Could not convert str '{char_str}' to char"))
491    }
492
493    fn find_prev_char(&self, index: usize) -> Option<char> {
494        if index == 0 {
495            return None;
496        }
497
498        let mut pos = index - 1;
499        while !self.is_char_boundary(pos) {
500            pos -= 1;
501        }
502        Some(self.char_at(pos))
503    }
504
505    fn matches_pattern(&self, pattern: &str, match_words: bool) -> bool {
506        let value = &self.to_lowercase();
507        let pattern = &pattern.to_lowercase();
508
509        if match_words {
510            value.matches_word(pattern)
511        } else {
512            WildMatch::new(pattern).matches(value)
513        }
514    }
515
516    fn matches_word(&self, pattern: &str) -> bool {
517        if self == pattern {
518            return true;
519        }
520        if pattern.is_empty() {
521            return false;
522        }
523
524        let has_wildcards = pattern.contains(['?', '*']);
525
526        if has_wildcards {
527            let mut chunks: Vec<String> = vec![];
528            let mut prev_wildcard = false;
529            let mut chunk_start = 0;
530
531            for (i, c) in pattern.char_indices() {
532                if matches!(c, '?' | '*') && !prev_wildcard {
533                    if i != 0 {
534                        chunks.push(regex::escape(&pattern[chunk_start..i]));
535                        chunk_start = i;
536                    }
537
538                    prev_wildcard = true;
539                } else if prev_wildcard {
540                    let chunk = &pattern[chunk_start..i];
541                    chunks.push(chunk.wildcards_to_regex());
542
543                    chunk_start = i;
544                    prev_wildcard = false;
545                }
546            }
547
548            let len = pattern.len();
549            if !prev_wildcard {
550                chunks.push(regex::escape(&pattern[chunk_start..len]));
551            } else if prev_wildcard {
552                let chunk = &pattern[chunk_start..len];
553                chunks.push(chunk.wildcards_to_regex());
554            }
555
556            // The word characters in ASCII compatible mode (with the `-u` flag) match the
557            // definition in the spec: any character not in the set `[A-Za-z0-9_]`.
558            let regex = format!(r"(?-u:^|\W|\b){}(?-u:\b|\W|$)", chunks.concat());
559            let re = Regex::new(&regex).expect("regex construction should succeed");
560            re.is_match(self.as_bytes())
561        } else {
562            match self.find(pattern) {
563                Some(start) => {
564                    let end = start + pattern.len();
565
566                    // Look if the match has word boundaries.
567                    let word_boundary_start = !self.char_at(start).is_word_char()
568                        || !self.find_prev_char(start).is_some_and(|c| c.is_word_char());
569
570                    if word_boundary_start {
571                        let word_boundary_end = end == self.len()
572                            || !self.find_prev_char(end).unwrap().is_word_char()
573                            || !self.char_at(end).is_word_char();
574
575                        if word_boundary_end {
576                            return true;
577                        }
578                    }
579
580                    // Find next word.
581                    let non_word_str = &self[start..];
582                    let Some(non_word) = non_word_str.find(|c: char| !c.is_word_char()) else {
583                        return false;
584                    };
585
586                    let word_str = &non_word_str[non_word..];
587                    let Some(word) = word_str.find(|c: char| c.is_word_char()) else {
588                        return false;
589                    };
590
591                    word_str[word..].matches_word(pattern)
592                }
593                None => false,
594            }
595        }
596    }
597
598    fn wildcards_to_regex(&self) -> String {
599        // Simplify pattern to avoid performance issues:
600        // - The glob `?**?**?` is equivalent to the glob `???*`
601        // - The glob `???*` is equivalent to the regex `.{3,}`
602        let question_marks = self.matches('?').count();
603
604        if self.contains('*') {
605            format!(".{{{question_marks},}}")
606        } else {
607            format!(".{{{question_marks}}}")
608        }
609    }
610}
611
612#[cfg(test)]
613mod tests {
614    use std::collections::BTreeMap;
615
616    use assert_matches2::assert_matches;
617    use js_int::{int, uint, Int};
618    use macro_rules_attribute::apply;
619    use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
620    use smol_macros::test;
621
622    use super::{
623        FlattenedJson, PushCondition, PushConditionPowerLevelsCtx, PushConditionRoomCtx,
624        RoomMemberCountIs, StrExt,
625    };
626    use crate::{
627        owned_room_id, owned_user_id,
628        power_levels::{NotificationPowerLevels, NotificationPowerLevelsKey},
629        room_version_rules::{AuthorizationRules, RoomPowerLevelsRules},
630        OwnedUserId,
631    };
632
633    #[test]
634    fn serialize_event_match_condition() {
635        let json_data = json!({
636            "key": "content.msgtype",
637            "kind": "event_match",
638            "pattern": "m.notice"
639        });
640        assert_eq!(
641            to_json_value(PushCondition::EventMatch {
642                key: "content.msgtype".into(),
643                pattern: "m.notice".into(),
644            })
645            .unwrap(),
646            json_data
647        );
648    }
649
650    #[test]
651    fn serialize_contains_display_name_condition() {
652        assert_eq!(
653            to_json_value(PushCondition::ContainsDisplayName).unwrap(),
654            json!({ "kind": "contains_display_name" })
655        );
656    }
657
658    #[test]
659    fn serialize_room_member_count_condition() {
660        let json_data = json!({
661            "is": "2",
662            "kind": "room_member_count"
663        });
664        assert_eq!(
665            to_json_value(PushCondition::RoomMemberCount { is: RoomMemberCountIs::from(uint!(2)) })
666                .unwrap(),
667            json_data
668        );
669    }
670
671    #[test]
672    fn serialize_sender_notification_permission_condition() {
673        let json_data = json!({
674            "key": "room",
675            "kind": "sender_notification_permission"
676        });
677        assert_eq!(
678            json_data,
679            to_json_value(PushCondition::SenderNotificationPermission { key: "room".into() })
680                .unwrap()
681        );
682    }
683
684    #[test]
685    fn deserialize_event_match_condition() {
686        let json_data = json!({
687            "key": "content.msgtype",
688            "kind": "event_match",
689            "pattern": "m.notice"
690        });
691        assert_matches!(
692            from_json_value::<PushCondition>(json_data).unwrap(),
693            PushCondition::EventMatch { key, pattern }
694        );
695        assert_eq!(key, "content.msgtype");
696        assert_eq!(pattern, "m.notice");
697    }
698
699    #[test]
700    fn deserialize_contains_display_name_condition() {
701        assert_matches!(
702            from_json_value::<PushCondition>(json!({ "kind": "contains_display_name" })).unwrap(),
703            PushCondition::ContainsDisplayName
704        );
705    }
706
707    #[test]
708    fn deserialize_room_member_count_condition() {
709        let json_data = json!({
710            "is": "2",
711            "kind": "room_member_count"
712        });
713        assert_matches!(
714            from_json_value::<PushCondition>(json_data).unwrap(),
715            PushCondition::RoomMemberCount { is }
716        );
717        assert_eq!(is, RoomMemberCountIs::from(uint!(2)));
718    }
719
720    #[test]
721    fn deserialize_sender_notification_permission_condition() {
722        let json_data = json!({
723            "key": "room",
724            "kind": "sender_notification_permission"
725        });
726        assert_matches!(
727            from_json_value::<PushCondition>(json_data).unwrap(),
728            PushCondition::SenderNotificationPermission { key }
729        );
730        assert_eq!(key, NotificationPowerLevelsKey::Room);
731    }
732
733    #[test]
734    fn words_match() {
735        assert!("foo bar".matches_word("foo"));
736        assert!(!"Foo bar".matches_word("foo"));
737        assert!(!"foobar".matches_word("foo"));
738        assert!("foobar foo".matches_word("foo"));
739        assert!(!"foobar foobar".matches_word("foo"));
740        assert!(!"foobar bar".matches_word("bar bar"));
741        assert!("foobar bar bar".matches_word("bar bar"));
742        assert!(!"foobar bar barfoo".matches_word("bar bar"));
743        assert!("conduit ⚡️".matches_word("conduit ⚡️"));
744        assert!("conduit ⚡️".matches_word("conduit"));
745        assert!("conduit ⚡️".matches_word("⚡️"));
746        assert!("conduit⚡️".matches_word("conduit"));
747        assert!("conduit⚡️".matches_word("⚡️"));
748        assert!("⚡️conduit".matches_word("conduit"));
749        assert!("⚡️conduit".matches_word("⚡️"));
750        assert!("Ruma Dev👩‍💻".matches_word("Dev"));
751        assert!("Ruma Dev👩‍💻".matches_word("👩‍💻"));
752        assert!("Ruma Dev👩‍💻".matches_word("Dev👩‍💻"));
753
754        // Regex syntax is escaped
755        assert!(!"matrix".matches_word(r"\w*"));
756        assert!(r"\w".matches_word(r"\w*"));
757        assert!(!"matrix".matches_word("[a-z]*"));
758        assert!("[a-z] and [0-9]".matches_word("[a-z]*"));
759        assert!(!"m".matches_word("[[:alpha:]]?"));
760        assert!("[[:alpha:]]!".matches_word("[[:alpha:]]?"));
761
762        // From the spec: <https://spec.matrix.org/v1.16/client-server-api/#conditions-1>
763        assert!("An example event.".matches_word("ex*ple"));
764        assert!("exple".matches_word("ex*ple"));
765        assert!("An exciting triple-whammy".matches_word("ex*ple"));
766    }
767
768    #[test]
769    fn patterns_match() {
770        // Word matching without glob
771        assert!("foo bar".matches_pattern("foo", true));
772        assert!("Foo bar".matches_pattern("foo", true));
773        assert!(!"foobar".matches_pattern("foo", true));
774        assert!("".matches_pattern("", true));
775        assert!(!"foo".matches_pattern("", true));
776        assert!("foo bar".matches_pattern("foo bar", true));
777        assert!(" foo bar ".matches_pattern("foo bar", true));
778        assert!("baz foo bar baz".matches_pattern("foo bar", true));
779        assert!("foo baré".matches_pattern("foo bar", true));
780        assert!(!"bar foo".matches_pattern("foo bar", true));
781        assert!("foo bar".matches_pattern("foo ", true));
782        assert!("foo ".matches_pattern("foo ", true));
783        assert!("foo  ".matches_pattern("foo ", true));
784        assert!(" foo  ".matches_pattern("foo ", true));
785
786        // Word matching with glob
787        assert!("foo bar".matches_pattern("foo*", true));
788        assert!("foo bar".matches_pattern("foo b?r", true));
789        assert!(" foo bar ".matches_pattern("foo b?r", true));
790        assert!("baz foo bar baz".matches_pattern("foo b?r", true));
791        assert!("foo baré".matches_pattern("foo b?r", true));
792        assert!(!"bar foo".matches_pattern("foo b?r", true));
793        assert!("foo bar".matches_pattern("f*o ", true));
794        assert!("foo ".matches_pattern("f*o ", true));
795        assert!("foo  ".matches_pattern("f*o ", true));
796        assert!(" foo  ".matches_pattern("f*o ", true));
797
798        // Glob matching
799        assert!(!"foo bar".matches_pattern("foo", false));
800        assert!("foo".matches_pattern("foo", false));
801        assert!("foo".matches_pattern("foo*", false));
802        assert!("foobar".matches_pattern("foo*", false));
803        assert!("foo bar".matches_pattern("foo*", false));
804        assert!(!"foo".matches_pattern("foo?", false));
805        assert!("fooo".matches_pattern("foo?", false));
806        assert!("FOO".matches_pattern("foo", false));
807        assert!("".matches_pattern("", false));
808        assert!("".matches_pattern("*", false));
809        assert!(!"foo".matches_pattern("", false));
810
811        // From the spec: <https://spec.matrix.org/v1.16/client-server-api/#conditions-1>
812        assert!("Lunch plans".matches_pattern("lunc?*", false));
813        assert!("LUNCH".matches_pattern("lunc?*", false));
814        assert!(!" lunch".matches_pattern("lunc?*", false));
815        assert!(!"lunc".matches_pattern("lunc?*", false));
816    }
817
818    fn sender() -> OwnedUserId {
819        owned_user_id!("@worthy_whale:server.name")
820    }
821
822    fn push_context() -> PushConditionRoomCtx {
823        let mut users = BTreeMap::new();
824        users.insert(sender(), int!(25));
825
826        let power_levels = PushConditionPowerLevelsCtx {
827            users,
828            users_default: int!(50),
829            notifications: NotificationPowerLevels { room: int!(50) },
830            rules: RoomPowerLevelsRules::new(&AuthorizationRules::V1, None),
831        };
832
833        let mut ctx = PushConditionRoomCtx::new(
834            owned_room_id!("!room:server.name"),
835            uint!(3),
836            owned_user_id!("@gorilla:server.name"),
837            "Groovy Gorilla".into(),
838        );
839        ctx.power_levels = Some(power_levels);
840        ctx
841    }
842
843    fn first_flattened_event() -> FlattenedJson {
844        FlattenedJson::from_value(json!({
845            "sender": "@worthy_whale:server.name",
846            "content": {
847                "msgtype": "m.text",
848                "body": "@room Give a warm welcome to Groovy Gorilla",
849            },
850        }))
851    }
852
853    fn second_flattened_event() -> FlattenedJson {
854        FlattenedJson::from_value(json!({
855            "sender": "@party_bot:server.name",
856            "content": {
857                "msgtype": "m.notice",
858                "body": "Everybody come to party!",
859            },
860        }))
861    }
862
863    #[apply(test!)]
864    async fn event_match_applies() {
865        let context = push_context();
866        let first_event = first_flattened_event();
867        let second_event = second_flattened_event();
868
869        let correct_room = PushCondition::EventMatch {
870            key: "room_id".into(),
871            pattern: "!room:server.name".into(),
872        };
873        let incorrect_room = PushCondition::EventMatch {
874            key: "room_id".into(),
875            pattern: "!incorrect:server.name".into(),
876        };
877
878        assert!(correct_room.applies(&first_event, &context).await);
879        assert!(!incorrect_room.applies(&first_event, &context).await);
880
881        let keyword =
882            PushCondition::EventMatch { key: "content.body".into(), pattern: "come".into() };
883
884        assert!(!keyword.applies(&first_event, &context).await);
885        assert!(keyword.applies(&second_event, &context).await);
886
887        let msgtype =
888            PushCondition::EventMatch { key: "content.msgtype".into(), pattern: "m.notice".into() };
889
890        assert!(!msgtype.applies(&first_event, &context).await);
891        assert!(msgtype.applies(&second_event, &context).await);
892    }
893
894    #[apply(test!)]
895    async fn room_member_count_is_applies() {
896        let context = push_context();
897        let event = first_flattened_event();
898
899        let member_count_eq =
900            PushCondition::RoomMemberCount { is: RoomMemberCountIs::from(uint!(3)) };
901        let member_count_gt =
902            PushCondition::RoomMemberCount { is: RoomMemberCountIs::from(uint!(2)..) };
903        let member_count_lt =
904            PushCondition::RoomMemberCount { is: RoomMemberCountIs::from(..uint!(3)) };
905
906        assert!(member_count_eq.applies(&event, &context).await);
907        assert!(member_count_gt.applies(&event, &context).await);
908        assert!(!member_count_lt.applies(&event, &context).await);
909    }
910
911    #[apply(test!)]
912    async fn contains_display_name_applies() {
913        let context = push_context();
914        let first_event = first_flattened_event();
915        let second_event = second_flattened_event();
916
917        let contains_display_name = PushCondition::ContainsDisplayName;
918
919        assert!(contains_display_name.applies(&first_event, &context).await);
920        assert!(!contains_display_name.applies(&second_event, &context).await);
921    }
922
923    #[apply(test!)]
924    async fn sender_notification_permission_applies() {
925        let context = push_context();
926        let first_event = first_flattened_event();
927        let second_event = second_flattened_event();
928
929        let sender_notification_permission =
930            PushCondition::SenderNotificationPermission { key: "room".into() };
931
932        assert!(!sender_notification_permission.applies(&first_event, &context).await);
933        assert!(sender_notification_permission.applies(&second_event, &context).await);
934    }
935
936    #[cfg(feature = "unstable-msc3932")]
937    #[apply(test!)]
938    async fn room_version_supports_applies() {
939        use assign::assign;
940
941        let context_not_matching = push_context();
942        let context_matching = assign!(
943            PushConditionRoomCtx::new(
944                owned_room_id!("!room:server.name"),
945                uint!(3),
946                owned_user_id!("@gorilla:server.name"),
947                "Groovy Gorilla".into(),
948            ), {
949                power_levels: context_not_matching.power_levels.clone(),
950                supported_features: vec![super::RoomVersionFeature::ExtensibleEvents],
951            }
952        );
953
954        let simple_event = FlattenedJson::from_value(json!({
955            "sender": "@worthy_whale:server.name",
956            "content": {
957                "msgtype": "org.matrix.msc3932.extensible_events",
958                "body": "@room Give a warm welcome to Groovy Gorilla",
959            },
960        }));
961
962        let room_version_condition = PushCondition::RoomVersionSupports {
963            feature: super::RoomVersionFeature::ExtensibleEvents,
964        };
965
966        assert!(room_version_condition.applies(&simple_event, &context_matching).await);
967        assert!(!room_version_condition.applies(&simple_event, &context_not_matching).await);
968    }
969
970    #[apply(test!)]
971    async fn event_property_is_applies() {
972        use crate::push::condition::ScalarJsonValue;
973
974        let context = push_context();
975        let event = FlattenedJson::from_value(json!({
976            "sender": "@worthy_whale:server.name",
977            "content": {
978                "msgtype": "m.text",
979                "body": "Boom!",
980                "org.fake.boolean": false,
981                "org.fake.number": 13,
982                "org.fake.null": null,
983            },
984        }));
985
986        let string_match = PushCondition::EventPropertyIs {
987            key: "content.body".to_owned(),
988            value: "Boom!".into(),
989        };
990        assert!(string_match.applies(&event, &context).await);
991
992        let string_no_match =
993            PushCondition::EventPropertyIs { key: "content.body".to_owned(), value: "Boom".into() };
994        assert!(!string_no_match.applies(&event, &context).await);
995
996        let wrong_type =
997            PushCondition::EventPropertyIs { key: "content.body".to_owned(), value: false.into() };
998        assert!(!wrong_type.applies(&event, &context).await);
999
1000        let bool_match = PushCondition::EventPropertyIs {
1001            key: r"content.org\.fake\.boolean".to_owned(),
1002            value: false.into(),
1003        };
1004        assert!(bool_match.applies(&event, &context).await);
1005
1006        let bool_no_match = PushCondition::EventPropertyIs {
1007            key: r"content.org\.fake\.boolean".to_owned(),
1008            value: true.into(),
1009        };
1010        assert!(!bool_no_match.applies(&event, &context).await);
1011
1012        let int_match = PushCondition::EventPropertyIs {
1013            key: r"content.org\.fake\.number".to_owned(),
1014            value: int!(13).into(),
1015        };
1016        assert!(int_match.applies(&event, &context).await);
1017
1018        let int_no_match = PushCondition::EventPropertyIs {
1019            key: r"content.org\.fake\.number".to_owned(),
1020            value: int!(130).into(),
1021        };
1022        assert!(!int_no_match.applies(&event, &context).await);
1023
1024        let null_match = PushCondition::EventPropertyIs {
1025            key: r"content.org\.fake\.null".to_owned(),
1026            value: ScalarJsonValue::Null,
1027        };
1028        assert!(null_match.applies(&event, &context).await);
1029    }
1030
1031    #[apply(test!)]
1032    async fn event_property_contains_applies() {
1033        use crate::push::condition::ScalarJsonValue;
1034
1035        let context = push_context();
1036        let event = FlattenedJson::from_value(json!({
1037            "sender": "@worthy_whale:server.name",
1038            "content": {
1039                "org.fake.array": ["Boom!", false, 13, null],
1040            },
1041        }));
1042
1043        let wrong_key =
1044            PushCondition::EventPropertyContains { key: "send".to_owned(), value: false.into() };
1045        assert!(!wrong_key.applies(&event, &context).await);
1046
1047        let string_match = PushCondition::EventPropertyContains {
1048            key: r"content.org\.fake\.array".to_owned(),
1049            value: "Boom!".into(),
1050        };
1051        assert!(string_match.applies(&event, &context).await);
1052
1053        let string_no_match = PushCondition::EventPropertyContains {
1054            key: r"content.org\.fake\.array".to_owned(),
1055            value: "Boom".into(),
1056        };
1057        assert!(!string_no_match.applies(&event, &context).await);
1058
1059        let bool_match = PushCondition::EventPropertyContains {
1060            key: r"content.org\.fake\.array".to_owned(),
1061            value: false.into(),
1062        };
1063        assert!(bool_match.applies(&event, &context).await);
1064
1065        let bool_no_match = PushCondition::EventPropertyContains {
1066            key: r"content.org\.fake\.array".to_owned(),
1067            value: true.into(),
1068        };
1069        assert!(!bool_no_match.applies(&event, &context).await);
1070
1071        let int_match = PushCondition::EventPropertyContains {
1072            key: r"content.org\.fake\.array".to_owned(),
1073            value: int!(13).into(),
1074        };
1075        assert!(int_match.applies(&event, &context).await);
1076
1077        let int_no_match = PushCondition::EventPropertyContains {
1078            key: r"content.org\.fake\.array".to_owned(),
1079            value: int!(130).into(),
1080        };
1081        assert!(!int_no_match.applies(&event, &context).await);
1082
1083        let null_match = PushCondition::EventPropertyContains {
1084            key: r"content.org\.fake\.array".to_owned(),
1085            value: ScalarJsonValue::Null,
1086        };
1087        assert!(null_match.applies(&event, &context).await);
1088    }
1089
1090    #[apply(test!)]
1091    async fn room_creators_always_have_notification_permission() {
1092        let mut context = push_context();
1093        context.power_levels = Some(PushConditionPowerLevelsCtx {
1094            users: BTreeMap::new(),
1095            users_default: Int::MIN,
1096            notifications: NotificationPowerLevels { room: Int::MAX },
1097            rules: RoomPowerLevelsRules::new(&AuthorizationRules::V12, Some(sender())),
1098        });
1099
1100        let first_event = first_flattened_event();
1101
1102        let sender_notification_permission =
1103            PushCondition::SenderNotificationPermission { key: NotificationPowerLevelsKey::Room };
1104
1105        assert!(sender_notification_permission.applies(&first_event, &context).await);
1106    }
1107
1108    #[cfg(feature = "unstable-msc4306")]
1109    #[apply(test!)]
1110    async fn thread_subscriptions_match() {
1111        use crate::{event_id, EventId};
1112
1113        let context = push_context().with_has_thread_subscription_fn(|event_id: &EventId| {
1114            Box::pin(async move {
1115                // Simulate thread subscriptions for testing.
1116                event_id == event_id!("$subscribed_thread")
1117            })
1118        });
1119
1120        let subscribed_thread_event = FlattenedJson::from_value(json!({
1121            "event_id": "$thread_response",
1122            "sender": "@worthy_whale:server.name",
1123            "content": {
1124                "msgtype": "m.text",
1125                "body": "response in thread $subscribed_thread",
1126                "m.relates_to": {
1127                    "rel_type": "m.thread",
1128                    "event_id": "$subscribed_thread",
1129                    "is_falling_back": true,
1130                    "m.in_reply_to": {
1131                        "event_id": "$prev_event",
1132                    },
1133                },
1134            },
1135        }));
1136
1137        let unsubscribed_thread_event = FlattenedJson::from_value(json!({
1138            "event_id": "$thread_response2",
1139            "sender": "@worthy_whale:server.name",
1140            "content": {
1141                "msgtype": "m.text",
1142                "body": "response in thread $unsubscribed_thread",
1143                "m.relates_to": {
1144                    "rel_type": "m.thread",
1145                    "event_id": "$unsubscribed_thread",
1146                    "is_falling_back": true,
1147                    "m.in_reply_to": {
1148                        "event_id": "$prev_event2",
1149                    },
1150                },
1151            },
1152        }));
1153
1154        let non_thread_related_event = FlattenedJson::from_value(json!({
1155            "event_id": "$thread_response2",
1156            "sender": "@worthy_whale:server.name",
1157            "content": {
1158                "m.relates_to": {
1159                    "rel_type": "m.reaction",
1160                    "event_id": "$subscribed_thread",
1161                    "key": "👍",
1162                },
1163            },
1164        }));
1165
1166        let subscribed_thread_condition = PushCondition::ThreadSubscription { subscribed: true };
1167        assert!(subscribed_thread_condition.applies(&subscribed_thread_event, &context).await);
1168        assert!(!subscribed_thread_condition.applies(&unsubscribed_thread_event, &context).await);
1169        assert!(!subscribed_thread_condition.applies(&non_thread_related_event, &context).await);
1170
1171        let unsubscribed_thread_condition = PushCondition::ThreadSubscription { subscribed: false };
1172        assert!(unsubscribed_thread_condition.applies(&unsubscribed_thread_event, &context).await);
1173        assert!(!unsubscribed_thread_condition.applies(&subscribed_thread_event, &context).await);
1174        assert!(!unsubscribed_thread_condition.applies(&non_thread_related_event, &context).await);
1175    }
1176}