| 1 | use std::collections::{HashMap, HashSet}; |
| 2 | use std::sync::Mutex; |
| 3 | use std::time::Duration; |
| 4 | |
| 5 | use chatsvc::{EventKind, MemberHorizon, MessageEvent, StatusEvent, StatusKind}; |
| 6 | use chrono::{DateTime, Utc}; |
| 7 | use store::{MessageRecord, ReadHorizonRecord}; |
| 8 | |
| 9 | use crate::engine::{Conversation, MEETING_CHAT_KIND, META_USER_ID, SyncEngine}; |
| 10 | use crate::error::Result; |
| 11 | use crate::events::CoreEvent; |
| 12 | use crate::remote::Remote; |
| 13 | |
| 14 | pub const DEFAULT_RECEIPT_DEBOUNCE: Duration = Duration::from_millis(500); |
| 15 | |
| 16 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 17 | pub struct ReceiptReader { |
| 18 | pub name: String, |
| 19 | pub at: DateTime<Utc>, |
| 20 | } |
| 21 | |
| 22 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 23 | pub enum ReceiptState { |
| 24 | Sent, |
| 25 | Read { |
| 26 | readers: Vec<ReceiptReader>, |
| 27 | total_others: usize, |
| 28 | }, |
| 29 | Unknown, |
| 30 | } |
| 31 | |
| 32 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 33 | struct OtherMember { |
| 34 | name: String, |
| 35 | read_until: DateTime<Utc>, |
| 36 | read_at: DateTime<Utc>, |
| 37 | } |
| 38 | |
| 39 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 40 | struct ConversationReceipts { |
| 41 | my_user_id: String, |
| 42 | others: Vec<OtherMember>, |
| 43 | total_others: usize, |
| 44 | } |
| 45 | |
| 46 | pub(crate) struct ReceiptCache { |
| 47 | conversations: Mutex<HashMap<String, Option<ConversationReceipts>>>, |
| 48 | pending: Mutex<HashSet<String>>, |
| 49 | read_from_store: Mutex<HashSet<String>>, |
| 50 | pub(crate) debounce: Duration, |
| 51 | } |
| 52 | |
| 53 | impl Default for ReceiptCache { |
| 54 | fn default() -> Self { |
| 55 | ReceiptCache { |
| 56 | conversations: Mutex::new(HashMap::new()), |
| 57 | pending: Mutex::new(HashSet::new()), |
| 58 | read_from_store: Mutex::new(HashSet::new()), |
| 59 | debounce: DEFAULT_RECEIPT_DEBOUNCE, |
| 60 | } |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | pub(crate) fn locked<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> { |
| 65 | mutex |
| 66 | .lock() |
| 67 | .unwrap_or_else(|poisoned| poisoned.into_inner()) |
| 68 | } |
| 69 | |
| 70 | fn same_user(left: &str, right: &str) -> bool { |
| 71 | left.eq_ignore_ascii_case(right) |
| 72 | } |
| 73 | |
| 74 | fn user_of(member_id: &str) -> &str { |
| 75 | member_id.rsplit(':').next().unwrap_or(member_id) |
| 76 | } |
| 77 | |
| 78 | fn stored_horizon(horizon: MemberHorizon) -> ReadHorizonRecord { |
| 79 | ReadHorizonRecord { |
| 80 | member_id: horizon.member_id, |
| 81 | read_until: horizon.read_until, |
| 82 | read_at: horizon.read_at, |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | /// Meeting chats have no horizons, yet Teams marks own messages as sent there. |
| 87 | fn sent_only(my_user_id: &str) -> ConversationReceipts { |
| 88 | ConversationReceipts { |
| 89 | my_user_id: my_user_id.to_owned(), |
| 90 | others: Vec::new(), |
| 91 | total_others: 0, |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | fn build( |
| 96 | my_user_id: &str, |
| 97 | horizons: &[ReadHorizonRecord], |
| 98 | members: &[store::MemberRecord], |
| 99 | ) -> Option<ConversationReceipts> { |
| 100 | let mut others: Vec<OtherMember> = horizons |
| 101 | .iter() |
| 102 | .filter(|horizon| !same_user(user_of(&horizon.member_id), my_user_id)) |
| 103 | .map(|horizon| { |
| 104 | let user_id = user_of(&horizon.member_id); |
| 105 | let name = members |
| 106 | .iter() |
| 107 | .find(|member| { |
| 108 | member |
| 109 | .user_id |
| 110 | .as_deref() |
| 111 | .is_some_and(|known| same_user(known, user_id)) |
| 112 | }) |
| 113 | .map(|member| member.display_name.clone()) |
| 114 | .unwrap_or_default(); |
| 115 | OtherMember { |
| 116 | name, |
| 117 | read_until: horizon.read_until, |
| 118 | read_at: horizon.read_at.unwrap_or(horizon.read_until), |
| 119 | } |
| 120 | }) |
| 121 | .collect(); |
| 122 | if others.is_empty() { |
| 123 | return None; |
| 124 | } |
| 125 | others.sort_by(|left, right| left.name.cmp(&right.name)); |
| 126 | let known_others = members |
| 127 | .iter() |
| 128 | .filter(|member| { |
| 129 | member |
| 130 | .user_id |
| 131 | .as_deref() |
| 132 | .is_none_or(|known| !same_user(known, my_user_id)) |
| 133 | }) |
| 134 | .count(); |
| 135 | Some(ConversationReceipts { |
| 136 | my_user_id: my_user_id.to_owned(), |
| 137 | total_others: known_others.max(others.len()), |
| 138 | others, |
| 139 | }) |
| 140 | } |
| 141 | |
| 142 | fn state_of(receipts: &ConversationReceipts, record: &MessageRecord) -> ReceiptState { |
| 143 | let own = record |
| 144 | .sender_id |
| 145 | .as_deref() |
| 146 | .is_some_and(|sender| same_user(sender, &receipts.my_user_id)); |
| 147 | if !own || record.deleted { |
| 148 | return ReceiptState::Unknown; |
| 149 | } |
| 150 | let mut readers: Vec<ReceiptReader> = receipts |
| 151 | .others |
| 152 | .iter() |
| 153 | .filter(|member| member.read_until >= record.created_at) |
| 154 | .map(|member| ReceiptReader { |
| 155 | name: member.name.clone(), |
| 156 | at: member.read_at, |
| 157 | }) |
| 158 | .collect(); |
| 159 | if readers.is_empty() { |
| 160 | return ReceiptState::Sent; |
| 161 | } |
| 162 | readers.sort_by(|left, right| { |
| 163 | left.at |
| 164 | .cmp(&right.at) |
| 165 | .then_with(|| left.name.cmp(&right.name)) |
| 166 | }); |
| 167 | ReceiptState::Read { |
| 168 | readers, |
| 169 | total_others: receipts.total_others, |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | impl<R: Remote> SyncEngine<R> { |
| 174 | pub fn with_receipt_debounce(mut self, debounce: Duration) -> Self { |
| 175 | self.receipts.debounce = debounce; |
| 176 | self |
| 177 | } |
| 178 | |
| 179 | /// Own messages in chats only. Unknown for others' messages, channels, deleted messages and disabled receipts. |
| 180 | pub fn receipt_state(&self, conversation_id: &str, message_id: &str) -> ReceiptState { |
| 181 | let record = self |
| 182 | .store |
| 183 | .messages_by_id(conversation_id, &[message_id.to_owned()]) |
| 184 | .ok() |
| 185 | .and_then(|mut found| found.remove(message_id)); |
| 186 | record.map_or(ReceiptState::Unknown, |record| { |
| 187 | self.receipt_state_for(&record) |
| 188 | }) |
| 189 | } |
| 190 | |
| 191 | /// Memory first; the stored horizons of a chat are read once per session, so receipts show before the refresh. |
| 192 | pub fn receipt_state_for(&self, record: &MessageRecord) -> ReceiptState { |
| 193 | self.load_stored_receipts(&record.conversation_id); |
| 194 | let conversations = locked(&self.receipts.conversations); |
| 195 | match conversations.get(&record.conversation_id) { |
| 196 | Some(Some(receipts)) => state_of(receipts, record), |
| 197 | _ => ReceiptState::Unknown, |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | fn load_stored_receipts(&self, conversation_id: &str) { |
| 202 | if !locked(&self.receipts.read_from_store).insert(conversation_id.to_owned()) { |
| 203 | return; |
| 204 | } |
| 205 | if locked(&self.receipts.conversations).contains_key(conversation_id) { |
| 206 | return; |
| 207 | } |
| 208 | let Some(cached) = self.stored_receipts(conversation_id) else { |
| 209 | return; |
| 210 | }; |
| 211 | locked(&self.receipts.conversations) |
| 212 | .entry(conversation_id.to_owned()) |
| 213 | .or_insert(Some(cached)); |
| 214 | } |
| 215 | |
| 216 | fn stored_receipts(&self, conversation_id: &str) -> Option<ConversationReceipts> { |
| 217 | let horizons = self.store.read_horizons(conversation_id).ok()?; |
| 218 | if horizons.is_empty() { |
| 219 | return None; |
| 220 | } |
| 221 | let my_user_id = self.store.meta(META_USER_ID).ok()??; |
| 222 | let members = self.store.chat(conversation_id).ok()??.members; |
| 223 | build(&my_user_id, &horizons, &members) |
| 224 | } |
| 225 | |
| 226 | /// Call when a chat opens. Channels are skipped. |
| 227 | pub async fn refresh_receipts(&self, conversation_id: &str) -> Result<()> { |
| 228 | if matches!( |
| 229 | self.resolve(conversation_id).await?, |
| 230 | Conversation::Channel { .. } |
| 231 | ) { |
| 232 | return Ok(()); |
| 233 | } |
| 234 | let my_user_id = self.my_user_id().await?; |
| 235 | let horizons: Vec<ReadHorizonRecord> = self |
| 236 | .remote |
| 237 | .consumption_horizons(conversation_id) |
| 238 | .await? |
| 239 | .into_iter() |
| 240 | .map(stored_horizon) |
| 241 | .collect(); |
| 242 | self.store.set_read_horizons(conversation_id, &horizons)?; |
| 243 | locked(&self.receipts.read_from_store).insert(conversation_id.to_owned()); |
| 244 | let chat = self.store.chat(conversation_id)?; |
| 245 | let is_meeting = chat.as_ref().is_some_and(|chat| chat.kind == MEETING_CHAT_KIND); |
| 246 | let members = chat.map(|chat| chat.members).unwrap_or_default(); |
| 247 | let fresh = build(&my_user_id, &horizons, &members) |
| 248 | .or_else(|| is_meeting.then(|| sent_only(&my_user_id))); |
| 249 | let changed = locked(&self.receipts.conversations) |
| 250 | .insert(conversation_id.to_owned(), fresh.clone()) |
| 251 | .is_none_or(|previous| previous != fresh); |
| 252 | if changed { |
| 253 | let _ = self.events.send(CoreEvent::ReceiptsChanged { |
| 254 | conversation_id: conversation_id.to_owned(), |
| 255 | }); |
| 256 | } |
| 257 | Ok(()) |
| 258 | } |
| 259 | |
| 260 | /// Calls within the debounce window return at once, the first call does the single refresh. |
| 261 | pub async fn refresh_receipts_debounced(&self, conversation_id: &str) -> Result<()> { |
| 262 | if !locked(&self.receipts.pending).insert(conversation_id.to_owned()) { |
| 263 | return Ok(()); |
| 264 | } |
| 265 | tokio::time::sleep(self.receipts.debounce).await; |
| 266 | locked(&self.receipts.pending).remove(conversation_id); |
| 267 | self.refresh_receipts(conversation_id).await |
| 268 | } |
| 269 | |
| 270 | /// Only conversations opened before are refreshed. Opening a chat fetches anyway. |
| 271 | pub async fn handle_receipt_event(&self, event: &MessageEvent) { |
| 272 | if event.kind != EventKind::ReadReceipt { |
| 273 | return; |
| 274 | } |
| 275 | let Some(conversation_id) = event.conversation_id.as_deref() else { |
| 276 | return; |
| 277 | }; |
| 278 | if locked(&self.receipts.conversations).contains_key(conversation_id) { |
| 279 | let _ = self.refresh_receipts_debounced(conversation_id).await; |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | /// Refetches every known conversation after a reconnect or lost messages. |
| 284 | pub async fn handle_receipt_status(&self, status: &StatusEvent) { |
| 285 | if !matches!(status.kind, StatusKind::Connected | StatusKind::MessageLoss) { |
| 286 | return; |
| 287 | } |
| 288 | let known: Vec<String> = locked(&self.receipts.conversations) |
| 289 | .keys() |
| 290 | .cloned() |
| 291 | .collect(); |
| 292 | for conversation_id in known { |
| 293 | let _ = self.refresh_receipts(&conversation_id).await; |
| 294 | } |
| 295 | } |
| 296 | } |