Commit 31f8e04503

31f8e04503d3a146ea4408a8b9f0581fcffcb11d

parent: b3d2285a92

Unsigned

Darafei Praliaskouski <me@komzpa.net> · 2026-06-23 16:27 UTC
committer: <strk@kbt.io>

feat: add matrix redact command

Layout: unified · split

src/commands/mod.rs +4
@@ -16,6 +16,7 @@ mod me;
16mod media; 16mod media;
17mod page_up; 17mod page_up;
18mod part; 18mod part;
19mod redact;
19mod upload; 20mod upload;
20mod verification; 21mod verification;
21 22
@@ -28,6 +29,7 @@ use me::MeCommand;
28use media::MediaCommand; 29use media::MediaCommand;
29use page_up::PageUpCommand; 30use page_up::PageUpCommand;
30use part::PartCommand; 31use part::PartCommand;
32use redact::RedactCommand;
31use upload::UploadCommand; 33use upload::UploadCommand;
32 34
33pub struct Commands { 35pub struct Commands {
@@ -35,6 +37,7 @@ pub struct Commands {
35 _keys: Command, 37 _keys: Command,
36 _devices: Command, 38 _devices: Command,
37 _page_up: CommandRun, 39 _page_up: CommandRun,
40 _redact: Command,
38 _verification: Command, 41 _verification: Command,
39 _buffer_clear: CommandRun, 42 _buffer_clear: CommandRun,
40 _join: CommandRun, 43 _join: CommandRun,
@@ -53,6 +56,7 @@ impl Commands {
53 _devices: DevicesCommand::create(servers)?, 56 _devices: DevicesCommand::create(servers)?,
54 _keys: KeysCommand::create(servers)?, 57 _keys: KeysCommand::create(servers)?,
55 _page_up: PageUpCommand::create(servers)?, 58 _page_up: PageUpCommand::create(servers)?,
59 _redact: RedactCommand::create(servers)?,
56 _verification: VerificationCommand::create(servers)?, 60 _verification: VerificationCommand::create(servers)?,
57 _buffer_clear: BufferClearCommand::create(servers)?, 61 _buffer_clear: BufferClearCommand::create(servers)?,
58 _join: JoinCommand::create(servers)?, 62 _join: JoinCommand::create(servers)?,
src/commands/redact.rs added +144
@@ -0,0 +1,144 @@
1use clap::{App as Argparse, AppSettings as ArgParseSettings, Arg};
2use matrix_sdk::ruma::{EventId, OwnedEventId};
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
12const EVENT_ID_TAG_PREFIX: &str = "matrix_id_";
13
14pub struct RedactCommand {
15 servers: Servers,
16}
17
18impl RedactCommand {
19 pub fn create(servers: &Servers) -> Result<Command, ()> {
20 let settings = CommandSettings::new("redact")
21 .description("Redact a Matrix event in the current room.")
22 .add_argument("[event-id] [reason...]")
23 .arguments_description(
24 "event-id: The Matrix event ID to redact. If omitted, the latest \
25 unredacted event in the current buffer is used.
26 reason: Optional reason for the redaction. If no event ID is given, all text \
27 is used as the reason for redacting the latest unredacted event.",
28 );
29
30 Command::new(
31 settings,
32 RedactCommand {
33 servers: servers.clone(),
34 },
35 )
36 }
37
38 fn latest_event_id(buffer: &Buffer) -> Option<OwnedEventId> {
39 buffer.lines().rev().find_map(|line| {
40 let tags = line.tags();
41
42 if tags.iter().any(|tag| tag.as_ref() == "matrix_redacted") {
43 return None;
44 }
45
46 tags.iter()
47 .find_map(|tag| tag.as_ref().strip_prefix(EVENT_ID_TAG_PREFIX))
48 .and_then(|event_id| EventId::parse(event_id).ok())
49 })
50 }
51
52 fn parse_arguments(
53 buffer: &Buffer,
54 arguments: Option<Vec<&str>>,
55 ) -> Result<(OwnedEventId, Option<String>), String> {
56 let Some(arguments) = arguments else {
57 return Self::latest_event_id(buffer)
58 .map(|event_id| (event_id, None))
59 .ok_or_else(|| "No Matrix event found to redact.".to_owned());
60 };
61
62 let Some((first, rest)) = arguments.split_first() else {
63 return Self::latest_event_id(buffer)
64 .map(|event_id| (event_id, None))
65 .ok_or_else(|| "No Matrix event found to redact.".to_owned());
66 };
67
68 if first.starts_with('$') && EventId::parse(*first).is_err() {
69 return Err(format!("Invalid Matrix event ID: {}", first));
70 }
71
72 if let Ok(event_id) = EventId::parse(*first) {
73 let reason = if rest.is_empty() {
74 None
75 } else {
76 Some(rest.join(" "))
77 };
78
79 Ok((event_id, reason))
80 } else {
81 Self::latest_event_id(buffer)
82 .map(|event_id| (event_id, Some(arguments.join(" "))))
83 .ok_or_else(|| "No Matrix event found to redact.".to_owned())
84 }
85 }
86
87 fn redact(
88 &self,
89 buffer: &Buffer,
90 event_id: OwnedEventId,
91 reason: Option<String>,
92 ) {
93 if let Some(room) = self.servers.find_room(buffer) {
94 let room = room.room().clone();
95
96 match self.servers.runtime().block_on(room.redact(
97 &event_id,
98 reason.as_deref(),
99 None,
100 )) {
101 Ok(_) => (),
102 Err(error) => Weechat::print(&format!(
103 "{}Failed to redact {}: {}",
104 Weechat::prefix(Prefix::Error),
105 event_id,
106 error
107 )),
108 }
109 } else {
110 Weechat::print(
111 "The /redact command needs to be run in a Matrix room buffer.",
112 );
113 }
114 }
115}
116
117impl CommandCallback for RedactCommand {
118 fn callback(&mut self, _: &Weechat, buffer: &Buffer, arguments: Args) {
119 let parser = Argparse::new("redact")
120 .about("Redact a Matrix event in the current room.")
121 .settings(&[
122 ArgParseSettings::DisableHelpFlags,
123 ArgParseSettings::DisableVersion,
124 ])
125 .arg(
126 Arg::with_name("arguments")
127 .multiple(true)
128 .allow_hyphen_values(true),
129 );
130
131 parse_and_run(parser, arguments, |matches| {
132 let arguments = matches.values_of("arguments").map(|a| a.collect());
133
134 match Self::parse_arguments(buffer, arguments) {
135 Ok((event_id, reason)) => self.redact(buffer, event_id, reason),
136 Err(error) => Weechat::print(&format!(
137 "{}{}",
138 Weechat::prefix(Prefix::Error),
139 error
140 )),
141 }
142 });
143 }
144}