Commit 4f892cd751

4f892cd7519e4b2ebdca97d1b23de6652cd9cdab

parent: dc2516a27e

Unsigned

Damir Jelić <poljar@termina.org.uk> · 2020-10-12 17:06 UTC

room_buffer: Refactor the local echo feature.

This patch also changes the way we print out our own messages if the
local echo is disabled, we print our own messages immediately when we
get a valid response from the server.

Layout: unified · split

src/room_buffer.rs +177 −85
@@ -37,9 +37,9 @@ use matrix_sdk::{
3737 },
3838 AnyMessageEventContent, AnyPossiblyRedactedSyncMessageEvent,
3939 AnyRedactedSyncMessageEvent, AnySyncMessageEvent, AnySyncRoomEvent,
40 AnySyncStateEvent, SyncStateEvent,
40 AnySyncStateEvent, SyncMessageEvent, SyncStateEvent,
4141 },
42 identifiers::{RoomId, UserId},
42 identifiers::{EventId, RoomId, UserId},
4343 locks::{RwLock, RwLockReadGuard},
4444 uuid::Uuid,
4545 Room,
@@ -78,6 +78,28 @@ pub struct RoomBuffer {
7878 buffer_handle: BufferHandle,
7979}
8080
81#[derive(Clone)]
82struct MatrixRoom {
83 homeserver: Rc<Url>,
84 room_id: Rc<RoomId>,
85 own_user_id: Rc<UserId>,
86 room: Arc<RwLock<Room>>,
87
88 config: Rc<RefCell<Config>>,
89 connection: Rc<RefCell<Option<Connection>>>,
90
91 typing_notice_time: Rc<RefCell<Option<Instant>>>,
92 typing_in_flight: Rc<Mutex<()>>,
93
94 outgoing_messages: MessageQueue,
95
96 members: Rc<RefCell<HashMap<UserId, WeechatRoomMember>>>,
97}
98
99pub enum RoomError {
100 NonExistentMember(UserId),
101}
102
81103#[derive(Clone, Debug)]
82104pub struct WeechatRoomMember {
83105 pub user_id: Rc<UserId>,
@@ -88,6 +110,31 @@ pub struct WeechatRoomMember {
88110 pub color: Rc<String>,
89111}
90112
113#[derive(Debug, Clone, Default)]
114pub struct MessageQueue {
115 queue: Rc<RefCell<HashMap<Uuid, (bool, MessageEventContent)>>>,
116}
117
118impl MessageQueue {
119 fn new() -> Self {
120 Self {
121 queue: Rc::new(RefCell::new(HashMap::new())),
122 }
123 }
124
125 fn add(&self, uuid: Uuid, content: MessageEventContent) {
126 self.queue.borrow_mut().insert(uuid, (false, content));
127 }
128
129 fn add_with_echo(&self, uuid: Uuid, content: MessageEventContent) {
130 self.queue.borrow_mut().insert(uuid, (true, content));
131 }
132
133 fn remove(&self, uuid: Uuid) -> Option<(bool, MessageEventContent)> {
134 self.queue.borrow_mut().remove(&uuid)
135 }
136}
137
91138impl WeechatRoomMember {
92139 pub fn new(
93140 user_id: &UserId,
@@ -107,39 +154,15 @@ impl WeechatRoomMember {
107154 }
108155}
109156
110pub enum RoomError {
111 NonExistentMember(UserId),
112}
113
114#[derive(Clone)]
115struct MatrixRoom {
116 homeserver: Rc<Url>,
117 room_id: Rc<RoomId>,
118 own_user_id: Rc<UserId>,
119 room: Arc<RwLock<Room>>,
120
121 config: Rc<RefCell<Config>>,
122 connection: Rc<RefCell<Option<Connection>>>,
123
124 typing_notice_time: Rc<RefCell<Option<Instant>>>,
125 typing_in_flight: Rc<Mutex<()>>,
126
127 local_echo_queue: Rc<RefCell<HashMap<Uuid, MessageEventContent>>>,
128
129 members: Rc<RefCell<HashMap<UserId, WeechatRoomMember>>>,
130}
131
132157#[async_trait(?Send)]
133158impl BufferInputCallbackAsync for MatrixRoom {
134159 async fn callback(&mut self, buffer_handle: BufferHandle, input: String) {
135160 // TODO parse the input here and produce a formatted body.
136 let content = AnyMessageEventContent::RoomMessage(
137 MessageEventContent::Text(TextMessageEventContent {
138 body: input,
139 formatted: None,
140 relates_to: None,
141 }),
142 );
161 let content = MessageEventContent::Text(TextMessageEventContent {
162 body: input,
163 formatted: None,
164 relates_to: None,
165 });
143166
144167 self.send_message(buffer_handle, content).await;
145168 }
@@ -149,20 +172,28 @@ impl MatrixRoom {
149172 pub async fn send_message(
150173 &self,
151174 buffer: BufferHandle,
152 content: AnyMessageEventContent,
175 content: MessageEventContent,
153176 ) {
154177 let uuid = Uuid::new_v4();
155178
156179 if let Some(c) = &*self.connection.borrow() {
157 self.queue_up_local_echo(buffer.clone(), uuid, &content);
158 // TODO check for errors and print them out.
159 match c.send_message(&self.room_id, content, Some(uuid)).await {
160 // TODO the event id is in the response, this needs to end up in
161 // a tag.
162 Ok(_r) => {
163 self.replace_local_echo(buffer, uuid);
180 self.queue_outgoing_message(buffer.clone(), uuid, &content);
181 match c
182 .send_message(
183 &self.room_id,
184 AnyMessageEventContent::RoomMessage(content),
185 Some(uuid),
186 )
187 .await
188 {
189 Ok(r) => {
190 self.handle_outgoing_message(buffer, uuid, &r.event_id);
191 }
192 Err(_e) => {
193 // TODO print out an error, remember to modify the local
194 // echo line if there is one.
195 self.outgoing_messages.remove(uuid);
164196 }
165 Err(_e) => (),
166197 }
167198 } else {
168199 let buffer = buffer
@@ -173,17 +204,16 @@ impl MatrixRoom {
173204 }
174205 }
175206
176 pub fn queue_up_local_echo(
207 // Add the content of the message to our outgoing messag queue and print out
208 // a local echo line if local echo is enabled.
209 pub fn queue_outgoing_message(
177210 &self,
178211 buffer_handle: BufferHandle,
179212 uuid: Uuid,
180 content: &AnyMessageEventContent,
213 content: &MessageEventContent,
181214 ) {
182215 if self.config.borrow().look().local_echo() {
183 if let AnyMessageEventContent::RoomMessage(
184 MessageEventContent::Text(c),
185 ) = content
186 {
216 if let MessageEventContent::Text(c) = content {
187217 let members = self.members.borrow();
188218 let sender =
189219 members.get(&self.own_user_id).unwrap_or_else(|| {
@@ -196,9 +226,12 @@ impl MatrixRoom {
196226 self.print_rendered_event(&b, local_echo)
197227 }
198228
199 let mut echo_queue = self.local_echo_queue.borrow_mut();
200 echo_queue.insert(uuid, MessageEventContent::Text(c.clone()));
229 self.outgoing_messages.add_with_echo(uuid, content.clone());
230 } else {
231 self.outgoing_messages.add(uuid, content.clone());
201232 }
233 } else {
234 self.outgoing_messages.add(uuid, content.clone());
202235 }
203236 }
204237
@@ -215,48 +248,104 @@ impl MatrixRoom {
215248 }
216249 }
217250
218 /// Replace the local echo line with a normal line for the event content
219 /// with the given UUID.
220 ///
221 /// If no content with the given UUID was found in the local echo queue
222 /// false is returned, if the event was successfully found and replaced true
223 /// is returned.
224 pub fn replace_local_echo(
251 /// Replace the local echo of an event with a fully rendered one.
252 fn replace_local_echo(
225253 &self,
226 buffer_handle: BufferHandle,
227254 uuid: Uuid,
228 ) -> bool {
255 buffer: &Buffer,
256 rendered: RenderedEvent,
257 ) {
229258 let uuid_tag = Cow::from(format!("matrix_echo_{}", uuid.to_string()));
230
231259 let line_contains_uuid = |l: &BufferLine| l.tags().contains(&uuid_tag);
232260
233 if let Some(content) = self.local_echo_queue.borrow_mut().remove(&uuid)
234 {
235 let content = match content {
236 MessageEventContent::Text(c) => c.render(&()),
237 // TODO support more message types.
238 _ => return false,
261 let mut lines = buffer.lines();
262 let mut first_line = lines.rfind(line_contains_uuid);
263 let mut line_num = 0;
264
265 while let Some(line) = &first_line {
266 let rendered_line = &rendered.content.lines[line_num];
267
268 line.set_message(&rendered_line.message);
269
270 line_num += 1;
271 first_line = lines.next_back().filter(line_contains_uuid);
272 }
273 }
274
275 fn handle_outgoing_message(
276 &self,
277 buffer_handle: BufferHandle,
278 uuid: Uuid,
279 event_id: &EventId,
280 ) {
281 if let Some((echo, content)) = self.outgoing_messages.remove(uuid) {
282 let event = SyncMessageEvent {
283 sender: (&*self.own_user_id).clone(),
284 origin_server_ts: std::time::SystemTime::now(),
285 event_id: event_id.clone(),
286 content,
287 unsigned: Default::default(),
239288 };
240289
290 let event = AnySyncMessageEvent::RoomMessage(event);
291
292 let rendered = self
293 .render_message_event(&event)
294 .expect("Sent out an event that we don't know how to render");
295
241296 if let Ok(buffer) = buffer_handle.upgrade() {
242 let mut lines = buffer.lines();
243 let mut first_line = lines.rfind(line_contains_uuid);
244 let mut line_num = 0;
297 if echo {
298 self.replace_local_echo(uuid, &buffer, rendered);
299 } else {
300 self.print_rendered_event(&buffer, rendered);
301 }
302 }
303 }
304 }
245305
246 while let Some(line) = &first_line {
247 let rendered_line = &content.lines[line_num];
306 fn render_message_event(
307 &self,
308 event: &AnySyncMessageEvent,
309 ) -> Option<RenderedEvent> {
310 use AnyMessageEventContent::*;
311 use MessageEventContent::*;
248312
249 line.set_message(&rendered_line.message);
313 let members = self.members.borrow();
250314
251 line_num += 1;
252 first_line = lines.next_back().filter(line_contains_uuid);
315 // TODO remove this expect.
316 let sender = members
317 .get(event.sender())
318 .expect("Rendering a message but the sender isn't in the nicklist");
319
320 let send_time = event.origin_server_ts();
321
322 let rendered = match event.content() {
323 RoomEncrypted(c) => c.render_with_prefix(send_time, sender, &()),
324 RoomMessage(c) => match c {
325 Text(c) => c.render_with_prefix(send_time, sender, &()),
326 Emote(c) => c.render_with_prefix(send_time, sender, sender),
327 Notice(c) => c.render_with_prefix(send_time, sender, sender),
328 ServerNotice(c) => {
329 c.render_with_prefix(send_time, sender, sender)
253330 }
254 }
331 Location(c) => c.render_with_prefix(send_time, sender, sender),
332 Audio(c) => {
333 c.render_with_prefix(send_time, sender, &self.homeserver)
334 }
335 Video(c) => {
336 c.render_with_prefix(send_time, sender, &self.homeserver)
337 }
338 File(c) => {
339 c.render_with_prefix(send_time, sender, &self.homeserver)
340 }
341 Image(c) => {
342 c.render_with_prefix(send_time, sender, &self.homeserver)
343 }
344 },
345 _ => return None,
346 };
255347
256 true
257 } else {
258 false
259 }
348 Some(rendered)
260349 }
261350}
262351
@@ -279,7 +368,7 @@ impl RoomBuffer {
279368 room,
280369 own_user_id: Rc::new(own_user_id.to_owned()),
281370 members: Rc::new(RefCell::new(HashMap::new())),
282 local_echo_queue: Rc::new(RefCell::new(HashMap::new())),
371 outgoing_messages: MessageQueue::new(),
283372 };
284373
285374 let buffer_handle = BufferBuilderAsync::new(&room_id.to_string())
@@ -402,7 +491,7 @@ impl RoomBuffer {
402491 ///
403492 /// buffer.send_message(content).await
404493 /// ```
405 pub async fn send_message(&self, content: AnyMessageEventContent) {
494 pub async fn send_message(&self, content: MessageEventContent) {
406495 let buffer = self.buffer_handle.clone();
407496 self.inner.send_message(buffer, content).await
408497 }
@@ -883,14 +972,17 @@ impl RoomBuffer {
883972 }
884973
885974 pub fn handle_room_message(&self, event: &AnySyncMessageEvent) {
975 // If the event has a transaction id it's an event that we sent out
976 // ourselves, the content will be in the outgoing message queue and it
977 // may have been printed out as a local echo.
886978 if let Some(id) = &event.unsigned().transaction_id {
887979 if let Ok(id) = Uuid::parse_str(id) {
888 if self
889 .inner
890 .replace_local_echo(self.buffer_handle.clone(), id)
891 {
892 return;
893 }
980 self.inner.handle_outgoing_message(
981 self.buffer_handle.clone(),
982 id,
983 event.event_id(),
984 );
985 return;
894986 }
895987 }
896988