Commit c9c547acc1

c9c547acc1b46ff378fc2b954767459852608b37

parent: 3629f15e0d

Unregistered key

Ulyssa <git@ulyssa.dev> · 2023-02-10 01:53 UTC

Support sending and displaying message reactions (#2)

Layout: unified · split

Cargo.lock +34 −6
@@ -752,6 +752,15 @@ version = "1.8.0"
752source = "registry+https://github.com/rust-lang/crates.io-index" 752source = "registry+https://github.com/rust-lang/crates.io-index"
753checksum = "90e5c1c8368803113bf0c9584fc495a58b86dc8a29edbf8fe877d21d9507e797" 753checksum = "90e5c1c8368803113bf0c9584fc495a58b86dc8a29edbf8fe877d21d9507e797"
754 754
755[[package]]
756name = "emojis"
757version = "0.5.2"
758source = "registry+https://github.com/rust-lang/crates.io-index"
759checksum = "44fe60b864b6544ad211d4053ced474a9b9d2c8d66b77f01d6c6bcfed10c6bf0"
760dependencies = [
761 "phf 0.11.1",
762]
763
755[[package]] 764[[package]]
756name = "encoding_rs" 765name = "encoding_rs"
757version = "0.8.31" 766version = "0.8.31"
@@ -1165,6 +1174,7 @@ dependencies = [
1165 "clap", 1174 "clap",
1166 "css-color-parser", 1175 "css-color-parser",
1167 "dirs", 1176 "dirs",
1177 "emojis",
1168 "gethostname", 1178 "gethostname",
1169 "html5ever", 1179 "html5ever",
1170 "lazy_static 1.4.0", 1180 "lazy_static 1.4.0",
@@ -1434,7 +1444,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
1434checksum = "7a2629bb1404f3d34c2e921f21fd34ba00b206124c81f65c50b43b6aaefeb016" 1444checksum = "7a2629bb1404f3d34c2e921f21fd34ba00b206124c81f65c50b43b6aaefeb016"
1435dependencies = [ 1445dependencies = [
1436 "log", 1446 "log",
1437 "phf", 1447 "phf 0.10.1",
1438 "phf_codegen", 1448 "phf_codegen",
1439 "string_cache", 1449 "string_cache",
1440 "string_cache_codegen", 1450 "string_cache_codegen",
@@ -1884,7 +1894,16 @@ version = "0.10.1"
1884source = "registry+https://github.com/rust-lang/crates.io-index" 1894source = "registry+https://github.com/rust-lang/crates.io-index"
1885checksum = "fabbf1ead8a5bcbc20f5f8b939ee3f5b0f6f281b6ad3468b84656b658b455259" 1895checksum = "fabbf1ead8a5bcbc20f5f8b939ee3f5b0f6f281b6ad3468b84656b658b455259"
1886dependencies = [ 1896dependencies = [
1887 "phf_shared", 1897 "phf_shared 0.10.0",
1898]
1899
1900[[package]]
1901name = "phf"
1902version = "0.11.1"
1903source = "registry+https://github.com/rust-lang/crates.io-index"
1904checksum = "928c6535de93548188ef63bb7c4036bd415cd8f36ad25af44b9789b2ee72a48c"
1905dependencies = [
1906 "phf_shared 0.11.1",
1888] 1907]
1889 1908
1890[[package]] 1909[[package]]
@@ -1894,7 +1913,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
1894checksum = "4fb1c3a8bc4dd4e5cfce29b44ffc14bedd2ee294559a294e2a4d4c9e9a6a13cd" 1913checksum = "4fb1c3a8bc4dd4e5cfce29b44ffc14bedd2ee294559a294e2a4d4c9e9a6a13cd"
1895dependencies = [ 1914dependencies = [
1896 "phf_generator", 1915 "phf_generator",
1897 "phf_shared", 1916 "phf_shared 0.10.0",
1898] 1917]
1899 1918
1900[[package]] 1919[[package]]
@@ -1903,7 +1922,7 @@ version = "0.10.0"
1903source = "registry+https://github.com/rust-lang/crates.io-index" 1922source = "registry+https://github.com/rust-lang/crates.io-index"
1904checksum = "5d5285893bb5eb82e6aaf5d59ee909a06a16737a8970984dd7746ba9283498d6" 1923checksum = "5d5285893bb5eb82e6aaf5d59ee909a06a16737a8970984dd7746ba9283498d6"
1905dependencies = [ 1924dependencies = [
1906 "phf_shared", 1925 "phf_shared 0.10.0",
1907 "rand 0.8.5", 1926 "rand 0.8.5",
1908] 1927]
1909 1928
@@ -1916,6 +1935,15 @@ dependencies = [
1916 "siphasher", 1935 "siphasher",
1917] 1936]
1918 1937
1938[[package]]
1939name = "phf_shared"
1940version = "0.11.1"
1941source = "registry+https://github.com/rust-lang/crates.io-index"
1942checksum = "e1fb5f6f826b772a8d4c0394209441e7d37cbbb967ae9c7e0e8134365c9ee676"
1943dependencies = [
1944 "siphasher",
1945]
1946
1919[[package]] 1947[[package]]
1920name = "pin-project" 1948name = "pin-project"
1921version = "1.0.12" 1949version = "1.0.12"
@@ -2637,7 +2665,7 @@ dependencies = [
2637 "new_debug_unreachable", 2665 "new_debug_unreachable",
2638 "once_cell", 2666 "once_cell",
2639 "parking_lot 0.12.1", 2667 "parking_lot 0.12.1",
2640 "phf_shared", 2668 "phf_shared 0.10.0",
2641 "precomputed-hash", 2669 "precomputed-hash",
2642 "serde", 2670 "serde",
2643] 2671]
@@ -2649,7 +2677,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
2649checksum = "6bb30289b722be4ff74a408c3cc27edeaad656e06cb1fe8fa9231fa59c728988" 2677checksum = "6bb30289b722be4ff74a408c3cc27edeaad656e06cb1fe8fa9231fa59c728988"
2650dependencies = [ 2678dependencies = [
2651 "phf_generator", 2679 "phf_generator",
2652 "phf_shared", 2680 "phf_shared 0.10.0",
2653 "proc-macro2", 2681 "proc-macro2",
2654 "quote", 2682 "quote",
2655] 2683]
Cargo.toml +1
@@ -19,6 +19,7 @@ chrono = "0.4"
19clap = {version = "4.0", features = ["derive"]} 19clap = {version = "4.0", features = ["derive"]}
20css-color-parser = "0.1.2" 20css-color-parser = "0.1.2"
21dirs = "4.0.0" 21dirs = "4.0.0"
22emojis = "~0.5.2"
22gethostname = "0.4.1" 23gethostname = "0.4.1"
23html5ever = "0.26.0" 24html5ever = "0.26.0"
24markup5ever_rcdom = "0.2.0" 25markup5ever_rcdom = "0.2.0"
src/base.rs +112 −13
@@ -10,14 +10,19 @@ use matrix_sdk::{
10 encryption::verification::SasVerification, 10 encryption::verification::SasVerification,
11 room::Joined, 11 room::Joined,
12 ruma::{ 12 ruma::{
13 events::room::message::{ 13 events::{
14 OriginalRoomMessageEvent, 14 reaction::ReactionEvent,
15 Relation, 15 room::message::{
16 Replacement, 16 OriginalRoomMessageEvent,
17 RoomMessageEvent, 17 Relation,
18 RoomMessageEventContent, 18 Replacement,
19 RoomMessageEvent,
20 RoomMessageEventContent,
21 },
22 tag::{TagName, Tags},
23 AnyMessageLikeEvent,
24 MessageLikeEvent,
19 }, 25 },
20 events::tag::{TagName, Tags},
21 EventId, 26 EventId,
22 OwnedEventId, 27 OwnedEventId,
23 OwnedRoomId, 28 OwnedRoomId,
@@ -88,11 +93,20 @@ pub enum MessageAction {
88 /// Edit a sent message. 93 /// Edit a sent message.
89 Edit, 94 Edit,
90 95
91 /// Redact a message. 96 /// React to a message with an Emoji.
97 React(String),
98
99 /// Redact a message, with an optional reason.
92 Redact(Option<String>), 100 Redact(Option<String>),
93 101
94 /// Reply to a message. 102 /// Reply to a message.
95 Reply, 103 Reply,
104
105 /// Unreact to a message.
106 ///
107 /// If no specific Emoji to remove to is specified, then all reactions from the user on the
108 /// message are removed.
109 Unreact(Option<String>),
96} 110}
97 111
98bitflags::bitflags! { 112bitflags::bitflags! {
@@ -226,6 +240,12 @@ pub type AsyncProgramStore = Arc<AsyncMutex<ProgramStore>>;
226 240
227pub type IambResult<T> = UIResult<T, IambInfo>; 241pub type IambResult<T> = UIResult<T, IambInfo>;
228 242
243/// Reaction events for some message.
244///
245/// The event identifier used as a key here is the ID for the reaction, and not for the message
246/// it's reacting to.
247pub type MessageReactions = HashMap<OwnedEventId, (String, OwnedUserId)>;
248
229pub type Receipts = HashMap<OwnedEventId, Vec<OwnedUserId>>; 249pub type Receipts = HashMap<OwnedEventId, Vec<OwnedUserId>>;
230 250
231#[derive(thiserror::Error, Debug)] 251#[derive(thiserror::Error, Debug)]
@@ -292,32 +312,103 @@ pub enum RoomFetchStatus {
292 NotStarted, 312 NotStarted,
293} 313}
294 314
315pub enum EventLocation {
316 Message(MessageKey),
317 Reaction(OwnedEventId),
318}
319
320impl EventLocation {
321 fn to_message_key(&self) -> Option<&MessageKey> {
322 if let EventLocation::Message(key) = self {
323 Some(key)
324 } else {
325 None
326 }
327 }
328}
329
295#[derive(Default)] 330#[derive(Default)]
296pub struct RoomInfo { 331pub struct RoomInfo {
332 /// The display name for this room.
297 pub name: Option<String>, 333 pub name: Option<String>,
334
335 /// The tags placed on this room.
298 pub tags: Option<Tags>, 336 pub tags: Option<Tags>,
299 337
300 pub keys: HashMap<OwnedEventId, MessageKey>, 338 /// A map of event IDs to where they are stored in this struct.
339 pub keys: HashMap<OwnedEventId, EventLocation>,
340
341 /// The messages loaded for this room.
301 pub messages: Messages, 342 pub messages: Messages,
302 343
344 /// A map of read markers to display on different events.
303 pub receipts: HashMap<OwnedEventId, Vec<OwnedUserId>>, 345 pub receipts: HashMap<OwnedEventId, Vec<OwnedUserId>>,
346
347 /// An event ID for where we should indicate we've read up to.
304 pub read_till: Option<OwnedEventId>, 348 pub read_till: Option<OwnedEventId>,
305 349
350 /// A map of message identifiers to a map of reaction events.
351 pub reactions: HashMap<OwnedEventId, MessageReactions>,
352
353 /// Where to continue fetching from when we continue loading scrollback history.
306 pub fetch_id: RoomFetchStatus, 354 pub fetch_id: RoomFetchStatus,
355
356 /// The time that we last fetched scrollback for this room.
307 pub fetch_last: Option<Instant>, 357 pub fetch_last: Option<Instant>,
358
359 /// Users currently typing in this room, and when we received notification of them doing so.
308 pub users_typing: Option<(Instant, Vec<OwnedUserId>)>, 360 pub users_typing: Option<(Instant, Vec<OwnedUserId>)>,
309} 361}
310 362
311impl RoomInfo { 363impl RoomInfo {
364 pub fn get_reactions(&self, event_id: &EventId) -> Vec<(&str, usize)> {
365 if let Some(reacts) = self.reactions.get(event_id) {
366 let mut counts = HashMap::new();
367
368 for (key, _) in reacts.values() {
369 let count = counts.entry(key.as_str()).or_default();
370 *count += 1;
371 }
372
373 let mut reactions = counts.into_iter().collect::<Vec<_>>();
374 reactions.sort();
375
376 reactions
377 } else {
378 vec![]
379 }
380 }
381
312 pub fn get_event(&self, event_id: &EventId) -> Option<&Message> { 382 pub fn get_event(&self, event_id: &EventId) -> Option<&Message> {
313 self.messages.get(self.keys.get(event_id)?) 383 self.messages.get(self.keys.get(event_id)?.to_message_key()?)
384 }
385
386 pub fn insert_reaction(&mut self, react: ReactionEvent) {
387 match react {
388 MessageLikeEvent::Original(react) => {
389 let rel_id = react.content.relates_to.event_id;
390 let key = react.content.relates_to.key;
391
392 let message = self.reactions.entry(rel_id.clone()).or_default();
393 let event_id = react.event_id;
394 let user_id = react.sender;
395
396 message.insert(event_id.clone(), (key, user_id));
397
398 let loc = EventLocation::Reaction(rel_id);
399 self.keys.insert(event_id, loc);
400 },
401 MessageLikeEvent::Redacted(_) => {
402 return;
403 },
404 }
314 } 405 }
315 406
316 pub fn insert_edit(&mut self, msg: Replacement) { 407 pub fn insert_edit(&mut self, msg: Replacement) {
317 let event_id = msg.event_id; 408 let event_id = msg.event_id;
318 let new_content = msg.new_content; 409 let new_content = msg.new_content;
319 410
320 let key = if let Some(k) = self.keys.get(&event_id) { 411 let key = if let Some(EventLocation::Message(k)) = self.keys.get(&event_id) {
321 k 412 k
322 } else { 413 } else {
323 return; 414 return;
@@ -346,7 +437,7 @@ impl RoomInfo {
346 let event_id = msg.event_id().to_owned(); 437 let event_id = msg.event_id().to_owned();
347 let key = (msg.origin_server_ts().into(), event_id.clone()); 438 let key = (msg.origin_server_ts().into(), event_id.clone());
348 439
349 self.keys.insert(event_id.clone(), key.clone()); 440 self.keys.insert(event_id.clone(), EventLocation::Message(key.clone()));
350 self.messages.insert(key, msg.into()); 441 self.messages.insert(key, msg.into());
351 442
352 // Remove any echo. 443 // Remove any echo.
@@ -519,7 +610,15 @@ impl ChatStore {
519 match res { 610 match res {
520 Ok((fetch_id, msgs)) => { 611 Ok((fetch_id, msgs)) => {
521 for msg in msgs.into_iter() { 612 for msg in msgs.into_iter() {
522 info.insert(msg); 613 match msg {
614 AnyMessageLikeEvent::RoomMessage(msg) => {
615 info.insert(msg);
616 },
617 AnyMessageLikeEvent::Reaction(ev) => {
618 info.insert_reaction(ev);
619 },
620 _ => continue,
621 }
523 } 622 }
524 623
525 info.fetch_id = 624 info.fetch_id =
src/commands.rs +53 −4
@@ -163,8 +163,8 @@ fn iamb_cancel(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
163 return Result::Err(CommandError::InvalidArgument); 163 return Result::Err(CommandError::InvalidArgument);
164 } 164 }
165 165
166 let ract = IambAction::from(MessageAction::Cancel); 166 let mact = IambAction::from(MessageAction::Cancel);
167 let step = CommandStep::Continue(ract.into(), ctx.context.take()); 167 let step = CommandStep::Continue(mact.into(), ctx.context.take());
168 168
169 return Ok(step); 169 return Ok(step);
170} 170}
@@ -174,8 +174,55 @@ fn iamb_edit(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
174 return Result::Err(CommandError::InvalidArgument); 174 return Result::Err(CommandError::InvalidArgument);
175 } 175 }
176 176
177 let ract = IambAction::from(MessageAction::Edit); 177 let mact = IambAction::from(MessageAction::Edit);
178 let step = CommandStep::Continue(ract.into(), ctx.context.take()); 178 let step = CommandStep::Continue(mact.into(), ctx.context.take());
179
180 return Ok(step);
181}
182
183fn iamb_react(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
184 let args = desc.arg.strings()?;
185
186 if args.len() != 1 {
187 return Result::Err(CommandError::InvalidArgument);
188 }
189
190 let k = args[0].as_str();
191
192 if let Some(emoji) = emojis::get(k).or_else(|| emojis::get_by_shortcode(k)) {
193 let mact = IambAction::from(MessageAction::React(emoji.to_string()));
194 let step = CommandStep::Continue(mact.into(), ctx.context.take());
195
196 return Ok(step);
197 } else {
198 let msg = format!("Invalid Emoji or shortcode: {k}");
199
200 return Result::Err(CommandError::Error(msg));
201 }
202}
203
204fn iamb_unreact(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
205 let mut args = desc.arg.strings()?;
206
207 if args.len() > 1 {
208 return Result::Err(CommandError::InvalidArgument);
209 }
210
211 let mact = if let Some(k) = args.pop() {
212 let k = k.as_str();
213
214 if let Some(emoji) = emojis::get(k).or_else(|| emojis::get_by_shortcode(k)) {
215 IambAction::from(MessageAction::Unreact(Some(emoji.to_string())))
216 } else {
217 let msg = format!("Invalid Emoji or shortcode: {k}");
218
219 return Result::Err(CommandError::Error(msg));
220 }
221 } else {
222 IambAction::from(MessageAction::Unreact(None))
223 };
224
225 let step = CommandStep::Continue(mact.into(), ctx.context.take());
179 226
180 return Ok(step); 227 return Ok(step);
181} 228}
@@ -356,11 +403,13 @@ fn add_iamb_commands(cmds: &mut ProgramCommands) {
356 cmds.add_command(ProgramCommand { names: vec!["invite".into()], f: iamb_invite }); 403 cmds.add_command(ProgramCommand { names: vec!["invite".into()], f: iamb_invite });
357 cmds.add_command(ProgramCommand { names: vec!["join".into()], f: iamb_join }); 404 cmds.add_command(ProgramCommand { names: vec!["join".into()], f: iamb_join });
358 cmds.add_command(ProgramCommand { names: vec!["members".into()], f: iamb_members }); 405 cmds.add_command(ProgramCommand { names: vec!["members".into()], f: iamb_members });
406 cmds.add_command(ProgramCommand { names: vec!["react".into()], f: iamb_react });
359 cmds.add_command(ProgramCommand { names: vec!["redact".into()], f: iamb_redact }); 407 cmds.add_command(ProgramCommand { names: vec!["redact".into()], f: iamb_redact });
360 cmds.add_command(ProgramCommand { names: vec!["reply".into()], f: iamb_reply }); 408 cmds.add_command(ProgramCommand { names: vec!["reply".into()], f: iamb_reply });
361 cmds.add_command(ProgramCommand { names: vec!["rooms".into()], f: iamb_rooms }); 409 cmds.add_command(ProgramCommand { names: vec!["rooms".into()], f: iamb_rooms });
362 cmds.add_command(ProgramCommand { names: vec!["room".into()], f: iamb_room }); 410 cmds.add_command(ProgramCommand { names: vec!["room".into()], f: iamb_room });
363 cmds.add_command(ProgramCommand { names: vec!["spaces".into()], f: iamb_spaces }); 411 cmds.add_command(ProgramCommand { names: vec!["spaces".into()], f: iamb_spaces });
412 cmds.add_command(ProgramCommand { names: vec!["unreact".into()], f: iamb_unreact });
364 cmds.add_command(ProgramCommand { names: vec!["upload".into()], f: iamb_upload }); 413 cmds.add_command(ProgramCommand { names: vec!["upload".into()], f: iamb_upload });
365 cmds.add_command(ProgramCommand { names: vec!["verify".into()], f: iamb_verify }); 414 cmds.add_command(ProgramCommand { names: vec!["verify".into()], f: iamb_verify });
366 cmds.add_command(ProgramCommand { names: vec!["welcome".into()], f: iamb_welcome }); 415 cmds.add_command(ProgramCommand { names: vec!["welcome".into()], f: iamb_welcome });
src/config.rs +10
@@ -178,6 +178,8 @@ fn merge_users(a: Option<UserOverrides>, b: Option<UserOverrides>) -> Option<Use
178 178
179#[derive(Clone)] 179#[derive(Clone)]
180pub struct TunableValues { 180pub struct TunableValues {
181 pub reaction_display: bool,
182 pub reaction_shortcode_display: bool,
181 pub read_receipt_send: bool, 183 pub read_receipt_send: bool,
182 pub read_receipt_display: bool, 184 pub read_receipt_display: bool,
183 pub typing_notice_send: bool, 185 pub typing_notice_send: bool,
@@ -188,6 +190,8 @@ pub struct TunableValues {
188 190
189#[derive(Clone, Default, Deserialize)] 191#[derive(Clone, Default, Deserialize)]
190pub struct Tunables { 192pub struct Tunables {
193 pub reaction_display: Option<bool>,
194 pub reaction_shortcode_display: Option<bool>,
191 pub read_receipt_send: Option<bool>, 195 pub read_receipt_send: Option<bool>,
192 pub read_receipt_display: Option<bool>, 196 pub read_receipt_display: Option<bool>,
193 pub typing_notice_send: Option<bool>, 197 pub typing_notice_send: Option<bool>,
@@ -199,6 +203,10 @@ pub struct Tunables {
199impl Tunables { 203impl Tunables {
200 fn merge(self, other: Self) -> Self { 204 fn merge(self, other: Self) -> Self {
201 Tunables { 205 Tunables {
206 reaction_display: self.reaction_display.or(other.reaction_display),
207 reaction_shortcode_display: self
208 .reaction_shortcode_display
209 .or(other.reaction_shortcode_display),
202 read_receipt_send: self.read_receipt_send.or(other.read_receipt_send), 210 read_receipt_send: self.read_receipt_send.or(other.read_receipt_send),
203 read_receipt_display: self.read_receipt_display.or(other.read_receipt_display), 211 read_receipt_display: self.read_receipt_display.or(other.read_receipt_display),
204 typing_notice_send: self.typing_notice_send.or(other.typing_notice_send), 212 typing_notice_send: self.typing_notice_send.or(other.typing_notice_send),
@@ -210,6 +218,8 @@ impl Tunables {
210 218
211 fn values(self) -> TunableValues { 219 fn values(self) -> TunableValues {
212 TunableValues { 220 TunableValues {
221 reaction_display: self.reaction_display.unwrap_or(true),
222 reaction_shortcode_display: self.reaction_shortcode_display.unwrap_or(false),
213 read_receipt_send: self.read_receipt_send.unwrap_or(true), 223 read_receipt_send: self.read_receipt_send.unwrap_or(true),
214 read_receipt_display: self.read_receipt_display.unwrap_or(true), 224 read_receipt_display: self.read_receipt_display.unwrap_or(true),
215 typing_notice_send: self.typing_notice_send.unwrap_or(true), 225 typing_notice_send: self.typing_notice_send.unwrap_or(true),
src/message/mod.rs +39 −1
@@ -24,6 +24,7 @@ use matrix_sdk::ruma::{
24 }, 24 },
25 redaction::SyncRoomRedactionEvent, 25 redaction::SyncRoomRedactionEvent,
26 }, 26 },
27 AnyMessageLikeEvent,
27 Redact, 28 Redact,
28 }, 29 },
29 EventId, 30 EventId,
@@ -52,7 +53,7 @@ use crate::{
52mod html; 53mod html;
53mod printer; 54mod printer;
54 55
55pub type MessageFetchResult = IambResult<(Option<String>, Vec<RoomMessageEvent>)>; 56pub type MessageFetchResult = IambResult<(Option<String>, Vec<AnyMessageLikeEvent>)>;
56pub type MessageKey = (MessageTimeStamp, OwnedEventId); 57pub type MessageKey = (MessageTimeStamp, OwnedEventId);
57pub type Messages = BTreeMap<MessageKey, Message>; 58pub type Messages = BTreeMap<MessageKey, Message>;
58 59
@@ -682,6 +683,43 @@ impl Message {
682 fmt.push_spans(space_span(width, style).into(), style, &mut text); 683 fmt.push_spans(space_span(width, style).into(), style, &mut text);
683 } 684 }
684 685
686 if settings.tunables.reaction_display {
687 let mut emojis = printer::TextPrinter::new(width, style, false);
688 let mut reactions = 0;
689
690 for (key, count) in info.get_reactions(self.event.event_id()).into_iter() {
691 if reactions != 0 {
692 emojis.push_str(" ", style);
693 }
694
695 let name = if settings.tunables.reaction_shortcode_display {
696 if let Some(emoji) = emojis::get(key) {
697 if let Some(short) = emoji.shortcode() {
698 short
699 } else {
700 // No ASCII shortcode name to show.
701 continue;
702 }
703 } else if key.chars().all(|c| c.is_ascii_alphanumeric()) {
704 key
705 } else {
706 // Not an Emoji or a printable ASCII string.
707 continue;
708 }
709 } else {
710 key
711 };
712
713 emojis.push_str(format!("[{name} {count}]"), style);
714
715 reactions += 1;
716 }
717
718 if reactions > 0 {
719 fmt.push_text(emojis.finish(), style, &mut text);
720 }
721 }
722
685 return text; 723 return text;
686 } 724 }
687 725
src/tests.rs +10 −7
@@ -20,7 +20,7 @@ use tokio::sync::mpsc::unbounded_channel;
20use url::Url; 20use url::Url;
21 21
22use crate::{ 22use crate::{
23 base::{ChatStore, ProgramStore, RoomFetchStatus, RoomInfo}, 23 base::{ChatStore, EventLocation, ProgramStore, RoomFetchStatus, RoomInfo},
24 config::{ 24 config::{
25 user_color, 25 user_color,
26 user_style_from_color, 26 user_style_from_color,
@@ -117,14 +117,14 @@ pub fn mock_message5() -> Message {
117 mock_room1_message(content, TEST_USER2.clone(), MSG4_KEY.clone()) 117 mock_room1_message(content, TEST_USER2.clone(), MSG4_KEY.clone())
118} 118}
119 119
120pub fn mock_keys() -> HashMap<OwnedEventId, MessageKey> { 120pub fn mock_keys() -> HashMap<OwnedEventId, EventLocation> {
121 let mut keys = HashMap::new(); 121 let mut keys = HashMap::new();
122 122
123 keys.insert(MSG1_EVID.clone(), MSG1_KEY.clone()); 123 keys.insert(MSG1_EVID.clone(), EventLocation::Message(MSG1_KEY.clone()));
124 keys.insert(MSG2_EVID.clone(), MSG2_KEY.clone()); 124 keys.insert(MSG2_EVID.clone(), EventLocation::Message(MSG2_KEY.clone()));
125 keys.insert(MSG3_EVID.clone(), MSG3_KEY.clone()); 125 keys.insert(MSG3_EVID.clone(), EventLocation::Message(MSG3_KEY.clone()));
126 keys.insert(MSG4_EVID.clone(), MSG4_KEY.clone()); 126 keys.insert(MSG4_EVID.clone(), EventLocation::Message(MSG4_KEY.clone()));
127 keys.insert(MSG5_EVID.clone(), MSG5_KEY.clone()); 127 keys.insert(MSG5_EVID.clone(), EventLocation::Message(MSG5_KEY.clone()));
128 128
129 keys 129 keys
130} 130}
@@ -151,6 +151,7 @@ pub fn mock_room() -> RoomInfo {
151 151
152 receipts: HashMap::new(), 152 receipts: HashMap::new(),
153 read_till: None, 153 read_till: None,
154 reactions: HashMap::new(),
154 155
155 fetch_id: RoomFetchStatus::NotStarted, 156 fetch_id: RoomFetchStatus::NotStarted,
156 fetch_last: None, 157 fetch_last: None,
@@ -169,6 +170,8 @@ pub fn mock_dirs() -> DirectoryValues {
169pub fn mock_tunables() -> TunableValues { 170pub fn mock_tunables() -> TunableValues {
170 TunableValues { 171 TunableValues {
171 default_room: None, 172 default_room: None,
173 reaction_display: true,
174 reaction_shortcode_display: false,
172 read_receipt_send: true, 175 read_receipt_send: true,
173 read_receipt_display: true, 176 read_receipt_display: true,
174 typing_notice_send: true, 177 typing_notice_send: true,
src/windows/room/chat.rs +73 −10
@@ -9,8 +9,9 @@ use tokio;
9use matrix_sdk::{ 9use matrix_sdk::{
10 attachment::AttachmentConfig, 10 attachment::AttachmentConfig,
11 media::{MediaFormat, MediaRequest}, 11 media::{MediaFormat, MediaRequest},
12 room::Room as MatrixRoom, 12 room::{Joined, Room as MatrixRoom},
13 ruma::{ 13 ruma::{
14 events::reaction::{ReactionEventContent, Relation as Reaction},
14 events::room::message::{ 15 events::room::message::{
15 MessageType, 16 MessageType,
16 OriginalRoomMessageEvent, 17 OriginalRoomMessageEvent,
@@ -19,6 +20,7 @@ use matrix_sdk::{
19 RoomMessageEventContent, 20 RoomMessageEventContent,
20 TextMessageEventContent, 21 TextMessageEventContent,
21 }, 22 },
23 EventId,
22 OwnedRoomId, 24 OwnedRoomId,
23 RoomId, 25 RoomId,
24 }, 26 },
@@ -73,6 +75,7 @@ use crate::base::{
73}; 75};
74 76
75use crate::message::{Message, MessageEvent, MessageKey, MessageTimeStamp}; 77use crate::message::{Message, MessageEvent, MessageKey, MessageTimeStamp};
78use crate::worker::Requester;
76 79
77use super::scrollback::{Scrollback, ScrollbackState}; 80use super::scrollback::{Scrollback, ScrollbackState};
78 81
@@ -115,6 +118,10 @@ impl ChatState {
115 } 118 }
116 } 119 }
117 120
121 fn get_joined(&self, worker: &Requester) -> Result<Joined, IambError> {
122 worker.client.get_joined_room(self.id()).ok_or(IambError::NotJoined)
123 }
124
118 fn get_reply_to<'a>(&self, info: &'a RoomInfo) -> Option<&'a OriginalRoomMessageEvent> { 125 fn get_reply_to<'a>(&self, info: &'a RoomInfo) -> Option<&'a OriginalRoomMessageEvent> {
119 let key = self.reply_to.as_ref()?; 126 let key = self.reply_to.as_ref()?;
120 let msg = info.messages.get(key)?; 127 let msg = info.messages.get(key)?;
@@ -149,7 +156,10 @@ impl ChatState {
149 let settings = &store.application.settings; 156 let settings = &store.application.settings;
150 let info = store.application.rooms.entry(self.room_id.clone()).or_default(); 157 let info = store.application.rooms.entry(self.room_id.clone()).or_default();
151 158
152 let msg = self.scrollback.get_mut(info).ok_or(IambError::NoSelectedMessage)?; 159 let msg = self
160 .scrollback
161 .get_mut(&mut info.messages)
162 .ok_or(IambError::NoSelectedMessage)?;
153 163
154 match act { 164 match act {
155 MessageAction::Cancel => { 165 MessageAction::Cancel => {
@@ -282,19 +292,32 @@ impl ChatState {
282 292
283 Ok(None) 293 Ok(None)
284 }, 294 },
285 MessageAction::Redact(reason) => { 295 MessageAction::React(emoji) => {
286 let room = store 296 let room = self.get_joined(&store.application.worker)?;
287 .application 297 let event_id = match &msg.event {
288 .worker 298 MessageEvent::Original(ev) => ev.event_id.clone(),
289 .client 299 MessageEvent::Local(event_id, _) => event_id.clone(),
290 .get_joined_room(self.id()) 300 MessageEvent::Redacted(_) => {
291 .ok_or(IambError::NotJoined)?; 301 let msg = "Cannot react to a redacted message";
302 let err = UIError::Failure(msg.into());
303
304 return Err(err);
305 },
306 };
292 307
308 let reaction = Reaction::new(event_id, emoji);
309 let msg = ReactionEventContent::new(reaction);
310 let _ = room.send(msg, None).await.map_err(IambError::from)?;
311
312 Ok(None)
313 },
314 MessageAction::Redact(reason) => {
315 let room = self.get_joined(&store.application.worker)?;
293 let event_id = match &msg.event { 316 let event_id = match &msg.event {
294 MessageEvent::Original(ev) => ev.event_id.clone(), 317 MessageEvent::Original(ev) => ev.event_id.clone(),
295 MessageEvent::Local(event_id, _) => event_id.clone(), 318 MessageEvent::Local(event_id, _) => event_id.clone(),
296 MessageEvent::Redacted(_) => { 319 MessageEvent::Redacted(_) => {
297 let msg = ""; 320 let msg = "Cannot redact already redacted message";
298 let err = UIError::Failure(msg.into()); 321 let err = UIError::Failure(msg.into());
299 322
300 return Err(err); 323 return Err(err);
@@ -311,6 +334,46 @@ impl ChatState {
311 self.reply_to = self.scrollback.get_key(info); 334 self.reply_to = self.scrollback.get_key(info);
312 self.focus = RoomFocus::MessageBar; 335 self.focus = RoomFocus::MessageBar;
313 336
337 Ok(None)
338 },
339 MessageAction::Unreact(emoji) => {
340 let room = self.get_joined(&store.application.worker)?;
341 let event_id: &EventId = match &msg.event {
342 MessageEvent::Original(ev) => ev.event_id.as_ref(),
343 MessageEvent::Local(event_id, _) => event_id.as_ref(),
344 MessageEvent::Redacted(_) => {
345 let msg = "Cannot unreact to a redacted message";
346 let err = UIError::Failure(msg.into());
347
348 return Err(err);
349 },
350 };
351
352 let reactions = match info.reactions.get(event_id) {
353 Some(r) => r,
354 None => return Ok(None),
355 };
356
357 let reactions = reactions.iter().filter_map(|(event_id, (reaction, user_id))| {
358 if user_id != &settings.profile.user_id {
359 return None;
360 }
361
362 if let Some(emoji) = &emoji {
363 if emoji == reaction {
364 return Some(event_id);
365 } else {
366 return None;
367 }
368 } else {
369 return Some(event_id);
370 }
371 });
372
373 for reaction in reactions {
374 let _ = room.redact(reaction, None, None).await.map_err(IambError::from)?;
375 }
376
314 Ok(None) 377 Ok(None)
315 }, 378 },
316 } 379 }
src/windows/room/scrollback.rs +4 −4
@@ -62,7 +62,7 @@ use modalkit::editing::{
62use crate::{ 62use crate::{
63 base::{IambBufferId, IambInfo, ProgramContext, ProgramStore, RoomFocus, RoomInfo}, 63 base::{IambBufferId, IambInfo, ProgramContext, ProgramStore, RoomFocus, RoomInfo},
64 config::ApplicationSettings, 64 config::ApplicationSettings,
65 message::{Message, MessageCursor, MessageKey}, 65 message::{Message, MessageCursor, MessageKey, Messages},
66}; 66};
67 67
68fn nth_key_before(pos: MessageKey, n: usize, info: &RoomInfo) -> MessageKey { 68fn nth_key_before(pos: MessageKey, n: usize, info: &RoomInfo) -> MessageKey {
@@ -164,11 +164,11 @@ impl ScrollbackState {
164 .or_else(|| info.messages.last_key_value().map(|kv| kv.0.clone())) 164 .or_else(|| info.messages.last_key_value().map(|kv| kv.0.clone()))
165 } 165 }
166 166
167 pub fn get_mut<'a>(&mut self, info: &'a mut RoomInfo) -> Option<&'a mut Message> { 167 pub fn get_mut<'a>(&mut self, messages: &'a mut Messages) -> Option<&'a mut Message> {
168 if let Some(k) = &self.cursor.timestamp { 168 if let Some(k) = &self.cursor.timestamp {
169 info.messages.get_mut(k) 169 messages.get_mut(k)
170 } else { 170 } else {
171 info.messages.last_entry().map(|o| o.into_mut()) 171 messages.last_entry().map(|o| o.into_mut())
172 } 172 }
173 } 173 }
174 174
src/worker.rs +31 −17
@@ -32,6 +32,7 @@ use matrix_sdk::{
32 start::{OriginalSyncKeyVerificationStartEvent, ToDeviceKeyVerificationStartEvent}, 32 start::{OriginalSyncKeyVerificationStartEvent, ToDeviceKeyVerificationStartEvent},
33 VerificationMethod, 33 VerificationMethod,
34 }, 34 },
35 reaction::ReactionEventContent,
35 room::{ 36 room::{
36 message::{MessageType, RoomMessageEventContent}, 37 message::{MessageType, RoomMessageEventContent},
37 name::RoomNameEventContent, 38 name::RoomNameEventContent,
@@ -39,7 +40,6 @@ use matrix_sdk::{
39 }, 40 },
40 tag::Tags, 41 tag::Tags,
41 typing::SyncTypingEvent, 42 typing::SyncTypingEvent,
42 AnyMessageLikeEvent,
43 AnyTimelineEvent, 43 AnyTimelineEvent,
44 SyncMessageLikeEvent, 44 SyncMessageLikeEvent,
45 SyncStateEvent, 45 SyncStateEvent,
@@ -57,7 +57,7 @@ use matrix_sdk::{
57use modalkit::editing::action::{EditInfo, InfoMessage, UIError}; 57use modalkit::editing::action::{EditInfo, InfoMessage, UIError};
58 58
59use crate::{ 59use crate::{
60 base::{AsyncProgramStore, IambError, IambResult, Receipts, VerifyAction}, 60 base::{AsyncProgramStore, EventLocation, IambError, IambResult, Receipts, VerifyAction},
61 message::MessageFetchResult, 61 message::MessageFetchResult,
62 ApplicationSettings, 62 ApplicationSettings,
63}; 63};
@@ -552,6 +552,20 @@ impl ClientWorker {
552 }, 552 },
553 ); 553 );
554 554
555 let _ = self.client.add_event_handler(
556 |ev: SyncMessageLikeEvent<ReactionEventContent>,
557 room: MatrixRoom,
558 store: Ctx<AsyncProgramStore>| {
559 async move {
560 let room_id = room.room_id();
561
562 let mut locked = store.lock().await;
563 let info = locked.application.get_room_info(room_id.to_owned());
564 info.insert_reaction(ev.into_full_event(room_id.to_owned()));
565 }
566 },
567 );
568
555 let _ = self.client.add_event_handler( 569 let _ = self.client.add_event_handler(
556 |ev: OriginalSyncRoomRedactionEvent, 570 |ev: OriginalSyncRoomRedactionEvent,
557 room: MatrixRoom, 571 room: MatrixRoom,
@@ -564,15 +578,21 @@ impl ClientWorker {
564 let mut locked = store.lock().await; 578 let mut locked = store.lock().await;
565 let info = locked.application.get_room_info(room_id.to_owned()); 579 let info = locked.application.get_room_info(room_id.to_owned());
566 580
567 let key = if let Some(k) = info.keys.get(&ev.redacts) { 581 match info.keys.get(&ev.redacts) {
568 k 582 None => return,
569 } else { 583 Some(EventLocation::Message(key)) => {
570 return; 584 if let Some(msg) = info.messages.get_mut(key) {
571 }; 585 let ev = SyncRoomRedactionEvent::Original(ev);
586 msg.event.redact(ev, room_version);
587 }
588 },
589 Some(EventLocation::Reaction(event_id)) => {
590 if let Some(reactions) = info.reactions.get_mut(event_id) {
591 reactions.remove(&ev.redacts);
592 }
572 593
573 if let Some(msg) = info.messages.get_mut(key) { 594 info.keys.remove(&ev.redacts);
574 let ev = SyncRoomRedactionEvent::Original(ev); 595 },
575 msg.event.redact(ev, room_version);
576 } 596 }
577 } 597 }
578 }, 598 },
@@ -891,13 +911,7 @@ impl ClientWorker {
891 911
892 let msgs = chunk.into_iter().filter_map(|ev| { 912 let msgs = chunk.into_iter().filter_map(|ev| {
893 match ev.event.deserialize() { 913 match ev.event.deserialize() {
894 Ok(AnyTimelineEvent::MessageLike(msg)) => { 914 Ok(AnyTimelineEvent::MessageLike(msg)) => Some(msg),
895 if let AnyMessageLikeEvent::RoomMessage(msg) = msg {
896 Some(msg)
897 } else {
898 None
899 }
900 },
901 Ok(AnyTimelineEvent::State(_)) => None, 915 Ok(AnyTimelineEvent::State(_)) => None,
902 Err(_) => None, 916 Err(_) => None,
903 } 917 }