| 1 | use std::collections::HashSet; |
| 2 | |
| 3 | use chatsvc::{ConversationRef, MessageLinks}; |
| 4 | use store::MessageRecord; |
| 5 | |
| 6 | use crate::engine::{Conversation, Delta, SyncEngine}; |
| 7 | use crate::error::Result; |
| 8 | use crate::links::{LinkPreview, has_links_markup, has_stored_links, is_public_link}; |
| 9 | use crate::remote::Remote; |
| 10 | |
| 11 | const LINKS_PAGE_SIZE: usize = 50; |
| 12 | const MAX_REPLY_THREADS: usize = 5; |
| 13 | |
| 14 | impl<R: Remote> SyncEngine<R> { |
| 15 | /// `None` when the page has no title and no image, or the link is not public. |
| 16 | pub async fn link_preview_for(&self, url: &str) -> Result<Option<LinkPreview>> { |
| 17 | if !is_public_link(url) { |
| 18 | return Ok(None); |
| 19 | } |
| 20 | let cached = self |
| 21 | .link_previews |
| 22 | .lock() |
| 23 | .unwrap_or_else(|poisoned| poisoned.into_inner()) |
| 24 | .get(url) |
| 25 | .cloned(); |
| 26 | if let Some(preview) = cached { |
| 27 | return Ok(preview); |
| 28 | } |
| 29 | let info = self.remote.link_info(url).await?; |
| 30 | let preview = LinkPreview::from_info(url, &info); |
| 31 | self.link_previews |
| 32 | .lock() |
| 33 | .unwrap_or_else(|poisoned| poisoned.into_inner()) |
| 34 | .insert(url.to_owned(), preview.clone()); |
| 35 | Ok(preview) |
| 36 | } |
| 37 | |
| 38 | /// Network failures leave the records as they are. |
| 39 | pub(crate) async fn attach_delta_links( |
| 40 | &self, |
| 41 | conversation_id: &str, |
| 42 | delta: &mut Delta, |
| 43 | ) -> bool { |
| 44 | let mut records: Vec<&mut MessageRecord> = delta |
| 45 | .added |
| 46 | .iter_mut() |
| 47 | .chain(delta.updated.iter_mut()) |
| 48 | .collect(); |
| 49 | self.attach_links(conversation_id, &mut records).await |
| 50 | } |
| 51 | |
| 52 | /// Once per conversation and session, for cached messages stored before their links were known. |
| 53 | pub(crate) async fn backfill_links(&self, conversation_id: &str) -> bool { |
| 54 | let first = self |
| 55 | .links_backfilled |
| 56 | .lock() |
| 57 | .unwrap_or_else(|poisoned| poisoned.into_inner()) |
| 58 | .insert(conversation_id.to_owned()); |
| 59 | if !first { |
| 60 | return false; |
| 61 | } |
| 62 | let Ok(mut cached) = self.store.messages(conversation_id, None, LINKS_PAGE_SIZE) else { |
| 63 | return false; |
| 64 | }; |
| 65 | let mut records: Vec<&mut MessageRecord> = cached |
| 66 | .iter_mut() |
| 67 | .filter(|record| !has_stored_links(&record.links_json)) |
| 68 | .collect(); |
| 69 | self.attach_links(conversation_id, &mut records).await |
| 70 | } |
| 71 | |
| 72 | pub(crate) async fn attach_links( |
| 73 | &self, |
| 74 | conversation_id: &str, |
| 75 | records: &mut [&mut MessageRecord], |
| 76 | ) -> bool { |
| 77 | let Ok(conversation) = self.resolve_stored(conversation_id) else { |
| 78 | return false; |
| 79 | }; |
| 80 | let targets = link_conversations(conversation_id, &conversation, records); |
| 81 | let mut changed = false; |
| 82 | for target in targets { |
| 83 | let Ok(found) = self.remote.message_links(&target, LINKS_PAGE_SIZE).await else { |
| 84 | continue; |
| 85 | }; |
| 86 | for MessageLinks { |
| 87 | message_id, |
| 88 | links_json, |
| 89 | } in found |
| 90 | { |
| 91 | if !has_stored_links(&links_json) { |
| 92 | continue; |
| 93 | } |
| 94 | let Some(record) = records.iter_mut().find(|record| { |
| 95 | record.message_id == message_id |
| 96 | && has_links_markup(record) |
| 97 | && record.links_json != links_json |
| 98 | }) else { |
| 99 | continue; |
| 100 | }; |
| 101 | record.links_json = links_json; |
| 102 | changed |= self |
| 103 | .store |
| 104 | .set_message_links(conversation_id, &message_id, &record.links_json) |
| 105 | .unwrap_or(false); |
| 106 | } |
| 107 | } |
| 108 | changed |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | fn link_conversations( |
| 113 | conversation_id: &str, |
| 114 | conversation: &Conversation, |
| 115 | records: &[&mut MessageRecord], |
| 116 | ) -> Vec<ConversationRef> { |
| 117 | let candidates: Vec<&MessageRecord> = records |
| 118 | .iter() |
| 119 | .map(|record| &**record) |
| 120 | .filter(|record| has_links_markup(record)) |
| 121 | .collect(); |
| 122 | if candidates.is_empty() { |
| 123 | return Vec::new(); |
| 124 | } |
| 125 | match conversation { |
| 126 | Conversation::Chat => vec![ConversationRef::chat(conversation_id)], |
| 127 | Conversation::Channel { .. } => { |
| 128 | let mut targets = Vec::new(); |
| 129 | if candidates.iter().any(|record| record.reply_to_id.is_none()) { |
| 130 | targets.push(ConversationRef::channel_root(conversation_id)); |
| 131 | } |
| 132 | let mut seen = HashSet::new(); |
| 133 | let roots = candidates |
| 134 | .iter() |
| 135 | .filter_map(|record| record.reply_to_id.as_deref()) |
| 136 | .filter(|root_id| seen.insert(*root_id)) |
| 137 | .take(MAX_REPLY_THREADS); |
| 138 | targets.extend( |
| 139 | roots.map(|root_id| ConversationRef::channel_reply(conversation_id, root_id)), |
| 140 | ); |
| 141 | targets |
| 142 | } |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | #[cfg(test)] |
| 147 | mod tests { |
| 148 | use super::*; |
| 149 | |
| 150 | fn record(message_id: &str, reply_to_id: Option<&str>, body_html: &str) -> MessageRecord { |
| 151 | MessageRecord { |
| 152 | message_id: message_id.to_owned(), |
| 153 | reply_to_id: reply_to_id.map(str::to_owned), |
| 154 | body_html: body_html.to_owned(), |
| 155 | ..MessageRecord::default() |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | fn targets( |
| 160 | conversation: &Conversation, |
| 161 | mut records: Vec<MessageRecord>, |
| 162 | ) -> Vec<ConversationRef> { |
| 163 | let refs: Vec<&mut MessageRecord> = records.iter_mut().collect(); |
| 164 | link_conversations("19:c", conversation, &refs) |
| 165 | } |
| 166 | |
| 167 | #[test] |
| 168 | fn messages_without_anchors_need_no_request() { |
| 169 | assert!(targets(&Conversation::Chat, vec![record("1", None, "<p>hi</p>")]).is_empty()); |
| 170 | } |
| 171 | |
| 172 | #[test] |
| 173 | fn a_chat_is_read_once() { |
| 174 | let found = targets( |
| 175 | &Conversation::Chat, |
| 176 | vec![ |
| 177 | record("1", None, "<a href=\"https://a.example\">a</a>"), |
| 178 | record("2", None, "<a href=\"https://b.example\">b</a>"), |
| 179 | ], |
| 180 | ); |
| 181 | assert_eq!(found, vec![ConversationRef::chat("19:c")]); |
| 182 | } |
| 183 | |
| 184 | #[test] |
| 185 | fn channel_replies_are_read_per_thread_with_a_cap() { |
| 186 | let anchor = "<a href=\"https://a.example\">a</a>"; |
| 187 | let mut records = vec![record("1", None, anchor)]; |
| 188 | records.extend( |
| 189 | (0..8).map(|index| record(&format!("r{index}"), Some(&format!("root{index}")), anchor)), |
| 190 | ); |
| 191 | let found = targets( |
| 192 | &Conversation::Channel { |
| 193 | team_id: "t".into(), |
| 194 | }, |
| 195 | records, |
| 196 | ); |
| 197 | assert_eq!(found.len(), 1 + MAX_REPLY_THREADS); |
| 198 | assert_eq!(found[0], ConversationRef::channel_root("19:c")); |
| 199 | assert_eq!(found[1], ConversationRef::channel_reply("19:c", "root0")); |
| 200 | } |
| 201 | } |