| 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; |
| 8 | |
| 9 | use crate::engine::{Conversation, 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 | pub(crate) debounce: Duration, |
| 50 | } |
| 51 | |
| 52 | impl Default for ReceiptCache { |
| 53 | fn default() -> Self { |
| 54 | ReceiptCache { |
| 55 | conversations: Mutex::new(HashMap::new()), |
| 56 | pending: Mutex::new(HashSet::new()), |
| 57 | debounce: DEFAULT_RECEIPT_DEBOUNCE, |
| 58 | } |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | fn locked<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> { |
| 63 | mutex |
| 64 | .lock() |
| 65 | .unwrap_or_else(|poisoned| poisoned.into_inner()) |
| 66 | } |
| 67 | |
| 68 | fn same_user(left: &str, right: &str) -> bool { |
| 69 | left.eq_ignore_ascii_case(right) |
| 70 | } |
| 71 | |
| 72 | fn user_of(member_id: &str) -> &str { |
| 73 | member_id.rsplit(':').next().unwrap_or(member_id) |
| 74 | } |
| 75 | |
| 76 | fn build( |
| 77 | my_user_id: &str, |
| 78 | horizons: &[MemberHorizon], |
| 79 | members: &[store::MemberRecord], |
| 80 | ) -> Option<ConversationReceipts> { |
| 81 | let mut others: Vec<OtherMember> = horizons |
| 82 | .iter() |
| 83 | .filter(|horizon| !same_user(user_of(&horizon.member_id), my_user_id)) |
| 84 | .map(|horizon| { |
| 85 | let user_id = user_of(&horizon.member_id); |
| 86 | let name = members |
| 87 | .iter() |
| 88 | .find(|member| { |
| 89 | member |
| 90 | .user_id |
| 91 | .as_deref() |
| 92 | .is_some_and(|known| same_user(known, user_id)) |
| 93 | }) |
| 94 | .map(|member| member.display_name.clone()) |
| 95 | .unwrap_or_default(); |
| 96 | OtherMember { |
| 97 | name, |
| 98 | read_until: horizon.read_until, |
| 99 | read_at: horizon.read_at.unwrap_or(horizon.read_until), |
| 100 | } |
| 101 | }) |
| 102 | .collect(); |
| 103 | if others.is_empty() { |
| 104 | return None; |
| 105 | } |
| 106 | others.sort_by(|left, right| left.name.cmp(&right.name)); |
| 107 | let known_others = members |
| 108 | .iter() |
| 109 | .filter(|member| { |
| 110 | member |
| 111 | .user_id |
| 112 | .as_deref() |
| 113 | .is_none_or(|known| !same_user(known, my_user_id)) |
| 114 | }) |
| 115 | .count(); |
| 116 | Some(ConversationReceipts { |
| 117 | my_user_id: my_user_id.to_owned(), |
| 118 | total_others: known_others.max(others.len()), |
| 119 | others, |
| 120 | }) |
| 121 | } |
| 122 | |
| 123 | fn state_of(receipts: &ConversationReceipts, record: &MessageRecord) -> ReceiptState { |
| 124 | let own = record |
| 125 | .sender_id |
| 126 | .as_deref() |
| 127 | .is_some_and(|sender| same_user(sender, &receipts.my_user_id)); |
| 128 | if !own || record.deleted { |
| 129 | return ReceiptState::Unknown; |
| 130 | } |
| 131 | let mut readers: Vec<ReceiptReader> = receipts |
| 132 | .others |
| 133 | .iter() |
| 134 | .filter(|member| member.read_until >= record.created_at) |
| 135 | .map(|member| ReceiptReader { |
| 136 | name: member.name.clone(), |
| 137 | at: member.read_at, |
| 138 | }) |
| 139 | .collect(); |
| 140 | if readers.is_empty() { |
| 141 | return ReceiptState::Sent; |
| 142 | } |
| 143 | readers.sort_by(|left, right| { |
| 144 | left.at |
| 145 | .cmp(&right.at) |
| 146 | .then_with(|| left.name.cmp(&right.name)) |
| 147 | }); |
| 148 | ReceiptState::Read { |
| 149 | readers, |
| 150 | total_others: receipts.total_others, |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | impl<R: Remote> SyncEngine<R> { |
| 155 | pub fn with_receipt_debounce(mut self, debounce: Duration) -> Self { |
| 156 | self.receipts.debounce = debounce; |
| 157 | self |
| 158 | } |
| 159 | |
| 160 | /// Own messages in chats only. Unknown for others' messages, channels, deleted messages and disabled receipts. |
| 161 | pub fn receipt_state(&self, conversation_id: &str, message_id: &str) -> ReceiptState { |
| 162 | let record = self |
| 163 | .store |
| 164 | .messages_by_id(conversation_id, &[message_id.to_owned()]) |
| 165 | .ok() |
| 166 | .and_then(|mut found| found.remove(message_id)); |
| 167 | record.map_or(ReceiptState::Unknown, |record| { |
| 168 | self.receipt_state_for(&record) |
| 169 | }) |
| 170 | } |
| 171 | |
| 172 | /// Memory only, cheap enough to call per rendered message. |
| 173 | pub fn receipt_state_for(&self, record: &MessageRecord) -> ReceiptState { |
| 174 | let conversations = locked(&self.receipts.conversations); |
| 175 | match conversations.get(&record.conversation_id) { |
| 176 | Some(Some(receipts)) => state_of(receipts, record), |
| 177 | _ => ReceiptState::Unknown, |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | /// Call when a chat opens. Channels are skipped. |
| 182 | pub async fn refresh_receipts(&self, conversation_id: &str) -> Result<()> { |
| 183 | if matches!(self.resolve(conversation_id)?, Conversation::Channel { .. }) { |
| 184 | return Ok(()); |
| 185 | } |
| 186 | let my_user_id = self.my_user_id().await?; |
| 187 | let horizons = self.remote.consumption_horizons(conversation_id).await?; |
| 188 | let members = self |
| 189 | .store |
| 190 | .chat(conversation_id)? |
| 191 | .map(|chat| chat.members) |
| 192 | .unwrap_or_default(); |
| 193 | let fresh = build(&my_user_id, &horizons, &members); |
| 194 | let changed = locked(&self.receipts.conversations) |
| 195 | .insert(conversation_id.to_owned(), fresh.clone()) |
| 196 | .is_none_or(|previous| previous != fresh); |
| 197 | if changed { |
| 198 | let _ = self.events.send(CoreEvent::ReceiptsChanged { |
| 199 | conversation_id: conversation_id.to_owned(), |
| 200 | }); |
| 201 | } |
| 202 | Ok(()) |
| 203 | } |
| 204 | |
| 205 | /// Calls within the debounce window return at once, the first call does the single refresh. |
| 206 | pub async fn refresh_receipts_debounced(&self, conversation_id: &str) -> Result<()> { |
| 207 | if !locked(&self.receipts.pending).insert(conversation_id.to_owned()) { |
| 208 | return Ok(()); |
| 209 | } |
| 210 | tokio::time::sleep(self.receipts.debounce).await; |
| 211 | locked(&self.receipts.pending).remove(conversation_id); |
| 212 | self.refresh_receipts(conversation_id).await |
| 213 | } |
| 214 | |
| 215 | /// Only conversations opened before are refreshed. Opening a chat fetches anyway. |
| 216 | pub async fn handle_receipt_event(&self, event: &MessageEvent) { |
| 217 | if event.kind != EventKind::ReadReceipt { |
| 218 | return; |
| 219 | } |
| 220 | let Some(conversation_id) = event.conversation_id.as_deref() else { |
| 221 | return; |
| 222 | }; |
| 223 | if locked(&self.receipts.conversations).contains_key(conversation_id) { |
| 224 | let _ = self.refresh_receipts_debounced(conversation_id).await; |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | /// Refetches every known conversation after a reconnect or lost messages. |
| 229 | pub async fn handle_receipt_status(&self, status: &StatusEvent) { |
| 230 | if !matches!(status.kind, StatusKind::Connected | StatusKind::MessageLoss) { |
| 231 | return; |
| 232 | } |
| 233 | let known: Vec<String> = locked(&self.receipts.conversations) |
| 234 | .keys() |
| 235 | .cloned() |
| 236 | .collect(); |
| 237 | for conversation_id in known { |
| 238 | let _ = self.refresh_receipts(&conversation_id).await; |
| 239 | } |
| 240 | } |
| 241 | } |