Commit 71cb0107c2
Unregistered key
Layout: unified · split
src/base.rs +53 −13
| @@ -16,6 +16,7 @@ use emojis::Emoji; | |||
| 16 | use matrix_sdk::ruma::events::receipt::ReceiptThread; | 16 | use matrix_sdk::ruma::events::receipt::ReceiptThread; |
| 17 | use matrix_sdk::ruma::events::room::MediaSource; | 17 | use matrix_sdk::ruma::events::room::MediaSource; |
| 18 | use matrix_sdk::ruma::events::sticker::StickerEvent; | 18 | use matrix_sdk::ruma::events::sticker::StickerEvent; |
| 19 | use matrix_sdk::ruma::OwnedTransactionId; | ||
| 19 | use ratatui::{ | 20 | use ratatui::{ |
| 20 | buffer::Buffer, | 21 | buffer::Buffer, |
| 21 | layout::{Alignment, Rect}, | 22 | layout::{Alignment, Rect}, |
| @@ -733,6 +734,10 @@ pub enum IambError { | |||
| 733 | #[error("Matrix client error: {0}")] | 734 | #[error("Matrix client error: {0}")] |
| 734 | Matrix(#[from] matrix_sdk::Error), | 735 | Matrix(#[from] matrix_sdk::Error), |
| 735 | 736 | ||
| 737 | /// A failure when sending a message. | ||
| 738 | #[error("Send queue error: {0}")] | ||
| 739 | SendQueue(#[from] matrix_sdk::send_queue::RoomSendQueueError), | ||
| 740 | |||
| 736 | /// A failure in the sled storage. | 741 | /// A failure in the sled storage. |
| 737 | #[error("Matrix client storage error: {0}")] | 742 | #[error("Matrix client storage error: {0}")] |
| 738 | Store(#[from] matrix_sdk::StoreError), | 743 | Store(#[from] matrix_sdk::StoreError), |
| @@ -867,6 +872,19 @@ impl EventLocation { | |||
| 867 | } | 872 | } |
| 868 | } | 873 | } |
| 869 | 874 | ||
| 875 | /// Indicates where a local echo lives in the [`ChatStore`]. | ||
| 876 | #[derive(Debug, Clone)] | ||
| 877 | pub enum EchoLocation { | ||
| 878 | /// The [`OwnedTransactionId`] belongs to a message. | ||
| 879 | /// | ||
| 880 | /// If the first argument is [`None`], then it's part of the main scrollback. When [`Some`], it | ||
| 881 | /// specifies which thread it's in reply to. | ||
| 882 | Message(Option<OwnedEventId>, MessageKey), | ||
| 883 | |||
| 884 | /// The local echo has been replaced by an event with this event id. | ||
| 885 | Replaced(OwnedEventId), | ||
| 886 | } | ||
| 887 | |||
| 870 | #[derive(Clone, Debug, Default, Eq, PartialEq)] | 888 | #[derive(Clone, Debug, Default, Eq, PartialEq)] |
| 871 | pub struct UnreadInfo { | 889 | pub struct UnreadInfo { |
| 872 | pub(crate) unread_mark: bool, | 890 | pub(crate) unread_mark: bool, |
| @@ -985,6 +1003,7 @@ pub struct RoomInfo { | |||
| 985 | 1003 | ||
| 986 | /// A map of event IDs to where they are stored in this struct. | 1004 | /// A map of event IDs to where they are stored in this struct. |
| 987 | pub keys: HashMap<OwnedEventId, EventLocation>, | 1005 | pub keys: HashMap<OwnedEventId, EventLocation>, |
| 1006 | pub echo_keys: HashMap<OwnedTransactionId, EchoLocation>, | ||
| 988 | 1007 | ||
| 989 | /// The messages loaded for this room. | 1008 | /// The messages loaded for this room. |
| 990 | messages: Messages, | 1009 | messages: Messages, |
| @@ -1030,6 +1049,7 @@ impl Default for RoomInfo { | |||
| 1030 | name: Default::default(), | 1049 | name: Default::default(), |
| 1031 | tags: Default::default(), | 1050 | tags: Default::default(), |
| 1032 | keys: Default::default(), | 1051 | keys: Default::default(), |
| 1052 | echo_keys: Default::default(), | ||
| 1033 | event_receipts: Default::default(), | 1053 | event_receipts: Default::default(), |
| 1034 | user_receipts: Default::default(), | 1054 | user_receipts: Default::default(), |
| 1035 | reactions: Default::default(), | 1055 | reactions: Default::default(), |
| @@ -1203,8 +1223,10 @@ impl RoomInfo { | |||
| 1203 | ) { | 1223 | ) { |
| 1204 | match sticker { | 1224 | match sticker { |
| 1205 | MessageLikeEvent::Original(ref sticker_content) => { | 1225 | MessageLikeEvent::Original(ref sticker_content) => { |
| 1206 | let key = | 1226 | let key = MessageKey { |
| 1207 | (sticker_content.origin_server_ts.into(), sticker_content.event_id.clone()); | 1227 | ts: sticker_content.origin_server_ts.into(), |
| 1228 | id: sticker_content.event_id.clone().into(), | ||
| 1229 | }; | ||
| 1208 | 1230 | ||
| 1209 | let loc = EventLocation::Sticker(key.clone()); | 1231 | let loc = EventLocation::Sticker(key.clone()); |
| 1210 | 1232 | ||
| @@ -1221,7 +1243,11 @@ impl RoomInfo { | |||
| 1221 | } | 1243 | } |
| 1222 | }, | 1244 | }, |
| 1223 | MessageLikeEvent::Redacted(ref redaction) => { | 1245 | MessageLikeEvent::Redacted(ref redaction) => { |
| 1224 | let key = (redaction.origin_server_ts.into(), redaction.event_id.clone()); | 1246 | let key = MessageKey { |
| 1247 | ts: redaction.origin_server_ts.into(), | ||
| 1248 | id: redaction.event_id.clone().into(), | ||
| 1249 | }; | ||
| 1250 | |||
| 1225 | self.messages.insert_message(key.clone(), sticker.clone()); | 1251 | self.messages.insert_message(key.clone(), sticker.clone()); |
| 1226 | }, | 1252 | }, |
| 1227 | } | 1253 | } |
| @@ -1252,7 +1278,7 @@ impl RoomInfo { | |||
| 1252 | MessageEvent::Original(orig) => { | 1278 | MessageEvent::Original(orig) => { |
| 1253 | orig.content.apply_replacement(new_msgtype); | 1279 | orig.content.apply_replacement(new_msgtype); |
| 1254 | }, | 1280 | }, |
| 1255 | MessageEvent::Local(_, content) => { | 1281 | MessageEvent::Local(_, _, content) => { |
| 1256 | content.apply_replacement(new_msgtype); | 1282 | content.apply_replacement(new_msgtype); |
| 1257 | }, | 1283 | }, |
| 1258 | MessageEvent::Redacted(_, _) | | 1284 | MessageEvent::Redacted(_, _) | |
| @@ -1270,7 +1296,10 @@ impl RoomInfo { | |||
| 1270 | 1296 | ||
| 1271 | pub fn insert_any_state(&mut self, msg: AnySyncStateEvent) { | 1297 | pub fn insert_any_state(&mut self, msg: AnySyncStateEvent) { |
| 1272 | let event_id = msg.event_id().to_owned(); | 1298 | let event_id = msg.event_id().to_owned(); |
| 1273 | let key = (msg.origin_server_ts().into(), event_id.clone()); | 1299 | let key = MessageKey { |
| 1300 | ts: msg.origin_server_ts().into(), | ||
| 1301 | id: event_id.clone().into(), | ||
| 1302 | }; | ||
| 1274 | 1303 | ||
| 1275 | let loc = EventLocation::State(key.clone()); | 1304 | let loc = EventLocation::State(key.clone()); |
| 1276 | self.keys.insert(event_id, loc); | 1305 | self.keys.insert(event_id, loc); |
| @@ -1290,14 +1319,17 @@ impl RoomInfo { | |||
| 1290 | unread_messages: room.num_unread_messages(), | 1319 | unread_messages: room.num_unread_messages(), |
| 1291 | unread_notifications: room.num_unread_notifications(), | 1320 | unread_notifications: room.num_unread_notifications(), |
| 1292 | unread_mentions: room.num_unread_mentions(), | 1321 | unread_mentions: room.num_unread_mentions(), |
| 1293 | latest: last_message.map(|((ts, _), _)| ts.to_owned()), | 1322 | latest: last_message.map(|(key, _)| key.ts.to_owned()), |
| 1294 | } | 1323 | } |
| 1295 | } | 1324 | } |
| 1296 | 1325 | ||
| 1297 | /// Inserts events that couldn't be decrypted into the scrollback. | 1326 | /// Inserts events that couldn't be decrypted into the scrollback. |
| 1298 | pub fn insert_encrypted(&mut self, msg: RoomEncryptedEvent) { | 1327 | pub fn insert_encrypted(&mut self, msg: RoomEncryptedEvent) { |
| 1299 | let event_id = msg.event_id().to_owned(); | 1328 | let event_id = msg.event_id().to_owned(); |
| 1300 | let key = (msg.origin_server_ts().into(), event_id.clone()); | 1329 | let key = MessageKey { |
| 1330 | ts: msg.origin_server_ts().into(), | ||
| 1331 | id: event_id.clone().into(), | ||
| 1332 | }; | ||
| 1301 | 1333 | ||
| 1302 | self.keys.insert(event_id, EventLocation::Message(None, key.clone())); | 1334 | self.keys.insert(event_id, EventLocation::Message(None, key.clone())); |
| 1303 | self.messages.insert(key, msg.into()); | 1335 | self.messages.insert(key, msg.into()); |
| @@ -1306,7 +1338,10 @@ impl RoomInfo { | |||
| 1306 | /// Insert a new message. | 1338 | /// Insert a new message. |
| 1307 | pub fn insert_message(&mut self, msg: RoomMessageEvent) { | 1339 | pub fn insert_message(&mut self, msg: RoomMessageEvent) { |
| 1308 | let event_id = msg.event_id().to_owned(); | 1340 | let event_id = msg.event_id().to_owned(); |
| 1309 | let key = (msg.origin_server_ts().into(), event_id.clone()); | 1341 | let key = MessageKey { |
| 1342 | ts: msg.origin_server_ts().into(), | ||
| 1343 | id: event_id.clone().into(), | ||
| 1344 | }; | ||
| 1310 | 1345 | ||
| 1311 | let loc = EventLocation::Message(None, key.clone()); | 1346 | let loc = EventLocation::Message(None, key.clone()); |
| 1312 | self.keys.insert(event_id, loc); | 1347 | self.keys.insert(event_id, loc); |
| @@ -1315,7 +1350,10 @@ impl RoomInfo { | |||
| 1315 | 1350 | ||
| 1316 | fn insert_thread(&mut self, msg: RoomMessageEvent, thread_root: OwnedEventId) { | 1351 | fn insert_thread(&mut self, msg: RoomMessageEvent, thread_root: OwnedEventId) { |
| 1317 | let event_id = msg.event_id().to_owned(); | 1352 | let event_id = msg.event_id().to_owned(); |
| 1318 | let key = (msg.origin_server_ts().into(), event_id.clone()); | 1353 | let key = MessageKey { |
| 1354 | ts: msg.origin_server_ts().into(), | ||
| 1355 | id: event_id.clone().into(), | ||
| 1356 | }; | ||
| 1319 | 1357 | ||
| 1320 | let replies = self | 1358 | let replies = self |
| 1321 | .threads | 1359 | .threads |
| @@ -1407,11 +1445,13 @@ impl RoomInfo { | |||
| 1407 | } | 1445 | } |
| 1408 | 1446 | ||
| 1409 | pub fn fully_read(&mut self, user_id: OwnedUserId, thread: ReceiptThread) { | 1447 | pub fn fully_read(&mut self, user_id: OwnedUserId, thread: ReceiptThread) { |
| 1410 | let Some(messages) = (match &thread { | 1448 | let messages = match &thread { |
| 1411 | ReceiptThread::Main => self.get_thread(None), | 1449 | ReceiptThread::Main => self.get_thread(None), |
| 1412 | ReceiptThread::Thread(root) => self.get_thread(Some(root)), | 1450 | ReceiptThread::Thread(root) => self.get_thread(Some(root)), |
| 1413 | _ => None, | 1451 | _ => None, |
| 1414 | }) else { | 1452 | }; |
| 1453 | |||
| 1454 | let Some(messages) = messages else { | ||
| 1415 | return; | 1455 | return; |
| 1416 | }; | 1456 | }; |
| 1417 | 1457 | ||
| @@ -1427,11 +1467,11 @@ impl RoomInfo { | |||
| 1427 | MessageEvent::Redacted(..) | 1467 | MessageEvent::Redacted(..) |
| 1428 | ) | 1468 | ) |
| 1429 | }) | 1469 | }) |
| 1430 | .map(|(_, msg)| msg.event.event_id().to_owned()) | 1470 | .flat_map(|(_, msg)| msg.event.event_id()) |
| 1431 | .next_back(); | 1471 | .next_back(); |
| 1432 | 1472 | ||
| 1433 | if let Some(event_id) = event_id { | 1473 | if let Some(event_id) = event_id { |
| 1434 | self.set_receipt(thread, user_id, event_id); | 1474 | self.set_receipt(thread, user_id, event_id.to_owned()); |
| 1435 | } | 1475 | } |
| 1436 | } | 1476 | } |
| 1437 | 1477 | ||
src/message/mod.rs +80 −112
| @@ -14,6 +14,8 @@ use matrix_sdk::ruma::events::receipt::ReceiptThread; | |||
| 14 | use matrix_sdk::ruma::events::room::MediaSource; | 14 | use matrix_sdk::ruma::events::room::MediaSource; |
| 15 | use matrix_sdk::ruma::events::sticker::StickerEvent; | 15 | use matrix_sdk::ruma::events::sticker::StickerEvent; |
| 16 | use matrix_sdk::ruma::events::{AnyRedactionEvent, MessageLikeEvent}; | 16 | use matrix_sdk::ruma::events::{AnyRedactionEvent, MessageLikeEvent}; |
| 17 | use matrix_sdk::ruma::OwnedTransactionId; | ||
| 18 | use matrix_sdk::send_queue::SendHandle; | ||
| 17 | use unicode_width::UnicodeWidthStr; | 19 | use unicode_width::UnicodeWidthStr; |
| 18 | 20 | ||
| 19 | use matrix_sdk::ruma::{ | 21 | use matrix_sdk::ruma::{ |
| @@ -77,7 +79,15 @@ pub use html::TreeGenState; | |||
| 77 | 79 | ||
| 78 | type ProtocolPreview<'a> = (&'a Protocol, u16, u16); | 80 | type ProtocolPreview<'a> = (&'a Protocol, u16, u16); |
| 79 | 81 | ||
| 80 | pub type MessageKey = (MessageTimeStamp, OwnedEventId); | 82 | /// The key used for uniquely identifying messages within a room and its threads. |
| 83 | /// | ||
| 84 | /// Note that the ordering of the fields is important here, so that the derived | ||
| 85 | /// `Ord` trait will sort by timestamp first, and then sort by the message ID. | ||
| 86 | #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)] | ||
| 87 | pub struct MessageKey { | ||
| 88 | pub ts: MessageTimeStamp, | ||
| 89 | pub id: MessageId, | ||
| 90 | } | ||
| 81 | 91 | ||
| 82 | pub struct Messages(BTreeMap<MessageKey, Message>, pub ReceiptThread); | 92 | pub struct Messages(BTreeMap<MessageKey, Message>, pub ReceiptThread); |
| 83 | 93 | ||
| @@ -109,16 +119,10 @@ impl Messages { | |||
| 109 | } | 119 | } |
| 110 | 120 | ||
| 111 | pub fn insert_message(&mut self, key: MessageKey, msg: impl Into<Message>) { | 121 | pub fn insert_message(&mut self, key: MessageKey, msg: impl Into<Message>) { |
| 112 | let event_id = key.1.clone(); | ||
| 113 | let mut msg = msg.into(); | 122 | let mut msg = msg.into(); |
| 114 | |||
| 115 | msg.event.strip_reply_fallback(); | 123 | msg.event.strip_reply_fallback(); |
| 116 | 124 | ||
| 117 | self.0.insert(key, msg); | 125 | self.0.insert(key, msg); |
| 118 | |||
| 119 | // Remove any echo. | ||
| 120 | let key = (MessageTimeStamp::LocalEcho, event_id); | ||
| 121 | let _ = self.0.remove(&key); | ||
| 122 | } | 126 | } |
| 123 | } | 127 | } |
| 124 | 128 | ||
| @@ -161,10 +165,10 @@ fn hash_finish_usize(hasher: DefaultHasher) -> Option<usize> { | |||
| 161 | } | 165 | } |
| 162 | } | 166 | } |
| 163 | 167 | ||
| 164 | /// Hash an [EventId] into a [usize]. | 168 | /// Hash an [`MessageId`] into a [`usize`]. |
| 165 | fn hash_event_id(event_id: &EventId) -> Option<usize> { | 169 | fn hash_message_id(id: &MessageId) -> Option<usize> { |
| 166 | let mut hasher = DefaultHasher::new(); | 170 | let mut hasher = DefaultHasher::new(); |
| 167 | event_id.hash(&mut hasher); | 171 | id.hash(&mut hasher); |
| 168 | hash_finish_usize(hasher) | 172 | hash_finish_usize(hasher) |
| 169 | } | 173 | } |
| 170 | 174 | ||
| @@ -200,11 +204,25 @@ fn placeholder_frame( | |||
| 200 | Some(placeholder) | 204 | Some(placeholder) |
| 201 | } | 205 | } |
| 202 | 206 | ||
| 203 | #[inline] | 207 | #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Hash)] |
| 204 | fn millis_to_datetime(ms: UInt) -> DateTime<LocalTz> { | 208 | pub enum MessageId { |
| 205 | let time = i64::from(ms) / 1000; | 209 | Origin(OwnedEventId), |
| 206 | let time = DateTime::from_timestamp(time, 0).unwrap_or_default(); | 210 | Local(OwnedTransactionId), |
| 207 | time.into() | 211 | } |
| 212 | |||
| 213 | impl MessageId { | ||
| 214 | pub fn as_origin(&self) -> Option<&EventId> { | ||
| 215 | match self { | ||
| 216 | Self::Origin(id) => Some(id), | ||
| 217 | _ => None, | ||
| 218 | } | ||
| 219 | } | ||
| 220 | } | ||
| 221 | |||
| 222 | impl From<OwnedEventId> for MessageId { | ||
| 223 | fn from(value: OwnedEventId) -> Self { | ||
| 224 | Self::Origin(value) | ||
| 225 | } | ||
| 208 | } | 226 | } |
| 209 | 227 | ||
| 210 | #[derive(thiserror::Error, Debug)] | 228 | #[derive(thiserror::Error, Debug)] |
| @@ -216,83 +234,40 @@ pub enum TimeStampIntError { | |||
| 216 | UIntError(<UInt as TryFrom<u64>>::Error), | 234 | UIntError(<UInt as TryFrom<u64>>::Error), |
| 217 | } | 235 | } |
| 218 | 236 | ||
| 219 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] | 237 | #[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord)] |
| 220 | pub enum MessageTimeStamp { | 238 | pub struct MessageTimeStamp(pub MilliSecondsSinceUnixEpoch); |
| 221 | OriginServer(UInt), | ||
| 222 | LocalEcho, | ||
| 223 | } | ||
| 224 | 239 | ||
| 225 | impl MessageTimeStamp { | 240 | impl MessageTimeStamp { |
| 226 | fn as_datetime(&self) -> DateTime<LocalTz> { | 241 | fn as_datetime(self) -> DateTime<LocalTz> { |
| 227 | match self { | 242 | let time = i64::from(self.0 .0) / 1000; |
| 228 | MessageTimeStamp::OriginServer(ms) => millis_to_datetime(*ms), | 243 | let time = DateTime::from_timestamp(time, 0).unwrap_or_default(); |
| 229 | MessageTimeStamp::LocalEcho => LocalTz::now(), | 244 | time.into() |
| 230 | } | ||
| 231 | } | 245 | } |
| 232 | 246 | ||
| 233 | fn same_day(&self, other: &Self) -> bool { | 247 | fn same_day(self, other: Self) -> bool { |
| 234 | let dt1 = self.as_datetime(); | 248 | let dt1 = self.as_datetime(); |
| 235 | let dt2 = other.as_datetime(); | 249 | let dt2 = other.as_datetime(); |
| 236 | 250 | ||
| 237 | dt1.date_naive() == dt2.date_naive() | 251 | dt1.date_naive() == dt2.date_naive() |
| 238 | } | 252 | } |
| 239 | 253 | ||
| 240 | fn show_date(&self) -> Option<Span<'_>> { | 254 | fn show_date(self) -> Option<Span<'static>> { |
| 241 | let time = self.as_datetime().format("%A, %B %d %Y").to_string(); | 255 | let time = self.as_datetime().format("%A, %B %d %Y").to_string(); |
| 242 | 256 | ||
| 243 | Span::styled(time, BOLD_STYLE).into() | 257 | Span::styled(time, BOLD_STYLE).into() |
| 244 | } | 258 | } |
| 245 | 259 | ||
| 246 | fn show_time(&self) -> Option<Span<'_>> { | 260 | fn show_time(self) -> Option<Span<'static>> { |
| 247 | match self { | 261 | let time = self.as_datetime().format("%T"); |
| 248 | MessageTimeStamp::OriginServer(ms) => { | 262 | let time = format!(" [{time}]"); |
| 249 | let time = millis_to_datetime(*ms).format("%T"); | ||
| 250 | let time = format!(" [{time}]"); | ||
| 251 | 263 | ||
| 252 | Span::raw(time).into() | 264 | Span::raw(time).into() |
| 253 | }, | ||
| 254 | MessageTimeStamp::LocalEcho => None, | ||
| 255 | } | ||
| 256 | } | ||
| 257 | |||
| 258 | fn is_local_echo(&self) -> bool { | ||
| 259 | matches!(self, MessageTimeStamp::LocalEcho) | ||
| 260 | } | ||
| 261 | |||
| 262 | pub fn as_millis(&self) -> Option<MilliSecondsSinceUnixEpoch> { | ||
| 263 | match self { | ||
| 264 | MessageTimeStamp::OriginServer(ms) => MilliSecondsSinceUnixEpoch(*ms).into(), | ||
| 265 | MessageTimeStamp::LocalEcho => None, | ||
| 266 | } | ||
| 267 | } | ||
| 268 | } | ||
| 269 | |||
| 270 | impl Ord for MessageTimeStamp { | ||
| 271 | fn cmp(&self, other: &Self) -> Ordering { | ||
| 272 | match (self, other) { | ||
| 273 | (MessageTimeStamp::OriginServer(_), MessageTimeStamp::LocalEcho) => Ordering::Less, | ||
| 274 | (MessageTimeStamp::OriginServer(a), MessageTimeStamp::OriginServer(b)) => a.cmp(b), | ||
| 275 | (MessageTimeStamp::LocalEcho, MessageTimeStamp::OriginServer(_)) => Ordering::Greater, | ||
| 276 | (MessageTimeStamp::LocalEcho, MessageTimeStamp::LocalEcho) => Ordering::Equal, | ||
| 277 | } | ||
| 278 | } | ||
| 279 | } | ||
| 280 | |||
| 281 | impl PartialOrd for MessageTimeStamp { | ||
| 282 | fn partial_cmp(&self, other: &Self) -> Option<Ordering> { | ||
| 283 | Some(self.cmp(other)) | ||
| 284 | } | ||
| 285 | } | ||
| 286 | |||
| 287 | impl From<UInt> for MessageTimeStamp { | ||
| 288 | fn from(millis: UInt) -> Self { | ||
| 289 | MessageTimeStamp::OriginServer(millis) | ||
| 290 | } | 265 | } |
| 291 | } | 266 | } |
| 292 | 267 | ||
| 293 | impl From<MilliSecondsSinceUnixEpoch> for MessageTimeStamp { | 268 | impl From<MilliSecondsSinceUnixEpoch> for MessageTimeStamp { |
| 294 | fn from(millis: MilliSecondsSinceUnixEpoch) -> Self { | 269 | fn from(millis: MilliSecondsSinceUnixEpoch) -> Self { |
| 295 | MessageTimeStamp::OriginServer(millis.0) | 270 | Self(millis) |
| 296 | } | 271 | } |
| 297 | } | 272 | } |
| 298 | 273 | ||
| @@ -300,10 +275,7 @@ impl TryFrom<&MessageTimeStamp> for usize { | |||
| 300 | type Error = TimeStampIntError; | 275 | type Error = TimeStampIntError; |
| 301 | 276 | ||
| 302 | fn try_from(ts: &MessageTimeStamp) -> Result<Self, Self::Error> { | 277 | fn try_from(ts: &MessageTimeStamp) -> Result<Self, Self::Error> { |
| 303 | let n = match ts { | 278 | let n = usize::try_from(u64::from(ts.0 .0))?; |
| 304 | MessageTimeStamp::LocalEcho => 0, | ||
| 305 | MessageTimeStamp::OriginServer(u) => usize::try_from(u64::from(*u))?, | ||
| 306 | }; | ||
| 307 | 279 | ||
| 308 | Ok(n) | 280 | Ok(n) |
| 309 | } | 281 | } |
| @@ -313,14 +285,10 @@ impl TryFrom<usize> for MessageTimeStamp { | |||
| 313 | type Error = TimeStampIntError; | 285 | type Error = TimeStampIntError; |
| 314 | 286 | ||
| 315 | fn try_from(u: usize) -> Result<Self, Self::Error> { | 287 | fn try_from(u: usize) -> Result<Self, Self::Error> { |
| 316 | if u == 0 { | 288 | let n = u64::try_from(u)?; |
| 317 | Ok(MessageTimeStamp::LocalEcho) | 289 | let n = UInt::try_from(n).map_err(TimeStampIntError::UIntError)?; |
| 318 | } else { | ||
| 319 | let n = u64::try_from(u)?; | ||
| 320 | let n = UInt::try_from(n).map_err(TimeStampIntError::UIntError)?; | ||
| 321 | 290 | ||
| 322 | Ok(MessageTimeStamp::from(n)) | 291 | Ok(MessageTimeStamp::from(MilliSecondsSinceUnixEpoch(n))) |
| 323 | } | ||
| 324 | } | 292 | } |
| 325 | } | 293 | } |
| 326 | 294 | ||
| @@ -354,33 +322,30 @@ impl MessageCursor { | |||
| 354 | 322 | ||
| 355 | pub fn from_cursor(cursor: &Cursor, thread: &Messages) -> Option<Self> { | 323 | pub fn from_cursor(cursor: &Cursor, thread: &Messages) -> Option<Self> { |
| 356 | let ev_hash = cursor.get_x(); | 324 | let ev_hash = cursor.get_x(); |
| 357 | let ev_term = OwnedEventId::try_from("$").ok()?; | 325 | let ev_term = OwnedEventId::try_from("$").ok()?.into(); |
| 358 | 326 | ||
| 359 | let ts_start = MessageTimeStamp::try_from(cursor.get_y()).ok()?; | 327 | let ts_start = MessageTimeStamp::try_from(cursor.get_y()).ok()?; |
| 360 | let start = (ts_start, ev_term); | 328 | let start = MessageKey { ts: ts_start, id: ev_term }; |
| 361 | 329 | ||
| 362 | for ((ts, event_id), _) in thread.range(&start..) { | 330 | for (key, _) in thread.range(&start..) { |
| 363 | if hash_event_id(event_id)? == ev_hash { | 331 | if hash_message_id(&key.id)? == ev_hash { |
| 364 | return Self::from((*ts, event_id.clone())).into(); | 332 | return Self::from(key.clone()).into(); |
| 365 | } | 333 | } |
| 366 | 334 | ||
| 367 | if ts > &ts_start { | 335 | if key.ts > ts_start { |
| 368 | break; | 336 | break; |
| 369 | } | 337 | } |
| 370 | } | 338 | } |
| 371 | 339 | ||
| 372 | // If we can't find the cursor, then go to the nearest timestamp. | 340 | // If we can't find the cursor, then go to the nearest timestamp. |
| 373 | thread | 341 | thread.range(start..).next().map(|(key, _)| Self::from(key.clone())) |
| 374 | .range(start..) | ||
| 375 | .next() | ||
| 376 | .map(|((ts, ev), _)| Self::from((*ts, ev.clone()))) | ||
| 377 | } | 342 | } |
| 378 | 343 | ||
| 379 | pub fn to_cursor(&self, thread: &Messages) -> Option<Cursor> { | 344 | pub fn to_cursor(&self, thread: &Messages) -> Option<Cursor> { |
| 380 | let (ts, event_id) = self.to_key(thread)?; | 345 | let key = self.to_key(thread)?; |
| 381 | 346 | ||
| 382 | let y = usize::try_from(ts).ok()?; | 347 | let y = usize::try_from(&key.ts).ok()?; |
| 383 | let x = hash_event_id(event_id)?; | 348 | let x = hash_message_id(&key.id)?; |
| 384 | 349 | ||
| 385 | Cursor::new(y, x).into() | 350 | Cursor::new(y, x).into() |
| 386 | } | 351 | } |
| @@ -436,20 +401,22 @@ pub enum MessageEvent { | |||
| 436 | Redacted(OwnedEventId, Option<String>), | 401 | Redacted(OwnedEventId, Option<String>), |
| 437 | State(Box<AnySyncStateEvent>), | 402 | State(Box<AnySyncStateEvent>), |
| 438 | Sticker(Box<StickerEvent>), | 403 | Sticker(Box<StickerEvent>), |
| 439 | Local(OwnedEventId, Box<RoomMessageEventContent>), | 404 | Local(OwnedTransactionId, SendHandle, Box<RoomMessageEventContent>), |
| 440 | } | 405 | } |
| 441 | 406 | ||
| 442 | impl MessageEvent { | 407 | impl MessageEvent { |
| 443 | pub fn event_id(&self) -> &EventId { | 408 | pub fn event_id(&self) -> Option<&EventId> { |
| 444 | match self { | 409 | let event_id = match self { |
| 445 | MessageEvent::EncryptedOriginal(ev) => ev.event_id.as_ref(), | 410 | MessageEvent::EncryptedOriginal(ev) => ev.event_id.as_ref(), |
| 446 | MessageEvent::EncryptedRedacted(ev) => ev.event_id.as_ref(), | 411 | MessageEvent::EncryptedRedacted(ev) => ev.event_id.as_ref(), |
| 447 | MessageEvent::Original(ev) => ev.event_id.as_ref(), | 412 | MessageEvent::Original(ev) => ev.event_id.as_ref(), |
| 448 | MessageEvent::Redacted(event_id, _) => event_id.as_ref(), | 413 | MessageEvent::Redacted(event_id, _) => event_id.as_ref(), |
| 449 | MessageEvent::State(ev) => ev.event_id(), | 414 | MessageEvent::State(ev) => ev.event_id(), |
| 415 | MessageEvent::Local(..) => return None, | ||
| 450 | MessageEvent::Sticker(ev) => ev.event_id(), | 416 | MessageEvent::Sticker(ev) => ev.event_id(), |
| 451 | MessageEvent::Local(event_id, _) => event_id.as_ref(), | 417 | }; |
| 452 | } | 418 | |
| 419 | Some(event_id) | ||
| 453 | } | 420 | } |
| 454 | 421 | ||
| 455 | pub fn content(&self) -> Option<&RoomMessageEventContent> { | 422 | pub fn content(&self) -> Option<&RoomMessageEventContent> { |
| @@ -460,7 +427,7 @@ impl MessageEvent { | |||
| 460 | MessageEvent::Redacted(_, _) => None, | 427 | MessageEvent::Redacted(_, _) => None, |
| 461 | MessageEvent::State(_) => None, | 428 | MessageEvent::State(_) => None, |
| 462 | MessageEvent::Sticker(_) => None, | 429 | MessageEvent::Sticker(_) => None, |
| 463 | MessageEvent::Local(_, content) => Some(content), | 430 | MessageEvent::Local(_, _, content) => Some(content), |
| 464 | } | 431 | } |
| 465 | } | 432 | } |
| 466 | 433 | ||
| @@ -481,7 +448,7 @@ impl MessageEvent { | |||
| 481 | MessageEvent::Redacted(_, reason) => body_cow_reason(reason.as_deref()), | 448 | MessageEvent::Redacted(_, reason) => body_cow_reason(reason.as_deref()), |
| 482 | MessageEvent::Sticker(ev) => body_cow_sticker(ev), | 449 | MessageEvent::Sticker(ev) => body_cow_sticker(ev), |
| 483 | MessageEvent::State(ev) => body_cow_state(ev), | 450 | MessageEvent::State(ev) => body_cow_state(ev), |
| 484 | MessageEvent::Local(_, content) => body_cow_content(content), | 451 | MessageEvent::Local(_, _, content) => body_cow_content(content), |
| 485 | } | 452 | } |
| 486 | } | 453 | } |
| 487 | 454 | ||
| @@ -493,7 +460,7 @@ impl MessageEvent { | |||
| 493 | MessageEvent::Redacted(_, _) => return None, | 460 | MessageEvent::Redacted(_, _) => return None, |
| 494 | MessageEvent::State(ev) => return Some(html_state(ev)), | 461 | MessageEvent::State(ev) => return Some(html_state(ev)), |
| 495 | MessageEvent::Sticker(_) => return None, | 462 | MessageEvent::Sticker(_) => return None, |
| 496 | MessageEvent::Local(_, content) => content, | 463 | MessageEvent::Local(_, _, content) => content, |
| 497 | }; | 464 | }; |
| 498 | 465 | ||
| 499 | if let MessageType::Text(content) = &content.msgtype { | 466 | if let MessageType::Text(content) = &content.msgtype { |
| @@ -513,12 +480,12 @@ impl MessageEvent { | |||
| 513 | MessageEvent::EncryptedRedacted(_) => return, | 480 | MessageEvent::EncryptedRedacted(_) => return, |
| 514 | MessageEvent::Redacted(_, _) => return, | 481 | MessageEvent::Redacted(_, _) => return, |
| 515 | MessageEvent::State(_) => return, | 482 | MessageEvent::State(_) => return, |
| 516 | MessageEvent::Local(_, _) => return, | ||
| 517 | MessageEvent::Sticker(ev) => { | 483 | MessageEvent::Sticker(ev) => { |
| 518 | let event_id = ev.event_id().to_owned(); | 484 | let event_id = ev.event_id().to_owned(); |
| 519 | let reason = redaction_reason_event(redaction); | 485 | let reason = redaction_reason_event(redaction); |
| 520 | *self = MessageEvent::Redacted(event_id, reason); | 486 | *self = MessageEvent::Redacted(event_id, reason); |
| 521 | }, | 487 | }, |
| 488 | MessageEvent::Local(..) => return, | ||
| 522 | MessageEvent::Original(ev) => { | 489 | MessageEvent::Original(ev) => { |
| 523 | let event_id = ev.event_id.to_owned(); | 490 | let event_id = ev.event_id.to_owned(); |
| 524 | let reason = redaction_reason_event(redaction); | 491 | let reason = redaction_reason_event(redaction); |
| @@ -926,7 +893,7 @@ impl Message { | |||
| 926 | let content = match &self.event { | 893 | let content = match &self.event { |
| 927 | MessageEvent::EncryptedOriginal(_) => return None, | 894 | MessageEvent::EncryptedOriginal(_) => return None, |
| 928 | MessageEvent::EncryptedRedacted(_) => return None, | 895 | MessageEvent::EncryptedRedacted(_) => return None, |
| 929 | MessageEvent::Local(_, content) => content, | 896 | MessageEvent::Local(_, _, content) => content, |
| 930 | MessageEvent::Original(ev) => &ev.content, | 897 | MessageEvent::Original(ev) => &ev.content, |
| 931 | MessageEvent::Redacted(_, _) => return None, | 898 | MessageEvent::Redacted(_, _) => return None, |
| 932 | MessageEvent::State(_) => return None, | 899 | MessageEvent::State(_) => return None, |
| @@ -948,7 +915,7 @@ impl Message { | |||
| 948 | let content = match &self.event { | 915 | let content = match &self.event { |
| 949 | MessageEvent::EncryptedOriginal(_) => return None, | 916 | MessageEvent::EncryptedOriginal(_) => return None, |
| 950 | MessageEvent::EncryptedRedacted(_) => return None, | 917 | MessageEvent::EncryptedRedacted(_) => return None, |
| 951 | MessageEvent::Local(_, content) => content, | 918 | MessageEvent::Local(_, _, content) => content, |
| 952 | MessageEvent::Original(ev) => &ev.content, | 919 | MessageEvent::Original(ev) => &ev.content, |
| 953 | MessageEvent::Redacted(_, _) => return None, | 920 | MessageEvent::Redacted(_, _) => return None, |
| 954 | MessageEvent::State(_) => return None, | 921 | MessageEvent::State(_) => return None, |
| @@ -973,7 +940,7 @@ impl Message { | |||
| 973 | style = style.add_modifier(StyleModifier::REVERSED) | 940 | style = style.add_modifier(StyleModifier::REVERSED) |
| 974 | } | 941 | } |
| 975 | 942 | ||
| 976 | if self.timestamp.is_local_echo() { | 943 | if matches!(self.event, MessageEvent::Local(..)) { |
| 977 | style = style.add_modifier(StyleModifier::ITALIC); | 944 | style = style.add_modifier(StyleModifier::ITALIC); |
| 978 | } | 945 | } |
| 979 | 946 | ||
| @@ -994,7 +961,7 @@ impl Message { | |||
| 994 | ) -> MessageFormatter<'a> { | 961 | ) -> MessageFormatter<'a> { |
| 995 | let orig = width; | 962 | let orig = width; |
| 996 | let date = match &prev { | 963 | let date = match &prev { |
| 997 | Some(prev) if prev.timestamp.same_day(&self.timestamp) => None, | 964 | Some(prev) if prev.timestamp.same_day(self.timestamp) => None, |
| 998 | _ => self.timestamp.show_date(), | 965 | _ => self.timestamp.show_date(), |
| 999 | }; | 966 | }; |
| 1000 | let user_gutter = settings.tunables.user_gutter_width; | 967 | let user_gutter = settings.tunables.user_gutter_width; |
| @@ -1009,7 +976,7 @@ impl Message { | |||
| 1009 | let read = info | 976 | let read = info |
| 1010 | .event_receipts | 977 | .event_receipts |
| 1011 | .values() | 978 | .values() |
| 1012 | .filter_map(|receipts| receipts.get(self.event.event_id())) | 979 | .filter_map(|receipts| self.event.event_id().and_then(|id| receipts.get(id))) |
| 1013 | .flat_map(|read| read.iter()) | 980 | .flat_map(|read| read.iter()) |
| 1014 | .map(|user_id| user_id.to_owned()) | 981 | .map(|user_id| user_id.to_owned()) |
| 1015 | .collect(); | 982 | .collect(); |
| @@ -1103,11 +1070,12 @@ impl Message { | |||
| 1103 | } | 1070 | } |
| 1104 | 1071 | ||
| 1105 | if settings.tunables.reaction_display { | 1072 | if settings.tunables.reaction_display { |
| 1106 | let reactions = info.get_reactions(self.event.event_id()); | 1073 | let reactions = |
| 1074 | self.event.event_id().map(|id| info.get_reactions(id)).unwrap_or_default(); | ||
| 1107 | fmt.push_reactions(reactions, style, &mut text); | 1075 | fmt.push_reactions(reactions, style, &mut text); |
| 1108 | } | 1076 | } |
| 1109 | 1077 | ||
| 1110 | if let Some(thread) = info.get_thread(Some(self.event.event_id())) { | 1078 | if let Some(thread) = self.event.event_id().and_then(|id| info.get_thread(Some(id))) { |
| 1111 | fmt.push_thread_reply_count(thread.len(), &mut text); | 1079 | fmt.push_thread_reply_count(thread.len(), &mut text); |
| 1112 | } | 1080 | } |
| 1113 | 1081 | ||
| @@ -1188,7 +1156,7 @@ impl Message { | |||
| 1188 | ) -> SenderSpan<'a> { | 1156 | ) -> SenderSpan<'a> { |
| 1189 | if let Some(prev) = prev { | 1157 | if let Some(prev) = prev { |
| 1190 | if self.sender == prev.sender && | 1158 | if self.sender == prev.sender && |
| 1191 | self.timestamp.same_day(&prev.timestamp) && | 1159 | self.timestamp.same_day(prev.timestamp) && |
| 1192 | !self.event.is_emote() | 1160 | !self.event.is_emote() |
| 1193 | { | 1161 | { |
| 1194 | return SenderSpan::None; | 1162 | return SenderSpan::None; |
src/tests.rs +29 −18
| @@ -1,6 +1,7 @@ | |||
| 1 | use std::path::PathBuf; | 1 | use std::path::PathBuf; |
| 2 | use std::{collections::HashMap, iter::FromIterator as _}; | 2 | use std::{collections::HashMap, iter::FromIterator as _}; |
| 3 | 3 | ||
| 4 | use matrix_sdk::ruma::MilliSecondsSinceUnixEpoch; | ||
| 4 | use matrix_sdk::ruma::{ | 5 | use matrix_sdk::ruma::{ |
| 5 | event_id, | 6 | event_id, |
| 6 | events::room::message::RoomMessageEventContent, | 7 | events::room::message::RoomMessageEventContent, |
| @@ -19,6 +20,7 @@ use ratatui::style::{Color, Style}; | |||
| 19 | use serde_json::{Map, Value}; | 20 | use serde_json::{Map, Value}; |
| 20 | use tokio::sync::mpsc::unbounded_channel; | 21 | use tokio::sync::mpsc::unbounded_channel; |
| 21 | 22 | ||
| 23 | use crate::message::MessageTimeStamp; | ||
| 22 | use crate::{ | 24 | use crate::{ |
| 23 | base::{ChatStore, EventLocation, ProgramStore, RoomInfo}, | 25 | base::{ChatStore, EventLocation, ProgramStore, RoomInfo}, |
| 24 | config::{ | 26 | config::{ |
| @@ -37,13 +39,7 @@ use crate::{ | |||
| 37 | UserDisplayStyle, | 39 | UserDisplayStyle, |
| 38 | UserDisplayTunables, | 40 | UserDisplayTunables, |
| 39 | }, | 41 | }, |
| 40 | message::{ | 42 | message::{Message, MessageEvent, MessageKey, Messages}, |
| 41 | Message, | ||
| 42 | MessageEvent, | ||
| 43 | MessageKey, | ||
| 44 | MessageTimeStamp::{LocalEcho, OriginServer}, | ||
| 45 | Messages, | ||
| 46 | }, | ||
| 47 | worker::Requester, | 43 | worker::Requester, |
| 48 | }; | 44 | }; |
| 49 | 45 | ||
| @@ -64,11 +60,27 @@ lazy_static! { | |||
| 64 | pub static ref MSG4_EVID: OwnedEventId = | 60 | pub static ref MSG4_EVID: OwnedEventId = |
| 65 | event_id!("$JP6qFV7WyXk5ZnexM3:example.com").to_owned(); | 61 | event_id!("$JP6qFV7WyXk5ZnexM3:example.com").to_owned(); |
| 66 | pub static ref MSG5_EVID: OwnedEventId = EventId::new_v1(server_name!("example.com")); | 62 | pub static ref MSG5_EVID: OwnedEventId = EventId::new_v1(server_name!("example.com")); |
| 67 | pub static ref MSG1_KEY: MessageKey = (LocalEcho, MSG1_EVID.clone()); | 63 | pub static ref MSG1_KEY: MessageKey = MessageKey { |
| 68 | pub static ref MSG2_KEY: MessageKey = (OriginServer(UInt::new(1).unwrap()), MSG2_EVID.clone()); | 64 | // 2000-01-01T00:00:00 |
| 69 | pub static ref MSG3_KEY: MessageKey = (OriginServer(UInt::new(2).unwrap()), MSG3_EVID.clone()); | 65 | ts: MessageTimeStamp(MilliSecondsSinceUnixEpoch(UInt::new(946681200).unwrap())), |
| 70 | pub static ref MSG4_KEY: MessageKey = (OriginServer(UInt::new(2).unwrap()), MSG4_EVID.clone()); | 66 | id: MSG1_EVID.clone().into() |
| 71 | pub static ref MSG5_KEY: MessageKey = (OriginServer(UInt::new(8).unwrap()), MSG5_EVID.clone()); | 67 | }; |
| 68 | pub static ref MSG2_KEY: MessageKey = MessageKey { | ||
| 69 | ts: MessageTimeStamp(MilliSecondsSinceUnixEpoch(UInt::new(1).unwrap())), | ||
| 70 | id: MSG2_EVID.clone().into() | ||
| 71 | }; | ||
| 72 | pub static ref MSG3_KEY: MessageKey = MessageKey { | ||
| 73 | ts: MessageTimeStamp(MilliSecondsSinceUnixEpoch(UInt::new(2).unwrap())), | ||
| 74 | id: MSG3_EVID.clone().into() | ||
| 75 | }; | ||
| 76 | pub static ref MSG4_KEY: MessageKey = MessageKey { | ||
| 77 | ts: MessageTimeStamp(MilliSecondsSinceUnixEpoch(UInt::new(2).unwrap())), | ||
| 78 | id: MSG4_EVID.clone().into() | ||
| 79 | }; | ||
| 80 | pub static ref MSG5_KEY: MessageKey = MessageKey { | ||
| 81 | ts: MessageTimeStamp(MilliSecondsSinceUnixEpoch(UInt::new(8).unwrap())), | ||
| 82 | id: MSG5_EVID.clone().into() | ||
| 83 | }; | ||
| 72 | } | 84 | } |
| 73 | 85 | ||
| 74 | pub fn user_style(user: &str) -> Style { | 86 | pub fn user_style(user: &str) -> Style { |
| @@ -80,13 +92,13 @@ pub fn mock_room1_message( | |||
| 80 | sender: OwnedUserId, | 92 | sender: OwnedUserId, |
| 81 | key: MessageKey, | 93 | key: MessageKey, |
| 82 | ) -> Message { | 94 | ) -> Message { |
| 83 | let timestamp = key.0.as_millis().unwrap(); | 95 | let timestamp = key.ts.0; |
| 84 | let event_id = key.1; | 96 | let event_id = key.id.as_origin().unwrap(); |
| 85 | 97 | ||
| 86 | let event = serde_json::from_value(Value::Object(Map::from_iter([ | 98 | let event = serde_json::from_value(Value::Object(Map::from_iter([ |
| 87 | ("type".to_owned(), Value::String("m.room.message".into())), | 99 | ("type".to_owned(), Value::String("m.room.message".into())), |
| 88 | ("content".to_owned(), serde_json::to_value(&content).unwrap()), | 100 | ("content".to_owned(), serde_json::to_value(&content).unwrap()), |
| 89 | ("event_id".to_owned(), serde_json::to_value(&event_id).unwrap()), | 101 | ("event_id".to_owned(), serde_json::to_value(event_id).unwrap()), |
| 90 | ("sender".to_owned(), serde_json::to_value(&sender).unwrap()), | 102 | ("sender".to_owned(), serde_json::to_value(&sender).unwrap()), |
| 91 | ("origin_server_ts".to_owned(), serde_json::to_value(timestamp).unwrap()), | 103 | ("origin_server_ts".to_owned(), serde_json::to_value(timestamp).unwrap()), |
| 92 | ("room_id".to_owned(), serde_json::to_value(&*TEST_ROOM1_ID).unwrap()), | 104 | ("room_id".to_owned(), serde_json::to_value(&*TEST_ROOM1_ID).unwrap()), |
| @@ -98,9 +110,8 @@ pub fn mock_room1_message( | |||
| 98 | 110 | ||
| 99 | pub fn mock_message1() -> Message { | 111 | pub fn mock_message1() -> Message { |
| 100 | let content = RoomMessageEventContent::text_plain("writhe"); | 112 | let content = RoomMessageEventContent::text_plain("writhe"); |
| 101 | let content = MessageEvent::Local(MSG1_EVID.clone(), content.into()); | ||
| 102 | 113 | ||
| 103 | Message::new(content, TEST_USER1.clone(), MSG1_KEY.0) | 114 | mock_room1_message(content, TEST_USER1.clone(), MSG1_KEY.clone()) |
| 104 | } | 115 | } |
| 105 | 116 | ||
| 106 | pub fn mock_message2() -> Message { | 117 | pub fn mock_message2() -> Message { |
| @@ -130,7 +141,7 @@ pub fn mock_message5() -> Message { | |||
| 130 | pub fn mock_keys() -> HashMap<OwnedEventId, EventLocation> { | 141 | pub fn mock_keys() -> HashMap<OwnedEventId, EventLocation> { |
| 131 | let mut keys = HashMap::new(); | 142 | let mut keys = HashMap::new(); |
| 132 | 143 | ||
| 133 | keys.insert(MSG1_EVID.clone(), EventLocation::Message(None, MSG1_KEY.clone())); | 144 | keys.insert(MSG1_EVID.clone(), EventLocation::Message(None, MSG2_KEY.clone())); |
| 134 | keys.insert(MSG2_EVID.clone(), EventLocation::Message(None, MSG2_KEY.clone())); | 145 | keys.insert(MSG2_EVID.clone(), EventLocation::Message(None, MSG2_KEY.clone())); |
| 135 | keys.insert(MSG3_EVID.clone(), EventLocation::Message(None, MSG3_KEY.clone())); | 146 | keys.insert(MSG3_EVID.clone(), EventLocation::Message(None, MSG3_KEY.clone())); |
| 136 | keys.insert(MSG4_EVID.clone(), EventLocation::Message(None, MSG4_KEY.clone())); | 147 | keys.insert(MSG4_EVID.clone(), EventLocation::Message(None, MSG4_KEY.clone())); |
src/windows/mod.rs +3 −3
| @@ -1695,7 +1695,7 @@ impl Promptable<ProgramContext, ProgramStore, IambInfo> for MemberItem { | |||
| 1695 | #[cfg(test)] | 1695 | #[cfg(test)] |
| 1696 | mod tests { | 1696 | mod tests { |
| 1697 | use super::*; | 1697 | use super::*; |
| 1698 | use matrix_sdk::ruma::{room_alias_id, server_name}; | 1698 | use matrix_sdk::ruma::{room_alias_id, server_name, MilliSecondsSinceUnixEpoch}; |
| 1699 | 1699 | ||
| 1700 | #[derive(Debug, Eq, PartialEq)] | 1700 | #[derive(Debug, Eq, PartialEq)] |
| 1701 | struct TestRoomItem { | 1701 | struct TestRoomItem { |
| @@ -1830,7 +1830,7 @@ mod tests { | |||
| 1830 | alias: None, | 1830 | alias: None, |
| 1831 | name: "Room 2", | 1831 | name: "Room 2", |
| 1832 | unread: UnreadInfo { | 1832 | unread: UnreadInfo { |
| 1833 | latest: Some(MessageTimeStamp::OriginServer(40u32.into())), | 1833 | latest: Some(MessageTimeStamp(MilliSecondsSinceUnixEpoch(40u32.into()))), |
| 1834 | unread_mark: false, | 1834 | unread_mark: false, |
| 1835 | unread_messages: 0, | 1835 | unread_messages: 0, |
| 1836 | unread_notifications: 0, | 1836 | unread_notifications: 0, |
| @@ -1845,7 +1845,7 @@ mod tests { | |||
| 1845 | alias: None, | 1845 | alias: None, |
| 1846 | name: "Room 3", | 1846 | name: "Room 3", |
| 1847 | unread: UnreadInfo { | 1847 | unread: UnreadInfo { |
| 1848 | latest: Some(MessageTimeStamp::OriginServer(20u32.into())), | 1848 | latest: Some(MessageTimeStamp(MilliSecondsSinceUnixEpoch(20u32.into()))), |
| 1849 | unread_mark: false, | 1849 | unread_mark: false, |
| 1850 | unread_messages: 0, | 1850 | unread_messages: 0, |
| 1851 | unread_notifications: 0, | 1851 | unread_notifications: 0, |
src/windows/room/chat.rs +81 −54
| @@ -26,13 +26,12 @@ use matrix_sdk::{ | |||
| 26 | OriginalRoomMessageEvent, | 26 | OriginalRoomMessageEvent, |
| 27 | Relation, | 27 | Relation, |
| 28 | ReplyWithinThread, | 28 | ReplyWithinThread, |
| 29 | RoomMessageEventContent, | ||
| 30 | TextMessageEventContent, | ||
| 31 | }, | 29 | }, |
| 32 | OwnedEventId, | 30 | OwnedEventId, |
| 33 | OwnedRoomId, | 31 | OwnedRoomId, |
| 34 | RoomId, | 32 | RoomId, |
| 35 | }, | 33 | }, |
| 34 | send_queue::RoomSendQueueError, | ||
| 36 | RoomState, | 35 | RoomState, |
| 37 | }; | 36 | }; |
| 38 | 37 | ||
| @@ -72,6 +71,7 @@ use modalkit::prelude::*; | |||
| 72 | 71 | ||
| 73 | use crate::base::{ | 72 | use crate::base::{ |
| 74 | DownloadFlags, | 73 | DownloadFlags, |
| 74 | EchoLocation, | ||
| 75 | IambAction, | 75 | IambAction, |
| 76 | IambBufferId, | 76 | IambBufferId, |
| 77 | IambError, | 77 | IambError, |
| @@ -87,14 +87,7 @@ use crate::base::{ | |||
| 87 | }; | 87 | }; |
| 88 | 88 | ||
| 89 | use crate::config::EncryptionIndicatorLocation; | 89 | use crate::config::EncryptionIndicatorLocation; |
| 90 | use crate::message::{ | 90 | use crate::message::{text_to_message, MessageEvent, MessageId, MessageKey, TreeGenState}; |
| 91 | text_to_message, | ||
| 92 | Message, | ||
| 93 | MessageEvent, | ||
| 94 | MessageKey, | ||
| 95 | MessageTimeStamp, | ||
| 96 | TreeGenState, | ||
| 97 | }; | ||
| 98 | use crate::worker::Requester; | 91 | use crate::worker::Requester; |
| 99 | 92 | ||
| 100 | use super::scrollback::{Scrollback, ScrollbackState}; | 93 | use super::scrollback::{Scrollback, ScrollbackState}; |
| @@ -346,7 +339,7 @@ impl ChatState { | |||
| 346 | 339 | ||
| 347 | let ev = match &msg.event { | 340 | let ev = match &msg.event { |
| 348 | MessageEvent::Original(ev) => &ev.content, | 341 | MessageEvent::Original(ev) => &ev.content, |
| 349 | MessageEvent::Local(_, ev) => ev.deref(), | 342 | MessageEvent::Local(_, _, ev) => ev.deref(), |
| 350 | _ => { | 343 | _ => { |
| 351 | let msg = "Cannot edit a redacted message"; | 344 | let msg = "Cannot edit a redacted message"; |
| 352 | let err = UIError::Failure(msg.into()); | 345 | let err = UIError::Failure(msg.into()); |
| @@ -393,7 +386,14 @@ impl ChatState { | |||
| 393 | MessageEvent::EncryptedOriginal(ev) => ev.event_id.clone(), | 386 | MessageEvent::EncryptedOriginal(ev) => ev.event_id.clone(), |
| 394 | MessageEvent::EncryptedRedacted(ev) => ev.event_id.clone(), | 387 | MessageEvent::EncryptedRedacted(ev) => ev.event_id.clone(), |
| 395 | MessageEvent::Original(ev) => ev.event_id.clone(), | 388 | MessageEvent::Original(ev) => ev.event_id.clone(), |
| 396 | MessageEvent::Local(event_id, _) => event_id.clone(), | 389 | MessageEvent::Local(..) => { |
| 390 | // XXX: Implement reactions for local echos | ||
| 391 | |||
| 392 | let msg = "Cannot react to a local echo"; | ||
| 393 | let err = UIError::Failure(msg.into()); | ||
| 394 | |||
| 395 | return Err(err); | ||
| 396 | }, | ||
| 397 | MessageEvent::State(ev) => ev.event_id().to_owned(), | 397 | MessageEvent::State(ev) => ev.event_id().to_owned(), |
| 398 | MessageEvent::Sticker(ev) => ev.event_id().to_owned(), | 398 | MessageEvent::Sticker(ev) => ev.event_id().to_owned(), |
| 399 | MessageEvent::Redacted(_, _) => { | 399 | MessageEvent::Redacted(_, _) => { |
| @@ -413,7 +413,8 @@ impl ChatState { | |||
| 413 | 413 | ||
| 414 | let reaction = Annotation::new(event_id, emoji); | 414 | let reaction = Annotation::new(event_id, emoji); |
| 415 | let msg = ReactionEventContent::new(reaction); | 415 | let msg = ReactionEventContent::new(reaction); |
| 416 | let _ = room.send(msg).await.map_err(IambError::from)?; | 416 | |
| 417 | room.send_queue().send(msg.into()).await.map_err(IambError::from)?; | ||
| 417 | 418 | ||
| 418 | Ok(None) | 419 | Ok(None) |
| 419 | }, | 420 | }, |
| @@ -432,7 +433,22 @@ impl ChatState { | |||
| 432 | MessageEvent::EncryptedOriginal(ev) => ev.event_id.clone(), | 433 | MessageEvent::EncryptedOriginal(ev) => ev.event_id.clone(), |
| 433 | MessageEvent::EncryptedRedacted(ev) => ev.event_id.clone(), | 434 | MessageEvent::EncryptedRedacted(ev) => ev.event_id.clone(), |
| 434 | MessageEvent::Original(ev) => ev.event_id.clone(), | 435 | MessageEvent::Original(ev) => ev.event_id.clone(), |
| 435 | MessageEvent::Local(event_id, _) => event_id.clone(), | 436 | MessageEvent::Local(_, handle, _) => { |
| 437 | let succeeded = handle | ||
| 438 | .abort() | ||
| 439 | .await | ||
| 440 | .map_err(RoomSendQueueError::from) | ||
| 441 | .map_err(IambError::from)?; | ||
| 442 | |||
| 443 | if !succeeded { | ||
| 444 | let msg = "local echo was already sent; please retry"; | ||
| 445 | let err = UIError::Failure(msg.into()); | ||
| 446 | |||
| 447 | return Err(err); | ||
| 448 | } | ||
| 449 | |||
| 450 | return Ok(None); | ||
| 451 | }, | ||
| 436 | MessageEvent::State(ev) => ev.event_id().to_owned(), | 452 | MessageEvent::State(ev) => ev.event_id().to_owned(), |
| 437 | MessageEvent::Sticker(ev) => ev.event_id().to_owned(), | 453 | MessageEvent::Sticker(ev) => ev.event_id().to_owned(), |
| 438 | MessageEvent::Redacted(_, _) => { | 454 | MessageEvent::Redacted(_, _) => { |
| @@ -496,7 +512,12 @@ impl ChatState { | |||
| 496 | MessageEvent::EncryptedOriginal(ev) => ev.event_id.clone(), | 512 | MessageEvent::EncryptedOriginal(ev) => ev.event_id.clone(), |
| 497 | MessageEvent::EncryptedRedacted(ev) => ev.event_id.clone(), | 513 | MessageEvent::EncryptedRedacted(ev) => ev.event_id.clone(), |
| 498 | MessageEvent::Original(ev) => ev.event_id.clone(), | 514 | MessageEvent::Original(ev) => ev.event_id.clone(), |
| 499 | MessageEvent::Local(event_id, _) => event_id.clone(), | 515 | MessageEvent::Local(..) => { |
| 516 | let msg = "Cannot unreact to a local echo"; | ||
| 517 | let err = UIError::Failure(msg.into()); | ||
| 518 | |||
| 519 | return Err(err); | ||
| 520 | }, | ||
| 500 | MessageEvent::State(ev) => ev.event_id().to_owned(), | 521 | MessageEvent::State(ev) => ev.event_id().to_owned(), |
| 501 | MessageEvent::Sticker(ev) => ev.event_id().to_owned(), | 522 | MessageEvent::Sticker(ev) => ev.event_id().to_owned(), |
| 502 | MessageEvent::Redacted(_, _) => { | 523 | MessageEvent::Redacted(_, _) => { |
| @@ -545,9 +566,8 @@ impl ChatState { | |||
| 545 | ) -> IambResult<EditInfo> { | 566 | ) -> IambResult<EditInfo> { |
| 546 | let room = self.get_joined(&store.application.worker)?; | 567 | let room = self.get_joined(&store.application.worker)?; |
| 547 | let info = store.application.rooms.get_or_default(self.id().to_owned()); | 568 | let info = store.application.rooms.get_or_default(self.id().to_owned()); |
| 548 | let mut show_echo = true; | ||
| 549 | 569 | ||
| 550 | let (event_id, msg) = match act { | 570 | match act { |
| 551 | SendAction::Submit | SendAction::SubmitFromEditor => { | 571 | SendAction::Submit | SendAction::SubmitFromEditor => { |
| 552 | let msg = self.tbox.get(); | 572 | let msg = self.tbox.get(); |
| 553 | 573 | ||
| @@ -570,13 +590,48 @@ impl ChatState { | |||
| 570 | 590 | ||
| 571 | let mut msg = text_to_message(msg); | 591 | let mut msg = text_to_message(msg); |
| 572 | 592 | ||
| 573 | if let Some((_, event_id)) = &self.editing { | 593 | if let Some(key) = &self.editing { |
| 594 | let id = match &key.id { | ||
| 595 | MessageId::Origin(id) => id, | ||
| 596 | MessageId::Local(transaction_id) => { | ||
| 597 | match info.echo_keys.get(transaction_id) { | ||
| 598 | Some(EchoLocation::Replaced(id)) => id, | ||
| 599 | Some(EchoLocation::Message(thread, orig_key)) => { | ||
| 600 | let Some(MessageEvent::Local(_, handle, _)) = info | ||
| 601 | .get_thread(thread.as_deref()) | ||
| 602 | .and_then(|thread| thread.get(orig_key)) | ||
| 603 | .map(|msg| &msg.event) | ||
| 604 | else { | ||
| 605 | let msg = "local echo not found in store"; | ||
| 606 | return Err(UIError::Failure(msg.into())); | ||
| 607 | }; | ||
| 608 | |||
| 609 | let succeeded = handle | ||
| 610 | .edit(msg.into()) | ||
| 611 | .await | ||
| 612 | .map_err(RoomSendQueueError::from) | ||
| 613 | .map_err(IambError::from)?; | ||
| 614 | |||
| 615 | if !succeeded { | ||
| 616 | let msg = "local echo was already sent; please retry"; | ||
| 617 | return Err(UIError::Failure(msg.into())); | ||
| 618 | } | ||
| 619 | |||
| 620 | self.reset(); | ||
| 621 | return Ok(None); | ||
| 622 | }, | ||
| 623 | None => { | ||
| 624 | let msg = "local echo not found in store"; | ||
| 625 | return Err(UIError::Failure(msg.into())); | ||
| 626 | }, | ||
| 627 | } | ||
| 628 | }, | ||
| 629 | }; | ||
| 630 | |||
| 574 | msg.relates_to = Some(Relation::Replacement(Replacement::new( | 631 | msg.relates_to = Some(Relation::Replacement(Replacement::new( |
| 575 | event_id.clone(), | 632 | id.to_owned(), |
| 576 | msg.msgtype.clone().into(), | 633 | msg.msgtype.clone().into(), |
| 577 | ))); | 634 | ))); |
| 578 | |||
| 579 | show_echo = false; | ||
| 580 | } else if let Some(thread_root) = self.scrollback.thread() { | 635 | } else if let Some(thread_root) = self.scrollback.thread() { |
| 581 | if let Some(m) = self.get_reply_to(info) { | 636 | if let Some(m) = self.get_reply_to(info) { |
| 582 | msg = msg.make_for_thread(m, ReplyWithinThread::Yes, AddMentions::No); | 637 | msg = msg.make_for_thread(m, ReplyWithinThread::Yes, AddMentions::No); |
| @@ -589,15 +644,10 @@ impl ChatState { | |||
| 589 | msg = msg.make_reply_to(m, ForwardThread::Yes, AddMentions::No); | 644 | msg = msg.make_reply_to(m, ForwardThread::Yes, AddMentions::No); |
| 590 | } | 645 | } |
| 591 | 646 | ||
| 592 | // XXX: second parameter can be a locally unique transaction id. | 647 | room.send_queue().send(msg.into()).await.map_err(IambError::from)?; |
| 593 | // Useful for doing retries. | ||
| 594 | let resp = room.send(msg.clone()).await.map_err(IambError::from)?; | ||
| 595 | let event_id = resp.response.event_id; | ||
| 596 | 648 | ||
| 597 | // Reset message bar state now that it's been sent. | 649 | // Reset message bar state now that it's been sent. |
| 598 | self.reset(); | 650 | self.reset(); |
| 599 | |||
| 600 | (event_id, msg) | ||
| 601 | }, | 651 | }, |
| 602 | SendAction::Upload(file) => { | 652 | SendAction::Upload(file) => { |
| 603 | let path = Path::new(file.as_str()); | 653 | let path = Path::new(file.as_str()); |
| @@ -610,17 +660,10 @@ impl ChatState { | |||
| 610 | .unwrap_or_else(|| Cow::from("Attachment")); | 660 | .unwrap_or_else(|| Cow::from("Attachment")); |
| 611 | let config = AttachmentConfig::new(); | 661 | let config = AttachmentConfig::new(); |
| 612 | 662 | ||
| 613 | let resp = room | 663 | room.send_queue() |
| 614 | .send_attachment(name.as_ref(), &mime, bytes, config) | 664 | .send_attachment(name.as_ref(), mime, bytes, config) |
| 615 | .await | 665 | .await |
| 616 | .map_err(IambError::from)?; | 666 | .map_err(IambError::from)?; |
| 617 | |||
| 618 | // Mock up the local echo message for the scrollback. | ||
| 619 | let msg = TextMessageEventContent::plain(format!("[Attached File: {name}]")); | ||
| 620 | let msg = MessageType::Text(msg); | ||
| 621 | let msg = RoomMessageEventContent::new(msg); | ||
| 622 | |||
| 623 | (resp.event_id, msg) | ||
| 624 | }, | 667 | }, |
| 625 | SendAction::UploadImage(width, height, bytes) => { | 668 | SendAction::UploadImage(width, height, bytes) => { |
| 626 | // Convert to png because arboard does not give us the mime type. | 669 | // Convert to png because arboard does not give us the mime type. |
| @@ -639,27 +682,11 @@ impl ChatState { | |||
| 639 | let name = "Clipboard.png"; | 682 | let name = "Clipboard.png"; |
| 640 | let config = AttachmentConfig::new(); | 683 | let config = AttachmentConfig::new(); |
| 641 | 684 | ||
| 642 | let resp = room | 685 | room.send_queue() |
| 643 | .send_attachment(name, &mime, bytes, config) | 686 | .send_attachment(name, mime, bytes, config) |
| 644 | .await | 687 | .await |
| 645 | .map_err(IambError::from)?; | 688 | .map_err(IambError::from)?; |
| 646 | |||
| 647 | // Mock up the local echo message for the scrollback. | ||
| 648 | let msg = TextMessageEventContent::plain(format!("[Attached File: {name}]")); | ||
| 649 | let msg = MessageType::Text(msg); | ||
| 650 | let msg = RoomMessageEventContent::new(msg); | ||
| 651 | |||
| 652 | (resp.event_id, msg) | ||
| 653 | }, | 689 | }, |
| 654 | }; | ||
| 655 | |||
| 656 | if show_echo { | ||
| 657 | let user = store.application.settings.profile.user_id.clone(); | ||
| 658 | let key = (MessageTimeStamp::LocalEcho, event_id.clone()); | ||
| 659 | let msg = MessageEvent::Local(event_id, msg.into()); | ||
| 660 | let msg = Message::new(msg, user, MessageTimeStamp::LocalEcho); | ||
| 661 | let thread = self.scrollback.get_thread_mut(info); | ||
| 662 | thread.insert(key, msg); | ||
| 663 | } | 690 | } |
| 664 | 691 | ||
| 665 | // Jump to the end of the scrollback to show the message. | 692 | // Jump to the end of the scrollback to show the message. |
src/windows/room/mod.rs +9 −7
| @@ -229,13 +229,15 @@ pub async fn room_command( | |||
| 229 | if !is_unread { | 229 | if !is_unread { |
| 230 | let user_id = store.application.settings.profile.user_id.clone(); | 230 | let user_id = store.application.settings.profile.user_id.clone(); |
| 231 | let info = store.application.get_room_info(id.to_owned()); | 231 | let info = store.application.get_room_info(id.to_owned()); |
| 232 | let messages = info.get_thread(None).expect("room main timeline doesn't exit"); | 232 | let messages = info.get_thread(None).expect("room main timeline doesn't exist"); |
| 233 | if let Some(((_, event_id), _)) = messages.last_key_value() { | 233 | if let Some((key, _)) = messages.last_key_value() { |
| 234 | info.set_receipt( | 234 | if let Some(event_id) = key.id.as_origin() { |
| 235 | matrix_sdk::ruma::events::receipt::ReceiptThread::Main, | 235 | info.set_receipt( |
| 236 | user_id, | 236 | matrix_sdk::ruma::events::receipt::ReceiptThread::Main, |
| 237 | event_id.to_owned(), | 237 | user_id, |
| 238 | ); | 238 | event_id.to_owned(), |
| 239 | ); | ||
| 240 | } | ||
| 239 | } | 241 | } |
| 240 | } | 242 | } |
| 241 | 243 | ||
src/windows/room/scrollback.rs +9 −5
| @@ -1047,9 +1047,13 @@ impl Promptable<ProgramContext, ProgramStore, IambInfo> for ScrollbackState { | |||
| 1047 | let err = EditError::Failure(msg.into()); | 1047 | let err = EditError::Failure(msg.into()); |
| 1048 | Err(err) | 1048 | Err(err) |
| 1049 | } else { | 1049 | } else { |
| 1050 | let root = key.1.clone(); | 1050 | let Some(root) = key.id.as_origin() else { |
| 1051 | let msg = "Cannot create thread for local echo."; | ||
| 1052 | let err = EditError::Failure(msg.into()); | ||
| 1053 | return Err(err); | ||
| 1054 | }; | ||
| 1051 | let room_id = self.room_id.clone(); | 1055 | let room_id = self.room_id.clone(); |
| 1052 | let id = IambId::Room(room_id, Some(root)); | 1056 | let id = IambId::Room(room_id, Some(root.to_owned())); |
| 1053 | let open = WindowAction::Switch(OpenTarget::Application(id)); | 1057 | let open = WindowAction::Switch(OpenTarget::Application(id)); |
| 1054 | Ok(vec![(open.into(), ctx.clone())]) | 1058 | Ok(vec![(open.into(), ctx.clone())]) |
| 1055 | } | 1059 | } |
| @@ -1425,8 +1429,8 @@ impl StatefulWidget for Scrollback<'_> { | |||
| 1425 | let _ = lines.drain(..n); | 1429 | let _ = lines.drain(..n); |
| 1426 | } | 1430 | } |
| 1427 | 1431 | ||
| 1428 | if let Some(((ts, event_id), row, _, _)) = lines.first() { | 1432 | if let Some((key, row, _, _)) = lines.first() { |
| 1429 | state.viewctx.corner.timestamp = Some((*ts, event_id.clone())); | 1433 | state.viewctx.corner.timestamp = Some((*key).clone()); |
| 1430 | state.viewctx.corner.text_row = *row; | 1434 | state.viewctx.corner.text_row = *row; |
| 1431 | } | 1435 | } |
| 1432 | 1436 | ||
| @@ -1434,7 +1438,7 @@ impl StatefulWidget for Scrollback<'_> { | |||
| 1434 | let x = area.left(); | 1438 | let x = area.left(); |
| 1435 | 1439 | ||
| 1436 | let mut image_previews = vec![]; | 1440 | let mut image_previews = vec![]; |
| 1437 | for ((_, _), _, txt, line_preview) in lines.into_iter() { | 1441 | for (_, _, txt, line_preview) in lines.into_iter() { |
| 1438 | let _ = buf.set_line(x, y, &txt, area.width); | 1442 | let _ = buf.set_line(x, y, &txt, area.width); |
| 1439 | if let Some((backend, msg_x, _)) = line_preview { | 1443 | if let Some((backend, msg_x, _)) = line_preview { |
| 1440 | image_previews.push((x + msg_x, y, backend)); | 1444 | image_previews.push((x + msg_x, y, backend)); |
src/worker.rs +126 −2
| @@ -13,8 +13,12 @@ use std::time::{Duration, Instant}; | |||
| 13 | 13 | ||
| 14 | use futures::{stream::FuturesUnordered, StreamExt}; | 14 | use futures::{stream::FuturesUnordered, StreamExt}; |
| 15 | use gethostname::gethostname; | 15 | use gethostname::gethostname; |
| 16 | use matrix_sdk::ruma::events::relation::Thread; | ||
| 17 | use matrix_sdk::ruma::events::room::message::Relation; | ||
| 16 | use matrix_sdk::ruma::events::room::MediaSource; | 18 | use matrix_sdk::ruma::events::room::MediaSource; |
| 17 | use matrix_sdk::ruma::events::sticker::StickerEventContent; | 19 | use matrix_sdk::ruma::events::sticker::StickerEventContent; |
| 20 | use matrix_sdk::ruma::events::AnyMessageLikeEventContent; | ||
| 21 | use matrix_sdk::send_queue::{LocalEcho, LocalEchoContent, RoomSendQueueUpdate, SendQueueUpdate}; | ||
| 18 | use ratatui_image::picker::Picker; | 22 | use ratatui_image::picker::Picker; |
| 19 | use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender}; | 23 | use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender}; |
| 20 | use tokio::sync::Semaphore; | 24 | use tokio::sync::Semaphore; |
| @@ -90,8 +94,9 @@ use matrix_sdk::{ | |||
| 90 | use modalkit::errors::UIError; | 94 | use modalkit::errors::UIError; |
| 91 | use modalkit::prelude::{EditInfo, InfoMessage}; | 95 | use modalkit::prelude::{EditInfo, InfoMessage}; |
| 92 | 96 | ||
| 93 | use crate::base::MessageNeed; | 97 | use crate::base::{EchoLocation, MessageNeed}; |
| 94 | use crate::config::ImagePreviewSize; | 98 | use crate::config::ImagePreviewSize; |
| 99 | use crate::message::{Message, MessageEvent, MessageId, MessageKey}; | ||
| 95 | use crate::notifications::register_notifications; | 100 | use crate::notifications::register_notifications; |
| 96 | use crate::preview::load_image; | 101 | use crate::preview::load_image; |
| 97 | use crate::{ | 102 | use crate::{ |
| @@ -523,6 +528,122 @@ async fn send_receipts_forever(client: &Client, store: &AsyncProgramStore) { | |||
| 523 | } | 528 | } |
| 524 | } | 529 | } |
| 525 | 530 | ||
| 531 | fn insert_local_echo( | ||
| 532 | own_user_id: OwnedUserId, | ||
| 533 | info: &mut RoomInfo, | ||
| 534 | echo: LocalEcho, | ||
| 535 | ) -> Result<(), serde_json::Error> { | ||
| 536 | let LocalEcho { transaction_id, content } = echo; | ||
| 537 | |||
| 538 | match content { | ||
| 539 | LocalEchoContent::Event { serialized_event, send_handle, .. } => { | ||
| 540 | let content = serialized_event.deserialize()?; | ||
| 541 | let AnyMessageLikeEventContent::RoomMessage(msg) = content else { | ||
| 542 | // XXX: Handle other event types | ||
| 543 | return Ok(()); | ||
| 544 | }; | ||
| 545 | |||
| 546 | let thread = match msg.relates_to.as_ref() { | ||
| 547 | Some(Relation::Replacement(..)) => { | ||
| 548 | // XXX: Show echo on edited message | ||
| 549 | return Ok(()); | ||
| 550 | }, | ||
| 551 | Some(Relation::Thread(Thread { event_id, .. })) => Some(event_id.to_owned()), | ||
| 552 | _ => None, | ||
| 553 | }; | ||
| 554 | |||
| 555 | let ts = send_handle.created_at.into(); | ||
| 556 | let key = MessageKey { ts, id: MessageId::Local(transaction_id.clone()) }; | ||
| 557 | let msg = MessageEvent::Local(transaction_id.clone(), send_handle, msg.into()); | ||
| 558 | let msg = Message::new(msg, own_user_id, ts); | ||
| 559 | |||
| 560 | info.echo_keys | ||
| 561 | .insert(transaction_id, EchoLocation::Message(thread.clone(), key.clone())); | ||
| 562 | |||
| 563 | let thread = info.get_thread_mut(thread); | ||
| 564 | thread.insert(key, msg); | ||
| 565 | }, | ||
| 566 | LocalEchoContent::Redaction { .. } => { | ||
| 567 | // Don't show anything locally for the redaction until the server actually does it. | ||
| 568 | }, | ||
| 569 | LocalEchoContent::React { .. } => { | ||
| 570 | // XXX: Handle reactions to local echos | ||
| 571 | }, | ||
| 572 | } | ||
| 573 | Ok(()) | ||
| 574 | } | ||
| 575 | |||
| 576 | async fn subscribe_sendqueue_forever(client: &Client, store: &AsyncProgramStore) { | ||
| 577 | let own_user_id = client.user_id().unwrap(); | ||
| 578 | let mut receiver = client.send_queue().subscribe(); | ||
| 579 | |||
| 580 | // load unsent requests | ||
| 581 | if let Ok(room_echos) = client.send_queue().local_echoes().await { | ||
| 582 | let mut locked = store.lock().await; | ||
| 583 | for (room_id, echos) in room_echos { | ||
| 584 | let info = locked.application.get_room_info(room_id); | ||
| 585 | for echo in echos { | ||
| 586 | let _ = insert_local_echo(own_user_id.to_owned(), info, echo); | ||
| 587 | } | ||
| 588 | } | ||
| 589 | } | ||
| 590 | |||
| 591 | while let Ok(SendQueueUpdate { room_id, update }) = receiver.recv().await { | ||
| 592 | let mut locked = store.lock().await; | ||
| 593 | let info = locked.application.get_room_info(room_id); | ||
| 594 | match update { | ||
| 595 | RoomSendQueueUpdate::NewLocalEvent(echo) => { | ||
| 596 | let _ = insert_local_echo(own_user_id.to_owned(), info, echo); | ||
| 597 | }, | ||
| 598 | RoomSendQueueUpdate::ReplacedLocalEvent { transaction_id, new_content } => { | ||
| 599 | let Some(EchoLocation::Message(thread, key)) = | ||
| 600 | info.echo_keys.get(&transaction_id).cloned() | ||
| 601 | else { | ||
| 602 | continue; | ||
| 603 | }; | ||
| 604 | |||
| 605 | let Ok(content) = new_content.deserialize() else { | ||
| 606 | continue; | ||
| 607 | }; | ||
| 608 | let AnyMessageLikeEventContent::RoomMessage(new_content) = content else { | ||
| 609 | // XXX: Handle other event types | ||
| 610 | continue; | ||
| 611 | }; | ||
| 612 | |||
| 613 | let Some(msg) = info.get_thread_mut(thread).get_mut(&key) else { | ||
| 614 | continue; | ||
| 615 | }; | ||
| 616 | |||
| 617 | let MessageEvent::Local(_, _, msg) = &mut msg.event else { | ||
| 618 | continue; | ||
| 619 | }; | ||
| 620 | |||
| 621 | *msg = new_content.into(); | ||
| 622 | }, | ||
| 623 | |||
| 624 | RoomSendQueueUpdate::SendError { .. } => { | ||
| 625 | // XXX: Show the error to the user | ||
| 626 | }, | ||
| 627 | RoomSendQueueUpdate::CancelledLocalEvent { transaction_id } => { | ||
| 628 | info.echo_keys.remove(&transaction_id); | ||
| 629 | }, | ||
| 630 | RoomSendQueueUpdate::SentEvent { transaction_id, event_id } => { | ||
| 631 | if let Some(location) = info.echo_keys.get_mut(&transaction_id) { | ||
| 632 | let location = std::mem::replace(location, EchoLocation::Replaced(event_id)); | ||
| 633 | |||
| 634 | if let EchoLocation::Message(thread, key) = location { | ||
| 635 | info.get_thread_mut(thread).remove(&key); | ||
| 636 | } | ||
| 637 | } | ||
| 638 | }, | ||
| 639 | |||
| 640 | RoomSendQueueUpdate::RetryEvent { .. } | RoomSendQueueUpdate::MediaUpload { .. } => { | ||
| 641 | // Ignore these events | ||
| 642 | }, | ||
| 643 | } | ||
| 644 | } | ||
| 645 | } | ||
| 646 | |||
| 526 | pub async fn do_first_sync(client: &Client, store: &AsyncProgramStore) -> Result<(), MatrixError> { | 647 | pub async fn do_first_sync(client: &Client, store: &AsyncProgramStore) -> Result<(), MatrixError> { |
| 527 | // Perform an initial, lazily-loaded sync. | 648 | // Perform an initial, lazily-loaded sync. |
| 528 | let mut room = RoomEventFilter::default(); | 649 | let mut room = RoomEventFilter::default(); |
| @@ -538,6 +659,8 @@ pub async fn do_first_sync(client: &Client, store: &AsyncProgramStore) -> Result | |||
| 538 | 659 | ||
| 539 | client.sync_once(settings).await?; | 660 | client.sync_once(settings).await?; |
| 540 | 661 | ||
| 662 | client.send_queue().respawn_tasks_for_rooms_with_unsent_requests().await; | ||
| 663 | |||
| 541 | // Populate sync_info with our initial set of rooms/dms/spaces. | 664 | // Populate sync_info with our initial set of rooms/dms/spaces. |
| 542 | refresh_rooms(client, store).await; | 665 | refresh_rooms(client, store).await; |
| 543 | 666 | ||
| @@ -1267,7 +1390,8 @@ impl ClientWorker { | |||
| 1267 | let rcpt = send_receipts_forever(&client, &store); | 1390 | let rcpt = send_receipts_forever(&client, &store); |
| 1268 | let room = refresh_rooms_forever(&client, &store); | 1391 | let room = refresh_rooms_forever(&client, &store); |
| 1269 | let notifications = register_notifications(&client, &settings, &store); | 1392 | let notifications = register_notifications(&client, &settings, &store); |
| 1270 | let ((), (), (), ()) = tokio::join!(load, rcpt, room, notifications); | 1393 | let sendqueue = subscribe_sendqueue_forever(&client, &store); |
| 1394 | let ((), (), (), (), ()) = tokio::join!(load, rcpt, room, notifications, sendqueue); | ||
| 1271 | } | 1395 | } |
| 1272 | }) | 1396 | }) |
| 1273 | .into(); | 1397 | .into(); |