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#[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 #[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 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#[derive(Clone, Debug)]
79#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
80pub enum PushCondition {
81 EventMatch {
83 key: String,
87
88 pattern: String,
93 },
94
95 ContainsDisplayName,
98
99 RoomMemberCount {
101 is: RoomMemberCountIs,
103 },
104
105 SenderNotificationPermission {
108 key: NotificationPowerLevelsKey,
113 },
114
115 #[cfg(feature = "unstable-msc3931")]
117 RoomVersionSupports {
118 feature: RoomVersionFeature,
120 },
121
122 EventPropertyIs {
124 key: String,
128
129 value: ScalarJsonValue,
131 },
132
133 EventPropertyContains {
135 key: String,
139
140 value: ScalarJsonValue,
142 },
143
144 #[cfg(feature = "unstable-msc4306")]
149 ThreadSubscription {
150 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 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 return false;
221 };
222
223 if event.get_str("content.m\\.relates_to.rel_type") != Some("m.thread") {
225 return false;
226 }
227
228 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#[doc(hidden)]
246#[derive(Clone, Debug, Deserialize, Serialize)]
247#[allow(clippy::exhaustive_structs)]
248pub struct _CustomPushCondition {
249 kind: String,
251
252 #[serde(flatten)]
254 data: BTreeMap<String, JsonValue>,
255}
256
257#[derive(Clone)]
259#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
260pub struct PushConditionRoomCtx {
261 pub room_id: OwnedRoomId,
263
264 pub member_count: UInt,
266
267 pub user_id: OwnedUserId,
269
270 pub user_display_name: String,
272
273 pub power_levels: Option<PushConditionPowerLevelsCtx>,
277
278 #[cfg(feature = "unstable-msc3931")]
280 pub supported_features: Vec<RoomVersionFeature>,
281
282 #[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 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 #[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 pub fn with_power_levels(self, power_levels: PushConditionPowerLevelsCtx) -> Self {
364 Self { power_levels: Some(power_levels), ..self }
365 }
366}
367
368#[derive(Clone, Debug)]
372#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
373pub struct PushConditionPowerLevelsCtx {
374 pub users: BTreeMap<OwnedUserId, Int>,
376
377 pub users_default: Int,
379
380 pub notifications: NotificationPowerLevels,
382
383 pub rules: RoomPowerLevelsRules,
385}
386
387impl PushConditionPowerLevelsCtx {
388 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 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 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
424trait CharExt {
426 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
436trait StrExt {
438 fn char_len(&self, index: usize) -> usize;
441
442 fn char_at(&self, index: usize) -> char;
445
446 fn find_prev_char(&self, index: usize) -> Option<char>;
451
452 fn matches_pattern(&self, pattern: &str, match_words: bool) -> bool;
460
461 fn matches_word(&self, pattern: &str) -> bool;
470
471 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 let regex = format!(r"(?-u:^|\W|\b){}(?-u:\b|\W|$)", chunks.concat());
559 let re = Regex::new(®ex).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 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 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 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 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 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 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 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 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 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 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}