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::{
7 7
8use crate::{config::ConfigHandle, Servers}; 8use crate::{config::ConfigHandle, Servers};
9 9
10mod access;
10mod buffer_clear; 11mod buffer_clear;
11mod buffer_switch; 12mod buffer_switch;
12mod devices; 13mod devices;
@@ -32,6 +33,7 @@ mod upload;
32mod verification; 33mod verification;
33mod verify; 34mod verify;
34 35
36use access::RoomAccessCommand;
35use buffer_clear::BufferClearCommand; 37use buffer_clear::BufferClearCommand;
36use buffer_switch::BufferSwitchCommand; 38use buffer_switch::BufferSwitchCommand;
37 39
@@ -59,6 +61,7 @@ use upload::UploadCommand;
59use verify::VerifyCommand; 61use verify::VerifyCommand;
60 62
61pub struct Commands { 63pub struct Commands {
64 _room_access: Command,
62 _matrix: Command, 65 _matrix: Command,
63 _mention_send: CommandRun, 66 _mention_send: CommandRun,
64 _matrix_upload: CommandRun, 67 _matrix_upload: CommandRun,
@@ -92,6 +95,7 @@ impl Commands {
92 config: &ConfigHandle, 95 config: &ConfigHandle,
93 ) -> Result<Commands, ()> { 96 ) -> Result<Commands, ()> {
94 Ok(Commands { 97 Ok(Commands {
98 _room_access: RoomAccessCommand::create(servers)?,
95 _matrix: MatrixCommand::create(servers, config)?, 99 _matrix: MatrixCommand::create(servers, config)?,
96 _mention_send: MentionSendCommand::create(servers)?, 100 _mention_send: MentionSendCommand::create(servers)?,
97 _matrix_upload: MatrixUploadCommand::create(servers)?, 101 _matrix_upload: MatrixUploadCommand::create(servers)?,
src/room/mod.rs +33
@@ -68,6 +68,7 @@ use matrix_sdk::{
68 EncryptedEventScheme, Relation as EncryptedRelation, 68 EncryptedEventScheme, Relation as EncryptedRelation,
69 RoomEncryptedEventContent, 69 RoomEncryptedEventContent,
70 }, 70 },
71 join_rules::RoomJoinRulesEventContent,
71 member::RoomMemberEventContent, 72 member::RoomMemberEventContent,
72 message::{ 73 message::{
73 MessageType, Relation, ReplyWithinThread, 74 MessageType, Relation, ReplyWithinThread,
@@ -79,6 +80,7 @@ use matrix_sdk::{
79 AnySyncStateEvent, AnySyncTimelineEvent, AnyTimelineEvent, 80 AnySyncStateEvent, AnySyncTimelineEvent, AnyTimelineEvent,
80 OriginalSyncMessageLikeEvent, SyncMessageLikeEvent, SyncStateEvent, 81 OriginalSyncMessageLikeEvent, SyncMessageLikeEvent, SyncStateEvent,
81 }, 82 },
83 room::JoinRule,
82 serde::Raw, 84 serde::Raw,
83 EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomAliasId, 85 EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomAliasId,
84 OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, OwnedTransactionId, 86 OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, OwnedTransactionId,
@@ -1686,6 +1688,37 @@ impl MatrixRoom {
1686 } 1688 }
1687 } 1689 }
1688 1690
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
1689 pub async fn ban_user(&self, user_id: OwnedUserId, reason: Option<String>) { 1722 pub async fn ban_user(&self, user_id: OwnedUserId, reason: Option<String>) {
1690 let Some(connection) = self.connection.borrow().clone() else { 1723 let Some(connection) = self.connection.borrow().clone() else {
1691 self.print_error("Not connected. Please connect first."); 1724 self.print_error("Not connected. Please connect first.");