1use std::{
2 collections::BTreeMap, future::Future, ops::RangeBounds, pin::Pin, str::FromStr, sync::Arc,
3};
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
13use crate::{
14 EventId, OwnedRoomId, OwnedUserId, UserId,
15 power_levels::{NotificationPowerLevels, NotificationPowerLevelsKey},
16 room_version_rules::RoomPowerLevelsRules,
17};
18#[cfg(feature = "unstable-msc3931")]
19use crate::{PrivOwnedStr, RoomVersionId};
20
21mod flattened_json;
22mod push_condition_serde;
23mod room_member_count_is;
24
25pub use self::{
26 flattened_json::{FlattenedJson, FlattenedJsonValue, ScalarJsonValue},
27 room_member_count_is::{ComparisonOperator, RoomMemberCountIs},
28};
29
30#[cfg(feature = "unstable-msc3931")]
32#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
33#[derive(Clone, StringEnum)]
34#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
35pub enum RoomVersionFeature {
36 #[cfg(feature = "unstable-msc3932")]
42 #[ruma_enum(rename = "org.matrix.msc3932.extensible_events")]
43 ExtensibleEvents,
44
45 #[doc(hidden)]
46 _Custom(PrivOwnedStr),
47}
48
49#[cfg(feature = "unstable-msc3931")]
50impl RoomVersionFeature {
51 pub fn list_for_room_version(version: &RoomVersionId) -> Vec<Self> {
53 match version {
54 RoomVersionId::V1
55 | RoomVersionId::V2
56 | RoomVersionId::V3
57 | RoomVersionId::V4
58 | RoomVersionId::V5
59 | RoomVersionId::V6
60 | RoomVersionId::V7
61 | RoomVersionId::V8
62 | RoomVersionId::V9
63 | RoomVersionId::V10
64 | RoomVersionId::V11
65 | RoomVersionId::V12
66 | RoomVersionId::_Custom(_) => vec![],
67 #[cfg(feature = "unstable-msc2870")]
68 RoomVersionId::MSC2870 => vec![],
69 }
70 }
71}
72
73#[derive(Clone, Debug)]
75#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
76pub enum PushCondition {
77 EventMatch {
79 key: String,
83
84 pattern: String,
89 },
90
91 #[deprecated]
94 ContainsDisplayName,
95
96 RoomMemberCount {
98 is: RoomMemberCountIs,
100 },
101
102 SenderNotificationPermission {
105 key: NotificationPowerLevelsKey,
110 },
111
112 #[cfg(feature = "unstable-msc3931")]
114 RoomVersionSupports {
115 feature: RoomVersionFeature,
117 },
118
119 EventPropertyIs {
121 key: String,
125
126 value: ScalarJsonValue,
128 },
129
130 EventPropertyContains {
132 key: String,
136
137 value: ScalarJsonValue,
139 },
140
141 #[cfg(feature = "unstable-msc4306")]
146 ThreadSubscription {
147 subscribed: bool,
150 },
151
152 #[doc(hidden)]
153 _Custom(_CustomPushCondition),
154}
155
156pub(super) fn check_event_match(
157 event: &FlattenedJson,
158 key: &str,
159 pattern: &str,
160 context: &PushConditionRoomCtx,
161) -> bool {
162 let value = match key {
163 "room_id" => context.room_id.as_str(),
164 _ => match event.get_str(key) {
165 Some(v) => v,
166 None => return false,
167 },
168 };
169
170 value.matches_pattern(pattern, key == "content.body")
171}
172
173impl PushCondition {
174 pub async fn applies(&self, event: &FlattenedJson, context: &PushConditionRoomCtx) -> bool {
182 if event.get_str("sender").is_some_and(|sender| sender == context.user_id) {
183 return false;
184 }
185
186 match self {
187 Self::EventMatch { key, pattern } => check_event_match(event, key, pattern, context),
188 #[allow(deprecated)]
189 Self::ContainsDisplayName => {
190 let Some(value) = event.get_str("content.body") else { return false };
191 value.matches_pattern(&context.user_display_name, true)
192 }
193 Self::RoomMemberCount { is } => is.contains(&context.member_count),
194 Self::SenderNotificationPermission { key } => {
195 let Some(power_levels) = &context.power_levels else { return false };
196 let Some(sender_id) = event.get_str("sender") else { return false };
197 let Ok(sender_id) = <&UserId>::try_from(sender_id) else { return false };
198
199 power_levels.has_sender_notification_permission(sender_id, key)
200 }
201 #[cfg(feature = "unstable-msc3931")]
202 Self::RoomVersionSupports { feature } => match feature {
203 RoomVersionFeature::ExtensibleEvents => {
204 context.supported_features.contains(&RoomVersionFeature::ExtensibleEvents)
205 }
206 RoomVersionFeature::_Custom(_) => false,
207 },
208 Self::EventPropertyIs { key, value } => event.get(key).is_some_and(|v| v == value),
209 Self::EventPropertyContains { key, value } => event
210 .get(key)
211 .and_then(FlattenedJsonValue::as_array)
212 .is_some_and(|a| a.contains(value)),
213 #[cfg(feature = "unstable-msc4306")]
214 Self::ThreadSubscription { subscribed: must_be_subscribed } => {
215 let Some(has_thread_subscription_fn) = &context.has_thread_subscription_fn else {
216 return false;
219 };
220
221 if event.get_str("content.m\\.relates_to.rel_type") != Some("m.thread") {
223 return false;
224 }
225
226 let Some(Ok(thread_root)) =
228 event.get_str("content.m\\.relates_to.event_id").map(<&EventId>::try_from)
229 else {
230 return false;
231 };
232
233 let is_subscribed = has_thread_subscription_fn(thread_root).await;
234
235 *must_be_subscribed == is_subscribed
236 }
237 Self::_Custom(_) => false,
238 }
239 }
240}
241
242#[doc(hidden)]
244#[derive(Clone, Debug, Deserialize, Serialize)]
245#[allow(clippy::exhaustive_structs)]
246pub struct _CustomPushCondition {
247 kind: String,
249
250 #[serde(flatten)]
252 data: BTreeMap<String, JsonValue>,
253}
254
255#[derive(Clone)]
257#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
258pub struct PushConditionRoomCtx {
259 pub room_id: OwnedRoomId,
261
262 pub member_count: UInt,
264
265 pub user_id: OwnedUserId,
267
268 pub user_display_name: String,
270
271 pub power_levels: Option<PushConditionPowerLevelsCtx>,
275
276 #[cfg(feature = "unstable-msc3931")]
278 pub supported_features: Vec<RoomVersionFeature>,
279
280 #[cfg(feature = "unstable-msc4306")]
286 has_thread_subscription_fn: Option<Arc<HasThreadSubscriptionFn>>,
287
288 #[cfg(not(feature = "unstable-msc4306"))]
293 has_thread_subscription_fn: std::marker::PhantomData<Arc<HasThreadSubscriptionFn>>,
294}
295
296#[cfg(not(target_family = "wasm"))]
297type HasThreadSubscriptionFuture<'a> = Pin<Box<dyn Future<Output = bool> + Send + 'a>>;
298
299#[cfg(target_family = "wasm")]
300type HasThreadSubscriptionFuture<'a> = Pin<Box<dyn Future<Output = bool> + 'a>>;
301
302#[cfg(not(target_family = "wasm"))]
303type HasThreadSubscriptionFn =
304 dyn for<'a> Fn(&'a EventId) -> HasThreadSubscriptionFuture<'a> + Send + Sync;
305
306#[cfg(target_family = "wasm")]
307type HasThreadSubscriptionFn = dyn for<'a> Fn(&'a EventId) -> HasThreadSubscriptionFuture<'a>;
308
309impl std::fmt::Debug for PushConditionRoomCtx {
310 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
311 let mut debug_struct = f.debug_struct("PushConditionRoomCtx");
312
313 debug_struct
314 .field("room_id", &self.room_id)
315 .field("member_count", &self.member_count)
316 .field("user_id", &self.user_id)
317 .field("user_display_name", &self.user_display_name)
318 .field("power_levels", &self.power_levels);
319
320 #[cfg(feature = "unstable-msc3931")]
321 debug_struct.field("supported_features", &self.supported_features);
322
323 debug_struct.finish_non_exhaustive()
324 }
325}
326
327impl PushConditionRoomCtx {
328 pub fn new(
330 room_id: OwnedRoomId,
331 member_count: UInt,
332 user_id: OwnedUserId,
333 user_display_name: String,
334 ) -> Self {
335 Self {
336 room_id,
337 member_count,
338 user_id,
339 user_display_name,
340 power_levels: None,
341 #[cfg(feature = "unstable-msc3931")]
342 supported_features: Vec::new(),
343 has_thread_subscription_fn: Default::default(),
344 }
345 }
346
347 #[cfg(feature = "unstable-msc4306")]
352 pub fn with_has_thread_subscription_fn(
353 self,
354 #[cfg(not(target_family = "wasm"))]
355 has_thread_subscription_fn: impl for<'a> Fn(
356 &'a EventId,
357 ) -> HasThreadSubscriptionFuture<'a>
358 + Send
359 + Sync
360 + 'static,
361 #[cfg(target_family = "wasm")]
362 has_thread_subscription_fn: impl for<'a> Fn(
363 &'a EventId,
364 ) -> HasThreadSubscriptionFuture<'a>
365 + 'static,
366 ) -> Self {
367 Self { has_thread_subscription_fn: Some(Arc::new(has_thread_subscription_fn)), ..self }
368 }
369
370 pub fn with_power_levels(self, power_levels: PushConditionPowerLevelsCtx) -> Self {
372 Self { power_levels: Some(power_levels), ..self }
373 }
374}
375
376#[derive(Clone, Debug)]
380#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
381pub struct PushConditionPowerLevelsCtx {
382 pub users: BTreeMap<OwnedUserId, Int>,
384
385 pub users_default: Int,
387
388 pub notifications: NotificationPowerLevels,
390
391 pub rules: RoomPowerLevelsRules,
393}
394
395impl PushConditionPowerLevelsCtx {
396 pub fn new(
398 users: BTreeMap<OwnedUserId, Int>,
399 users_default: Int,
400 notifications: NotificationPowerLevels,
401 rules: RoomPowerLevelsRules,
402 ) -> Self {
403 Self { users, users_default, notifications, rules }
404 }
405
406 pub fn has_sender_notification_permission(
408 &self,
409 user_id: &UserId,
410 key: &NotificationPowerLevelsKey,
411 ) -> bool {
412 let Some(notification_power_level) = self.notifications.get(key) else {
413 return false;
415 };
416
417 if self
418 .rules
419 .privileged_creators
420 .as_ref()
421 .is_some_and(|creators| creators.contains(user_id))
422 {
423 return true;
424 }
425
426 let user_power_level = self.users.get(user_id).unwrap_or(&self.users_default);
427
428 user_power_level >= notification_power_level
429 }
430}
431
432trait CharExt {
434 fn is_word_char(&self) -> bool;
436}
437
438impl CharExt for char {
439 fn is_word_char(&self) -> bool {
440 self.is_ascii_alphanumeric() || *self == '_'
441 }
442}
443
444trait StrExt {
446 fn char_len(&self, index: usize) -> usize;
449
450 fn char_at(&self, index: usize) -> char;
453
454 fn find_prev_char(&self, index: usize) -> Option<char>;
459
460 fn matches_pattern(&self, pattern: &str, match_words: bool) -> bool;
468
469 fn matches_word(&self, pattern: &str) -> bool;
478
479 fn wildcards_to_regex(&self) -> String;
483}
484
485impl StrExt for str {
486 fn char_len(&self, index: usize) -> usize {
487 let mut len = 1;
488 while !self.is_char_boundary(index + len) {
489 len += 1;
490 }
491 len
492 }
493
494 fn char_at(&self, index: usize) -> char {
495 let end = index + self.char_len(index);
496 let char_str = &self[index..end];
497 char::from_str(char_str)
498 .unwrap_or_else(|_| panic!("Could not convert str '{char_str}' to char"))
499 }
500
501 fn find_prev_char(&self, index: usize) -> Option<char> {
502 if index == 0 {
503 return None;
504 }
505
506 let mut pos = index - 1;
507 while !self.is_char_boundary(pos) {
508 pos -= 1;
509 }
510 Some(self.char_at(pos))
511 }
512
513 fn matches_pattern(&self, pattern: &str, match_words: bool) -> bool {
514 let value = &self.to_lowercase();
515 let pattern = &pattern.to_lowercase();
516
517 if match_words {
518 value.matches_word(pattern)
519 } else {
520 WildMatch::new(pattern).matches(value)
521 }
522 }
523
524 fn matches_word(&self, pattern: &str) -> bool {
525 if self == pattern {
526 return true;
527 }
528 if pattern.is_empty() {
529 return false;
530 }
531
532 let has_wildcards = pattern.contains(['?', '*']);
533
534 if has_wildcards {
535 let mut chunks: Vec<String> = vec![];
536 let mut prev_wildcard = false;
537 let mut chunk_start = 0;
538
539 for (i, c) in pattern.char_indices() {
540 if matches!(c, '?' | '*') && !prev_wildcard {
541 if i != 0 {
542 chunks.push(regex::escape(&pattern[chunk_start..i]));
543 chunk_start = i;
544 }
545
546 prev_wildcard = true;
547 } else if prev_wildcard {
548 let chunk = &pattern[chunk_start..i];
549 chunks.push(chunk.wildcards_to_regex());
550
551 chunk_start = i;
552 prev_wildcard = false;
553 }
554 }
555
556 let len = pattern.len();
557 if !prev_wildcard {
558 chunks.push(regex::escape(&pattern[chunk_start..len]));
559 } else if prev_wildcard {
560 let chunk = &pattern[chunk_start..len];
561 chunks.push(chunk.wildcards_to_regex());
562 }
563
564 let regex = format!(r"(?-u:^|\W|\b){}(?-u:\b|\W|$)", chunks.concat());
567 let re = Regex::new(®ex).expect("regex construction should succeed");
568 re.is_match(self.as_bytes())
569 } else {
570 match self.find(pattern) {
571 Some(start) => {
572 let end = start + pattern.len();
573
574 let word_boundary_start = !self.char_at(start).is_word_char()
576 || !self.find_prev_char(start).is_some_and(|c| c.is_word_char());
577
578 if word_boundary_start {
579 let word_boundary_end = end == self.len()
580 || !self.find_prev_char(end).unwrap().is_word_char()
581 || !self.char_at(end).is_word_char();
582
583 if word_boundary_end {
584 return true;
585 }
586 }
587
588 let non_word_str = &self[start..];
590 let Some(non_word) = non_word_str.find(|c: char| !c.is_word_char()) else {
591 return false;
592 };
593
594 let word_str = &non_word_str[non_word..];
595 let Some(word) = word_str.find(|c: char| c.is_word_char()) else {
596 return false;
597 };
598
599 word_str[word..].matches_word(pattern)
600 }
601 None => false,
602 }
603 }
604 }
605
606 fn wildcards_to_regex(&self) -> String {
607 let question_marks = self.matches('?').count();
611
612 if self.contains('*') {
613 format!(".{{{question_marks},}}")
614 } else {
615 format!(".{{{question_marks}}}")
616 }
617 }
618}
619
620#[cfg(test)]
621mod tests {
622 use std::collections::BTreeMap;
623
624 use assert_matches2::assert_matches;
625 use js_int::{Int, int, uint};
626 use macro_rules_attribute::apply;
627 use serde_json::{from_value as from_json_value, json};
628 use smol_macros::test;
629
630 use super::{
631 FlattenedJson, PushCondition, PushConditionPowerLevelsCtx, PushConditionRoomCtx,
632 RoomMemberCountIs, StrExt,
633 };
634 use crate::{
635 OwnedUserId, assert_to_canonical_json_eq, owned_room_id, owned_user_id,
636 power_levels::{NotificationPowerLevels, NotificationPowerLevelsKey},
637 room_version_rules::{AuthorizationRules, RoomPowerLevelsRules},
638 };
639
640 #[test]
641 fn serialize_event_match_condition() {
642 assert_to_canonical_json_eq!(
643 PushCondition::EventMatch { key: "content.msgtype".into(), pattern: "m.notice".into() },
644 json!({
645 "key": "content.msgtype",
646 "kind": "event_match",
647 "pattern": "m.notice"
648 }),
649 );
650 }
651
652 #[test]
653 #[allow(deprecated)]
654 fn serialize_contains_display_name_condition() {
655 assert_to_canonical_json_eq!(
656 PushCondition::ContainsDisplayName,
657 json!({ "kind": "contains_display_name" }),
658 );
659 }
660
661 #[test]
662 fn serialize_room_member_count_condition() {
663 assert_to_canonical_json_eq!(
664 PushCondition::RoomMemberCount { is: RoomMemberCountIs::from(uint!(2)) },
665 json!({
666 "is": "2",
667 "kind": "room_member_count"
668 }),
669 );
670 }
671
672 #[test]
673 fn serialize_sender_notification_permission_condition() {
674 assert_to_canonical_json_eq!(
675 PushCondition::SenderNotificationPermission { key: "room".into() },
676 json!({
677 "key": "room",
678 "kind": "sender_notification_permission"
679 }),
680 );
681 }
682
683 #[test]
684 fn deserialize_event_match_condition() {
685 let json_data = json!({
686 "key": "content.msgtype",
687 "kind": "event_match",
688 "pattern": "m.notice"
689 });
690 assert_matches!(
691 from_json_value::<PushCondition>(json_data).unwrap(),
692 PushCondition::EventMatch { key, pattern }
693 );
694 assert_eq!(key, "content.msgtype");
695 assert_eq!(pattern, "m.notice");
696 }
697
698 #[test]
699 #[allow(deprecated)]
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 #[allow(deprecated)]
913 async fn contains_display_name_applies() {
914 let context = push_context();
915 let first_event = first_flattened_event();
916 let second_event = second_flattened_event();
917
918 let contains_display_name = PushCondition::ContainsDisplayName;
919
920 assert!(contains_display_name.applies(&first_event, &context).await);
921 assert!(!contains_display_name.applies(&second_event, &context).await);
922 }
923
924 #[apply(test!)]
925 async fn sender_notification_permission_applies() {
926 let context = push_context();
927 let first_event = first_flattened_event();
928 let second_event = second_flattened_event();
929
930 let sender_notification_permission =
931 PushCondition::SenderNotificationPermission { key: "room".into() };
932
933 assert!(!sender_notification_permission.applies(&first_event, &context).await);
934 assert!(sender_notification_permission.applies(&second_event, &context).await);
935 }
936
937 #[cfg(feature = "unstable-msc3932")]
938 #[apply(test!)]
939 async fn room_version_supports_applies() {
940 use assign::assign;
941
942 let context_not_matching = push_context();
943 let context_matching = assign!(
944 PushConditionRoomCtx::new(
945 owned_room_id!("!room:server.name"),
946 uint!(3),
947 owned_user_id!("@gorilla:server.name"),
948 "Groovy Gorilla".into(),
949 ), {
950 power_levels: context_not_matching.power_levels.clone(),
951 supported_features: vec![super::RoomVersionFeature::ExtensibleEvents],
952 }
953 );
954
955 let simple_event = FlattenedJson::from_value(json!({
956 "sender": "@worthy_whale:server.name",
957 "content": {
958 "msgtype": "org.matrix.msc3932.extensible_events",
959 "body": "@room Give a warm welcome to Groovy Gorilla",
960 },
961 }));
962
963 let room_version_condition = PushCondition::RoomVersionSupports {
964 feature: super::RoomVersionFeature::ExtensibleEvents,
965 };
966
967 assert!(room_version_condition.applies(&simple_event, &context_matching).await);
968 assert!(!room_version_condition.applies(&simple_event, &context_not_matching).await);
969 }
970
971 #[apply(test!)]
972 async fn event_property_is_applies() {
973 use crate::push::condition::ScalarJsonValue;
974
975 let context = push_context();
976 let event = FlattenedJson::from_value(json!({
977 "sender": "@worthy_whale:server.name",
978 "content": {
979 "msgtype": "m.text",
980 "body": "Boom!",
981 "org.fake.boolean": false,
982 "org.fake.number": 13,
983 "org.fake.null": null,
984 },
985 }));
986
987 let string_match = PushCondition::EventPropertyIs {
988 key: "content.body".to_owned(),
989 value: "Boom!".into(),
990 };
991 assert!(string_match.applies(&event, &context).await);
992
993 let string_no_match =
994 PushCondition::EventPropertyIs { key: "content.body".to_owned(), value: "Boom".into() };
995 assert!(!string_no_match.applies(&event, &context).await);
996
997 let wrong_type =
998 PushCondition::EventPropertyIs { key: "content.body".to_owned(), value: false.into() };
999 assert!(!wrong_type.applies(&event, &context).await);
1000
1001 let bool_match = PushCondition::EventPropertyIs {
1002 key: r"content.org\.fake\.boolean".to_owned(),
1003 value: false.into(),
1004 };
1005 assert!(bool_match.applies(&event, &context).await);
1006
1007 let bool_no_match = PushCondition::EventPropertyIs {
1008 key: r"content.org\.fake\.boolean".to_owned(),
1009 value: true.into(),
1010 };
1011 assert!(!bool_no_match.applies(&event, &context).await);
1012
1013 let int_match = PushCondition::EventPropertyIs {
1014 key: r"content.org\.fake\.number".to_owned(),
1015 value: int!(13).into(),
1016 };
1017 assert!(int_match.applies(&event, &context).await);
1018
1019 let int_no_match = PushCondition::EventPropertyIs {
1020 key: r"content.org\.fake\.number".to_owned(),
1021 value: int!(130).into(),
1022 };
1023 assert!(!int_no_match.applies(&event, &context).await);
1024
1025 let null_match = PushCondition::EventPropertyIs {
1026 key: r"content.org\.fake\.null".to_owned(),
1027 value: ScalarJsonValue::Null,
1028 };
1029 assert!(null_match.applies(&event, &context).await);
1030 }
1031
1032 #[apply(test!)]
1033 async fn event_property_contains_applies() {
1034 use crate::push::condition::ScalarJsonValue;
1035
1036 let context = push_context();
1037 let event = FlattenedJson::from_value(json!({
1038 "sender": "@worthy_whale:server.name",
1039 "content": {
1040 "org.fake.array": ["Boom!", false, 13, null],
1041 },
1042 }));
1043
1044 let wrong_key =
1045 PushCondition::EventPropertyContains { key: "send".to_owned(), value: false.into() };
1046 assert!(!wrong_key.applies(&event, &context).await);
1047
1048 let string_match = PushCondition::EventPropertyContains {
1049 key: r"content.org\.fake\.array".to_owned(),
1050 value: "Boom!".into(),
1051 };
1052 assert!(string_match.applies(&event, &context).await);
1053
1054 let string_no_match = PushCondition::EventPropertyContains {
1055 key: r"content.org\.fake\.array".to_owned(),
1056 value: "Boom".into(),
1057 };
1058 assert!(!string_no_match.applies(&event, &context).await);
1059
1060 let bool_match = PushCondition::EventPropertyContains {
1061 key: r"content.org\.fake\.array".to_owned(),
1062 value: false.into(),
1063 };
1064 assert!(bool_match.applies(&event, &context).await);
1065
1066 let bool_no_match = PushCondition::EventPropertyContains {
1067 key: r"content.org\.fake\.array".to_owned(),
1068 value: true.into(),
1069 };
1070 assert!(!bool_no_match.applies(&event, &context).await);
1071
1072 let int_match = PushCondition::EventPropertyContains {
1073 key: r"content.org\.fake\.array".to_owned(),
1074 value: int!(13).into(),
1075 };
1076 assert!(int_match.applies(&event, &context).await);
1077
1078 let int_no_match = PushCondition::EventPropertyContains {
1079 key: r"content.org\.fake\.array".to_owned(),
1080 value: int!(130).into(),
1081 };
1082 assert!(!int_no_match.applies(&event, &context).await);
1083
1084 let null_match = PushCondition::EventPropertyContains {
1085 key: r"content.org\.fake\.array".to_owned(),
1086 value: ScalarJsonValue::Null,
1087 };
1088 assert!(null_match.applies(&event, &context).await);
1089 }
1090
1091 #[apply(test!)]
1092 async fn room_creators_always_have_notification_permission() {
1093 let mut context = push_context();
1094 context.power_levels = Some(PushConditionPowerLevelsCtx {
1095 users: BTreeMap::new(),
1096 users_default: Int::MIN,
1097 notifications: NotificationPowerLevels { room: Int::MAX },
1098 rules: RoomPowerLevelsRules::new(&AuthorizationRules::V12, Some(sender())),
1099 });
1100
1101 let first_event = first_flattened_event();
1102
1103 let sender_notification_permission =
1104 PushCondition::SenderNotificationPermission { key: NotificationPowerLevelsKey::Room };
1105
1106 assert!(sender_notification_permission.applies(&first_event, &context).await);
1107 }
1108
1109 #[cfg(feature = "unstable-msc4306")]
1110 #[apply(test!)]
1111 async fn thread_subscriptions_match() {
1112 use crate::{EventId, event_id};
1113
1114 let context = push_context().with_has_thread_subscription_fn(|event_id: &EventId| {
1115 Box::pin(async move {
1116 event_id == event_id!("$subscribed_thread")
1118 })
1119 });
1120
1121 let subscribed_thread_event = FlattenedJson::from_value(json!({
1122 "event_id": "$thread_response",
1123 "sender": "@worthy_whale:server.name",
1124 "content": {
1125 "msgtype": "m.text",
1126 "body": "response in thread $subscribed_thread",
1127 "m.relates_to": {
1128 "rel_type": "m.thread",
1129 "event_id": "$subscribed_thread",
1130 "is_falling_back": true,
1131 "m.in_reply_to": {
1132 "event_id": "$prev_event",
1133 },
1134 },
1135 },
1136 }));
1137
1138 let unsubscribed_thread_event = FlattenedJson::from_value(json!({
1139 "event_id": "$thread_response2",
1140 "sender": "@worthy_whale:server.name",
1141 "content": {
1142 "msgtype": "m.text",
1143 "body": "response in thread $unsubscribed_thread",
1144 "m.relates_to": {
1145 "rel_type": "m.thread",
1146 "event_id": "$unsubscribed_thread",
1147 "is_falling_back": true,
1148 "m.in_reply_to": {
1149 "event_id": "$prev_event2",
1150 },
1151 },
1152 },
1153 }));
1154
1155 let non_thread_related_event = FlattenedJson::from_value(json!({
1156 "event_id": "$thread_response2",
1157 "sender": "@worthy_whale:server.name",
1158 "content": {
1159 "m.relates_to": {
1160 "rel_type": "m.reaction",
1161 "event_id": "$subscribed_thread",
1162 "key": "👍",
1163 },
1164 },
1165 }));
1166
1167 let subscribed_thread_condition = PushCondition::ThreadSubscription { subscribed: true };
1168 assert!(subscribed_thread_condition.applies(&subscribed_thread_event, &context).await);
1169 assert!(!subscribed_thread_condition.applies(&unsubscribed_thread_event, &context).await);
1170 assert!(!subscribed_thread_condition.applies(&non_thread_related_event, &context).await);
1171
1172 let unsubscribed_thread_condition = PushCondition::ThreadSubscription { subscribed: false };
1173 assert!(unsubscribed_thread_condition.applies(&unsubscribed_thread_event, &context).await);
1174 assert!(!unsubscribed_thread_condition.applies(&subscribed_thread_event, &context).await);
1175 assert!(!unsubscribed_thread_condition.applies(&non_thread_related_event, &context).await);
1176 }
1177}