| 1 | use std::sync::LazyLock; |
| 2 | |
| 3 | use chrono::{DateTime, Utc}; |
| 4 | use regex::Regex; |
| 5 | use serde::Deserialize; |
| 6 | use store::MessageRecord; |
| 7 | |
| 8 | use crate::markdown::escape_html; |
| 9 | use crate::spans::html_to_spans; |
| 10 | use crate::stored::{AttachmentInfo, attachments, push_plain}; |
| 11 | |
| 12 | pub const FORWARDED_CONTENT_TYPE: &str = "forwardedMessageReference"; |
| 13 | pub(crate) const FORWARD_ITEMTYPE: &str = "schema.skype.com/Forward"; |
| 14 | pub const FORWARD_LOADING_TEXT: &str = "Loading forwarded message"; |
| 15 | pub const FORWARD_UNAVAILABLE_TEXT: &str = "Original message not available"; |
| 16 | |
| 17 | static MENTION_ID: LazyLock<Regex> = |
| 18 | LazyLock::new(|| Regex::new(r"<at\b[^>]*>").expect("mention tag pattern")); |
| 19 | |
| 20 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 21 | pub enum ForwardState { |
| 22 | Ready, |
| 23 | /// Cached without its original; the heal fetches it. |
| 24 | Loading, |
| 25 | Unavailable, |
| 26 | } |
| 27 | |
| 28 | /// The original message carried by a Graph `forwardedMessageReference` attachment. |
| 29 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 30 | pub struct ForwardInfo { |
| 31 | pub state: ForwardState, |
| 32 | pub attachment_id: Option<String>, |
| 33 | pub message_id: String, |
| 34 | pub conversation_id: Option<String>, |
| 35 | pub sender_id: Option<String>, |
| 36 | pub sender_name: Option<String>, |
| 37 | pub sent_at: Option<DateTime<Utc>>, |
| 38 | pub content_html: String, |
| 39 | } |
| 40 | |
| 41 | #[derive(Deserialize)] |
| 42 | #[serde(rename_all = "camelCase")] |
| 43 | struct ForwardContent { |
| 44 | original_message_id: Option<String>, |
| 45 | #[serde(default)] |
| 46 | original_message_content: String, |
| 47 | original_conversation_id: Option<String>, |
| 48 | original_sent_date_time: Option<DateTime<Utc>>, |
| 49 | original_message_sender: Option<graph::Sender>, |
| 50 | } |
| 51 | |
| 52 | impl ForwardInfo { |
| 53 | pub fn from_attachment(attachment: &AttachmentInfo) -> Option<ForwardInfo> { |
| 54 | if attachment.content_type.as_deref() != Some(FORWARDED_CONTENT_TYPE) { |
| 55 | return None; |
| 56 | } |
| 57 | let Some(raw) = attachment.content.as_deref() else { |
| 58 | return Some(ForwardInfo::without_content(attachment)); |
| 59 | }; |
| 60 | let content: ForwardContent = serde_json::from_str(raw).ok()?; |
| 61 | let sender = content.original_message_sender.as_ref(); |
| 62 | Some(ForwardInfo { |
| 63 | state: ForwardState::Ready, |
| 64 | message_id: content |
| 65 | .original_message_id |
| 66 | .or_else(|| attachment.id.clone())?, |
| 67 | attachment_id: attachment.id.clone(), |
| 68 | conversation_id: content.original_conversation_id, |
| 69 | sender_id: sender |
| 70 | .and_then(|sender| sender.user_id()) |
| 71 | .map(str::to_owned), |
| 72 | sender_name: sender |
| 73 | .and_then(|sender| sender.display_name()) |
| 74 | .map(str::to_owned), |
| 75 | sent_at: content.original_sent_date_time, |
| 76 | content_html: content.original_message_content, |
| 77 | }) |
| 78 | } |
| 79 | |
| 80 | fn without_content(attachment: &AttachmentInfo) -> ForwardInfo { |
| 81 | ForwardInfo { |
| 82 | state: if attachment.unavailable { |
| 83 | ForwardState::Unavailable |
| 84 | } else { |
| 85 | ForwardState::Loading |
| 86 | }, |
| 87 | attachment_id: attachment.id.clone(), |
| 88 | message_id: attachment.id.clone().unwrap_or_default(), |
| 89 | conversation_id: None, |
| 90 | sender_id: None, |
| 91 | sender_name: None, |
| 92 | sent_at: None, |
| 93 | content_html: String::new(), |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | pub fn text(&self) -> String { |
| 98 | let mut text = String::new(); |
| 99 | push_plain(&mut text, &html_to_spans(&self.content_html)); |
| 100 | text.trim().to_owned() |
| 101 | } |
| 102 | |
| 103 | pub fn html(&self, header: &ForwardHeader) -> String { |
| 104 | let sender = header |
| 105 | .sender |
| 106 | .as_deref() |
| 107 | .or(self.sender_name.as_deref()) |
| 108 | .map(|name| format!("<strong>{}</strong>", escape_html(name))) |
| 109 | .unwrap_or_default(); |
| 110 | let time = header |
| 111 | .time |
| 112 | .as_deref() |
| 113 | .map(|time| format!(" <span>{}</span>", escape_html(time))) |
| 114 | .unwrap_or_default(); |
| 115 | let content = match self.state { |
| 116 | ForwardState::Ready => MENTION_ID.replace_all(&self.content_html, "<at>"), |
| 117 | ForwardState::Loading => format!("<p><em>{FORWARD_LOADING_TEXT}</em></p>").into(), |
| 118 | ForwardState::Unavailable => { |
| 119 | format!("<p><em>{FORWARD_UNAVAILABLE_TEXT}</em></p>").into() |
| 120 | } |
| 121 | }; |
| 122 | format!( |
| 123 | "<blockquote itemscope=\"\" itemtype=\"http://{FORWARD_ITEMTYPE}\" itemid=\"{}\">{sender}{time}{content}</blockquote>", |
| 124 | escape_html(&self.message_id), |
| 125 | ) |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | /// What the forward quote names above the original: sender display name and sent time label. |
| 130 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 131 | pub struct ForwardHeader { |
| 132 | pub sender: Option<String>, |
| 133 | pub time: Option<String>, |
| 134 | } |
| 135 | |
| 136 | pub fn forwards(record: &MessageRecord) -> Vec<ForwardInfo> { |
| 137 | if record.deleted || !record.attachments_json.contains(FORWARDED_CONTENT_TYPE) { |
| 138 | return Vec::new(); |
| 139 | } |
| 140 | attachments(record) |
| 141 | .iter() |
| 142 | .filter_map(ForwardInfo::from_attachment) |
| 143 | .collect() |
| 144 | } |
| 145 | |
| 146 | pub fn forwarded_texts(record: &MessageRecord) -> Vec<String> { |
| 147 | forwards(record) |
| 148 | .iter() |
| 149 | .map(ForwardInfo::text) |
| 150 | .filter(|text| !text.is_empty()) |
| 151 | .collect() |
| 152 | } |
| 153 | |
| 154 | pub fn is_forwarded(record: &MessageRecord) -> bool { |
| 155 | !record.deleted && (record.body_html.contains(FORWARD_ITEMTYPE) || !forwards(record).is_empty()) |
| 156 | } |
| 157 | |
| 158 | fn is_stale_forward(attachment: &AttachmentInfo) -> bool { |
| 159 | attachment.content_type.as_deref() == Some(FORWARDED_CONTENT_TYPE) |
| 160 | && attachment.content.is_none() |
| 161 | && !attachment.unavailable |
| 162 | } |
| 163 | |
| 164 | /// A forward attachment cached before its content was kept, and not given up on. |
| 165 | pub(crate) fn lacks_forward_content(record: &MessageRecord) -> bool { |
| 166 | attachments(record).iter().any(is_stale_forward) |
| 167 | } |
| 168 | |
| 169 | /// `record` with each stale forward marked as unavailable, so it is not fetched again. |
| 170 | pub(crate) fn mark_forwards_unavailable(record: &MessageRecord) -> Option<MessageRecord> { |
| 171 | let mut stored = attachments(record); |
| 172 | let mut changed = false; |
| 173 | for attachment in stored |
| 174 | .iter_mut() |
| 175 | .filter(|attachment| is_stale_forward(attachment)) |
| 176 | { |
| 177 | attachment.unavailable = true; |
| 178 | changed = true; |
| 179 | } |
| 180 | let attachments_json = serde_json::to_string(&stored).ok()?; |
| 181 | changed.then(|| MessageRecord { |
| 182 | attachments_json, |
| 183 | ..record.clone() |
| 184 | }) |
| 185 | } |
| 186 | |
| 187 | /// `html` with each forward's `<attachment id>` tag replaced by its forward blockquote; a forward without a tag goes last. |
| 188 | pub(crate) fn inline_forwards( |
| 189 | record: &MessageRecord, |
| 190 | mut html: String, |
| 191 | header: &dyn Fn(&ForwardInfo) -> ForwardHeader, |
| 192 | ) -> String { |
| 193 | for forward in forwards(record) { |
| 194 | let block = forward.html(&header(&forward)); |
| 195 | let tag = forward |
| 196 | .attachment_id |
| 197 | .as_deref() |
| 198 | .map(|id| format!("<attachment id=\"{id}\"></attachment>")) |
| 199 | .filter(|tag| html.contains(tag)); |
| 200 | match tag { |
| 201 | Some(tag) => html = html.replacen(&tag, &block, 1), |
| 202 | None => html.push_str(&block), |
| 203 | } |
| 204 | } |
| 205 | html |
| 206 | } |
| 207 | |
| 208 | pub fn no_forward_header(_: &ForwardInfo) -> ForwardHeader { |
| 209 | ForwardHeader::default() |
| 210 | } |
| 211 | |
| 212 | #[cfg(test)] |
| 213 | mod tests { |
| 214 | use super::*; |
| 215 | use crate::mapping::message_record; |
| 216 | use crate::spans::Span; |
| 217 | use crate::stored::{copy_text, edit_preserved, linked_message_spans_with, readable_text}; |
| 218 | |
| 219 | const CHAT_ID: &str = "19:11111111-1111-4111-8111-111111111111_22222222-2222-4222-8222-222222222222@unq.gbl.spaces"; |
| 220 | const ORIGINAL_SENDER_ID: &str = "33333333-3333-4333-8333-333333333333"; |
| 221 | const ORIGINAL_TEXT: &str = "Keep it short and make sure everyone gets the key part"; |
| 222 | |
| 223 | fn forwarded_record() -> MessageRecord { |
| 224 | let message: graph::Message = |
| 225 | serde_json::from_str(include_str!("../tests/fixtures/forwarded_message.json")).unwrap(); |
| 226 | message_record(CHAT_ID, &message).unwrap() |
| 227 | } |
| 228 | |
| 229 | fn plain(spans: &[Span]) -> String { |
| 230 | let mut text = String::new(); |
| 231 | push_plain(&mut text, spans); |
| 232 | text |
| 233 | } |
| 234 | |
| 235 | #[test] |
| 236 | fn a_graph_forward_keeps_the_original_message() { |
| 237 | let record = forwarded_record(); |
| 238 | assert!(is_forwarded(&record)); |
| 239 | let found = forwards(&record); |
| 240 | assert_eq!(found.len(), 1); |
| 241 | let forward = &found[0]; |
| 242 | assert_eq!(forward.message_id, "1792149081221"); |
| 243 | assert_eq!(forward.attachment_id.as_deref(), Some("1792149081221")); |
| 244 | assert_eq!(forward.sender_id.as_deref(), Some(ORIGINAL_SENDER_ID)); |
| 245 | assert_eq!(forward.sender_name, None); |
| 246 | assert_eq!( |
| 247 | forward.conversation_id.as_deref(), |
| 248 | Some("19:5555555555554555a5555555555555aa@thread.v2") |
| 249 | ); |
| 250 | assert_eq!( |
| 251 | forward.sent_at, |
| 252 | Some("2026-10-16T11:11:21.221Z".parse().unwrap()) |
| 253 | ); |
| 254 | assert!(forward.text().starts_with(ORIGINAL_TEXT)); |
| 255 | } |
| 256 | |
| 257 | #[test] |
| 258 | fn the_forward_replaces_its_attachment_tag_with_a_quote_naming_the_original_sender() { |
| 259 | let record = forwarded_record(); |
| 260 | let spans = linked_message_spans_with(&record, &|_| None, &|forward| ForwardHeader { |
| 261 | sender: (forward.sender_id.as_deref() == Some(ORIGINAL_SENDER_ID)) |
| 262 | .then(|| "Ada Original".to_owned()), |
| 263 | time: Some("13:11".to_owned()), |
| 264 | }); |
| 265 | let [Span::BlockQuote(children)] = spans.as_slice() else { |
| 266 | panic!("expected one forward blockquote, got {spans:?}"); |
| 267 | }; |
| 268 | let text = plain(children); |
| 269 | assert!(text.starts_with("Ada Original 13:11"), "{text}"); |
| 270 | assert!(text.contains(ORIGINAL_TEXT), "{text}"); |
| 271 | } |
| 272 | |
| 273 | #[test] |
| 274 | fn the_forwarded_text_is_copied_but_not_part_of_the_own_text() { |
| 275 | let record = forwarded_record(); |
| 276 | assert_eq!(readable_text(&record), ""); |
| 277 | assert!(copy_text(&record).starts_with(ORIGINAL_TEXT)); |
| 278 | assert_eq!(forwarded_texts(&record).len(), 1); |
| 279 | } |
| 280 | |
| 281 | #[test] |
| 282 | fn an_edit_keeps_the_forward_attachment() { |
| 283 | let preserved = edit_preserved(&forwarded_record()); |
| 284 | assert_eq!(preserved.kept.len(), 1); |
| 285 | assert_eq!( |
| 286 | preserved.kept[0].content_type.as_deref(), |
| 287 | Some(FORWARDED_CONTENT_TYPE) |
| 288 | ); |
| 289 | } |
| 290 | |
| 291 | #[test] |
| 292 | fn a_mention_inside_the_forward_does_not_borrow_the_forwarders_mention() { |
| 293 | let mut record = forwarded_record(); |
| 294 | record.body_html = format!(r#"<p><at id="0">Bob Sample</at></p>{}"#, record.body_html); |
| 295 | record.attachments_json = record |
| 296 | .attachments_json |
| 297 | .replace("<p>Keep", r#"<p><at id=\\\"0\\\">Cleo Other</at> Keep"#); |
| 298 | record.mentions_json = r#"[{"user_id":"user-bob","name":"Bob Sample","id":0}]"#.to_owned(); |
| 299 | assert!(forwards(&record)[0].content_html.contains("Cleo Other")); |
| 300 | let spans = linked_message_spans_with(&record, &|_| None, &no_forward_header); |
| 301 | let mut mentions = Vec::new(); |
| 302 | collect_mentions(&spans, &mut mentions); |
| 303 | assert_eq!( |
| 304 | mentions, |
| 305 | [ |
| 306 | ( |
| 307 | "Bob Sample".to_owned(), |
| 308 | Some("teams-profile:user-bob".to_owned()) |
| 309 | ), |
| 310 | ("Cleo Other".to_owned(), None), |
| 311 | ] |
| 312 | ); |
| 313 | } |
| 314 | |
| 315 | fn collect_mentions(spans: &[Span], found: &mut Vec<(String, Option<String>)>) { |
| 316 | for span in spans { |
| 317 | match span { |
| 318 | Span::Mention { name, id } => found.push((name.clone(), id.clone())), |
| 319 | Span::BlockQuote(children) | Span::Bold(children) => { |
| 320 | collect_mentions(children, found); |
| 321 | } |
| 322 | _ => {} |
| 323 | } |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | #[test] |
| 328 | fn a_forward_cached_without_its_content_needs_a_refetch() { |
| 329 | let mut record = forwarded_record(); |
| 330 | assert!(!lacks_forward_content(&record)); |
| 331 | record.attachments_json = r#"[{"content_type":"forwardedMessageReference","name":null,"url":null,"text":null,"size":null,"quote":null,"id":"1792149081221","content":null}]"#.to_owned(); |
| 332 | assert!(lacks_forward_content(&record)); |
| 333 | let found = forwards(&record); |
| 334 | assert_eq!(found.len(), 1); |
| 335 | assert_eq!(found[0].state, ForwardState::Loading); |
| 336 | assert!(forwarded_texts(&record).is_empty()); |
| 337 | } |
| 338 | |
| 339 | fn quote_text(record: &MessageRecord) -> String { |
| 340 | let spans = linked_message_spans_with(record, &|_| None, &no_forward_header); |
| 341 | let [Span::BlockQuote(children)] = spans.as_slice() else { |
| 342 | panic!("expected one forward blockquote, got {spans:?}"); |
| 343 | }; |
| 344 | plain(children) |
| 345 | } |
| 346 | |
| 347 | #[test] |
| 348 | fn a_forward_without_content_shows_a_loading_line_until_it_is_given_up() { |
| 349 | let mut record = forwarded_record(); |
| 350 | record.attachments_json = r#"[{"content_type":"forwardedMessageReference","name":null,"url":null,"text":null,"size":null,"quote":null,"id":"1792149081221","content":null}]"#.to_owned(); |
| 351 | assert!(is_forwarded(&record)); |
| 352 | assert_eq!(quote_text(&record).trim(), FORWARD_LOADING_TEXT); |
| 353 | |
| 354 | let given_up = mark_forwards_unavailable(&record).unwrap(); |
| 355 | assert!(!lacks_forward_content(&given_up)); |
| 356 | assert_eq!(forwards(&given_up)[0].state, ForwardState::Unavailable); |
| 357 | assert_eq!(quote_text(&given_up).trim(), FORWARD_UNAVAILABLE_TEXT); |
| 358 | assert!(mark_forwards_unavailable(&given_up).is_none()); |
| 359 | assert!(edit_preserved(&given_up).kept.is_empty()); |
| 360 | } |
| 361 | |
| 362 | #[test] |
| 363 | fn a_deleted_forward_is_not_forwarded() { |
| 364 | let mut record = forwarded_record(); |
| 365 | record.deleted = true; |
| 366 | assert!(!is_forwarded(&record)); |
| 367 | assert!(forwards(&record).is_empty()); |
| 368 | } |
| 369 | } |