Commit 2a66496913

2a664969132f457824e6c2c90e4f25b6558be6ec

parent: b4fc574163

Unregistered key

Tony <11652273+rmsthebest@users.noreply.github.com> · 2024-08-17 21:43 UTC
committer: <noreply@github.com>

Add command to set per-room notification levels (#305)

Layout: unified · split

docs/iamb.1 +19
@@ -122,6 +122,25 @@ View a list of members of the currently focused room.
122Set the name of the currently focused room. 122Set the name of the currently focused room.
123.It Sy ":room name unset" 123.It Sy ":room name unset"
124Unset the name of the currently focused room. 124Unset the name of the currently focused room.
125.It Sy ":room notify set [level]"
126Set a notification level for the currently focused room.
127Valid levels are
128.Dq mute ,
129.Dq mentions ,
130.Dq keywords ,
131and
132.Dq all .
133Note that
134.Dq mentions
135and
136.Dq keywords
137are aliases for the same behaviour.
138.It Sy ":room notify unset"
139Unset any room-level notification configuration.
140.It Sy ":room notify show"
141Show the current room-level notification configuration.
142If the room is using the account-level default, then this will print
143.Dq default .
125.It Sy ":room tag set [tag]" 144.It Sy ":room tag set [tag]"
126Add a tag to the currently focused room. 145Add a tag to the currently focused room.
127.It Sy ":room tag unset [tag]" 146.It Sy ":room tag unset [tag]"
src/base.rs +10
@@ -378,6 +378,9 @@ pub enum RoomField {
378 /// The room topic. 378 /// The room topic.
379 Topic, 379 Topic,
380 380
381 /// Notification level.
382 NotificationMode,
383
381 /// The room's entire list of alternative aliases. 384 /// The room's entire list of alternative aliases.
382 Aliases, 385 Aliases,
383 386
@@ -612,6 +615,10 @@ pub type MessageReactions = HashMap<OwnedEventId, (String, OwnedUserId)>;
612/// Errors encountered during application use. 615/// Errors encountered during application use.
613#[derive(thiserror::Error, Debug)] 616#[derive(thiserror::Error, Debug)]
614pub enum IambError { 617pub enum IambError {
618 /// An invalid notification level was specified.
619 #[error("Invalid notification level: {0}")]
620 InvalidNotificationLevel(String),
621
615 /// An invalid user identifier was specified. 622 /// An invalid user identifier was specified.
616 #[error("Invalid user identifier: {0}")] 623 #[error("Invalid user identifier: {0}")]
617 InvalidUserId(String), 624 InvalidUserId(String),
@@ -691,6 +698,9 @@ pub enum IambError {
691 #[error("Verification request error: {0}")] 698 #[error("Verification request error: {0}")]
692 VerificationRequestError(#[from] matrix_sdk::encryption::identities::RequestVerificationError), 699 VerificationRequestError(#[from] matrix_sdk::encryption::identities::RequestVerificationError),
693 700
701 #[error("Notification setting error: {0}")]
702 NotificationSettingError(#[from] matrix_sdk::NotificationSettingsError),
703
694 /// A failure related to images. 704 /// A failure related to images.
695 #[error("Image error: {0}")] 705 #[error("Image error: {0}")]
696 Image(#[from] image::ImageError), 706 Image(#[from] image::ImageError),
src/commands.rs +34 −1
@@ -34,7 +34,7 @@ type ProgResult = CommandResult<ProgramCommand>;
34 34
35/// Convert strings the user types into a tag name. 35/// Convert strings the user types into a tag name.
36fn tag_name(name: String) -> Result<TagName, CommandError> { 36fn tag_name(name: String) -> Result<TagName, CommandError> {
37 let tag = match name.as_str() { 37 let tag = match name.to_lowercase().as_str() {
38 "fav" | "favorite" | "favourite" | "m.favourite" => TagName::Favorite, 38 "fav" | "favorite" | "favourite" | "m.favourite" => TagName::Favorite,
39 "low" | "lowpriority" | "low_priority" | "low-priority" | "m.lowpriority" => { 39 "low" | "lowpriority" | "low_priority" | "low-priority" | "m.lowpriority" => {
40 TagName::LowPriority 40 TagName::LowPriority
@@ -431,6 +431,18 @@ fn iamb_room(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
431 ("tag", "set", Some(s)) => RoomAction::Set(RoomField::Tag(tag_name(s)?), "".into()).into(), 431 ("tag", "set", Some(s)) => RoomAction::Set(RoomField::Tag(tag_name(s)?), "".into()).into(),
432 ("tag", "set", None) => return Result::Err(CommandError::InvalidArgument), 432 ("tag", "set", None) => return Result::Err(CommandError::InvalidArgument),
433 433
434 // :room notify set <notification-level>
435 ("notify", "set", Some(s)) => RoomAction::Set(RoomField::NotificationMode, s).into(),
436 ("notify", "set", None) => return Result::Err(CommandError::InvalidArgument),
437
438 // :room notify unset <notification-level>
439 ("notify", "unset", None) => RoomAction::Unset(RoomField::NotificationMode).into(),
440 ("notify", "unset", Some(_)) => return Result::Err(CommandError::InvalidArgument),
441
442 // :room notify show
443 ("notify", "show", None) => RoomAction::Show(RoomField::NotificationMode).into(),
444 ("notify", "show", Some(_)) => return Result::Err(CommandError::InvalidArgument),
445
434 // :room tag unset <tag-name> 446 // :room tag unset <tag-name>
435 ("tag", "unset", Some(s)) => RoomAction::Unset(RoomField::Tag(tag_name(s)?)).into(), 447 ("tag", "unset", Some(s)) => RoomAction::Unset(RoomField::Tag(tag_name(s)?)).into(),
436 ("tag", "unset", None) => return Result::Err(CommandError::InvalidArgument), 448 ("tag", "unset", None) => return Result::Err(CommandError::InvalidArgument),
@@ -977,6 +989,27 @@ mod tests {
977 ); 989 );
978 } 990 }
979 991
992 #[test]
993 fn test_cmd_room_notification_mode_set() {
994 let mut cmds = setup_commands();
995 let ctx = EditContext::default();
996
997 let cmd = format!("room notify set mute");
998 let res = cmds.input_cmd(&cmd, ctx.clone()).unwrap();
999 let act = RoomAction::Set(RoomField::NotificationMode, "mute".into());
1000 assert_eq!(res, vec![(act.into(), ctx.clone())]);
1001
1002 let cmd = format!("room notify unset");
1003 let res = cmds.input_cmd(&cmd, ctx.clone()).unwrap();
1004 let act = RoomAction::Unset(RoomField::NotificationMode);
1005 assert_eq!(res, vec![(act.into(), ctx.clone())]);
1006
1007 let cmd = format!("room notify show");
1008 let res = cmds.input_cmd(&cmd, ctx.clone()).unwrap();
1009 let act = RoomAction::Show(RoomField::NotificationMode);
1010 assert_eq!(res, vec![(act.into(), ctx.clone())]);
1011 }
1012
980 #[test] 1013 #[test]
981 fn test_cmd_invite() { 1014 fn test_cmd_invite() {
982 let mut cmds = setup_commands(); 1015 let mut cmds = setup_commands();
src/windows/room/mod.rs +72
@@ -2,6 +2,7 @@
2use std::collections::HashSet; 2use std::collections::HashSet;
3 3
4use matrix_sdk::{ 4use matrix_sdk::{
5 notification_settings::RoomNotificationMode,
5 room::Room as MatrixRoom, 6 room::Room as MatrixRoom,
6 ruma::{ 7 ruma::{
7 api::client::{ 8 api::client::{
@@ -82,6 +83,19 @@ macro_rules! delegate {
82 }; 83 };
83} 84}
84 85
86fn notification_mode(name: impl Into<String>) -> IambResult<RoomNotificationMode> {
87 let name = name.into();
88
89 let mode = match name.to_lowercase().as_str() {
90 "mute" => RoomNotificationMode::Mute,
91 "mentions" | "keywords" => RoomNotificationMode::MentionsAndKeywordsOnly,
92 "all" => RoomNotificationMode::AllMessages,
93 _ => return Err(IambError::InvalidNotificationLevel(name).into()),
94 };
95
96 Ok(mode)
97}
98
85/// State for a Matrix room or space. 99/// State for a Matrix room or space.
86/// 100///
87/// Since spaces function as special rooms within Matrix, we wrap their window state together, so 101/// Since spaces function as special rooms within Matrix, we wrap their window state together, so
@@ -296,6 +310,16 @@ impl RoomState {
296 let ev = RoomTopicEventContent::new(value); 310 let ev = RoomTopicEventContent::new(value);
297 let _ = room.send_state_event(ev).await.map_err(IambError::from)?; 311 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
298 }, 312 },
313 RoomField::NotificationMode => {
314 let mode = notification_mode(value)?;
315 let client = &store.application.worker.client;
316 let notifications = client.notification_settings().await;
317
318 notifications
319 .set_room_notification_mode(self.id(), mode)
320 .await
321 .map_err(IambError::from)?;
322 },
299 RoomField::CanonicalAlias => { 323 RoomField::CanonicalAlias => {
300 let client = &mut store.application.worker.client; 324 let client = &mut store.application.worker.client;
301 325
@@ -399,6 +423,15 @@ impl RoomState {
399 let ev = RoomTopicEventContent::new("".into()); 423 let ev = RoomTopicEventContent::new("".into());
400 let _ = room.send_state_event(ev).await.map_err(IambError::from)?; 424 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
401 }, 425 },
426 RoomField::NotificationMode => {
427 let client = &store.application.worker.client;
428 let notifications = client.notification_settings().await;
429
430 notifications
431 .delete_user_defined_room_rules(self.id())
432 .await
433 .map_err(IambError::from)?;
434 },
402 RoomField::CanonicalAlias => { 435 RoomField::CanonicalAlias => {
403 let Some(alias_to_destroy) = room.canonical_alias() else { 436 let Some(alias_to_destroy) = room.canonical_alias() else {
404 let msg = "This room has no canonical alias to unset"; 437 let msg = "This room has no canonical alias to unset";
@@ -481,6 +514,21 @@ impl RoomState {
481 Some(topic) => format!("Room topic: {topic:?}"), 514 Some(topic) => format!("Room topic: {topic:?}"),
482 } 515 }
483 }, 516 },
517 RoomField::NotificationMode => {
518 let client = &store.application.worker.client;
519 let notifications = client.notification_settings().await;
520 let mode =
521 notifications.get_user_defined_room_notification_mode(self.id()).await;
522
523 let level = match mode {
524 Some(RoomNotificationMode::Mute) => "mute",
525 Some(RoomNotificationMode::MentionsAndKeywordsOnly) => "keywords",
526 Some(RoomNotificationMode::AllMessages) => "all",
527 None => "default",
528 };
529
530 format!("Room notification level: {level:?}")
531 },
484 RoomField::Aliases => { 532 RoomField::Aliases => {
485 let aliases = room 533 let aliases = room
486 .alt_aliases() 534 .alt_aliases()
@@ -677,3 +725,27 @@ impl WindowOps<IambInfo> for RoomState {
677 } 725 }
678 } 726 }
679} 727}
728
729#[cfg(test)]
730mod tests {
731 use super::*;
732
733 #[test]
734 fn test_parse_room_notification_level() {
735 let tests = vec![
736 ("mute", RoomNotificationMode::Mute),
737 ("mentions", RoomNotificationMode::MentionsAndKeywordsOnly),
738 ("keywords", RoomNotificationMode::MentionsAndKeywordsOnly),
739 ("all", RoomNotificationMode::AllMessages),
740 ];
741
742 for (input, expect) in tests {
743 let res = notification_mode(input).unwrap();
744 assert_eq!(expect, res);
745 }
746
747 assert!(notification_mode("invalid").is_err());
748 assert!(notification_mode("not a level").is_err());
749 assert!(notification_mode("@user:example.com").is_err());
750 }
751}