| 1 | use chrono::{DateTime, Utc}; |
| 2 | use scraper::{ElementRef, Html}; |
| 3 | use serde::{Deserialize, Serialize}; |
| 4 | use store::MessageRecord; |
| 5 | |
| 6 | use crate::adaptive_card::{AdaptiveCard, card_content_text}; |
| 7 | use crate::markdown::escape_html; |
| 8 | use crate::mentions::MentionInput; |
| 9 | use crate::spans::{Span, html_to_spans}; |
| 10 | |
| 11 | const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji"; |
| 12 | const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply"; |
| 13 | |
| 14 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 15 | pub struct AttachmentInfo { |
| 16 | pub content_type: Option<String>, |
| 17 | pub name: Option<String>, |
| 18 | pub url: Option<String>, |
| 19 | pub text: Option<String>, |
| 20 | #[serde(default)] |
| 21 | pub size: Option<u64>, |
| 22 | #[serde(default)] |
| 23 | pub quote: Option<QuoteInfo>, |
| 24 | #[serde(default)] |
| 25 | pub id: Option<String>, |
| 26 | /// Raw content, kept only for quotes and cards so an edit can send them back unchanged. |
| 27 | #[serde(default)] |
| 28 | pub content: Option<String>, |
| 29 | } |
| 30 | |
| 31 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 32 | pub enum FileKind { |
| 33 | Word, |
| 34 | Excel, |
| 35 | PowerPoint, |
| 36 | Pdf, |
| 37 | Image, |
| 38 | Archive, |
| 39 | Other, |
| 40 | } |
| 41 | |
| 42 | impl FileKind { |
| 43 | pub fn from_name(name: &str) -> FileKind { |
| 44 | let Some((_, extension)) = name.rsplit_once('.') else { |
| 45 | return FileKind::Other; |
| 46 | }; |
| 47 | match extension.to_ascii_lowercase().as_str() { |
| 48 | "doc" | "docx" | "docm" | "dot" | "dotx" | "rtf" | "odt" => FileKind::Word, |
| 49 | "xls" | "xlsx" | "xlsm" | "xlsb" | "csv" | "ods" => FileKind::Excel, |
| 50 | "ppt" | "pptx" | "pptm" | "pps" | "ppsx" | "odp" => FileKind::PowerPoint, |
| 51 | "pdf" => FileKind::Pdf, |
| 52 | "png" | "jpg" | "jpeg" | "gif" | "bmp" | "webp" | "svg" | "heic" | "tif" | "tiff" => { |
| 53 | FileKind::Image |
| 54 | } |
| 55 | "zip" | "rar" | "7z" | "tar" | "gz" | "tgz" => FileKind::Archive, |
| 56 | _ => FileKind::Other, |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 62 | pub struct QuoteInfo { |
| 63 | pub message_id: String, |
| 64 | pub preview: String, |
| 65 | pub sender_name: Option<String>, |
| 66 | } |
| 67 | |
| 68 | /// Image inside a message body. `key()` is the image cache key. |
| 69 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 70 | pub struct ImageRef { |
| 71 | pub id: String, |
| 72 | pub url: String, |
| 73 | pub width: Option<u32>, |
| 74 | pub height: Option<u32>, |
| 75 | } |
| 76 | |
| 77 | impl ImageRef { |
| 78 | pub fn key(&self) -> &str { |
| 79 | &self.url |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | impl AttachmentInfo { |
| 84 | pub fn is_card(&self) -> bool { |
| 85 | self.content_type |
| 86 | .as_deref() |
| 87 | .is_some_and(|content_type| content_type.contains("card")) |
| 88 | } |
| 89 | |
| 90 | pub fn adaptive_card(&self) -> Option<AdaptiveCard> { |
| 91 | self.content |
| 92 | .as_deref() |
| 93 | .filter(|_| self.is_card()) |
| 94 | .and_then(AdaptiveCard::parse) |
| 95 | } |
| 96 | |
| 97 | pub fn card_text(&self) -> Option<String> { |
| 98 | let content = self.content.as_deref().filter(|_| self.is_card())?; |
| 99 | card_content_text(content).or_else(|| self.text.clone()) |
| 100 | } |
| 101 | |
| 102 | pub fn file_kind(&self) -> FileKind { |
| 103 | match self.name.as_deref().map(FileKind::from_name) { |
| 104 | Some(FileKind::Other) | None if self.has_image_content_type() => FileKind::Image, |
| 105 | Some(kind) => kind, |
| 106 | None => FileKind::Other, |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | fn has_image_content_type(&self) -> bool { |
| 111 | self.content_type |
| 112 | .as_deref() |
| 113 | .is_some_and(|content_type| content_type.starts_with("image/")) |
| 114 | } |
| 115 | |
| 116 | pub fn is_file(&self) -> bool { |
| 117 | self.content_type.as_deref() == Some("reference") && self.url.is_some() |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 122 | pub struct ReactionInfo { |
| 123 | pub reaction_type: String, |
| 124 | pub user_id: Option<String>, |
| 125 | pub user_name: Option<String>, |
| 126 | #[serde(default)] |
| 127 | pub created_at: Option<DateTime<Utc>>, |
| 128 | } |
| 129 | |
| 130 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 131 | pub struct MentionInfo { |
| 132 | pub user_id: Option<String>, |
| 133 | pub name: String, |
| 134 | #[serde(default)] |
| 135 | pub id: Option<i64>, |
| 136 | #[serde(default)] |
| 137 | pub target_id: Option<String>, |
| 138 | #[serde(default)] |
| 139 | pub group: bool, |
| 140 | } |
| 141 | |
| 142 | pub fn attachments(record: &MessageRecord) -> Vec<AttachmentInfo> { |
| 143 | serde_json::from_str(&record.attachments_json).unwrap_or_default() |
| 144 | } |
| 145 | |
| 146 | pub fn adaptive_cards(record: &MessageRecord) -> Vec<AdaptiveCard> { |
| 147 | attachments(record) |
| 148 | .iter() |
| 149 | .filter_map(AttachmentInfo::adaptive_card) |
| 150 | .collect() |
| 151 | } |
| 152 | |
| 153 | pub fn card_texts(record: &MessageRecord) -> Vec<String> { |
| 154 | attachments(record) |
| 155 | .iter() |
| 156 | .filter_map(AttachmentInfo::card_text) |
| 157 | .collect() |
| 158 | } |
| 159 | |
| 160 | pub fn reactions(record: &MessageRecord) -> Vec<ReactionInfo> { |
| 161 | serde_json::from_str(&record.reactions_json).unwrap_or_default() |
| 162 | } |
| 163 | |
| 164 | pub fn mentions(record: &MessageRecord) -> Vec<MentionInfo> { |
| 165 | let mut infos: Vec<MentionInfo> = |
| 166 | serde_json::from_str(&record.mentions_json).unwrap_or_default(); |
| 167 | for (index, info) in infos.iter_mut().enumerate() { |
| 168 | info.id = info.id.or(i64::try_from(index).ok()); |
| 169 | info.target_id = info.target_id.take().or_else(|| info.user_id.clone()); |
| 170 | } |
| 171 | infos |
| 172 | } |
| 173 | |
| 174 | pub fn quotes(record: &MessageRecord) -> Vec<QuoteInfo> { |
| 175 | attachments(record) |
| 176 | .into_iter() |
| 177 | .filter_map(|attachment| attachment.quote) |
| 178 | .collect() |
| 179 | } |
| 180 | |
| 181 | pub fn images(record: &MessageRecord) -> Vec<ImageRef> { |
| 182 | if record.deleted { |
| 183 | return Vec::new(); |
| 184 | } |
| 185 | let fragment = Html::parse_fragment(&record.body_html); |
| 186 | let mut found: Vec<ImageRef> = Vec::new(); |
| 187 | for element in fragment |
| 188 | .root_element() |
| 189 | .descendants() |
| 190 | .filter_map(ElementRef::wrap) |
| 191 | { |
| 192 | let value = element.value(); |
| 193 | let is_emoji = value |
| 194 | .attr("itemtype") |
| 195 | .is_some_and(|itemtype| itemtype.contains(EMOJI_ITEMTYPE)); |
| 196 | let Some(url) = value |
| 197 | .attr("src") |
| 198 | .filter(|url| value.name() == "img" && !is_emoji && !url.is_empty()) |
| 199 | else { |
| 200 | continue; |
| 201 | }; |
| 202 | if found.iter().any(|image| image.url == url) { |
| 203 | continue; |
| 204 | } |
| 205 | let style = value.attr("style").unwrap_or_default(); |
| 206 | found.push(ImageRef { |
| 207 | id: image_id(url), |
| 208 | url: url.to_owned(), |
| 209 | width: dimension(value.attr("width"), style, "width"), |
| 210 | height: dimension(value.attr("height"), style, "height"), |
| 211 | }); |
| 212 | } |
| 213 | found |
| 214 | } |
| 215 | |
| 216 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 217 | pub struct EditPreserved { |
| 218 | pub images_html: String, |
| 219 | pub files: Vec<graph::FileReference>, |
| 220 | pub kept: Vec<graph::KeptAttachment>, |
| 221 | } |
| 222 | |
| 223 | /// What an edit must carry over: the `<img>` elements, the file attachments and the quote or card attachments, each matched to its `<attachment id>` tag. |
| 224 | pub fn edit_preserved(record: &MessageRecord) -> EditPreserved { |
| 225 | let fragment = Html::parse_fragment(&record.body_html); |
| 226 | let mut preserved = EditPreserved::default(); |
| 227 | let mut tag_ids: Vec<&str> = Vec::new(); |
| 228 | for element in fragment |
| 229 | .root_element() |
| 230 | .descendants() |
| 231 | .filter_map(ElementRef::wrap) |
| 232 | { |
| 233 | let value = element.value(); |
| 234 | let is_emoji = value |
| 235 | .attr("itemtype") |
| 236 | .is_some_and(|itemtype| itemtype.contains(EMOJI_ITEMTYPE)); |
| 237 | match value.name() { |
| 238 | "img" if !is_emoji && value.attr("src").is_some_and(|src| !src.is_empty()) => { |
| 239 | preserved |
| 240 | .images_html |
| 241 | .push_str(&format!("<p>{}</p>", element.html())); |
| 242 | } |
| 243 | "attachment" => tag_ids.extend(value.attr("id")), |
| 244 | _ => {} |
| 245 | } |
| 246 | } |
| 247 | let stored = attachments(record); |
| 248 | let attachment_id = |attachment: &AttachmentInfo| { |
| 249 | attachment.id.clone().or_else(|| { |
| 250 | attachment |
| 251 | .quote |
| 252 | .as_ref() |
| 253 | .map(|quote| quote.message_id.clone()) |
| 254 | }) |
| 255 | }; |
| 256 | let mut unclaimed: Vec<&str> = tag_ids |
| 257 | .iter() |
| 258 | .copied() |
| 259 | .filter(|id| { |
| 260 | !stored.iter().any(|attachment| { |
| 261 | !attachment.is_file() && attachment_id(attachment).as_deref() == Some(*id) |
| 262 | }) |
| 263 | }) |
| 264 | .collect(); |
| 265 | for attachment in stored { |
| 266 | if attachment.is_file() { |
| 267 | let id = match attachment_id(&attachment) { |
| 268 | Some(id) if tag_ids.contains(&id.as_str()) => id, |
| 269 | Some(_) => continue, |
| 270 | None if unclaimed.is_empty() => continue, |
| 271 | None => unclaimed.remove(0).to_owned(), |
| 272 | }; |
| 273 | if let Some(content_url) = attachment.url { |
| 274 | preserved.files.push(graph::FileReference { |
| 275 | attachment_id: id, |
| 276 | content_url, |
| 277 | name: attachment.name.unwrap_or_default(), |
| 278 | }); |
| 279 | } |
| 280 | } else if let Some(id) = attachment_id(&attachment) |
| 281 | && tag_ids.contains(&id.as_str()) |
| 282 | && attachment.content.is_some() |
| 283 | { |
| 284 | preserved.kept.push(graph::KeptAttachment { |
| 285 | id, |
| 286 | content_type: attachment.content_type, |
| 287 | content: attachment.content, |
| 288 | content_url: attachment.url, |
| 289 | name: attachment.name, |
| 290 | }); |
| 291 | } |
| 292 | } |
| 293 | preserved |
| 294 | } |
| 295 | |
| 296 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 297 | pub struct FileCard { |
| 298 | pub name: String, |
| 299 | pub kind: FileKind, |
| 300 | pub content_type: Option<String>, |
| 301 | pub size: Option<u64>, |
| 302 | pub open_url: String, |
| 303 | } |
| 304 | |
| 305 | /// File attachments (`reference` type) with a name and a URL. `size` is rarely known; Graph does not send it for these. |
| 306 | pub fn files(record: &MessageRecord) -> Vec<FileCard> { |
| 307 | attachments(record) |
| 308 | .into_iter() |
| 309 | .filter(AttachmentInfo::is_file) |
| 310 | .map(|attachment| FileCard { |
| 311 | kind: attachment.file_kind(), |
| 312 | name: attachment.name.clone().unwrap_or_default(), |
| 313 | content_type: attachment.content_type.clone(), |
| 314 | size: attachment.size, |
| 315 | open_url: attachment.url.clone().unwrap_or_default(), |
| 316 | }) |
| 317 | .collect() |
| 318 | } |
| 319 | |
| 320 | /// Text for the clipboard: body and card text, mentions as `@name`, no markup. |
| 321 | pub fn copy_text(record: &MessageRecord) -> String { |
| 322 | let mut text = String::new(); |
| 323 | push_plain(&mut text, &message_spans(record)); |
| 324 | for card_text in card_texts(record) { |
| 325 | text.push('\n'); |
| 326 | text.push_str(&card_text); |
| 327 | } |
| 328 | text.trim().to_owned() |
| 329 | } |
| 330 | |
| 331 | pub(crate) fn push_plain(text: &mut String, spans: &[Span]) { |
| 332 | for span in spans { |
| 333 | match span { |
| 334 | Span::Text(value) | Span::Code(value) => text.push_str(value), |
| 335 | Span::CodeBlock { code, .. } => { |
| 336 | text.push_str(code); |
| 337 | text.push('\n'); |
| 338 | } |
| 339 | Span::Bold(children) |
| 340 | | Span::Italic(children) |
| 341 | | Span::Strike(children) |
| 342 | | Span::Underline(children) |
| 343 | | Span::Colored { children, .. } |
| 344 | | Span::Quote(children) |
| 345 | | Span::BlockQuote(children) |
| 346 | | Span::Link { children, .. } => push_plain(text, children), |
| 347 | Span::Heading { children, .. } => { |
| 348 | push_plain(text, children); |
| 349 | text.push('\n'); |
| 350 | } |
| 351 | Span::Mention { name, .. } => { |
| 352 | text.push('@'); |
| 353 | text.push_str(name); |
| 354 | } |
| 355 | Span::LineBreak | Span::Rule => text.push('\n'), |
| 356 | Span::List { |
| 357 | ordered, |
| 358 | start, |
| 359 | items, |
| 360 | } => { |
| 361 | for (offset, item) in items.iter().enumerate() { |
| 362 | if *ordered { |
| 363 | text.push_str(&format!("{}. ", *start as usize + offset)); |
| 364 | } else { |
| 365 | text.push_str("- "); |
| 366 | } |
| 367 | push_plain(text, item); |
| 368 | text.push('\n'); |
| 369 | } |
| 370 | } |
| 371 | Span::Table { rows, .. } => { |
| 372 | for row in rows { |
| 373 | for (index, cell) in row.iter().enumerate() { |
| 374 | if index > 0 { |
| 375 | text.push('\t'); |
| 376 | } |
| 377 | push_plain(text, cell); |
| 378 | } |
| 379 | text.push('\n'); |
| 380 | } |
| 381 | } |
| 382 | Span::Image { .. } => {} |
| 383 | } |
| 384 | } |
| 385 | } |
| 386 | |
| 387 | /// Own, not deleted. Whether the conversation supports the write is the engine's call. |
| 388 | pub fn can_edit(record: &MessageRecord, my_user_id: &str) -> bool { |
| 389 | !record.deleted && record.sender_id.as_deref() == Some(my_user_id) |
| 390 | } |
| 391 | |
| 392 | pub fn can_delete(record: &MessageRecord, my_user_id: &str) -> bool { |
| 393 | can_edit(record, my_user_id) |
| 394 | } |
| 395 | |
| 396 | fn image_id(url: &str) -> String { |
| 397 | let path = url.split(['?', '#']).next().unwrap_or(url); |
| 398 | let segments: Vec<&str> = path |
| 399 | .split('/') |
| 400 | .filter(|segment| !segment.is_empty()) |
| 401 | .collect(); |
| 402 | segments |
| 403 | .iter() |
| 404 | .position(|segment| matches!(*segment, "hostedContents" | "objects")) |
| 405 | .and_then(|index| segments.get(index + 1)) |
| 406 | .or(segments.last()) |
| 407 | .map_or_else(String::new, |segment| (*segment).to_owned()) |
| 408 | } |
| 409 | |
| 410 | fn dimension(attribute: Option<&str>, style: &str, property: &str) -> Option<u32> { |
| 411 | let from_style = || { |
| 412 | style.split(';').find_map(|declaration| { |
| 413 | let (name, value) = declaration.split_once(':')?; |
| 414 | (name.trim() == property).then(|| leading_number(value))? |
| 415 | }) |
| 416 | }; |
| 417 | attribute |
| 418 | .and_then(leading_number) |
| 419 | .or_else(from_style) |
| 420 | .filter(|pixels| *pixels > 0) |
| 421 | } |
| 422 | |
| 423 | fn leading_number(text: &str) -> Option<u32> { |
| 424 | let digits: String = text |
| 425 | .trim() |
| 426 | .chars() |
| 427 | .take_while(char::is_ascii_digit) |
| 428 | .collect(); |
| 429 | digits.parse().ok() |
| 430 | } |
| 431 | |
| 432 | pub fn message_spans(record: &MessageRecord) -> Vec<Span> { |
| 433 | spans_with_mentions(record, &mentions(record)) |
| 434 | } |
| 435 | |
| 436 | fn spans_with_mentions(record: &MessageRecord, infos: &[MentionInfo]) -> Vec<Span> { |
| 437 | let mut spans = html_to_spans(&with_inline_quotes(record)); |
| 438 | merge_split_mentions(&mut spans, infos); |
| 439 | spans |
| 440 | } |
| 441 | |
| 442 | fn with_inline_quotes(record: &MessageRecord) -> String { |
| 443 | let mut html = record.body_html.clone(); |
| 444 | for attachment in attachments(record) { |
| 445 | let Some(quote) = attachment.quote else { |
| 446 | continue; |
| 447 | }; |
| 448 | let id = attachment.id.unwrap_or_else(|| quote.message_id.clone()); |
| 449 | let tag = format!("<attachment id=\"{id}\"></attachment>"); |
| 450 | let block = quote_html("e); |
| 451 | if html.contains(&tag) { |
| 452 | html = html.replacen(&tag, &block, 1); |
| 453 | } else { |
| 454 | html.insert_str(0, &block); |
| 455 | } |
| 456 | } |
| 457 | html |
| 458 | } |
| 459 | |
| 460 | fn quote_html(quote: &QuoteInfo) -> String { |
| 461 | let sender = quote |
| 462 | .sender_name |
| 463 | .as_deref() |
| 464 | .map(|name| format!("<strong itemprop=\"mri\">{}</strong>", escape_html(name))) |
| 465 | .unwrap_or_default(); |
| 466 | format!( |
| 467 | "<blockquote itemscope=\"\" itemtype=\"http://{REPLY_ITEMTYPE}\" itemid=\"{}\">{sender}<p itemprop=\"preview\">{}</p></blockquote>", |
| 468 | escape_html("e.message_id), |
| 469 | escape_html("e.preview), |
| 470 | ) |
| 471 | } |
| 472 | |
| 473 | pub fn user_mention_inputs(record: &MessageRecord) -> Vec<MentionInput> { |
| 474 | let infos = mentions(record); |
| 475 | let mut inputs = Vec::new(); |
| 476 | collect_user_mentions(&spans_with_mentions(record, &infos), &infos, &mut inputs); |
| 477 | inputs |
| 478 | } |
| 479 | |
| 480 | fn collect_user_mentions(spans: &[Span], infos: &[MentionInfo], inputs: &mut Vec<MentionInput>) { |
| 481 | for span in spans { |
| 482 | match span { |
| 483 | Span::Bold(children) |
| 484 | | Span::Italic(children) |
| 485 | | Span::Strike(children) |
| 486 | | Span::Underline(children) |
| 487 | | Span::Colored { children, .. } |
| 488 | | Span::Heading { children, .. } |
| 489 | | Span::Quote(children) |
| 490 | | Span::BlockQuote(children) |
| 491 | | Span::Link { children, .. } => collect_user_mentions(children, infos, inputs), |
| 492 | Span::List { items, .. } => items |
| 493 | .iter() |
| 494 | .for_each(|item| collect_user_mentions(item, infos, inputs)), |
| 495 | Span::Table { rows, .. } => rows |
| 496 | .iter() |
| 497 | .flatten() |
| 498 | .for_each(|cell| collect_user_mentions(cell, infos, inputs)), |
| 499 | Span::Mention { name, id } => { |
| 500 | let parsed: Option<i64> = id.as_deref().and_then(|id| id.parse().ok()); |
| 501 | let user_id = infos |
| 502 | .iter() |
| 503 | .find(|info| parsed.is_some() && info.id == parsed) |
| 504 | .and_then(|info| info.user_id.as_deref()); |
| 505 | if let Some(user_id) = user_id { |
| 506 | inputs.push(MentionInput::user(user_id, name)); |
| 507 | } |
| 508 | } |
| 509 | _ => {} |
| 510 | } |
| 511 | } |
| 512 | } |
| 513 | |
| 514 | fn merge_split_mentions(spans: &mut Vec<Span>, mentions: &[MentionInfo]) { |
| 515 | let target_of = |id: &Option<String>| -> Option<String> { |
| 516 | let parsed: i64 = id.as_deref()?.parse().ok()?; |
| 517 | mentions |
| 518 | .iter() |
| 519 | .find(|info| info.id == Some(parsed))? |
| 520 | .target_id |
| 521 | .clone() |
| 522 | }; |
| 523 | let mut merged: Vec<Span> = Vec::with_capacity(spans.len()); |
| 524 | for mut span in std::mem::take(spans) { |
| 525 | match &mut span { |
| 526 | Span::Bold(children) |
| 527 | | Span::Italic(children) |
| 528 | | Span::Strike(children) |
| 529 | | Span::Underline(children) |
| 530 | | Span::Colored { children, .. } |
| 531 | | Span::Heading { children, .. } |
| 532 | | Span::Quote(children) |
| 533 | | Span::BlockQuote(children) |
| 534 | | Span::Link { children, .. } => merge_split_mentions(children, mentions), |
| 535 | Span::List { items, .. } => items |
| 536 | .iter_mut() |
| 537 | .for_each(|item| merge_split_mentions(item, mentions)), |
| 538 | Span::Table { rows, .. } => rows |
| 539 | .iter_mut() |
| 540 | .flatten() |
| 541 | .for_each(|cell| merge_split_mentions(cell, mentions)), |
| 542 | Span::Mention { name, id } => { |
| 543 | let continues = match merged.as_slice() { |
| 544 | [ |
| 545 | .., |
| 546 | Span::Mention { |
| 547 | id: previous_id, .. |
| 548 | }, |
| 549 | Span::Text(gap), |
| 550 | ] => { |
| 551 | gap.trim().is_empty() |
| 552 | && target_of(id).is_some() |
| 553 | && target_of(previous_id) == target_of(id) |
| 554 | } |
| 555 | _ => false, |
| 556 | }; |
| 557 | if continues { |
| 558 | merged.pop(); |
| 559 | if let Some(Span::Mention { |
| 560 | name: previous_name, |
| 561 | .. |
| 562 | }) = merged.last_mut() |
| 563 | { |
| 564 | previous_name.push(' '); |
| 565 | previous_name.push_str(name); |
| 566 | } |
| 567 | continue; |
| 568 | } |
| 569 | } |
| 570 | _ => {} |
| 571 | } |
| 572 | merged.push(span); |
| 573 | } |
| 574 | *spans = merged; |
| 575 | } |
| 576 | |
| 577 | #[cfg(test)] |
| 578 | mod tests { |
| 579 | use chrono::Utc; |
| 580 | |
| 581 | use super::*; |
| 582 | |
| 583 | fn record(body_html: &str, attachments_json: &str) -> MessageRecord { |
| 584 | MessageRecord { |
| 585 | conversation_id: "c".to_owned(), |
| 586 | message_id: "m".to_owned(), |
| 587 | reply_to_id: None, |
| 588 | sender_id: Some("u".to_owned()), |
| 589 | sender_name: None, |
| 590 | sender_application_id: None, |
| 591 | created_at: Utc::now(), |
| 592 | edited_at: None, |
| 593 | deleted: false, |
| 594 | body_html: body_html.to_owned(), |
| 595 | attachments_json: attachments_json.to_owned(), |
| 596 | reactions_json: "[]".to_owned(), |
| 597 | mentions_json: "[]".to_owned(), |
| 598 | } |
| 599 | } |
| 600 | |
| 601 | #[test] |
| 602 | fn reaction_without_created_at_still_parses() { |
| 603 | let mut stored = record("", "[]"); |
| 604 | stored.reactions_json = |
| 605 | r#"[{"reaction_type":"like","user_id":"u","user_name":null}]"#.to_owned(); |
| 606 | let parsed = reactions(&stored); |
| 607 | assert_eq!(parsed.len(), 1); |
| 608 | assert_eq!(parsed[0].created_at, None); |
| 609 | } |
| 610 | |
| 611 | #[test] |
| 612 | fn images_cover_hosted_contents_and_ams_and_skip_emoji() { |
| 613 | let html = concat!( |
| 614 | r#"<p>a</p><img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value" style="width:300px; height: 120px">"#, |
| 615 | 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">"#, |
| 616 | r#"<img itemtype="http://schema.skype.com/Emoji" src="https://x/e.png" alt="x">"#, |
| 617 | r#"<img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value">"#, |
| 618 | ); |
| 619 | let found = images(&record(html, "[]")); |
| 620 | assert_eq!(found.len(), 2); |
| 621 | assert_eq!( |
| 622 | (found[0].id.as_str(), found[0].width, found[0].height), |
| 623 | ("aWQ9", Some(300), Some(120)) |
| 624 | ); |
| 625 | assert_eq!( |
| 626 | (found[1].id.as_str(), found[1].width, found[1].height), |
| 627 | ("0-weu-d1-abc", Some(64), None) |
| 628 | ); |
| 629 | } |
| 630 | |
| 631 | #[test] |
| 632 | fn deleted_messages_have_no_images() { |
| 633 | let mut deleted = record(r#"<img src="https://x/y">"#, "[]"); |
| 634 | deleted.deleted = true; |
| 635 | assert!(images(&deleted).is_empty()); |
| 636 | } |
| 637 | |
| 638 | #[test] |
| 639 | fn edits_keep_images_and_match_files_to_their_attachment_tags() { |
| 640 | let html = "<p>text</p><p><img src=\"https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/9/$value\"></p><attachment id=\"G1\"></attachment>"; |
| 641 | let attachments = r#"[{"content_type":"reference","name":"a.pdf","url":"https://x/a.pdf","text":null,"id":"G1"}]"#; |
| 642 | let preserved = edit_preserved(&record(html, attachments)); |
| 643 | assert!( |
| 644 | preserved |
| 645 | .images_html |
| 646 | .starts_with("<p><img src=\"https://graph.microsoft.com/") |
| 647 | ); |
| 648 | assert!(!preserved.images_html.contains("text")); |
| 649 | assert_eq!(preserved.files.len(), 1); |
| 650 | assert_eq!(preserved.files[0].attachment_id, "G1"); |
| 651 | assert_eq!(preserved.files[0].content_url, "https://x/a.pdf"); |
| 652 | assert_eq!(preserved.files[0].name, "a.pdf"); |
| 653 | assert!(preserved.kept.is_empty()); |
| 654 | } |
| 655 | |
| 656 | const QUOTED_HTML: &str = |
| 657 | "<attachment id=\"Q1\"></attachment><p>answer</p><attachment id=\"F1\"></attachment>"; |
| 658 | |
| 659 | #[test] |
| 660 | fn a_quoted_reply_keeps_its_quote_and_pairs_the_file_by_id() { |
| 661 | let attachments = r#"[ |
| 662 | {"content_type":"messageReference","name":null,"url":null,"text":null,"id":"Q1","content":"{\"messageId\":\"Q1\",\"messagePreview\":\"hi\"}","quote":{"message_id":"Q1","preview":"hi","sender_name":null}}, |
| 663 | {"content_type":"reference","name":"a.pdf","url":"https://x/a.pdf","text":null,"id":"F1"} |
| 664 | ]"#; |
| 665 | let preserved = edit_preserved(&record(QUOTED_HTML, attachments)); |
| 666 | assert_eq!(preserved.files.len(), 1); |
| 667 | assert_eq!(preserved.files[0].attachment_id, "F1"); |
| 668 | assert_eq!(preserved.kept.len(), 1); |
| 669 | assert_eq!(preserved.kept[0].id, "Q1"); |
| 670 | assert_eq!( |
| 671 | preserved.kept[0].content_type.as_deref(), |
| 672 | Some("messageReference") |
| 673 | ); |
| 674 | assert!( |
| 675 | preserved.kept[0] |
| 676 | .content |
| 677 | .as_deref() |
| 678 | .unwrap() |
| 679 | .contains("messagePreview") |
| 680 | ); |
| 681 | } |
| 682 | |
| 683 | #[test] |
| 684 | fn records_cached_before_content_was_stored_leave_the_quote_out() { |
| 685 | let attachments = r#"[ |
| 686 | {"content_type":"messageReference","name":null,"url":null,"text":null,"quote":{"message_id":"Q1","preview":"hi","sender_name":null}}, |
| 687 | {"content_type":"reference","name":"a.pdf","url":"https://x/a.pdf","text":null} |
| 688 | ]"#; |
| 689 | let preserved = edit_preserved(&record(QUOTED_HTML, attachments)); |
| 690 | assert_eq!(preserved.files[0].attachment_id, "F1"); |
| 691 | assert!(preserved.kept.is_empty()); |
| 692 | } |
| 693 | |
| 694 | #[test] |
| 695 | fn file_kind_follows_the_extension_then_the_content_type() { |
| 696 | let kind = |name: Option<&str>, content_type: &str| { |
| 697 | AttachmentInfo { |
| 698 | content_type: Some(content_type.to_owned()), |
| 699 | name: name.map(str::to_owned), |
| 700 | url: None, |
| 701 | text: None, |
| 702 | size: None, |
| 703 | quote: None, |
| 704 | id: None, |
| 705 | content: None, |
| 706 | } |
| 707 | .file_kind() |
| 708 | }; |
| 709 | assert_eq!(kind(Some("Plan.DOCX"), "reference"), FileKind::Word); |
| 710 | assert_eq!(kind(Some("a.xlsx"), "reference"), FileKind::Excel); |
| 711 | assert_eq!(kind(Some("a.pptx"), "reference"), FileKind::PowerPoint); |
| 712 | assert_eq!(kind(Some("a.pdf"), "reference"), FileKind::Pdf); |
| 713 | assert_eq!(kind(Some("a.PNG"), "reference"), FileKind::Image); |
| 714 | assert_eq!(kind(Some("a.zip"), "reference"), FileKind::Archive); |
| 715 | assert_eq!(kind(Some("a.bin"), "reference"), FileKind::Other); |
| 716 | assert_eq!(kind(None, "image/png"), FileKind::Image); |
| 717 | assert_eq!(kind(Some("noextension"), "reference"), FileKind::Other); |
| 718 | } |
| 719 | |
| 720 | #[test] |
| 721 | fn files_expose_name_kind_and_open_url() { |
| 722 | 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}]"#; |
| 723 | let found = files(&record("", json)); |
| 724 | assert_eq!(found.len(), 1); |
| 725 | assert_eq!( |
| 726 | (found[0].name.as_str(), found[0].kind), |
| 727 | ("Plan.docx", FileKind::Word) |
| 728 | ); |
| 729 | assert_eq!(found[0].open_url, "https://x/Plan.docx"); |
| 730 | assert_eq!(found[0].size, None); |
| 731 | } |
| 732 | |
| 733 | #[test] |
| 734 | fn copy_text_flattens_markup_and_keeps_mentions_and_lines() { |
| 735 | let html = r#"<p>Hi <at id="0">Ada</at>, <b>look</b></p><p>second <a href="https://x">link</a></p>"#; |
| 736 | let text = copy_text(&record(html, "[]")); |
| 737 | assert!(text.starts_with("Hi @Ada, look"), "{text}"); |
| 738 | assert!(text.contains("second link"), "{text}"); |
| 739 | assert!(text.contains('\n')); |
| 740 | } |
| 741 | |
| 742 | #[test] |
| 743 | fn old_cached_attachments_still_parse() { |
| 744 | let parsed = attachments(&record( |
| 745 | "", |
| 746 | r#"[{"content_type":"reference","name":"a.pdf","url":"u","text":null}]"#, |
| 747 | )); |
| 748 | assert_eq!(parsed.len(), 1); |
| 749 | assert!(parsed[0].is_file()); |
| 750 | assert_eq!(parsed[0].size, None); |
| 751 | } |
| 752 | |
| 753 | #[test] |
| 754 | fn quote_references_are_extracted_from_the_message_reference_attachment() { |
| 755 | let attachment = graph::Attachment { |
| 756 | id: Some("1".to_owned()), |
| 757 | content_type: Some("messageReference".to_owned()), |
| 758 | content_url: None, |
| 759 | name: None, |
| 760 | content: Some( |
| 761 | r#"{"messageId":"1728","messagePreview":"Hello","messageSender":{"user":{"displayName":"Adele"}}}"#.to_owned(), |
| 762 | ), |
| 763 | }; |
| 764 | let info = crate::mapping::attachment_info(&attachment); |
| 765 | assert_eq!( |
| 766 | info.quote, |
| 767 | Some(QuoteInfo { |
| 768 | message_id: "1728".to_owned(), |
| 769 | preview: "Hello".to_owned(), |
| 770 | sender_name: Some("Adele".to_owned()) |
| 771 | }) |
| 772 | ); |
| 773 | let stored = record("", &serde_json::to_string(&[info]).unwrap()); |
| 774 | assert_eq!(quotes(&stored).len(), 1); |
| 775 | } |
| 776 | |
| 777 | #[test] |
| 778 | fn a_message_reference_renders_as_a_reply_quote_where_its_tag_sits() { |
| 779 | let json = r#"[{"content_type":"messageReference","name":null,"url":null,"text":null,"id":"Q1","quote":{"message_id":"Q1","preview":"a < b","sender_name":"Ada"}}]"#; |
| 780 | let stored = record("<p></p><attachment id=\"Q1\"></attachment>\ntest<p></p>", json); |
| 781 | let spans = message_spans(&stored); |
| 782 | let Some(Span::Quote(children)) = spans.first() else { |
| 783 | panic!("expected a reply quote first, got {spans:?}"); |
| 784 | }; |
| 785 | let mut quoted = String::new(); |
| 786 | push_plain(&mut quoted, children); |
| 787 | assert!(quoted.contains("Ada")); |
| 788 | assert!(quoted.contains("a < b")); |
| 789 | let mut own = String::new(); |
| 790 | push_plain(&mut own, &spans[1..]); |
| 791 | assert_eq!(own.trim(), "test"); |
| 792 | } |
| 793 | |
| 794 | #[test] |
| 795 | fn a_message_reference_without_its_tag_still_shows_the_quote() { |
| 796 | let json = r#"[{"content_type":"messageReference","name":null,"url":null,"text":null,"quote":{"message_id":"Q1","preview":"hi","sender_name":null}}]"#; |
| 797 | let spans = message_spans(&record("<p>answer</p>", json)); |
| 798 | assert!(matches!(spans.first(), Some(Span::Quote(_)))); |
| 799 | } |
| 800 | |
| 801 | fn with_mentions(body_html: &str, mentions_json: &str) -> MessageRecord { |
| 802 | let mut stored = record(body_html, "[]"); |
| 803 | stored.mentions_json = mentions_json.to_owned(); |
| 804 | stored |
| 805 | } |
| 806 | |
| 807 | fn mention_names(spans: &[Span]) -> Vec<&str> { |
| 808 | spans |
| 809 | .iter() |
| 810 | .filter_map(|span| match span { |
| 811 | Span::Mention { name, .. } => Some(name.as_str()), |
| 812 | _ => None, |
| 813 | }) |
| 814 | .collect() |
| 815 | } |
| 816 | |
| 817 | #[test] |
| 818 | fn a_tag_mention_split_per_word_merges_into_one() { |
| 819 | let json = r#"[ |
| 820 | {"user_id":null,"name":"Tip","id":0,"target_id":"T1"}, |
| 821 | {"user_id":null,"name":"of","id":1,"target_id":"T1"}, |
| 822 | {"user_id":null,"name":"the","id":2,"target_id":"T1"}, |
| 823 | {"user_id":null,"name":"day","id":3,"target_id":"T1"} |
| 824 | ]"#; |
| 825 | let html = r#"<p>Hey <at id="0">Tip</at> <at id="1">of</at> <at id="2">the</at> <at id="3">day</at>!</p>"#; |
| 826 | let spans = message_spans(&with_mentions(html, json)); |
| 827 | assert_eq!(mention_names(&spans), vec!["Tip of the day"]); |
| 828 | assert_eq!( |
| 829 | copy_text(&with_mentions(html, json)), |
| 830 | "Hey @Tip of the day!" |
| 831 | ); |
| 832 | } |
| 833 | |
| 834 | #[test] |
| 835 | fn a_two_word_user_name_merges_but_different_users_stay_apart() { |
| 836 | let json = r#"[ |
| 837 | {"user_id":"U1","name":"Ada","id":0,"target_id":"U1"}, |
| 838 | {"user_id":"U1","name":"Lovelace","id":1,"target_id":"U1"}, |
| 839 | {"user_id":"U2","name":"Bob","id":2,"target_id":"U2"} |
| 840 | ]"#; |
| 841 | let html = r#"<at id="0">Ada</at> <at id="1">Lovelace</at> <at id="2">Bob</at>"#; |
| 842 | let spans = message_spans(&with_mentions(html, json)); |
| 843 | assert_eq!(mention_names(&spans), vec!["Ada Lovelace", "Bob"]); |
| 844 | } |
| 845 | |
| 846 | #[test] |
| 847 | fn different_users_next_to_each_other_stay_two_mentions() { |
| 848 | let json = r#"[ |
| 849 | {"user_id":"U1","name":"Ada","id":0,"target_id":"U1"}, |
| 850 | {"user_id":"U2","name":"Bob","id":1,"target_id":"U2"} |
| 851 | ]"#; |
| 852 | let html = r#"<at id="0">Ada</at> <at id="1">Bob</at>"#; |
| 853 | let spans = message_spans(&with_mentions(html, json)); |
| 854 | assert_eq!(mention_names(&spans), vec!["Ada", "Bob"]); |
| 855 | } |
| 856 | |
| 857 | #[test] |
| 858 | fn nested_split_mentions_merge() { |
| 859 | let json = r#"[ |
| 860 | {"user_id":"U1","name":"Ada","id":0,"target_id":"U1"}, |
| 861 | {"user_id":"U1","name":"Lovelace","id":1,"target_id":"U1"} |
| 862 | ]"#; |
| 863 | let html = r#"<b><at id="0">Ada</at> <at id="1">Lovelace</at></b>"#; |
| 864 | let spans = message_spans(&with_mentions(html, json)); |
| 865 | let [Span::Bold(children)] = spans.as_slice() else { |
| 866 | panic!("bold expected: {spans:?}") |
| 867 | }; |
| 868 | assert_eq!(mention_names(children), vec!["Ada Lovelace"]); |
| 869 | } |
| 870 | |
| 871 | #[test] |
| 872 | fn old_mention_json_without_ids_merges_users_by_position() { |
| 873 | let json = r#"[{"user_id":"U1","name":"Ada"},{"user_id":"U1","name":"Lovelace"},{"user_id":null,"name":"Tip"},{"user_id":null,"name":"day"}]"#; |
| 874 | let html = r#"<at id="0">Ada</at> <at id="1">Lovelace</at> <at id="2">Tip</at> <at id="3">day</at>"#; |
| 875 | let stored = with_mentions(html, json); |
| 876 | let parsed = mentions(&stored); |
| 877 | assert_eq!( |
| 878 | (parsed[1].id, parsed[1].target_id.as_deref()), |
| 879 | (Some(1), Some("U1")) |
| 880 | ); |
| 881 | assert_eq!( |
| 882 | mention_names(&message_spans(&stored)), |
| 883 | vec!["Ada Lovelace", "Tip", "day"] |
| 884 | ); |
| 885 | } |
| 886 | |
| 887 | #[test] |
| 888 | fn edit_mentions_follow_the_merged_names() { |
| 889 | let json = r#"[ |
| 890 | {"user_id":"U1","name":"Ada","id":0,"target_id":"U1"}, |
| 891 | {"user_id":"U1","name":"Lovelace","id":1,"target_id":"U1"}, |
| 892 | {"user_id":"U2","name":"Bob","id":2,"target_id":"U2"} |
| 893 | ]"#; |
| 894 | let html = r#"<at id="0">Ada</at> <at id="1">Lovelace</at> and <at id="2">Bob</at>"#; |
| 895 | assert_eq!( |
| 896 | user_mention_inputs(&with_mentions(html, json)), |
| 897 | vec![ |
| 898 | MentionInput::user("U1", "Ada Lovelace"), |
| 899 | MentionInput::user("U2", "Bob"), |
| 900 | ] |
| 901 | ); |
| 902 | } |
| 903 | } |