Commit 774db68f72

774db68f7245d5e45ca31504a120ed8bcce541a5

parent: 8fd3f40181

Unsigned

Darafei Praliaskouski <me@komzpa.net> · 2026-08-06 18:37 UTC
committer: <strk@kbt.io>

feat: add room access control commands

Layout: unified · split

src/commands/access.rs added +150
@@ -0,0 +1,150 @@
1use clap::{App as Argparse, AppSettings as ArgParseSettings, Arg, SubCommand};
2use matrix_sdk::ruma::room::JoinRule;
3use weechat::{
4 buffer::Buffer,
5 hooks::{Command, CommandCallback, CommandSettings},
6 Args, Prefix, Weechat,
7};
8
9use super::parse_and_run;
10use crate::Servers;
11
12#[derive(Clone, Copy, Debug, Eq, PartialEq)]
13enum AccessAction {
14 Public,
15 Invite,
16}
17
18impl AccessAction {
19 fn rule(self) -> JoinRule {
20 match self {
21 Self::Public => JoinRule::Public,
22 Self::Invite => JoinRule::Invite,
23 }
24 }
25}
26
27pub struct RoomAccessCommand {
28 servers: Servers,
29}
30
31impl RoomAccessCommand {
32 pub fn create(servers: &Servers) -> Result<Command, ()> {
33 let settings = CommandSettings::new("room")
34 .description("Change access rules for the current Matrix room.")
35 .add_argument("make_public|make_invite_only")
36 .add_argument("set_join_rule <public|invite>")
37 .arguments_description(
38 "make_public: Allow anyone to join the room.\n\
39 make_invite_only: Require an invitation to join.\n\
40 set_join_rule: Set the join rule to public or invite.",
41 )
42 .add_completion(
43 "make_public|make_invite_only|set_join_rule public|invite",
44 );
45
46 Command::new(
47 settings,
48 Self {
49 servers: servers.clone(),
50 },
51 )
52 }
53
54 fn parser() -> Argparse<'static, 'static> {
55 Argparse::new("room")
56 .settings(&[
57 ArgParseSettings::DisableHelpFlags,
58 ArgParseSettings::DisableVersion,
59 ])
60 .subcommand(SubCommand::with_name("make_public"))
61 .subcommand(SubCommand::with_name("make_invite_only"))
62 .subcommand(
63 SubCommand::with_name("set_join_rule")
64 .arg(Arg::with_name("rule").required(true)),
65 )
66 }
67
68 fn action(matches: &clap::ArgMatches) -> Result<AccessAction, String> {
69 match matches.subcommand() {
70 ("make_public", _) => Ok(AccessAction::Public),
71 ("make_invite_only", _) => Ok(AccessAction::Invite),
72 ("set_join_rule", Some(args)) => match args.value_of("rule") {
73 Some("public") => Ok(AccessAction::Public),
74 Some("invite") | Some("invite_only") => Ok(AccessAction::Invite),
75 Some(rule) => Err(format!(
76 "Unsupported join rule `{}`; use public or invite.",
77 rule
78 )),
79 None => Err("A join rule is required.".to_owned()),
80 },
81 _ => Err("Usage: /room make_public|make_invite_only|set_join_rule <public|invite>".to_owned()),
82 }
83 }
84
85 fn run(&self, buffer: &Buffer, action: AccessAction) {
86 let Some(room) = self.servers.find_room(buffer) else {
87 buffer.print(&format!(
88 "{}The /room command needs to be run in a Matrix room buffer.",
89 Weechat::prefix(Prefix::Error)
90 ));
91 return;
92 };
93
94 Weechat::spawn(async move { room.set_join_rule(action.rule()).await })
95 .detach();
96 }
97}
98
99impl CommandCallback for RoomAccessCommand {
100 fn callback(&mut self, _: &Weechat, buffer: &Buffer, arguments: Args) {
101 parse_and_run(Self::parser(), arguments, |matches| match Self::action(
102 matches,
103 ) {
104 Ok(action) => self.run(buffer, action),
105 Err(error) => buffer.print(&format!(
106 "{}{}",
107 Weechat::prefix(Prefix::Error),
108 error
109 )),
110 });
111 }
112}
113
114#[cfg(test)]
115mod tests {
116 use super::{AccessAction, RoomAccessCommand};
117
118 fn parse(args: &[&str]) -> Result<AccessAction, String> {
119 let matches = RoomAccessCommand::parser()
120 .get_matches_from_safe(args)
121 .map_err(|error| error.to_string())?;
122 RoomAccessCommand::action(&matches)
123 }
124
125 #[test]
126 fn explicit_shortcuts_select_join_rules() {
127 assert_eq!(Ok(AccessAction::Public), parse(&["room", "make_public"]));
128 assert_eq!(
129 Ok(AccessAction::Invite),
130 parse(&["room", "make_invite_only"])
131 );
132 }
133
134 #[test]
135 fn generic_command_accepts_public_and_invite_rules() {
136 assert_eq!(
137 Ok(AccessAction::Public),
138 parse(&["room", "set_join_rule", "public"])
139 );
140 assert_eq!(
141 Ok(AccessAction::Invite),
142 parse(&["room", "set_join_rule", "invite"])
143 );
144 }
145
146 #[test]
147 fn generic_command_rejects_unsupported_rules() {
148 assert!(parse(&["room", "set_join_rule", "restricted"]).is_err());
149 }
150}
src/commands/mod.rs +4
@@ -7,6 +7,7 @@ use weechat::{
77
88use crate::{config::ConfigHandle, Servers};
99
10mod access;
1011mod buffer_clear;
1112mod buffer_switch;
1213mod devices;
@@ -32,6 +33,7 @@ mod upload;
3233mod verification;
3334mod verify;
3435
36use access::RoomAccessCommand;
3537use buffer_clear::BufferClearCommand;
3638use buffer_switch::BufferSwitchCommand;
3739
@@ -59,6 +61,7 @@ use upload::UploadCommand;
5961use verify::VerifyCommand;
6062
6163pub struct Commands {
64 _room_access: Command,
6265 _matrix: Command,
6366 _mention_send: CommandRun,
6467 _matrix_upload: CommandRun,
@@ -92,6 +95,7 @@ impl Commands {
9295 config: &ConfigHandle,
9396 ) -> Result<Commands, ()> {
9497 Ok(Commands {
98 _room_access: RoomAccessCommand::create(servers)?,
9599 _matrix: MatrixCommand::create(servers, config)?,
96100 _mention_send: MentionSendCommand::create(servers)?,
97101 _matrix_upload: MatrixUploadCommand::create(servers)?,
src/room/mod.rs +33
@@ -68,6 +68,7 @@ use matrix_sdk::{
6868 EncryptedEventScheme, Relation as EncryptedRelation,
6969 RoomEncryptedEventContent,
7070 },
71 join_rules::RoomJoinRulesEventContent,
7172 member::RoomMemberEventContent,
7273 message::{
7374 MessageType, Relation, ReplyWithinThread,
@@ -79,6 +80,7 @@ use matrix_sdk::{
7980 AnySyncStateEvent, AnySyncTimelineEvent, AnyTimelineEvent,
8081 OriginalSyncMessageLikeEvent, SyncMessageLikeEvent, SyncStateEvent,
8182 },
83 room::JoinRule,
8284 serde::Raw,
8385 EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomAliasId,
8486 OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, OwnedTransactionId,
@@ -1686,6 +1688,37 @@ impl MatrixRoom {
16861688 }
16871689 }
16881690
1691 pub async fn set_join_rule(&self, join_rule: JoinRule) {
1692 let Some(connection) = self.connection.borrow().clone() else {
1693 self.print_error("Not connected. Please connect first.");
1694 return;
1695 };
1696
1697 let room = self.room().clone();
1698 let description = match join_rule {
1699 JoinRule::Public => "public",
1700 JoinRule::Invite => "invite-only",
1701 _ => "requested",
1702 };
1703
1704 match connection
1705 .spawn(async move {
1706 room.send_state_event(RoomJoinRulesEventContent::new(join_rule))
1707 .await
1708 })
1709 .await
1710 {
1711 Ok(_) => self.print_network(&format!(
1712 "Room join rule changed to {}.",
1713 description
1714 )),
1715 Err(error) => self.print_error(&format!(
1716 "Failed to change room join rule: {}",
1717 error
1718 )),
1719 }
1720 }
1721
16891722 pub async fn ban_user(&self, user_id: OwnedUserId, reason: Option<String>) {
16901723 let Some(connection) = self.connection.borrow().clone() else {
16911724 self.print_error("Not connected. Please connect first.");