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