| 1 | use scraper::{ElementRef, Html}; |
| 2 | use serde::{Deserialize, Serialize}; |
| 3 | use store::MessageRecord; |
| 4 | |
| 5 | use crate::spans::{Span, html_to_spans}; |
| 6 | |
| 7 | const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji"; |
| 8 | |
| 9 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 10 | pub struct AttachmentInfo { |
| 11 | pub content_type: Option<String>, |
| 12 | pub name: Option<String>, |
| 13 | pub url: Option<String>, |
| 14 | pub text: Option<String>, |
| 15 | #[serde(default)] |
| 16 | pub size: Option<u64>, |
| 17 | #[serde(default)] |
| 18 | pub quote: Option<QuoteInfo>, |
| 19 | } |
| 20 | |
| 21 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 22 | pub enum FileKind { |
| 23 | Word, |
| 24 | Excel, |
| 25 | PowerPoint, |
| 26 | Pdf, |
| 27 | Image, |
| 28 | Archive, |
| 29 | Other, |
| 30 | } |
| 31 | |
| 32 | impl FileKind { |
| 33 | pub fn from_name(name: &str) -> FileKind { |
| 34 | let Some((_, extension)) = name.rsplit_once('.') else { |
| 35 | return FileKind::Other; |
| 36 | }; |
| 37 | match extension.to_ascii_lowercase().as_str() { |
| 38 | "doc" | "docx" | "docm" | "dot" | "dotx" | "rtf" | "odt" => FileKind::Word, |
| 39 | "xls" | "xlsx" | "xlsm" | "xlsb" | "csv" | "ods" => FileKind::Excel, |
| 40 | "ppt" | "pptx" | "pptm" | "pps" | "ppsx" | "odp" => FileKind::PowerPoint, |
| 41 | "pdf" => FileKind::Pdf, |
| 42 | "png" | "jpg" | "jpeg" | "gif" | "bmp" | "webp" | "svg" | "heic" | "tif" | "tiff" => { |
| 43 | FileKind::Image |
| 44 | } |
| 45 | "zip" | "rar" | "7z" | "tar" | "gz" | "tgz" => FileKind::Archive, |
| 46 | _ => FileKind::Other, |
| 47 | } |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 52 | pub struct QuoteInfo { |
| 53 | pub message_id: String, |
| 54 | pub preview: String, |
| 55 | pub sender_name: Option<String>, |
| 56 | } |
| 57 | |
| 58 | /// Image inside a message body. `key()` is the image cache key. |
| 59 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 60 | pub struct ImageRef { |
| 61 | pub id: String, |
| 62 | pub url: String, |
| 63 | pub width: Option<u32>, |
| 64 | pub height: Option<u32>, |
| 65 | } |
| 66 | |
| 67 | impl ImageRef { |
| 68 | pub fn key(&self) -> &str { |
| 69 | &self.url |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | impl AttachmentInfo { |
| 74 | pub fn is_card(&self) -> bool { |
| 75 | self.content_type |
| 76 | .as_deref() |
| 77 | .is_some_and(|content_type| content_type.contains("card")) |
| 78 | } |
| 79 | |
| 80 | pub fn file_kind(&self) -> FileKind { |
| 81 | match self.name.as_deref().map(FileKind::from_name) { |
| 82 | Some(FileKind::Other) | None if self.has_image_content_type() => FileKind::Image, |
| 83 | Some(kind) => kind, |
| 84 | None => FileKind::Other, |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | fn has_image_content_type(&self) -> bool { |
| 89 | self.content_type |
| 90 | .as_deref() |
| 91 | .is_some_and(|content_type| content_type.starts_with("image/")) |
| 92 | } |
| 93 | |
| 94 | pub fn is_file(&self) -> bool { |
| 95 | self.content_type.as_deref() == Some("reference") && self.url.is_some() |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 100 | pub struct ReactionInfo { |
| 101 | pub reaction_type: String, |
| 102 | pub user_id: Option<String>, |
| 103 | pub user_name: Option<String>, |
| 104 | } |
| 105 | |
| 106 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 107 | pub struct MentionInfo { |
| 108 | pub user_id: Option<String>, |
| 109 | pub name: String, |
| 110 | } |
| 111 | |
| 112 | pub fn attachments(record: &MessageRecord) -> Vec<AttachmentInfo> { |
| 113 | serde_json::from_str(&record.attachments_json).unwrap_or_default() |
| 114 | } |
| 115 | |
| 116 | pub fn reactions(record: &MessageRecord) -> Vec<ReactionInfo> { |
| 117 | serde_json::from_str(&record.reactions_json).unwrap_or_default() |
| 118 | } |
| 119 | |
| 120 | pub fn mentions(record: &MessageRecord) -> Vec<MentionInfo> { |
| 121 | serde_json::from_str(&record.mentions_json).unwrap_or_default() |
| 122 | } |
| 123 | |
| 124 | pub fn quotes(record: &MessageRecord) -> Vec<QuoteInfo> { |
| 125 | attachments(record) |
| 126 | .into_iter() |
| 127 | .filter_map(|attachment| attachment.quote) |
| 128 | .collect() |
| 129 | } |
| 130 | |
| 131 | pub fn images(record: &MessageRecord) -> Vec<ImageRef> { |
| 132 | if record.deleted { |
| 133 | return Vec::new(); |
| 134 | } |
| 135 | let fragment = Html::parse_fragment(&record.body_html); |
| 136 | let mut found: Vec<ImageRef> = Vec::new(); |
| 137 | for element in fragment |
| 138 | .root_element() |
| 139 | .descendants() |
| 140 | .filter_map(ElementRef::wrap) |
| 141 | { |
| 142 | let value = element.value(); |
| 143 | let is_emoji = value |
| 144 | .attr("itemtype") |
| 145 | .is_some_and(|itemtype| itemtype.contains(EMOJI_ITEMTYPE)); |
| 146 | let Some(url) = value |
| 147 | .attr("src") |
| 148 | .filter(|url| value.name() == "img" && !is_emoji && !url.is_empty()) |
| 149 | else { |
| 150 | continue; |
| 151 | }; |
| 152 | if found.iter().any(|image| image.url == url) { |
| 153 | continue; |
| 154 | } |
| 155 | let style = value.attr("style").unwrap_or_default(); |
| 156 | found.push(ImageRef { |
| 157 | id: image_id(url), |
| 158 | url: url.to_owned(), |
| 159 | width: dimension(value.attr("width"), style, "width"), |
| 160 | height: dimension(value.attr("height"), style, "height"), |
| 161 | }); |
| 162 | } |
| 163 | found |
| 164 | } |
| 165 | |
| 166 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 167 | pub struct FileCard { |
| 168 | pub name: String, |
| 169 | pub kind: FileKind, |
| 170 | pub content_type: Option<String>, |
| 171 | pub size: Option<u64>, |
| 172 | pub open_url: String, |
| 173 | } |
| 174 | |
| 175 | /// File attachments (`reference` type) with a name and a URL. `size` is rarely known; Graph does not send it for these. |
| 176 | pub fn files(record: &MessageRecord) -> Vec<FileCard> { |
| 177 | attachments(record) |
| 178 | .into_iter() |
| 179 | .filter(AttachmentInfo::is_file) |
| 180 | .map(|attachment| FileCard { |
| 181 | kind: attachment.file_kind(), |
| 182 | name: attachment.name.clone().unwrap_or_default(), |
| 183 | content_type: attachment.content_type.clone(), |
| 184 | size: attachment.size, |
| 185 | open_url: attachment.url.clone().unwrap_or_default(), |
| 186 | }) |
| 187 | .collect() |
| 188 | } |
| 189 | |
| 190 | /// Text for the clipboard: body and card text, mentions as `@name`, no markup. |
| 191 | pub fn copy_text(record: &MessageRecord) -> String { |
| 192 | let mut text = String::new(); |
| 193 | push_plain(&mut text, &message_spans(record)); |
| 194 | text.trim().to_owned() |
| 195 | } |
| 196 | |
| 197 | fn push_plain(text: &mut String, spans: &[Span]) { |
| 198 | for span in spans { |
| 199 | match span { |
| 200 | Span::Text(value) | Span::Code(value) => text.push_str(value), |
| 201 | Span::CodeBlock { code, .. } => { |
| 202 | text.push_str(code); |
| 203 | text.push('\n'); |
| 204 | } |
| 205 | Span::Bold(children) | Span::Italic(children) | Span::Quote(children) => { |
| 206 | push_plain(text, children) |
| 207 | } |
| 208 | Span::Link { children, .. } => push_plain(text, children), |
| 209 | Span::Mention { name } => { |
| 210 | text.push('@'); |
| 211 | text.push_str(name); |
| 212 | } |
| 213 | Span::LineBreak => text.push('\n'), |
| 214 | Span::ListItem(children) => { |
| 215 | text.push_str("- "); |
| 216 | push_plain(text, children); |
| 217 | text.push('\n'); |
| 218 | } |
| 219 | Span::Image { .. } => {} |
| 220 | } |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | /// Own, not deleted. Whether the conversation supports the write is the engine's call. |
| 225 | pub fn can_edit(record: &MessageRecord, my_user_id: &str) -> bool { |
| 226 | !record.deleted && record.sender_id.as_deref() == Some(my_user_id) |
| 227 | } |
| 228 | |
| 229 | pub fn can_delete(record: &MessageRecord, my_user_id: &str) -> bool { |
| 230 | can_edit(record, my_user_id) |
| 231 | } |
| 232 | |
| 233 | fn image_id(url: &str) -> String { |
| 234 | let path = url.split(['?', '#']).next().unwrap_or(url); |
| 235 | let segments: Vec<&str> = path |
| 236 | .split('/') |
| 237 | .filter(|segment| !segment.is_empty()) |
| 238 | .collect(); |
| 239 | segments |
| 240 | .iter() |
| 241 | .position(|segment| matches!(*segment, "hostedContents" | "objects")) |
| 242 | .and_then(|index| segments.get(index + 1)) |
| 243 | .or(segments.last()) |
| 244 | .map_or_else(String::new, |segment| (*segment).to_owned()) |
| 245 | } |
| 246 | |
| 247 | fn dimension(attribute: Option<&str>, style: &str, property: &str) -> Option<u32> { |
| 248 | let from_style = || { |
| 249 | style.split(';').find_map(|declaration| { |
| 250 | let (name, value) = declaration.split_once(':')?; |
| 251 | (name.trim() == property).then(|| leading_number(value))? |
| 252 | }) |
| 253 | }; |
| 254 | attribute |
| 255 | .and_then(leading_number) |
| 256 | .or_else(from_style) |
| 257 | .filter(|pixels| *pixels > 0) |
| 258 | } |
| 259 | |
| 260 | fn leading_number(text: &str) -> Option<u32> { |
| 261 | let digits: String = text |
| 262 | .trim() |
| 263 | .chars() |
| 264 | .take_while(char::is_ascii_digit) |
| 265 | .collect(); |
| 266 | digits.parse().ok() |
| 267 | } |
| 268 | |
| 269 | /// Body spans followed by the flattened text of adaptive-card attachments. |
| 270 | pub fn message_spans(record: &MessageRecord) -> Vec<Span> { |
| 271 | let mut spans = html_to_spans(&record.body_html); |
| 272 | for card_text in attachments(record) |
| 273 | .iter() |
| 274 | .filter(|attachment| attachment.is_card()) |
| 275 | .filter_map(|attachment| attachment.text.as_deref()) |
| 276 | { |
| 277 | if !spans.is_empty() { |
| 278 | spans.push(Span::LineBreak); |
| 279 | } |
| 280 | for (index, line) in card_text.lines().enumerate() { |
| 281 | if index > 0 { |
| 282 | spans.push(Span::LineBreak); |
| 283 | } |
| 284 | spans.push(Span::Text(line.to_owned())); |
| 285 | } |
| 286 | } |
| 287 | spans |
| 288 | } |
| 289 | |
| 290 | #[cfg(test)] |
| 291 | mod tests { |
| 292 | use chrono::Utc; |
| 293 | |
| 294 | use super::*; |
| 295 | |
| 296 | fn record(body_html: &str, attachments_json: &str) -> MessageRecord { |
| 297 | MessageRecord { |
| 298 | conversation_id: "c".to_owned(), |
| 299 | message_id: "m".to_owned(), |
| 300 | reply_to_id: None, |
| 301 | sender_id: Some("u".to_owned()), |
| 302 | sender_name: None, |
| 303 | created_at: Utc::now(), |
| 304 | edited_at: None, |
| 305 | deleted: false, |
| 306 | body_html: body_html.to_owned(), |
| 307 | attachments_json: attachments_json.to_owned(), |
| 308 | reactions_json: "[]".to_owned(), |
| 309 | mentions_json: "[]".to_owned(), |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | #[test] |
| 314 | fn images_cover_hosted_contents_and_ams_and_skip_emoji() { |
| 315 | let html = concat!( |
| 316 | r#"<p>a</p><img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value" style="width:300px; height: 120px">"#, |
| 317 | r#"<img itemtype="http://schema.skype.com/AMSImage" src="https://eu-api.asm.skype.com/v1/objects/0-weu-d1-abc/views/imgo" width="64" height="auto">"#, |
| 318 | r#"<img itemtype="http://schema.skype.com/Emoji" src="https://x/e.png" alt="x">"#, |
| 319 | r#"<img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value">"#, |
| 320 | ); |
| 321 | let found = images(&record(html, "[]")); |
| 322 | assert_eq!(found.len(), 2); |
| 323 | assert_eq!( |
| 324 | (found[0].id.as_str(), found[0].width, found[0].height), |
| 325 | ("aWQ9", Some(300), Some(120)) |
| 326 | ); |
| 327 | assert_eq!( |
| 328 | (found[1].id.as_str(), found[1].width, found[1].height), |
| 329 | ("0-weu-d1-abc", Some(64), None) |
| 330 | ); |
| 331 | } |
| 332 | |
| 333 | #[test] |
| 334 | fn deleted_messages_have_no_images() { |
| 335 | let mut deleted = record(r#"<img src="https://x/y">"#, "[]"); |
| 336 | deleted.deleted = true; |
| 337 | assert!(images(&deleted).is_empty()); |
| 338 | } |
| 339 | |
| 340 | #[test] |
| 341 | fn file_kind_follows_the_extension_then_the_content_type() { |
| 342 | let kind = |name: Option<&str>, content_type: &str| { |
| 343 | AttachmentInfo { |
| 344 | content_type: Some(content_type.to_owned()), |
| 345 | name: name.map(str::to_owned), |
| 346 | url: None, |
| 347 | text: None, |
| 348 | size: None, |
| 349 | quote: None, |
| 350 | } |
| 351 | .file_kind() |
| 352 | }; |
| 353 | assert_eq!(kind(Some("Plan.DOCX"), "reference"), FileKind::Word); |
| 354 | assert_eq!(kind(Some("a.xlsx"), "reference"), FileKind::Excel); |
| 355 | assert_eq!(kind(Some("a.pptx"), "reference"), FileKind::PowerPoint); |
| 356 | assert_eq!(kind(Some("a.pdf"), "reference"), FileKind::Pdf); |
| 357 | assert_eq!(kind(Some("a.PNG"), "reference"), FileKind::Image); |
| 358 | assert_eq!(kind(Some("a.zip"), "reference"), FileKind::Archive); |
| 359 | assert_eq!(kind(Some("a.bin"), "reference"), FileKind::Other); |
| 360 | assert_eq!(kind(None, "image/png"), FileKind::Image); |
| 361 | assert_eq!(kind(Some("noextension"), "reference"), FileKind::Other); |
| 362 | } |
| 363 | |
| 364 | #[test] |
| 365 | fn files_expose_name_kind_and_open_url() { |
| 366 | let json = r#"[{"content_type":"reference","name":"Plan.docx","url":"https://x/Plan.docx","text":null},{"content_type":"messageReference","name":null,"url":null,"text":null}]"#; |
| 367 | let found = files(&record("", json)); |
| 368 | assert_eq!(found.len(), 1); |
| 369 | assert_eq!( |
| 370 | (found[0].name.as_str(), found[0].kind), |
| 371 | ("Plan.docx", FileKind::Word) |
| 372 | ); |
| 373 | assert_eq!(found[0].open_url, "https://x/Plan.docx"); |
| 374 | assert_eq!(found[0].size, None); |
| 375 | } |
| 376 | |
| 377 | #[test] |
| 378 | fn copy_text_flattens_markup_and_keeps_mentions_and_lines() { |
| 379 | let html = r#"<p>Hi <at id="0">Ada</at>, <b>look</b></p><p>second <a href="https://x">link</a></p>"#; |
| 380 | let text = copy_text(&record(html, "[]")); |
| 381 | assert!(text.starts_with("Hi @Ada, look"), "{text}"); |
| 382 | assert!(text.contains("second link"), "{text}"); |
| 383 | assert!(text.contains('\n')); |
| 384 | } |
| 385 | |
| 386 | #[test] |
| 387 | fn old_cached_attachments_still_parse() { |
| 388 | let parsed = attachments(&record( |
| 389 | "", |
| 390 | r#"[{"content_type":"reference","name":"a.pdf","url":"u","text":null}]"#, |
| 391 | )); |
| 392 | assert_eq!(parsed.len(), 1); |
| 393 | assert!(parsed[0].is_file()); |
| 394 | assert_eq!(parsed[0].size, None); |
| 395 | } |
| 396 | |
| 397 | #[test] |
| 398 | fn quote_references_are_extracted_from_the_message_reference_attachment() { |
| 399 | let attachment = graph::Attachment { |
| 400 | id: Some("1".to_owned()), |
| 401 | content_type: Some("messageReference".to_owned()), |
| 402 | content_url: None, |
| 403 | name: None, |
| 404 | content: Some( |
| 405 | r#"{"messageId":"1728","messagePreview":"Hello","messageSender":{"user":{"displayName":"Adele"}}}"#.to_owned(), |
| 406 | ), |
| 407 | }; |
| 408 | let info = crate::mapping::attachment_info(&attachment); |
| 409 | assert_eq!( |
| 410 | info.quote, |
| 411 | Some(QuoteInfo { |
| 412 | message_id: "1728".to_owned(), |
| 413 | preview: "Hello".to_owned(), |
| 414 | sender_name: Some("Adele".to_owned()) |
| 415 | }) |
| 416 | ); |
| 417 | let stored = record("", &serde_json::to_string(&[info]).unwrap()); |
| 418 | assert_eq!(quotes(&stored).len(), 1); |
| 419 | } |
| 420 | } |