src/commands/access.rs
148 lines · 4577 bytes
12 symbols in this file
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 Knock,
17 Private,
18}
19
20impl AccessAction {
21 fn rule(self) -> JoinRule {
22 match self {
23 Self::Public => JoinRule::Public,
24 Self::Invite => JoinRule::Invite,
25 Self::Knock => JoinRule::Knock,
26 Self::Private => JoinRule::Private,
27 }
28 }
29}
30
31pub struct RoomAccessCommand {
32 servers: Servers,
33}
34
35impl RoomAccessCommand {
36 pub fn create(servers: &Servers) -> Result<Command, ()> {
37 let settings = CommandSettings::new("room")
38 .description("Change access rules for the current Matrix room.")
39 .add_argument("set_join_rule <public|invite|knock|private>")
40 .arguments_description(
41 "set_join_rule: Set the join rule to public, invite, knock, or private.",
42 )
43 .add_completion(
44 "set_join_rule public|invite|knock|private",
45 );
46
47 Command::new(
48 settings,
49 Self {
50 servers: servers.clone(),
51 },
52 )
53 }
54
55 fn parser() -> Argparse<'static, 'static> {
56 Argparse::new("room")
57 .settings(&[
58 ArgParseSettings::DisableHelpFlags,
59 ArgParseSettings::DisableVersion,
60 ])
61 .subcommand(
62 SubCommand::with_name("set_join_rule")
63 .arg(Arg::with_name("rule").required(true)),
64 )
65 }
66
67 fn action(matches: &clap::ArgMatches) -> Result<AccessAction, String> {
68 match matches.subcommand() {
69 ("set_join_rule", Some(args)) => match args.value_of("rule") {
70 Some("public") => Ok(AccessAction::Public),
71 Some("invite") | Some("invite_only") => Ok(AccessAction::Invite),
72 Some("knock") => Ok(AccessAction::Knock),
73 Some("private") => Ok(AccessAction::Private),
74 Some(rule) => Err(format!(
75 "Unsupported join rule `{}`; use public, invite, knock, or private.",
76 rule
77 )),
78 None => Err("A join rule is required.".to_owned()),
79 },
80 _ => Err("Usage: /room set_join_rule <public|invite|knock|private>".to_owned()),
81 }
82 }
83
84 fn run(&self, buffer: &Buffer, action: AccessAction) {
85 let Some(room) = self.servers.find_room(buffer) else {
86 buffer.print(&format!(
87 "{}The /room command needs to be run in a Matrix room buffer.",
88 Weechat::prefix(Prefix::Error)
89 ));
90 return;
91 };
92
93 Weechat::spawn(async move { room.set_join_rule(action.rule()).await })
94 .detach();
95 }
96}
97
98impl CommandCallback for RoomAccessCommand {
99 fn callback(&mut self, _: &Weechat, buffer: &Buffer, arguments: Args) {
100 parse_and_run(Self::parser(), arguments, |matches| match Self::action(
101 matches,
102 ) {
103 Ok(action) => self.run(buffer, action),
104 Err(error) => buffer.print(&format!(
105 "{}{}",
106 Weechat::prefix(Prefix::Error),
107 error
108 )),
109 });
110 }
111}
112
113#[cfg(test)]
114mod tests {
115 use super::{AccessAction, RoomAccessCommand};
116
117 fn parse(args: &[&str]) -> Result<AccessAction, String> {
118 let matches = RoomAccessCommand::parser()
119 .get_matches_from_safe(args)
120 .map_err(|error| error.to_string())?;
121 RoomAccessCommand::action(&matches)
122 }
123
124 #[test]
125 fn generic_command_accepts_public_and_invite_rules() {
126 assert_eq!(
127 Ok(AccessAction::Public),
128 parse(&["room", "set_join_rule", "public"])
129 );
130 assert_eq!(
131 Ok(AccessAction::Invite),
132 parse(&["room", "set_join_rule", "invite"])
133 );
134 assert_eq!(
135 Ok(AccessAction::Knock),
136 parse(&["room", "set_join_rule", "knock"])
137 );
138 assert_eq!(
139 Ok(AccessAction::Private),
140 parse(&["room", "set_join_rule", "private"])
141 );
142 }
143
144 #[test]
145 fn generic_command_rejects_unsupported_rules() {
146 assert!(parse(&["room", "set_join_rule", "restricted"]).is_err());
147 }
148}