| 1 | use std::ops::Range; |
| 2 | |
| 3 | use graph::{MentionTarget, OutgoingMention}; |
| 4 | use serde::{Deserialize, Serialize}; |
| 5 | |
| 6 | use crate::draft::{Draft, LineKind, MarkKind}; |
| 7 | use crate::error::{Error, Result}; |
| 8 | use crate::markdown::escape_html; |
| 9 | |
| 10 | /// `text` is the display name exactly as it appears after the `@` in the message text. |
| 11 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 12 | pub struct MentionInput { |
| 13 | pub target: MentionTarget, |
| 14 | pub text: String, |
| 15 | } |
| 16 | |
| 17 | impl MentionInput { |
| 18 | pub fn user(user_id: &str, text: &str) -> Self { |
| 19 | MentionInput { |
| 20 | target: MentionTarget::User { |
| 21 | user_id: user_id.to_owned(), |
| 22 | }, |
| 23 | text: text.to_owned(), |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | pub fn channel(channel_id: &str, text: &str) -> Self { |
| 28 | MentionInput { |
| 29 | target: MentionTarget::Channel { |
| 30 | channel_id: channel_id.to_owned(), |
| 31 | }, |
| 32 | text: text.to_owned(), |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | pub fn team(team_id: &str, text: &str) -> Self { |
| 37 | MentionInput { |
| 38 | target: MentionTarget::Team { |
| 39 | team_id: team_id.to_owned(), |
| 40 | }, |
| 41 | text: text.to_owned(), |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | pub fn everyone(chat_id: &str, text: &str) -> Self { |
| 46 | MentionInput { |
| 47 | target: MentionTarget::Everyone { |
| 48 | chat_id: chat_id.to_owned(), |
| 49 | }, |
| 50 | text: text.to_owned(), |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | pub fn tag(tag_id: &str, text: &str) -> Self { |
| 55 | MentionInput { |
| 56 | target: MentionTarget::Tag { |
| 57 | tag_id: tag_id.to_owned(), |
| 58 | }, |
| 59 | text: text.to_owned(), |
| 60 | } |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | fn same_char(expected: char, actual: char, ignore_case: bool) -> bool { |
| 65 | expected == actual || (ignore_case && expected.to_lowercase().eq(actual.to_lowercase())) |
| 66 | } |
| 67 | |
| 68 | fn word_char(character: Option<char>) -> bool { |
| 69 | character.is_some_and(char::is_alphanumeric) |
| 70 | } |
| 71 | |
| 72 | /// An `@` opens a mention only at the start, after whitespace or after opening punctuation: not in `ops@acme.com` or `medium.com/@ada`. |
| 73 | fn opens_mention(before: Option<char>) -> bool { |
| 74 | before.is_none_or(|character| character.is_whitespace() || "([{\"'<,:;".contains(character)) |
| 75 | } |
| 76 | |
| 77 | /// Byte length of the text that spells `name`, compared character by character. |
| 78 | fn spelled_len(text: &str, name: &str, ignore_case: bool) -> Option<usize> { |
| 79 | let mut characters = text.char_indices(); |
| 80 | let mut length = 0; |
| 81 | for expected in name.chars() { |
| 82 | let (offset, actual) = characters.next()?; |
| 83 | if !same_char(expected, actual, ignore_case) { |
| 84 | return None; |
| 85 | } |
| 86 | length = offset + actual.len_utf8(); |
| 87 | } |
| 88 | (length > 0).then_some(length) |
| 89 | } |
| 90 | |
| 91 | fn in_plain_run(draft: &Draft, span: &Range<usize>) -> bool { |
| 92 | let marks_allow = draft.marks().iter().all(|mark| { |
| 93 | let touches = mark.range.start < span.end && span.start < mark.range.end; |
| 94 | !touches |
| 95 | || (!matches!(mark.kind, MarkKind::Link(_) | MarkKind::Code) |
| 96 | && mark.range.start <= span.start |
| 97 | && mark.range.end >= span.end) |
| 98 | }); |
| 99 | let in_code_block = [span.start, span.end.saturating_sub(1)] |
| 100 | .into_iter() |
| 101 | .any(|offset| { |
| 102 | matches!( |
| 103 | draft.lines().get(draft.line_at(offset)), |
| 104 | Some(LineKind::Code(_)) |
| 105 | ) |
| 106 | }); |
| 107 | marks_allow && !in_code_block |
| 108 | } |
| 109 | |
| 110 | /// Every `@name` a mention may sit on: whole word on both sides, in plain text, not in a link, code or half-formatted. |
| 111 | pub fn plain_mention_spans(draft: &Draft, name: &str, ignore_case: bool) -> Vec<Range<usize>> { |
| 112 | let text = draft.text(); |
| 113 | text.match_indices('@') |
| 114 | .filter_map(|(start, _)| { |
| 115 | let end = start + 1 + spelled_len(&text[start + 1..], name, ignore_case)?; |
| 116 | let spans_ok = opens_mention(text[..start].chars().next_back()) |
| 117 | && !word_char(text[end..].chars().next()); |
| 118 | (spans_ok && in_plain_run(draft, &(start..end))).then_some(start..end) |
| 119 | }) |
| 120 | .collect() |
| 121 | } |
| 122 | |
| 123 | struct TextChar { |
| 124 | character: char, |
| 125 | start: usize, |
| 126 | end: usize, |
| 127 | plain: bool, |
| 128 | } |
| 129 | |
| 130 | const NAMED_ENTITIES: [(&str, char); 4] = [ |
| 131 | ("&", '&'), |
| 132 | ("<", '<'), |
| 133 | (">", '>'), |
| 134 | (""", '"'), |
| 135 | ]; |
| 136 | |
| 137 | fn decode_entity(rest: &str) -> Option<(char, usize)> { |
| 138 | if let Some((entity, character)) = NAMED_ENTITIES |
| 139 | .iter() |
| 140 | .find(|(entity, _)| rest.starts_with(entity)) |
| 141 | { |
| 142 | return Some((*character, entity.len())); |
| 143 | } |
| 144 | let numeric = rest.strip_prefix("&#")?; |
| 145 | let end = numeric.bytes().take(10).position(|byte| byte == b';')?; |
| 146 | let digits = &numeric[..end]; |
| 147 | let code = match digits.strip_prefix(['x', 'X']) { |
| 148 | Some(hex) if !hex.is_empty() && hex.bytes().all(|byte| byte.is_ascii_hexdigit()) => { |
| 149 | u32::from_str_radix(hex, 16).ok()? |
| 150 | } |
| 151 | None if !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit()) => { |
| 152 | digits.parse().ok()? |
| 153 | } |
| 154 | _ => return None, |
| 155 | }; |
| 156 | Some((char::from_u32(code)?, 2 + end + 1)) |
| 157 | } |
| 158 | |
| 159 | /// The characters of the text nodes with their HTML offsets; `plain` is false inside a, code and pre. |
| 160 | fn text_characters(html: &str) -> Vec<TextChar> { |
| 161 | let mut characters = Vec::new(); |
| 162 | let mut depth = 0usize; |
| 163 | let mut offset = 0; |
| 164 | while offset < html.len() { |
| 165 | let rest = &html[offset..]; |
| 166 | if rest.starts_with('<') |
| 167 | && let Some(close) = rest.find('>') |
| 168 | { |
| 169 | let tag = rest[1..close].trim(); |
| 170 | let closing = tag.starts_with('/'); |
| 171 | let name: String = tag |
| 172 | .trim_start_matches('/') |
| 173 | .chars() |
| 174 | .take_while(|character| character.is_ascii_alphanumeric()) |
| 175 | .collect::<String>() |
| 176 | .to_ascii_lowercase(); |
| 177 | if matches!(name.as_str(), "a" | "code" | "pre") && !tag.ends_with('/') { |
| 178 | depth = if closing { |
| 179 | depth.saturating_sub(1) |
| 180 | } else { |
| 181 | depth + 1 |
| 182 | }; |
| 183 | } |
| 184 | offset += close + 1; |
| 185 | if matches!( |
| 186 | name.as_str(), |
| 187 | "br" | "p" |
| 188 | | "div" |
| 189 | | "li" |
| 190 | | "ul" |
| 191 | | "ol" |
| 192 | | "blockquote" |
| 193 | | "pre" |
| 194 | | "h1" |
| 195 | | "h2" |
| 196 | | "h3" |
| 197 | | "h4" |
| 198 | | "h5" |
| 199 | | "h6" |
| 200 | | "hr" |
| 201 | | "table" |
| 202 | | "tr" |
| 203 | | "td" |
| 204 | | "th" |
| 205 | | "figure" |
| 206 | ) { |
| 207 | characters.push(TextChar { |
| 208 | character: ' ', |
| 209 | start: offset, |
| 210 | end: offset, |
| 211 | plain: true, |
| 212 | }); |
| 213 | } |
| 214 | continue; |
| 215 | } |
| 216 | let (character, length) = decode_entity(rest).unwrap_or_else(|| { |
| 217 | let character = rest.chars().next().unwrap_or_default(); |
| 218 | (character, character.len_utf8()) |
| 219 | }); |
| 220 | characters.push(TextChar { |
| 221 | character, |
| 222 | start: offset, |
| 223 | end: offset + length, |
| 224 | plain: depth == 0, |
| 225 | }); |
| 226 | offset += length; |
| 227 | } |
| 228 | characters |
| 229 | } |
| 230 | |
| 231 | fn spelled_at(characters: &[TextChar], at: usize, name: &[char]) -> bool { |
| 232 | let Some(span) = characters.get(at..at + 1 + name.len()) else { |
| 233 | return false; |
| 234 | }; |
| 235 | span[0].character == '@' |
| 236 | && span |
| 237 | .iter() |
| 238 | .zip(std::iter::once(&'@').chain(name)) |
| 239 | .all(|(found, expected)| found.character == *expected && found.plain) |
| 240 | && span.windows(2).all(|pair| pair[0].end == pair[1].start) |
| 241 | && opens_mention(at.checked_sub(1).map(|before| characters[before].character)) |
| 242 | && !word_char( |
| 243 | characters |
| 244 | .get(at + 1 + name.len()) |
| 245 | .map(|after| after.character), |
| 246 | ) |
| 247 | } |
| 248 | |
| 249 | /// Mentions are matched in order, each at the first `@text` after the previous one that sits in a plain text run (see `plain_mention_spans`). Unmatched mentions stay plain text. |
| 250 | pub fn apply_mentions(html: &str, inputs: &[MentionInput]) -> (String, Vec<OutgoingMention>) { |
| 251 | let characters = text_characters(html); |
| 252 | let mut output = String::with_capacity(html.len()); |
| 253 | let mut outgoing = Vec::new(); |
| 254 | let mut cursor = 0; |
| 255 | let mut next_character = 0; |
| 256 | for input in inputs { |
| 257 | let name: Vec<char> = input.text.chars().collect(); |
| 258 | let Some(at) = (next_character..characters.len()) |
| 259 | .find(|at| !name.is_empty() && spelled_at(&characters, *at, &name)) |
| 260 | else { |
| 261 | continue; |
| 262 | }; |
| 263 | let last = &characters[at + name.len()]; |
| 264 | let id = outgoing.len() as u32; |
| 265 | output.push_str(&html[cursor..characters[at].start]); |
| 266 | output.push_str(&format!( |
| 267 | "<at id=\"{id}\">{}</at>", |
| 268 | escape_html(&input.text) |
| 269 | )); |
| 270 | cursor = last.end; |
| 271 | next_character = at + name.len() + 1; |
| 272 | outgoing.push(OutgoingMention { |
| 273 | id, |
| 274 | text: input.text.clone(), |
| 275 | target: input.target.clone(), |
| 276 | }); |
| 277 | } |
| 278 | output.push_str(&html[cursor..]); |
| 279 | (output, outgoing) |
| 280 | } |
| 281 | |
| 282 | pub(crate) fn ensure_allowed_in_chat(inputs: &[MentionInput]) -> Result<()> { |
| 283 | if inputs.iter().any(|input| { |
| 284 | !matches!( |
| 285 | input.target, |
| 286 | MentionTarget::User { .. } | MentionTarget::Everyone { .. } |
| 287 | ) |
| 288 | }) { |
| 289 | return Err(Error::Unsupported( |
| 290 | "a channel, team or tag mention in a chat", |
| 291 | )); |
| 292 | } |
| 293 | Ok(()) |
| 294 | } |
| 295 | |
| 296 | #[cfg(test)] |
| 297 | mod tests { |
| 298 | use super::*; |
| 299 | |
| 300 | #[test] |
| 301 | fn a_mention_right_after_a_heading_or_rule_is_still_a_mention() { |
| 302 | for html in ["<h2>Plan</h2>@Ada please", "a<hr>@Ada please"] { |
| 303 | let (_, mentions) = apply_mentions(html, &[MentionInput::user("u1", "Ada")]); |
| 304 | assert_eq!(mentions.len(), 1, "{html}"); |
| 305 | } |
| 306 | } |
| 307 | |
| 308 | #[test] |
| 309 | fn mentions_become_at_tags_with_sequential_ids() { |
| 310 | let (html, mentions) = apply_mentions( |
| 311 | "hi @Ada Example and @Bo, see @General", |
| 312 | &[ |
| 313 | MentionInput::user("u1", "Ada Example"), |
| 314 | MentionInput::user("u2", "Bo"), |
| 315 | MentionInput::channel("19:c", "General"), |
| 316 | ], |
| 317 | ); |
| 318 | assert_eq!( |
| 319 | html, |
| 320 | "hi <at id=\"0\">Ada Example</at> and <at id=\"1\">Bo</at>, see <at id=\"2\">General</at>" |
| 321 | ); |
| 322 | assert_eq!( |
| 323 | mentions |
| 324 | .iter() |
| 325 | .map(|mention| mention.id) |
| 326 | .collect::<Vec<_>>(), |
| 327 | [0, 1, 2] |
| 328 | ); |
| 329 | } |
| 330 | |
| 331 | fn spans(markdown: &str, name: &str, ignore_case: bool) -> Vec<String> { |
| 332 | let draft = Draft::from_markdown(markdown); |
| 333 | plain_mention_spans(&draft, name, ignore_case) |
| 334 | .into_iter() |
| 335 | .map(|span| draft.text()[span].to_owned()) |
| 336 | .collect() |
| 337 | } |
| 338 | |
| 339 | fn placed(markdown: &str, name: &str) -> usize { |
| 340 | let html = Draft::from_markdown(markdown).to_html(); |
| 341 | apply_mentions(&html, &[MentionInput::user("u1", name)]) |
| 342 | .1 |
| 343 | .len() |
| 344 | } |
| 345 | |
| 346 | #[test] |
| 347 | fn a_mention_never_matches_inside_a_longer_name_or_after_a_word() { |
| 348 | assert_eq!(spans("@Adam and @Ada!", "Ada", false), ["@Ada"]); |
| 349 | assert!(spans("@Adam", "Ada", false).is_empty()); |
| 350 | assert!(spans("ops@Ada.example", "Ada", false).is_empty()); |
| 351 | assert!(spans("mail ops@acme.com", "acme", false).is_empty()); |
| 352 | assert_eq!(placed("ops@Ada x", "Ada"), 0); |
| 353 | assert_eq!(placed("@Adam then @Ada", "Ada"), 1); |
| 354 | } |
| 355 | |
| 356 | #[test] |
| 357 | fn mentions_stay_out_of_links_code_and_half_formatted_names() { |
| 358 | for markdown in [ |
| 359 | "[docs](https://example.com/@Ada)", |
| 360 | "see `@Ada` here", |
| 361 | "```\n@Ada\n```", |
| 362 | "read medium.com/@Ada today", |
| 363 | "@**Ada**", |
| 364 | "[@Ada](https://example.com)", |
| 365 | ] { |
| 366 | assert!(spans(markdown, "Ada", false).is_empty(), "{markdown}"); |
| 367 | assert_eq!(placed(markdown, "Ada"), 0, "{markdown}"); |
| 368 | } |
| 369 | for markdown in ["**@Ada** hi", "link https://example.com/@Ada and @Ada"] { |
| 370 | assert_eq!(spans(markdown, "Ada", false), ["@Ada"], "{markdown}"); |
| 371 | assert_eq!(placed(markdown, "Ada"), 1, "{markdown}"); |
| 372 | } |
| 373 | let html = Draft::from_markdown("https://example.com/@Ada then @Ada").to_html(); |
| 374 | let (tagged, _) = apply_mentions(&html, &[MentionInput::user("u1", "Ada")]); |
| 375 | assert!(tagged.contains("example.com/@Ada")); |
| 376 | assert!(tagged.ends_with("then <at id=\"0\">Ada</at>")); |
| 377 | } |
| 378 | |
| 379 | #[test] |
| 380 | fn mentions_after_line_breaks_and_block_edges_work_in_both_rules() { |
| 381 | for (markdown, name, expected) in [ |
| 382 | ("Hi team\n@Ada please", "Ada", 1), |
| 383 | ("@Ada\nthanks", "Ada", 1), |
| 384 | ("- @Ada\n- @Bo", "Bo", 1), |
| 385 | ("- @Ada\n- @Bo", "Ada", 1), |
| 386 | ("> x\n@Ada", "Ada", 1), |
| 387 | ("@O'Brien hi", "O'Brien", 1), |
| 388 | ("say @\"Ada\" now", "\"Ada\"", 1), |
| 389 | ] { |
| 390 | assert_eq!(spans(markdown, name, false).len(), expected, "{markdown}"); |
| 391 | assert_eq!(placed(markdown, name), expected, "{markdown}"); |
| 392 | } |
| 393 | } |
| 394 | |
| 395 | #[test] |
| 396 | fn numeric_entities_decode_like_named_ones() { |
| 397 | assert_eq!(decode_entity("'rest"), Some(('\'', 6)),); |
| 398 | assert_eq!(decode_entity("'"), Some(('\'', 5))); |
| 399 | assert_eq!(decode_entity("&#zz;"), None); |
| 400 | assert_eq!(decode_entity("&#+39;"), None); |
| 401 | assert_eq!(decode_entity("&#x+27;"), None); |
| 402 | assert_eq!(decode_entity("&#-1;"), None); |
| 403 | assert_eq!(decode_entity("&#;"), None); |
| 404 | assert_eq!(decode_entity("�"), None); |
| 405 | assert_eq!(decode_entity("&"), Some(('&', 5))); |
| 406 | } |
| 407 | |
| 408 | #[test] |
| 409 | fn case_insensitive_matching_keeps_offsets_after_wide_letters() { |
| 410 | let draft = Draft::from_markdown("\u{130} @ADA"); |
| 411 | let found = plain_mention_spans(&draft, "ada", true); |
| 412 | assert_eq!(found.len(), 1); |
| 413 | assert_eq!(&draft.text()[found[0].clone()], "@ADA"); |
| 414 | assert!(plain_mention_spans(&draft, "ada", false).is_empty()); |
| 415 | } |
| 416 | |
| 417 | #[test] |
| 418 | fn repeated_names_are_matched_left_to_right() { |
| 419 | let (html, mentions) = apply_mentions( |
| 420 | "@Ada then @Ada", |
| 421 | &[ |
| 422 | MentionInput::user("u1", "Ada"), |
| 423 | MentionInput::user("u2", "Ada"), |
| 424 | ], |
| 425 | ); |
| 426 | assert_eq!(html, "<at id=\"0\">Ada</at> then <at id=\"1\">Ada</at>"); |
| 427 | assert_eq!(mentions.len(), 2); |
| 428 | } |
| 429 | |
| 430 | #[test] |
| 431 | fn unmatched_mentions_are_dropped_and_ids_stay_dense() { |
| 432 | let (html, mentions) = apply_mentions( |
| 433 | "@Bo only", |
| 434 | &[ |
| 435 | MentionInput::user("u1", "Ada"), |
| 436 | MentionInput::user("u2", "Bo"), |
| 437 | ], |
| 438 | ); |
| 439 | assert_eq!(html, "<at id=\"0\">Bo</at> only"); |
| 440 | assert_eq!(mentions.len(), 1); |
| 441 | assert_eq!(mentions[0].id, 0); |
| 442 | } |
| 443 | |
| 444 | #[test] |
| 445 | fn names_are_html_escaped_like_the_body() { |
| 446 | let (html, mentions) = apply_mentions( |
| 447 | &crate::markdown_to_html("ping @Ada & Co <x>"), |
| 448 | &[MentionInput::user("u1", "Ada & Co")], |
| 449 | ); |
| 450 | assert_eq!(html, "ping <at id=\"0\">Ada & Co</at> <x>"); |
| 451 | assert_eq!(mentions[0].text, "Ada & Co"); |
| 452 | } |
| 453 | |
| 454 | #[test] |
| 455 | fn mentions_inside_formatted_draft_html_become_at_tags() { |
| 456 | let (html, mentions) = apply_mentions( |
| 457 | &crate::Draft::from_markdown("**hi @Ada** and `@Bo`").to_html(), |
| 458 | &[MentionInput::user("u1", "Ada")], |
| 459 | ); |
| 460 | assert_eq!(html, "<b>hi <at id=\"0\">Ada</at></b> and <code>@Bo</code>"); |
| 461 | assert_eq!(mentions.len(), 1); |
| 462 | } |
| 463 | |
| 464 | #[test] |
| 465 | fn chats_only_take_user_mentions() { |
| 466 | assert!(ensure_allowed_in_chat(&[MentionInput::user("u", "A")]).is_ok()); |
| 467 | assert!(ensure_allowed_in_chat(&[MentionInput::everyone("19:g", "Everyone")]).is_ok()); |
| 468 | assert!(ensure_allowed_in_chat(&[MentionInput::team("t", "Squad")]).is_err()); |
| 469 | assert!(ensure_allowed_in_chat(&[MentionInput::tag("tag-1", "Design")]).is_err()); |
| 470 | } |
| 471 | } |