src/commands/moderation.rs
157 lines · 4703 bytes
12 symbols in this file
1use clap::{App as Argparse, AppSettings as ArgParseSettings, Arg, ArgMatches};
2use matrix_sdk::ruma::{OwnedUserId, UserId};
3use weechat::{
4 buffer::Buffer,
5 hooks::{Command, CommandCallback, CommandSettings},
6 Args, Prefix, Weechat,
7};
8
9use super::parse_and_run;
10use crate::{Servers, PLUGIN_NAME};
11
12#[derive(Clone, Copy)]
13enum ModerationAction {
14 Ban,
15 Kick,
16 Unban,
17}
18
19impl ModerationAction {
20 fn command(&self) -> &'static str {
21 match self {
22 ModerationAction::Ban => "ban",
23 ModerationAction::Kick => "kick",
24 ModerationAction::Unban => "unban",
25 }
26 }
27
28 fn description(&self) -> &'static str {
29 match self {
30 ModerationAction::Ban => "Ban a Matrix user from the current room.",
31 ModerationAction::Kick => {
32 "Kick a Matrix user from the current room."
33 }
34 ModerationAction::Unban => {
35 "Unban a Matrix user from the current room."
36 }
37 }
38 }
39
40 fn verb(&self) -> &'static str {
41 match self {
42 ModerationAction::Ban => "ban",
43 ModerationAction::Kick => "kick",
44 ModerationAction::Unban => "unban",
45 }
46 }
47}
48
49pub struct ModerationCommand {
50 servers: Servers,
51 action: ModerationAction,
52}
53
54impl ModerationCommand {
55 fn create(
56 servers: &Servers,
57 action: ModerationAction,
58 ) -> Result<Command, ()> {
59 let settings = CommandSettings::new(action.command())
60 .description(action.description())
61 .add_argument("<user-id> [reason]")
62 .arguments_description(format!(
63 "user-id: The Matrix user ID to {}.\nreason: Optional reason.",
64 action.verb()
65 ))
66 .add_completion("%(matrix-users) %-");
67
68 Command::new(
69 settings,
70 ModerationCommand {
71 servers: servers.clone(),
72 action,
73 },
74 )
75 }
76
77 pub fn ban(servers: &Servers) -> Result<Command, ()> {
78 Self::create(servers, ModerationAction::Ban)
79 }
80
81 pub fn kick(servers: &Servers) -> Result<Command, ()> {
82 Self::create(servers, ModerationAction::Kick)
83 }
84
85 pub fn unban(servers: &Servers) -> Result<Command, ()> {
86 Self::create(servers, ModerationAction::Unban)
87 }
88
89 fn parse_reason(args: &ArgMatches) -> Option<String> {
90 args.values_of("reason")
91 .map(|values| values.collect::<Vec<_>>().join(" "))
92 .filter(|reason| !reason.is_empty())
93 }
94
95 fn run(
96 &self,
97 buffer: &Buffer,
98 user_id: OwnedUserId,
99 reason: Option<String>,
100 ) {
101 let Some(room) = self.servers.find_room(buffer) else {
102 Weechat::print(&format!(
103 "{}{}: /{} needs to be run in a Matrix room buffer.",
104 Weechat::prefix(Prefix::Error),
105 PLUGIN_NAME,
106 self.action.command()
107 ));
108 return;
109 };
110
111 let action = self.action;
112 Weechat::spawn(async move {
113 match action {
114 ModerationAction::Ban => room.ban_user(user_id, reason).await,
115 ModerationAction::Kick => room.kick_user(user_id, reason).await,
116 ModerationAction::Unban => {
117 room.unban_user(user_id, reason).await
118 }
119 };
120 })
121 .detach();
122 }
123}
124
125impl CommandCallback for ModerationCommand {
126 fn callback(&mut self, _: &Weechat, buffer: &Buffer, arguments: Args) {
127 let parser = Argparse::new(self.action.command())
128 .about(self.action.description())
129 .settings(&[
130 ArgParseSettings::DisableHelpFlags,
131 ArgParseSettings::DisableVersion,
132 ])
133 .arg(Arg::with_name("user-id").required(true).validator(|u| {
134 UserId::parse(u).map(|_| ()).map_err(|_| {
135 "The given user is not a valid user ID".to_owned()
136 })
137 }))
138 .arg(
139 Arg::with_name("reason")
140 .multiple(true)
141 .allow_hyphen_values(true),
142 );
143
144 parse_and_run(parser, arguments, |matches| {
145 let user_id = matches
146 .value_of("user-id")
147 .map(|u| {
148 UserId::parse(u)
149 .expect("Argument was already validated as a user ID")
150 })
151 .expect("User ID not set but was required");
152 let reason = Self::parse_reason(matches);
153
154 self.run(buffer, user_id, reason);
155 });
156 }
157}