src/room/mod.rs
642 lines · 20867 bytes
1//! Room buffer module.
2//!
3//! This module implements creates buffers that processes and prints out all the
4//! user visible events
5//!
6//! Care should be taken when handling events. Events can be state events or
7//! timeline events and they can come from a sync response or from a room
8//! messages response.
9//!
10//! Events coming from a sync response and are part of the timeline need to be
11//! printed out and they need to change the buffer state (e.g. when someone
12//! joins, they need to be added to the nicklist).
13//!
14//! Events coming from a sync response and are part of the room state only need
15//! to change the buffer state.
16//!
17//! Events coming from a room messages response, meaning they are old events,
18//! should never change the room state. They only should be printed out.
19//!
20//! Care should be taken to model this in a way that event formatting methods
21//! are pure functions so they can be reused e.g. if we print messages that
22//! we're sending ourselves before we receive them in a sync response, or if we
23//! decrypt a previously undecryptable event.
24
25mod members;
26
27use members::Members;
28pub use members::WeechatRoomMember;
29
30pub const BUFFER_CLOSED_ERROR: &str =
31 "Buffer got closed but Room is still lingering around";
32
33use std::{
34 borrow::Cow,
35 cell::RefCell,
36 collections::HashMap,
37 ops::Deref,
38 rc::Rc,
39 sync::{Arc, Mutex},
40 time::Instant,
41};
42
43use async_trait::async_trait;
44use futures::executor::block_on;
45use tracing::{debug, trace};
46use url::Url;
47
48use matrix_sdk::{
49 events::{
50 room::message::{MessageEventContent, TextMessageEventContent},
51 AnyMessageEventContent, AnyPossiblyRedactedSyncMessageEvent,
52 AnyRedactedSyncMessageEvent, AnySyncMessageEvent, AnySyncRoomEvent,
53 AnySyncStateEvent, SyncMessageEvent,
54 },
55 identifiers::{EventId, RoomId, UserId},
56 locks::{RwLock, RwLockReadGuard},
57 uuid::Uuid,
58 Room,
59};
60
61use weechat::{
62 buffer::{
63 Buffer, BufferBuilderAsync, BufferHandle, BufferInputCallbackAsync,
64 BufferLine,
65 },
66 Weechat,
67};
68
69use crate::{
70 config::Config,
71 connection::{Connection, TYPING_NOTICE_TIMEOUT},
72 render::{Render, RenderedEvent},
73};
74
75#[derive(Clone)]
76pub struct RoomBuffer {
77 inner: MatrixRoom,
78 buffer_handle: BufferHandle,
79}
80
81impl Deref for RoomBuffer {
82 type Target = MatrixRoom;
83
84 fn deref(&self) -> &Self::Target {
85 &self.inner
86 }
87}
88
89#[derive(Clone)]
90pub struct MatrixRoom {
91 homeserver: Rc<Url>,
92 room_id: Rc<RoomId>,
93 own_user_id: Rc<UserId>,
94 room: Arc<RwLock<Room>>,
95
96 config: Rc<RefCell<Config>>,
97 connection: Rc<RefCell<Option<Connection>>>,
98
99 typing_notice_time: Rc<RefCell<Option<Instant>>>,
100 typing_in_flight: Rc<Mutex<()>>,
101
102 outgoing_messages: MessageQueue,
103
104 members: Members,
105}
106
107#[derive(Debug, Clone, Default)]
108pub struct MessageQueue {
109 queue: Rc<RefCell<HashMap<Uuid, (bool, MessageEventContent)>>>,
110}
111
112impl MessageQueue {
113 fn new() -> Self {
114 Self {
115 queue: Rc::new(RefCell::new(HashMap::new())),
116 }
117 }
118
119 fn add(&self, uuid: Uuid, content: MessageEventContent) {
120 self.queue.borrow_mut().insert(uuid, (false, content));
121 }
122
123 fn add_with_echo(&self, uuid: Uuid, content: MessageEventContent) {
124 self.queue.borrow_mut().insert(uuid, (true, content));
125 }
126
127 fn remove(&self, uuid: Uuid) -> Option<(bool, MessageEventContent)> {
128 self.queue.borrow_mut().remove(&uuid)
129 }
130}
131
132#[async_trait(?Send)]
133impl BufferInputCallbackAsync for MatrixRoom {
134 async fn callback(&mut self, buffer_handle: BufferHandle, input: String) {
135 // TODO parse the input here and produce a formatted body.
136 let content = MessageEventContent::Text(TextMessageEventContent {
137 body: input,
138 formatted: None,
139 relates_to: None,
140 });
141
142 self.send_message(buffer_handle, content).await;
143 }
144}
145
146impl MatrixRoom {
147 pub async fn send_message(
148 &self,
149 buffer: BufferHandle,
150 content: MessageEventContent,
151 ) {
152 let uuid = Uuid::new_v4();
153
154 if let Some(c) = &*self.connection.borrow() {
155 self.queue_outgoing_message(buffer.clone(), uuid, &content);
156 match c
157 .send_message(
158 &self.room_id,
159 AnyMessageEventContent::RoomMessage(content),
160 Some(uuid),
161 )
162 .await
163 {
164 Ok(r) => {
165 self.handle_outgoing_message(buffer, uuid, &r.event_id);
166 }
167 Err(_e) => {
168 // TODO print out an error, remember to modify the local
169 // echo line if there is one.
170 self.outgoing_messages.remove(uuid);
171 }
172 }
173 } else {
174 let buffer = buffer
175 .upgrade()
176 .expect("Trying to send a message while the buffer is closed");
177
178 buffer.print("Error not connected");
179 }
180 }
181
182 // Add the content of the message to our outgoing messag queue and print out
183 // a local echo line if local echo is enabled.
184 pub fn queue_outgoing_message(
185 &self,
186 buffer_handle: BufferHandle,
187 uuid: Uuid,
188 content: &MessageEventContent,
189 ) {
190 if self.config.borrow().look().local_echo() {
191 if let MessageEventContent::Text(c) = content {
192 let sender =
193 self.members.get(&self.own_user_id).unwrap_or_else(|| {
194 panic!("No own member {}", self.own_user_id)
195 });
196
197 if let Ok(b) = buffer_handle.upgrade() {
198 let local_echo =
199 c.render_with_prefix_for_echo(&sender, uuid, &());
200 self.print_rendered_event(&b, local_echo)
201 }
202
203 self.outgoing_messages.add_with_echo(uuid, content.clone());
204 } else {
205 self.outgoing_messages.add(uuid, content.clone());
206 }
207 } else {
208 self.outgoing_messages.add(uuid, content.clone());
209 }
210 }
211
212 pub fn print_rendered_event(
213 &self,
214 buffer: &Buffer,
215 rendered: RenderedEvent,
216 ) {
217 for line in rendered.content.lines {
218 let message = format!("{}\t{}", &rendered.prefix, &line.message);
219 let tags: Vec<&str> =
220 line.tags.iter().map(|t| t.as_str()).collect();
221 buffer.print_date_tags(0, &tags, &message)
222 }
223 }
224
225 /// Replace the local echo of an event with a fully rendered one.
226 fn replace_local_echo(
227 &self,
228 uuid: Uuid,
229 buffer: &Buffer,
230 rendered: RenderedEvent,
231 ) {
232 let uuid_tag = Cow::from(format!("matrix_echo_{}", uuid.to_string()));
233 let line_contains_uuid = |l: &BufferLine| l.tags().contains(&uuid_tag);
234
235 let mut lines = buffer.lines();
236 let mut first_line = lines.rfind(line_contains_uuid);
237 let mut line_num = 0;
238
239 while let Some(line) = &first_line {
240 let rendered_line = &rendered.content.lines[line_num];
241
242 line.set_message(&rendered_line.message);
243
244 line_num += 1;
245 first_line = lines.next_back().filter(line_contains_uuid);
246 }
247 }
248
249 fn handle_outgoing_message(
250 &self,
251 buffer_handle: BufferHandle,
252 uuid: Uuid,
253 event_id: &EventId,
254 ) {
255 if let Some((echo, content)) = self.outgoing_messages.remove(uuid) {
256 let event = SyncMessageEvent {
257 sender: (&*self.own_user_id).clone(),
258 origin_server_ts: std::time::SystemTime::now(),
259 event_id: event_id.clone(),
260 content,
261 unsigned: Default::default(),
262 };
263
264 let event = AnySyncMessageEvent::RoomMessage(event);
265
266 let rendered = self
267 .render_message_event(&event)
268 .expect("Sent out an event that we don't know how to render");
269
270 if let Ok(buffer) = buffer_handle.upgrade() {
271 if echo {
272 self.replace_local_echo(uuid, &buffer, rendered);
273 } else {
274 self.print_rendered_event(&buffer, rendered);
275 }
276 }
277 }
278 }
279
280 pub fn room(&self) -> RwLockReadGuard<'_, Room> {
281 block_on(self.room.read())
282 }
283
284 pub fn room_id(&self) -> &RoomId {
285 &self.room_id
286 }
287
288 fn render_message_event(
289 &self,
290 event: &AnySyncMessageEvent,
291 ) -> Option<RenderedEvent> {
292 use AnyMessageEventContent::*;
293 use MessageEventContent::*;
294
295 // TODO remove this expect.
296 let sender = self
297 .members
298 .get(event.sender())
299 .expect("Rendering a message but the sender isn't in the nicklist");
300
301 let send_time = event.origin_server_ts();
302
303 let rendered = match event.content() {
304 RoomEncrypted(c) => c.render_with_prefix(send_time, &sender, &()),
305 RoomMessage(c) => match c {
306 Text(c) => c.render_with_prefix(send_time, &sender, &()),
307 Emote(c) => c.render_with_prefix(send_time, &sender, &sender),
308 Notice(c) => c.render_with_prefix(send_time, &sender, &sender),
309 ServerNotice(c) => {
310 c.render_with_prefix(send_time, &sender, &sender)
311 }
312 Location(c) => {
313 c.render_with_prefix(send_time, &sender, &sender)
314 }
315 Audio(c) => {
316 c.render_with_prefix(send_time, &sender, &self.homeserver)
317 }
318 Video(c) => {
319 c.render_with_prefix(send_time, &sender, &self.homeserver)
320 }
321 File(c) => {
322 c.render_with_prefix(send_time, &sender, &self.homeserver)
323 }
324 Image(c) => {
325 c.render_with_prefix(send_time, &sender, &self.homeserver)
326 }
327 },
328 _ => return None,
329 };
330
331 Some(rendered)
332 }
333}
334
335impl RoomBuffer {
336 pub fn new(
337 connection: &Rc<RefCell<Option<Connection>>>,
338 config: Rc<RefCell<Config>>,
339 room: Arc<RwLock<Room>>,
340 homeserver: &Url,
341 room_id: RoomId,
342 own_user_id: &UserId,
343 ) -> Self {
344 let members = Members::new(room.clone());
345 let mut room = MatrixRoom {
346 homeserver: Rc::new(homeserver.clone()),
347 room_id: Rc::new(room_id.clone()),
348 connection: connection.clone(),
349 typing_notice_time: Rc::new(RefCell::new(None)),
350 typing_in_flight: Rc::new(Mutex::new(())),
351 config,
352 room,
353 own_user_id: Rc::new(own_user_id.to_owned()),
354 members: members.clone(),
355 outgoing_messages: MessageQueue::new(),
356 };
357
358 let buffer_handle = BufferBuilderAsync::new(&room_id.to_string())
359 .input_callback(room.clone())
360 .close_callback(|_weechat: &Weechat, _buffer: &Buffer| {
361 // TODO remove the roombuffer from the server here.
362 // TODO leave the room if the plugin isn't unloading.
363 Ok(())
364 })
365 .build()
366 .expect("Can't create new room buffer");
367
368 let buffer = buffer_handle
369 .upgrade()
370 .expect("Can't upgrade newly created buffer");
371
372 buffer.enable_nicklist();
373
374 // This is fine since we're only given the room to the buffer input and
375 // the callback can only run once we yield controll back to Weechat.
376 unsafe {
377 *Rc::get_mut_unchecked(&mut room.members.buffer) =
378 Some(buffer_handle.clone());
379 }
380
381 RoomBuffer {
382 inner: room,
383 buffer_handle,
384 }
385 }
386
387 pub fn restore(
388 room: Arc<RwLock<Room>>,
389 connection: &Rc<RefCell<Option<Connection>>>,
390 config: Rc<RefCell<Config>>,
391 homeserver: &Url,
392 ) -> Self {
393 let room_clone = room.clone();
394 let room_lock = block_on(room.read());
395 let room_id = room_lock.room_id.to_owned();
396 let own_user_id = &room_lock.own_user_id;
397
398 let room_buffer = RoomBuffer::new(
399 connection,
400 config,
401 room_clone,
402 homeserver,
403 room_id,
404 own_user_id,
405 );
406
407 debug!("Restoring room {}", room_lock.room_id);
408
409 let matrix_members = room_lock
410 .joined_members
411 .values()
412 .chain(room_lock.invited_members.values());
413
414 for member in matrix_members {
415 let display_name = room_lock
416 .get_member(&member.user_id)
417 .unwrap()
418 .display_name
419 .clone();
420
421 trace!("Restoring member {}", member.user_id);
422 let member = WeechatRoomMember::new(
423 &member.user_id,
424 member.disambiguated_name(),
425 display_name,
426 );
427
428 room_buffer.members.add(member);
429 }
430
431 room_buffer.update_buffer_name();
432 room_buffer.restore_messages();
433
434 room_buffer
435 }
436
437 pub fn restore_messages(&self) {
438 use AnyPossiblyRedactedSyncMessageEvent::*;
439
440 let room = self.room();
441 let buffer = self.weechat_buffer();
442
443 if buffer.num_lines() == 0 {
444 for event in room.messages.iter() {
445 match event {
446 Regular(e) => self.handle_room_message(e),
447 Redacted(e) => self.handle_redacted_events(e),
448 }
449 }
450 }
451 }
452
453 /// Send the given content to the server.
454 ///
455 /// # Arguments
456 ///
457 /// * `content` - The content that should be sent to the server.
458 ///
459 /// # Examples
460 ///
461 /// ```
462 /// let content = MessageEventContent::Text(TextMessageEventContent {
463 /// body: "Hello world".to_owned(),
464 /// formatted: None,
465 /// relates_to: None,
466 /// });
467 /// let content = AnyMessageEventContent::RoomMessage(content);
468 ///
469 /// buffer.send_message(content).await
470 /// ```
471 pub async fn send_message(&self, content: MessageEventContent) {
472 let buffer = self.buffer_handle.clone();
473 self.inner.send_message(buffer, content).await
474 }
475
476 pub fn weechat_buffer(&self) -> Buffer {
477 self.buffer_handle.upgrade().expect(BUFFER_CLOSED_ERROR)
478 }
479
480 pub fn update_buffer_name(&self) {
481 let name = self.members.calculate_buffer_name();
482 self.weechat_buffer().set_name(&name)
483 }
484
485 /// Send out a typing notice.
486 ///
487 /// This will send out a typing notice or reset the one in progress, if
488 /// needed. It will make sure that only one typing notice request is in
489 /// flight at a time.
490 ///
491 /// Typing notices are sent out only if we have more than 4 letters in the
492 /// input and the input isn't a command.
493 ///
494 /// If the input is empty the typing notice is disabled.
495 pub fn update_typing_notice(&self) {
496 let typing_in_flight = self.inner.typing_in_flight.clone();
497 let buffer = self.weechat_buffer();
498 let input = buffer.input();
499
500 if input.starts_with('/') && !input.starts_with("//") {
501 // Don't send typing notices for commands.
502 return;
503 }
504
505 let connection = self.inner.connection.clone();
506 let room_id = self.inner.room_id.clone();
507 let typing_notice_time = self.inner.typing_notice_time.clone();
508
509 let send = async move |typing: bool| {
510 let typing_time = typing_notice_time;
511
512 // We're in the process of sending out a typing notice, so don't
513 // make the same request twice.
514 let guard = match typing_in_flight.try_lock() {
515 Ok(guard) => guard,
516 Err(_) => {
517 return;
518 }
519 };
520
521 if let Some(connection) = &*connection.borrow() {
522 let response =
523 connection.send_typing_notice(&*room_id, typing).await;
524
525 // We need to record the time when the last typing notice was
526 // sent to ensure we don't send out new ones while a previous
527 // one is active. If we cancelled the last notice (`!typing`),
528 // we record that there is currently no active notice.
529 //
530 // An unsuccessful response indicates the send operation failed.
531 // In this case we need to retry, so we don't update anything.
532
533 if response.is_ok() {
534 if typing {
535 *typing_time.borrow_mut() = Some(Instant::now());
536 } else {
537 *typing_time.borrow_mut() = None;
538 }
539 }
540 };
541
542 drop(guard)
543 };
544
545 let typing_time = self.inner.typing_notice_time.borrow_mut();
546
547 if input.len() < 4 && typing_time.is_some() {
548 // If we have an active typing notice and our input is short, e.g.
549 // we removed the input set the typing notice to false.
550 Weechat::spawn(send(false)).detach();
551 } else if input.len() >= 4 {
552 if let Some(typing_time) = &*typing_time {
553 // If we have some valid input, check if the typing notice
554 // expired and send one out if it indeed expired.
555 if typing_time.elapsed() > TYPING_NOTICE_TIMEOUT {
556 Weechat::spawn(send(true)).detach();
557 }
558 } else {
559 // If we have some valid input and no active typing notice, send
560 // one out.
561 Weechat::spawn(send(true)).detach();
562 }
563 }
564 }
565
566 pub fn handle_room_message(&self, event: &AnySyncMessageEvent) {
567 // If the event has a transaction id it's an event that we sent out
568 // ourselves, the content will be in the outgoing message queue and it
569 // may have been printed out as a local echo.
570 if let Some(id) = &event.unsigned().transaction_id {
571 if let Ok(id) = Uuid::parse_str(id) {
572 self.handle_outgoing_message(
573 self.buffer_handle.clone(),
574 id,
575 event.event_id(),
576 );
577 return;
578 }
579 }
580
581 if let Some(rendered) = self.render_message_event(event) {
582 self.print_rendered_event(rendered);
583 }
584 }
585
586 fn print_rendered_event(&self, rendered: RenderedEvent) {
587 let buffer = self.weechat_buffer();
588 self.inner.print_rendered_event(&buffer, rendered);
589 }
590
591 fn handle_redacted_events(&self, event: &AnyRedactedSyncMessageEvent) {
592 use AnyRedactedSyncMessageEvent::*;
593
594 if let RoomMessage(e) = event {
595 // TODO remove those expects and unwraps.
596 let redacter =
597 &e.unsigned.redacted_because.as_ref().unwrap().sender;
598 let redacter = self.members.get(redacter).expect(
599 "Rendering a message but the sender isn't in the nicklist",
600 );
601 let sender = self.members.get(&e.sender).expect(
602 "Rendering a message but the sender isn't in the nicklist",
603 );
604 let rendered =
605 e.render_with_prefix(&e.origin_server_ts, &sender, &redacter);
606
607 self.print_rendered_event(rendered);
608 }
609 }
610
611 pub fn handle_sync_room_event(&mut self, event: AnySyncRoomEvent) {
612 match &event {
613 AnySyncRoomEvent::Message(message) => {
614 self.handle_room_message(message)
615 }
616
617 AnySyncRoomEvent::RedactedMessage(e) => {
618 self.handle_redacted_events(e)
619 }
620 // We don't print out redacted state event for now.
621 AnySyncRoomEvent::RedactedState(_) => (),
622
623 AnySyncRoomEvent::State(event) => match event {
624 AnySyncStateEvent::RoomMember(e) => {
625 self.members.handle_membership_event(e, false)
626 }
627 AnySyncStateEvent::RoomName(_) => self.update_buffer_name(),
628 _ => (),
629 },
630 }
631 }
632
633 pub fn handle_sync_state_event(&mut self, event: AnySyncStateEvent) {
634 match &event {
635 AnySyncStateEvent::RoomMember(e) => {
636 self.members.handle_membership_event(e, true)
637 }
638 AnySyncStateEvent::RoomName(_) => self.update_buffer_name(),
639 _ => (),
640 }
641 }
642}