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::{
37 }, 37 },
38 AnyMessageEventContent, AnyPossiblyRedactedSyncMessageEvent, 38 AnyMessageEventContent, AnyPossiblyRedactedSyncMessageEvent,
39 AnyRedactedSyncMessageEvent, AnySyncMessageEvent, AnySyncRoomEvent, 39 AnyRedactedSyncMessageEvent, AnySyncMessageEvent, AnySyncRoomEvent,
40 AnySyncStateEvent, SyncStateEvent, 40 AnySyncStateEvent, SyncMessageEvent, SyncStateEvent,
41 }, 41 },
42 identifiers::{RoomId, UserId}, 42 identifiers::{EventId, RoomId, UserId},
43 locks::{RwLock, RwLockReadGuard}, 43 locks::{RwLock, RwLockReadGuard},
44 uuid::Uuid, 44 uuid::Uuid,
45 Room, 45 Room,
@@ -78,6 +78,28 @@ pub struct RoomBuffer {
78 buffer_handle: BufferHandle, 78 buffer_handle: BufferHandle,
79} 79}
80 80
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
81#[derive(Clone, Debug)] 103#[derive(Clone, Debug)]
82pub struct WeechatRoomMember { 104pub struct WeechatRoomMember {
83 pub user_id: Rc<UserId>, 105 pub user_id: Rc<UserId>,
@@ -88,6 +110,31 @@ pub struct WeechatRoomMember {
88 pub color: Rc<String>, 110 pub color: Rc<String>,
89} 111}
90 112
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
91impl WeechatRoomMember { 138impl WeechatRoomMember {
92 pub fn new( 139 pub fn new(
93 user_id: &UserId, 140 user_id: &UserId,
@@ -107,39 +154,15 @@ impl WeechatRoomMember {
107 } 154 }
108} 155}
109 156
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
132#[async_trait(?Send)] 157#[async_trait(?Send)]
133impl BufferInputCallbackAsync for MatrixRoom { 158impl BufferInputCallbackAsync for MatrixRoom {
134 async fn callback(&mut self, buffer_handle: BufferHandle, input: String) { 159 async fn callback(&mut self, buffer_handle: BufferHandle, input: String) {
135 // TODO parse the input here and produce a formatted body. 160 // TODO parse the input here and produce a formatted body.
136 let content = AnyMessageEventContent::RoomMessage( 161 let content = MessageEventContent::Text(TextMessageEventContent {
137 MessageEventContent::Text(TextMessageEventContent { 162 body: input,
138 body: input, 163 formatted: None,
139 formatted: None, 164 relates_to: None,
140 relates_to: None, 165 });
141 }),
142 );
143 166
144 self.send_message(buffer_handle, content).await; 167 self.send_message(buffer_handle, content).await;
145 } 168 }
@@ -149,20 +172,28 @@ impl MatrixRoom {
149 pub async fn send_message( 172 pub async fn send_message(
150 &self, 173 &self,
151 buffer: BufferHandle, 174 buffer: BufferHandle,
152 content: AnyMessageEventContent, 175 content: MessageEventContent,
153 ) { 176 ) {
154 let uuid = Uuid::new_v4(); 177 let uuid = Uuid::new_v4();
155 178
156 if let Some(c) = &*self.connection.borrow() { 179 if let Some(c) = &*self.connection.borrow() {
157 self.queue_up_local_echo(buffer.clone(), uuid, &content); 180 self.queue_outgoing_message(buffer.clone(), uuid, &content);
158 // TODO check for errors and print them out. 181 match c
159 match c.send_message(&self.room_id, content, Some(uuid)).await { 182 .send_message(
160 // TODO the event id is in the response, this needs to end up in 183 &self.room_id,
161 // a tag. 184 AnyMessageEventContent::RoomMessage(content),
162 Ok(_r) => { 185 Some(uuid),
163 self.replace_local_echo(buffer, 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);
164 } 196 }
165 Err(_e) => (),
166 } 197 }
167 } else { 198 } else {
168 let buffer = buffer 199 let buffer = buffer
@@ -173,17 +204,16 @@ impl MatrixRoom {
173 } 204 }
174 } 205 }
175 206
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(
177 &self, 210 &self,
178 buffer_handle: BufferHandle, 211 buffer_handle: BufferHandle,
179 uuid: Uuid, 212 uuid: Uuid,
180 content: &AnyMessageEventContent, 213 content: &MessageEventContent,
181 ) { 214 ) {
182 if self.config.borrow().look().local_echo() { 215 if self.config.borrow().look().local_echo() {
183 if let AnyMessageEventContent::RoomMessage( 216 if let MessageEventContent::Text(c) = content {
184 MessageEventContent::Text(c),
185 ) = content
186 {
187 let members = self.members.borrow(); 217 let members = self.members.borrow();
188 let sender = 218 let sender =
189 members.get(&self.own_user_id).unwrap_or_else(|| { 219 members.get(&self.own_user_id).unwrap_or_else(|| {
@@ -196,9 +226,12 @@ impl MatrixRoom {
196 self.print_rendered_event(&b, local_echo) 226 self.print_rendered_event(&b, local_echo)
197 } 227 }
198 228
199 let mut echo_queue = self.local_echo_queue.borrow_mut(); 229 self.outgoing_messages.add_with_echo(uuid, content.clone());
200 echo_queue.insert(uuid, MessageEventContent::Text(c.clone())); 230 } else {
231 self.outgoing_messages.add(uuid, content.clone());
201 } 232 }
233 } else {
234 self.outgoing_messages.add(uuid, content.clone());
202 } 235 }
203 } 236 }
204 237
@@ -215,48 +248,104 @@ impl MatrixRoom {
215 } 248 }
216 } 249 }
217 250
218 /// Replace the local echo line with a normal line for the event content 251 /// Replace the local echo of an event with a fully rendered one.
219 /// with the given UUID. 252 fn replace_local_echo(
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(
225 &self, 253 &self,
226 buffer_handle: BufferHandle,
227 uuid: Uuid, 254 uuid: Uuid,
228 ) -> bool { 255 buffer: &Buffer,
256 rendered: RenderedEvent,
257 ) {
229 let uuid_tag = Cow::from(format!("matrix_echo_{}", uuid.to_string())); 258 let uuid_tag = Cow::from(format!("matrix_echo_{}", uuid.to_string()));
230
231 let line_contains_uuid = |l: &BufferLine| l.tags().contains(&uuid_tag); 259 let line_contains_uuid = |l: &BufferLine| l.tags().contains(&uuid_tag);
232 260
233 if let Some(content) = self.local_echo_queue.borrow_mut().remove(&uuid) 261 let mut lines = buffer.lines();
234 { 262 let mut first_line = lines.rfind(line_contains_uuid);
235 let content = match content { 263 let mut line_num = 0;
236 MessageEventContent::Text(c) => c.render(&()), 264
237 // TODO support more message types. 265 while let Some(line) = &first_line {
238 _ => return false, 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(),
239 }; 288 };
240 289
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
241 if let Ok(buffer) = buffer_handle.upgrade() { 296 if let Ok(buffer) = buffer_handle.upgrade() {
242 let mut lines = buffer.lines(); 297 if echo {
243 let mut first_line = lines.rfind(line_contains_uuid); 298 self.replace_local_echo(uuid, &buffer, rendered);
244 let mut line_num = 0; 299 } else {
300 self.print_rendered_event(&buffer, rendered);
301 }
302 }
303 }
304 }
245 305
246 while let Some(line) = &first_line { 306 fn render_message_event(
247 let rendered_line = &content.lines[line_num]; 307 &self,
308 event: &AnySyncMessageEvent,
309 ) -> Option<RenderedEvent> {
310 use AnyMessageEventContent::*;
311 use MessageEventContent::*;
248 312
249 line.set_message(&rendered_line.message); 313 let members = self.members.borrow();
250 314
251 line_num += 1; 315 // TODO remove this expect.
252 first_line = lines.next_back().filter(line_contains_uuid); 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)
253 } 330 }
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 };
255 347
256 true 348 Some(rendered)
257 } else {
258 false
259 }
260 } 349 }
261} 350}
262 351
@@ -279,7 +368,7 @@ impl RoomBuffer {
279 room, 368 room,
280 own_user_id: Rc::new(own_user_id.to_owned()), 369 own_user_id: Rc::new(own_user_id.to_owned()),
281 members: Rc::new(RefCell::new(HashMap::new())), 370 members: Rc::new(RefCell::new(HashMap::new())),
282 local_echo_queue: Rc::new(RefCell::new(HashMap::new())), 371 outgoing_messages: MessageQueue::new(),
283 }; 372 };
284 373
285 let buffer_handle = BufferBuilderAsync::new(&room_id.to_string()) 374 let buffer_handle = BufferBuilderAsync::new(&room_id.to_string())
@@ -402,7 +491,7 @@ impl RoomBuffer {
402 /// 491 ///
403 /// buffer.send_message(content).await 492 /// buffer.send_message(content).await
404 /// ``` 493 /// ```
405 pub async fn send_message(&self, content: AnyMessageEventContent) { 494 pub async fn send_message(&self, content: MessageEventContent) {
406 let buffer = self.buffer_handle.clone(); 495 let buffer = self.buffer_handle.clone();
407 self.inner.send_message(buffer, content).await 496 self.inner.send_message(buffer, content).await
408 } 497 }
@@ -883,14 +972,17 @@ impl RoomBuffer {
883 } 972 }
884 973
885 pub fn handle_room_message(&self, event: &AnySyncMessageEvent) { 974 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.
886 if let Some(id) = &event.unsigned().transaction_id { 978 if let Some(id) = &event.unsigned().transaction_id {
887 if let Ok(id) = Uuid::parse_str(id) { 979 if let Ok(id) = Uuid::parse_str(id) {
888 if self 980 self.inner.handle_outgoing_message(
889 .inner 981 self.buffer_handle.clone(),
890 .replace_local_echo(self.buffer_handle.clone(), id) 982 id,
891 { 983 event.event_id(),
892 return; 984 );
893 } 985 return;
894 } 986 }
895 } 987 }
896 988