| 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 | |
| 15 | static MENTION_ID: LazyLock<Regex> = |
| 16 | LazyLock::new(|| Regex::new(r"<at\b[^>]*>").expect("mention tag pattern")); |
| 17 | |
| 18 | /// The original message carried by a Graph `forwardedMessageReference` attachment. |
| 19 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 20 | pub struct ForwardInfo { |
| 21 | pub attachment_id: Option<String>, |
| 22 | pub message_id: String, |
| 23 | pub conversation_id: Option<String>, |
| 24 | pub sender_id: Option<String>, |
| 25 | pub sender_name: Option<String>, |
| 26 | pub sent_at: Option<DateTime<Utc>>, |
| 27 | pub content_html: String, |
| 28 | } |
| 29 | |
| 30 | #[derive(Deserialize)] |
| 31 | #[serde(rename_all = "camelCase")] |
| 32 | struct ForwardContent { |
| 33 | original_message_id: Option<String>, |
| 34 | #[serde(default)] |
| 35 | original_message_content: String, |
| 36 | original_conversation_id: Option<String>, |
| 37 | original_sent_date_time: Option<DateTime<Utc>>, |
| 38 | original_message_sender: Option<graph::Sender>, |
| 39 | } |
| 40 | |
| 41 | impl ForwardInfo { |
| 42 | pub fn from_attachment(attachment: &AttachmentInfo) -> Option<ForwardInfo> { |
| 43 | if attachment.content_type.as_deref() != Some(FORWARDED_CONTENT_TYPE) { |
| 44 | return None; |
| 45 | } |
| 46 | let content: ForwardContent = serde_json::from_str(attachment.content.as_deref()?).ok()?; |
| 47 | let sender = content.original_message_sender.as_ref(); |
| 48 | Some(ForwardInfo { |
| 49 | message_id: content |
| 50 | .original_message_id |
| 51 | .or_else(|| attachment.id.clone())?, |
| 52 | attachment_id: attachment.id.clone(), |
| 53 | conversation_id: content.original_conversation_id, |
| 54 | sender_id: sender |
| 55 | .and_then(|sender| sender.user_id()) |
| 56 | .map(str::to_owned), |
| 57 | sender_name: sender |
| 58 | .and_then(|sender| sender.display_name()) |
| 59 | .map(str::to_owned), |
| 60 | sent_at: content.original_sent_date_time, |
| 61 | content_html: content.original_message_content, |
| 62 | }) |
| 63 | } |
| 64 | |
| 65 | pub fn text(&self) -> String { |
| 66 | let mut text = String::new(); |
| 67 | push_plain(&mut text, &html_to_spans(&self.content_html)); |
| 68 | text.trim().to_owned() |
| 69 | } |
| 70 | |
| 71 | pub fn html(&self, header: &ForwardHeader) -> String { |
| 72 | let sender = header |
| 73 | .sender |
| 74 | .as_deref() |
| 75 | .or(self.sender_name.as_deref()) |
| 76 | .map(|name| format!("<strong>{}</strong>", escape_html(name))) |
| 77 | .unwrap_or_default(); |
| 78 | let time = header |
| 79 | .time |
| 80 | .as_deref() |
| 81 | .map(|time| format!(" <span>{}</span>", escape_html(time))) |
| 82 | .unwrap_or_default(); |
| 83 | let content = MENTION_ID.replace_all(&self.content_html, "<at>"); |
| 84 | format!( |
| 85 | "<blockquote itemscope=\"\" itemtype=\"http://{FORWARD_ITEMTYPE}\" itemid=\"{}\">{sender}{time}{content}</blockquote>", |
| 86 | escape_html(&self.message_id), |
| 87 | ) |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | /// What the forward quote names above the original: sender display name and sent time label. |
| 92 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 93 | pub struct ForwardHeader { |
| 94 | pub sender: Option<String>, |
| 95 | pub time: Option<String>, |
| 96 | } |
| 97 | |
| 98 | pub fn forwards(record: &MessageRecord) -> Vec<ForwardInfo> { |
| 99 | if record.deleted || !record.attachments_json.contains(FORWARDED_CONTENT_TYPE) { |
| 100 | return Vec::new(); |
| 101 | } |
| 102 | attachments(record) |
| 103 | .iter() |
| 104 | .filter_map(ForwardInfo::from_attachment) |
| 105 | .collect() |
| 106 | } |
| 107 | |
| 108 | pub fn forwarded_texts(record: &MessageRecord) -> Vec<String> { |
| 109 | forwards(record) |
| 110 | .iter() |
| 111 | .map(ForwardInfo::text) |
| 112 | .filter(|text| !text.is_empty()) |
| 113 | .collect() |
| 114 | } |
| 115 | |
| 116 | pub fn is_forwarded(record: &MessageRecord) -> bool { |
| 117 | !record.deleted && (record.body_html.contains(FORWARD_ITEMTYPE) || !forwards(record).is_empty()) |
| 118 | } |
| 119 | |
| 120 | /// A forward attachment cached before its content was kept. |
| 121 | pub(crate) fn lacks_forward_content(record: &MessageRecord) -> bool { |
| 122 | attachments(record).iter().any(|attachment| { |
| 123 | attachment.content_type.as_deref() == Some(FORWARDED_CONTENT_TYPE) |
| 124 | && attachment.content.is_none() |
| 125 | }) |
| 126 | } |
| 127 | |
| 128 | /// `html` with each forward's `<attachment id>` tag replaced by its forward blockquote; a forward without a tag goes last. |
| 129 | pub(crate) fn inline_forwards( |
| 130 | record: &MessageRecord, |
| 131 | mut html: String, |
| 132 | header: &dyn Fn(&ForwardInfo) -> ForwardHeader, |
| 133 | ) -> String { |
| 134 | for forward in forwards(record) { |
| 135 | let block = forward.html(&header(&forward)); |
| 136 | let tag = forward |
| 137 | .attachment_id |
| 138 | .as_deref() |
| 139 | .map(|id| format!("<attachment id=\"{id}\"></attachment>")) |
| 140 | .filter(|tag| html.contains(tag)); |
| 141 | match tag { |
| 142 | Some(tag) => html = html.replacen(&tag, &block, 1), |
| 143 | None => html.push_str(&block), |
| 144 | } |
| 145 | } |
| 146 | html |
| 147 | } |
| 148 | |
| 149 | pub fn no_forward_header(_: &ForwardInfo) -> ForwardHeader { |
| 150 | ForwardHeader::default() |
| 151 | } |
| 152 | |
| 153 | #[cfg(test)] |
| 154 | mod tests { |
| 155 | use super::*; |
| 156 | use crate::mapping::message_record; |
| 157 | use crate::spans::Span; |
| 158 | use crate::stored::{copy_text, edit_preserved, linked_message_spans_with, readable_text}; |
| 159 | |
| 160 | const CHAT_ID: &str = "19:11111111-1111-4111-8111-111111111111_22222222-2222-4222-8222-222222222222@unq.gbl.spaces"; |
| 161 | const ORIGINAL_SENDER_ID: &str = "33333333-3333-4333-8333-333333333333"; |
| 162 | const ORIGINAL_TEXT: &str = "Keep it short and make sure everyone gets the key part"; |
| 163 | |
| 164 | fn forwarded_record() -> MessageRecord { |
| 165 | let message: graph::Message = |
| 166 | serde_json::from_str(include_str!("../tests/fixtures/forwarded_message.json")).unwrap(); |
| 167 | message_record(CHAT_ID, &message).unwrap() |
| 168 | } |
| 169 | |
| 170 | fn plain(spans: &[Span]) -> String { |
| 171 | let mut text = String::new(); |
| 172 | push_plain(&mut text, spans); |
| 173 | text |
| 174 | } |
| 175 | |
| 176 | #[test] |
| 177 | fn a_graph_forward_keeps_the_original_message() { |
| 178 | let record = forwarded_record(); |
| 179 | assert!(is_forwarded(&record)); |
| 180 | let found = forwards(&record); |
| 181 | assert_eq!(found.len(), 1); |
| 182 | let forward = &found[0]; |
| 183 | assert_eq!(forward.message_id, "1792149081221"); |
| 184 | assert_eq!(forward.attachment_id.as_deref(), Some("1792149081221")); |
| 185 | assert_eq!(forward.sender_id.as_deref(), Some(ORIGINAL_SENDER_ID)); |
| 186 | assert_eq!(forward.sender_name, None); |
| 187 | assert_eq!( |
| 188 | forward.conversation_id.as_deref(), |
| 189 | Some("19:5555555555554555a5555555555555aa@thread.v2") |
| 190 | ); |
| 191 | assert_eq!( |
| 192 | forward.sent_at, |
| 193 | Some("2026-10-16T11:11:21.221Z".parse().unwrap()) |
| 194 | ); |
| 195 | assert!(forward.text().starts_with(ORIGINAL_TEXT)); |
| 196 | } |
| 197 | |
| 198 | #[test] |
| 199 | fn the_forward_replaces_its_attachment_tag_with_a_quote_naming_the_original_sender() { |
| 200 | let record = forwarded_record(); |
| 201 | let spans = linked_message_spans_with(&record, &|_| None, &|forward| ForwardHeader { |
| 202 | sender: (forward.sender_id.as_deref() == Some(ORIGINAL_SENDER_ID)) |
| 203 | .then(|| "Ada Original".to_owned()), |
| 204 | time: Some("13:11".to_owned()), |
| 205 | }); |
| 206 | let [Span::BlockQuote(children)] = spans.as_slice() else { |
| 207 | panic!("expected one forward blockquote, got {spans:?}"); |
| 208 | }; |
| 209 | let text = plain(children); |
| 210 | assert!(text.starts_with("Ada Original 13:11"), "{text}"); |
| 211 | assert!(text.contains(ORIGINAL_TEXT), "{text}"); |
| 212 | } |
| 213 | |
| 214 | #[test] |
| 215 | fn the_forwarded_text_is_copied_but_not_part_of_the_own_text() { |
| 216 | let record = forwarded_record(); |
| 217 | assert_eq!(readable_text(&record), ""); |
| 218 | assert!(copy_text(&record).starts_with(ORIGINAL_TEXT)); |
| 219 | assert_eq!(forwarded_texts(&record).len(), 1); |
| 220 | } |
| 221 | |
| 222 | #[test] |
| 223 | fn an_edit_keeps_the_forward_attachment() { |
| 224 | let preserved = edit_preserved(&forwarded_record()); |
| 225 | assert_eq!(preserved.kept.len(), 1); |
| 226 | assert_eq!( |
| 227 | preserved.kept[0].content_type.as_deref(), |
| 228 | Some(FORWARDED_CONTENT_TYPE) |
| 229 | ); |
| 230 | } |
| 231 | |
| 232 | #[test] |
| 233 | fn a_mention_inside_the_forward_does_not_borrow_the_forwarders_mention() { |
| 234 | let mut record = forwarded_record(); |
| 235 | record.body_html = format!( |
| 236 | r#"<p><at id="0">Bob Sample</at></p>{}"#, |
| 237 | record.body_html |
| 238 | ); |
| 239 | record.attachments_json = record |
| 240 | .attachments_json |
| 241 | .replace("<p>Keep", r#"<p><at id=\\\"0\\\">Cleo Other</at> Keep"#); |
| 242 | record.mentions_json = |
| 243 | r#"[{"user_id":"user-bob","name":"Bob Sample","id":0}]"#.to_owned(); |
| 244 | assert!(forwards(&record)[0].content_html.contains("Cleo Other")); |
| 245 | let spans = linked_message_spans_with(&record, &|_| None, &no_forward_header); |
| 246 | let mut mentions = Vec::new(); |
| 247 | collect_mentions(&spans, &mut mentions); |
| 248 | assert_eq!( |
| 249 | mentions, |
| 250 | [ |
| 251 | ("Bob Sample".to_owned(), Some("teams-profile:user-bob".to_owned())), |
| 252 | ("Cleo Other".to_owned(), None), |
| 253 | ] |
| 254 | ); |
| 255 | } |
| 256 | |
| 257 | fn collect_mentions(spans: &[Span], found: &mut Vec<(String, Option<String>)>) { |
| 258 | for span in spans { |
| 259 | match span { |
| 260 | Span::Mention { name, id } => found.push((name.clone(), id.clone())), |
| 261 | Span::BlockQuote(children) | Span::Bold(children) => { |
| 262 | collect_mentions(children, found); |
| 263 | } |
| 264 | _ => {} |
| 265 | } |
| 266 | } |
| 267 | } |
| 268 | |
| 269 | #[test] |
| 270 | fn a_forward_cached_without_its_content_needs_a_refetch() { |
| 271 | let mut record = forwarded_record(); |
| 272 | assert!(!lacks_forward_content(&record)); |
| 273 | record.attachments_json = r#"[{"content_type":"forwardedMessageReference","name":null,"url":null,"text":null,"size":null,"quote":null,"id":"1792149081221","content":null}]"#.to_owned(); |
| 274 | assert!(lacks_forward_content(&record)); |
| 275 | assert!(forwards(&record).is_empty()); |
| 276 | } |
| 277 | |
| 278 | #[test] |
| 279 | fn a_deleted_forward_is_not_forwarded() { |
| 280 | let mut record = forwarded_record(); |
| 281 | record.deleted = true; |
| 282 | assert!(!is_forwarded(&record)); |
| 283 | assert!(forwards(&record).is_empty()); |
| 284 | } |
| 285 | } |