| 1 | use std::borrow::Cow; |
| 2 | use std::collections::HashMap; |
| 3 | use std::sync::OnceLock; |
| 4 | |
| 5 | const EMOTIONS: &str = include_str!("../assets/emotions.tsv"); |
| 6 | const EMOTICONS: &str = include_str!("../../app/assets/emoticons.tsv"); |
| 7 | const SKIN_TONES: std::ops::RangeInclusive<char> = '\u{1f3fb}'..='\u{1f3ff}'; |
| 8 | const TONE_MARKER: &str = "-tone"; |
| 9 | const ZERO_WIDTH_JOINER: char = '\u{200d}'; |
| 10 | const VARIATION_SELECTOR: char = '\u{fe0f}'; |
| 11 | const MAX_TONE: u8 = 5; |
| 12 | const CUSTOM_EMOJI_SEPARATOR: char = ';'; |
| 13 | const AMS_OBJECTS_BASE: &str = "https://de-prod.asyncgw.teams.microsoft.com/v1/objects/"; |
| 14 | const CUSTOM_EMOJI_VIEW: &str = "/views/imgt2_anim"; |
| 15 | |
| 16 | type Index = HashMap<&'static str, Vec<&'static str>>; |
| 17 | |
| 18 | fn index() -> &'static Index { |
| 19 | static PARSED: OnceLock<Index> = OnceLock::new(); |
| 20 | PARSED.get_or_init(|| { |
| 21 | EMOTIONS |
| 22 | .lines() |
| 23 | .filter_map(|line| { |
| 24 | let (glyph, keys) = line.split_once('\t')?; |
| 25 | Some((glyph, keys.split(' ').collect())) |
| 26 | }) |
| 27 | .collect() |
| 28 | }) |
| 29 | } |
| 30 | |
| 31 | fn diverse_ids() -> &'static std::collections::HashSet<&'static str> { |
| 32 | static PARSED: OnceLock<std::collections::HashSet<&'static str>> = OnceLock::new(); |
| 33 | PARSED.get_or_init(|| { |
| 34 | EMOTICONS |
| 35 | .lines() |
| 36 | .filter_map(|line| { |
| 37 | let fields: Vec<&str> = line.split('\t').collect(); |
| 38 | (fields.get(4) == Some(&"1")).then_some(fields[0]) |
| 39 | }) |
| 40 | .collect() |
| 41 | }) |
| 42 | } |
| 43 | |
| 44 | fn split_tone(glyph: &str) -> (String, Option<u32>) { |
| 45 | let tone = glyph |
| 46 | .chars() |
| 47 | .find(|character| SKIN_TONES.contains(character)) |
| 48 | .map(|tone| tone as u32 - *SKIN_TONES.start() as u32 + 1); |
| 49 | let base = glyph |
| 50 | .chars() |
| 51 | .filter(|character| !SKIN_TONES.contains(character)) |
| 52 | .collect(); |
| 53 | (base, tone) |
| 54 | } |
| 55 | |
| 56 | /// Teams sends a toned reaction as `{diverse id}-tone{n}`, so 👍🏼 is `yes-tone2`, not `like`. |
| 57 | pub fn reaction_key(glyph: &str) -> Option<String> { |
| 58 | let (base, tone) = split_tone(glyph); |
| 59 | let keys = emotion_keys(&base); |
| 60 | match tone { |
| 61 | Some(tone) => keys |
| 62 | .iter() |
| 63 | .find(|key| diverse_ids().contains(*key)) |
| 64 | .map(|key| format!("{key}{TONE_MARKER}{tone}")) |
| 65 | .or_else(|| keys.first().map(|key| key.to_string())), |
| 66 | None => keys.first().map(|key| key.to_string()), |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | /// Graph reads a toned reaction back without its tone, so removing one also clears the plain keys. |
| 71 | pub fn reaction_keys(glyph: &str) -> Vec<String> { |
| 72 | let (base, tone) = split_tone(glyph); |
| 73 | let plain = emotion_keys(&base).iter().map(|key| key.to_string()); |
| 74 | match tone { |
| 75 | Some(_) => { |
| 76 | let toned = reaction_key(glyph); |
| 77 | toned |
| 78 | .clone() |
| 79 | .into_iter() |
| 80 | .chain(plain.filter(|key| Some(key) != toned.as_ref())) |
| 81 | .collect() |
| 82 | } |
| 83 | None => plain.collect(), |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | /// The Teams rule: the modifier goes in once, before the first joiner, otherwise at the end; |
| 88 | /// a variation selector at that spot is dropped. |
| 89 | pub fn insert_skin_tone(base: &str, tone: u8) -> String { |
| 90 | let Some(modifier) = (1..=MAX_TONE) |
| 91 | .contains(&tone) |
| 92 | .then(|| char::from_u32(*SKIN_TONES.start() as u32 + u32::from(tone) - 1)) |
| 93 | .flatten() |
| 94 | else { |
| 95 | return base.to_owned(); |
| 96 | }; |
| 97 | let (head, tail) = base.split_at(base.find(ZERO_WIDTH_JOINER).unwrap_or(base.len())); |
| 98 | format!( |
| 99 | "{}{modifier}{tail}", |
| 100 | head.strip_suffix(VARIATION_SELECTOR).unwrap_or(head) |
| 101 | ) |
| 102 | } |
| 103 | |
| 104 | /// `yes-tone2` is 👍🏼: the chat service key of a reaction as the glyph Graph would report, |
| 105 | /// but with the tone Graph drops. |
| 106 | pub fn reaction_glyph_for_key(key: &str) -> Option<String> { |
| 107 | let (base_key, tone) = match key.rsplit_once(TONE_MARKER) { |
| 108 | Some((base, tone)) => match tone.parse::<u8>() { |
| 109 | Ok(tone) => (base, Some(tone)), |
| 110 | Err(_) => (key, None), |
| 111 | }, |
| 112 | None => (key, None), |
| 113 | }; |
| 114 | let base = emotion_glyph(base_key)?; |
| 115 | Some(match tone { |
| 116 | Some(tone) => insert_skin_tone(base, tone), |
| 117 | None => base.to_owned(), |
| 118 | }) |
| 119 | } |
| 120 | |
| 121 | pub fn emotion_glyph(key: &str) -> Option<&'static str> { |
| 122 | static GLYPHS: OnceLock<HashMap<&'static str, &'static str>> = OnceLock::new(); |
| 123 | GLYPHS |
| 124 | .get_or_init(|| { |
| 125 | EMOTIONS |
| 126 | .lines() |
| 127 | .filter_map(|line| line.split_once('\t')) |
| 128 | .flat_map(|(glyph, keys)| keys.split(' ').map(move |key| (key, glyph))) |
| 129 | .collect() |
| 130 | }) |
| 131 | .get(key) |
| 132 | .copied() |
| 133 | } |
| 134 | |
| 135 | pub fn emotion_keys(glyph: &str) -> &'static [&'static str] { |
| 136 | let bare = if glyph.contains('\u{FE0F}') { |
| 137 | Cow::Owned(glyph.replace('\u{FE0F}', "")) |
| 138 | } else { |
| 139 | Cow::Borrowed(glyph) |
| 140 | }; |
| 141 | index().get(bare.as_ref()).map_or(&[], Vec::as_slice) |
| 142 | } |
| 143 | |
| 144 | pub fn emotion_key(glyph: &str) -> Option<&'static str> { |
| 145 | emotion_keys(glyph).first().copied() |
| 146 | } |
| 147 | |
| 148 | const CUSTOM_TYPE: &str = "custom"; |
| 149 | const CUSTOM_UNDERSCORE: &str = "custom_"; |
| 150 | const CUSTOM_COLON: &str = "custom:"; |
| 151 | |
| 152 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 153 | pub struct CustomEmoji { |
| 154 | pub name: String, |
| 155 | pub object_id: String, |
| 156 | } |
| 157 | |
| 158 | impl CustomEmoji { |
| 159 | pub fn key(&self) -> String { |
| 160 | format!("{}{CUSTOM_EMOJI_SEPARATOR}{}", self.name, self.object_id) |
| 161 | } |
| 162 | |
| 163 | pub fn image_url(&self) -> String { |
| 164 | format!("{AMS_OBJECTS_BASE}{}{CUSTOM_EMOJI_VIEW}", self.object_id) |
| 165 | } |
| 166 | |
| 167 | /// The name to show in a tooltip or as `:name:`. `None` when we only have a placeholder. |
| 168 | pub fn display_name(&self) -> Option<&str> { |
| 169 | let name = self.name.trim(); |
| 170 | (!name.is_empty() && !name.eq_ignore_ascii_case(CUSTOM_TYPE)).then_some(name) |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | /// An org custom emoji hidden in a reaction key. |
| 175 | /// |
| 176 | /// Known shapes: |
| 177 | /// - `name;objectId` (chat service emotions) |
| 178 | /// - a Graph `hostedContents/...` URL whose id is `id={objectId},type=1,url=` |
| 179 | /// - an AMS object URL |
| 180 | /// - `custom_{objectId}` or a bare object id |
| 181 | pub fn custom_emoji(key: &str) -> Option<CustomEmoji> { |
| 182 | let key = key.trim(); |
| 183 | if let Some((name, object_id)) = key.split_once(CUSTOM_EMOJI_SEPARATOR) { |
| 184 | let object_id = object_id |
| 185 | .split([CUSTOM_EMOJI_SEPARATOR, '|']) |
| 186 | .next() |
| 187 | .unwrap_or(object_id) |
| 188 | .trim(); |
| 189 | let name = name |
| 190 | .strip_prefix(CUSTOM_UNDERSCORE) |
| 191 | .or_else(|| name.strip_prefix(CUSTOM_COLON)) |
| 192 | .unwrap_or(name) |
| 193 | .trim(); |
| 194 | if !name.is_empty() && crate::links::is_ams_object_id(object_id) { |
| 195 | return Some(CustomEmoji { |
| 196 | name: name.to_owned(), |
| 197 | object_id: object_id.to_owned(), |
| 198 | }); |
| 199 | } |
| 200 | } |
| 201 | if let Some(object_id) = crate::links::hosted_content_object_id(key) { |
| 202 | return Some(CustomEmoji { |
| 203 | name: CUSTOM_TYPE.to_owned(), |
| 204 | object_id, |
| 205 | }); |
| 206 | } |
| 207 | if let Some(object_id) = crate::links::object_id_from_ams_path(key) { |
| 208 | return Some(CustomEmoji { |
| 209 | name: CUSTOM_TYPE.to_owned(), |
| 210 | object_id: object_id.to_owned(), |
| 211 | }); |
| 212 | } |
| 213 | if let Some(object_id) = key |
| 214 | .strip_prefix(CUSTOM_UNDERSCORE) |
| 215 | .or_else(|| key.strip_prefix(CUSTOM_COLON)) |
| 216 | .map(str::trim) |
| 217 | .filter(|id| crate::links::is_ams_object_id(id)) |
| 218 | { |
| 219 | return Some(CustomEmoji { |
| 220 | name: CUSTOM_TYPE.to_owned(), |
| 221 | object_id: object_id.to_owned(), |
| 222 | }); |
| 223 | } |
| 224 | crate::links::is_ams_object_id(key).then(|| CustomEmoji { |
| 225 | name: CUSTOM_TYPE.to_owned(), |
| 226 | object_id: key.to_owned(), |
| 227 | }) |
| 228 | } |
| 229 | |
| 230 | /// Canonical `name;objectId` key from a Graph (or mixed) custom reaction payload. |
| 231 | /// |
| 232 | /// Graph stores `reactionType: "custom"` with the name and image in `displayName` |
| 233 | /// and `reactionContentUrl`. Returns `None` when this is not a custom reaction. |
| 234 | pub fn custom_reaction_key( |
| 235 | reaction_type: &str, |
| 236 | display_name: Option<&str>, |
| 237 | content_url: Option<&str>, |
| 238 | reaction_id: Option<&str>, |
| 239 | ) -> Option<String> { |
| 240 | let display_name = display_name.map(str::trim).filter(|name| !name.is_empty()); |
| 241 | if let Some(emoji) = custom_emoji(reaction_type) { |
| 242 | let name = display_name |
| 243 | .or_else(|| emoji.display_name()) |
| 244 | .unwrap_or(&emoji.name); |
| 245 | return Some( |
| 246 | CustomEmoji { |
| 247 | name: name.to_owned(), |
| 248 | object_id: emoji.object_id, |
| 249 | } |
| 250 | .key(), |
| 251 | ); |
| 252 | } |
| 253 | let object_id = content_url |
| 254 | .and_then(crate::links::hosted_content_object_id) |
| 255 | .or_else(|| { |
| 256 | content_url |
| 257 | .and_then(crate::links::object_id_from_ams_path) |
| 258 | .map(str::to_owned) |
| 259 | }) |
| 260 | .or_else(|| { |
| 261 | reaction_id |
| 262 | .map(str::trim) |
| 263 | .filter(|id| crate::links::is_ams_object_id(id)) |
| 264 | .map(str::to_owned) |
| 265 | }); |
| 266 | match (display_name, object_id) { |
| 267 | (Some(name), Some(object_id)) => Some( |
| 268 | CustomEmoji { |
| 269 | name: name.to_owned(), |
| 270 | object_id, |
| 271 | } |
| 272 | .key(), |
| 273 | ), |
| 274 | (None, Some(object_id)) if is_custom_reaction_type(reaction_type) => Some( |
| 275 | CustomEmoji { |
| 276 | name: CUSTOM_TYPE.to_owned(), |
| 277 | object_id, |
| 278 | } |
| 279 | .key(), |
| 280 | ), |
| 281 | (Some(name), None) if is_custom_reaction_type(reaction_type) => { |
| 282 | Some(format!("{CUSTOM_COLON}{name}")) |
| 283 | } |
| 284 | _ if is_custom_reaction_type(reaction_type) => Some(CUSTOM_TYPE.to_owned()), |
| 285 | _ => None, |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | pub fn is_custom_reaction_type(reaction_type: &str) -> bool { |
| 290 | let key = reaction_type.trim(); |
| 291 | key.eq_ignore_ascii_case(CUSTOM_TYPE) |
| 292 | || key.starts_with(CUSTOM_UNDERSCORE) |
| 293 | || key.starts_with(CUSTOM_COLON) |
| 294 | || custom_emoji(key).is_some() |
| 295 | } |
| 296 | |
| 297 | /// A reaction key that must not be drawn as text in a pill (`custom`, `name;id`, ...). |
| 298 | pub fn hides_raw_reaction_key(key: &str) -> bool { |
| 299 | if ["like", "heart", "laugh", "surprised", "sad", "angry"].contains(&key) { |
| 300 | return false; |
| 301 | } |
| 302 | if reaction_glyph_for_key(key).is_some() { |
| 303 | return false; |
| 304 | } |
| 305 | if key.chars().any(|character| !character.is_ascii()) { |
| 306 | return false; |
| 307 | } |
| 308 | is_custom_reaction_type(key) |
| 309 | || custom_emoji_display_name(key).is_some() |
| 310 | || crate::links::is_ams_object_id(key) |
| 311 | || key.contains(CUSTOM_EMOJI_SEPARATOR) |
| 312 | } |
| 313 | |
| 314 | pub fn custom_emoji_display_name(key: &str) -> Option<String> { |
| 315 | if let Some(name) = custom_emoji(key) |
| 316 | .as_ref() |
| 317 | .and_then(CustomEmoji::display_name) |
| 318 | { |
| 319 | return Some(name.to_owned()); |
| 320 | } |
| 321 | let key = key.trim(); |
| 322 | key.strip_prefix(CUSTOM_COLON) |
| 323 | .or_else(|| key.strip_prefix(CUSTOM_UNDERSCORE)) |
| 324 | .map(str::trim) |
| 325 | .filter(|name| !name.is_empty() && !crate::links::is_ams_object_id(name)) |
| 326 | .map(str::to_owned) |
| 327 | } |
| 328 | |
| 329 | #[cfg(test)] |
| 330 | mod tests { |
| 331 | use super::*; |
| 332 | |
| 333 | #[test] |
| 334 | fn custom_emoji_key_maps_to_its_ams_image() { |
| 335 | let emoji = custom_emoji("absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8") |
| 336 | .expect("custom emoji"); |
| 337 | assert_eq!(emoji.name, "absolute-cinema"); |
| 338 | assert_eq!( |
| 339 | emoji.image_url(), |
| 340 | "https://de-prod.asyncgw.teams.microsoft.com/v1/objects/0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8/views/imgt2_anim" |
| 341 | ); |
| 342 | assert_eq!(custom_emoji("like"), None); |
| 343 | assert_eq!(custom_emoji("x;../evil"), None); |
| 344 | assert_eq!(custom_emoji(";0-wcde-d3-1"), None); |
| 345 | assert_eq!(custom_emoji("custom"), None); |
| 346 | } |
| 347 | |
| 348 | #[test] |
| 349 | fn custom_emoji_keys_accept_graph_and_prefixed_variants() { |
| 350 | let object_id = "0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853"; |
| 351 | let hosted = format!( |
| 352 | "https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/{}/$value", |
| 353 | base64_id(object_id) |
| 354 | ); |
| 355 | let from_url = custom_emoji(&hosted).expect("hosted content"); |
| 356 | assert_eq!(from_url.object_id, object_id); |
| 357 | assert_eq!( |
| 358 | from_url.image_url(), |
| 359 | format!( |
| 360 | "https://de-prod.asyncgw.teams.microsoft.com/v1/objects/{object_id}/views/imgt2_anim" |
| 361 | ) |
| 362 | ); |
| 363 | |
| 364 | let from_prefix = custom_emoji(&format!("custom_{object_id}")).expect("prefixed"); |
| 365 | assert_eq!(from_prefix.object_id, object_id); |
| 366 | |
| 367 | let from_bare = custom_emoji(object_id).expect("bare object id"); |
| 368 | assert_eq!(from_bare.object_id, object_id); |
| 369 | |
| 370 | let from_ams = custom_emoji(&format!( |
| 371 | "https://de-prod.asyncgw.teams.microsoft.com/v1/objects/{object_id}/views/imgt2_anim" |
| 372 | )) |
| 373 | .expect("ams url"); |
| 374 | assert_eq!(from_ams.object_id, object_id); |
| 375 | } |
| 376 | |
| 377 | #[test] |
| 378 | fn graph_custom_reaction_payloads_become_a_name_and_object_key() { |
| 379 | let object_id = "0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853"; |
| 380 | let hosted = format!( |
| 381 | "https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/{}/$value", |
| 382 | base64_id(object_id) |
| 383 | ); |
| 384 | assert_eq!( |
| 385 | custom_reaction_key("custom", Some("tsignal"), Some(&hosted), None).as_deref(), |
| 386 | Some("tsignal;0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853") |
| 387 | ); |
| 388 | assert_eq!( |
| 389 | custom_reaction_key("custom", Some("party-parrot"), None, Some(object_id)).as_deref(), |
| 390 | Some("party-parrot;0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853") |
| 391 | ); |
| 392 | assert_eq!( |
| 393 | custom_reaction_key("custom", Some("tsignal"), None, None).as_deref(), |
| 394 | Some("custom:tsignal") |
| 395 | ); |
| 396 | assert_eq!( |
| 397 | custom_reaction_key("custom", None, None, None).as_deref(), |
| 398 | Some("custom") |
| 399 | ); |
| 400 | assert_eq!(custom_reaction_key("like", None, None, None), None); |
| 401 | assert_eq!( |
| 402 | custom_reaction_key( |
| 403 | "absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8", |
| 404 | None, |
| 405 | None, |
| 406 | None |
| 407 | ) |
| 408 | .as_deref(), |
| 409 | Some("absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8") |
| 410 | ); |
| 411 | assert!(hides_raw_reaction_key("custom")); |
| 412 | assert!(hides_raw_reaction_key("custom:tsignal")); |
| 413 | assert!(hides_raw_reaction_key( |
| 414 | "absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8" |
| 415 | )); |
| 416 | assert!(!hides_raw_reaction_key("like")); |
| 417 | assert!(!hides_raw_reaction_key("\u{1F44D}")); |
| 418 | assert_eq!( |
| 419 | custom_emoji_display_name("custom:tsignal").as_deref(), |
| 420 | Some("tsignal") |
| 421 | ); |
| 422 | assert_eq!( |
| 423 | custom_emoji_display_name("tsignal;0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853") |
| 424 | .as_deref(), |
| 425 | Some("tsignal") |
| 426 | ); |
| 427 | } |
| 428 | |
| 429 | fn base64_id(object_id: &str) -> String { |
| 430 | base64::Engine::encode( |
| 431 | &base64::engine::general_purpose::STANDARD, |
| 432 | format!("id={object_id},type=1,url="), |
| 433 | ) |
| 434 | } |
| 435 | |
| 436 | #[test] |
| 437 | fn resolves_teams_keys() { |
| 438 | assert_eq!( |
| 439 | emotion_key("\u{1F603}"), |
| 440 | Some("1f603_grinningfacewithbigeyes") |
| 441 | ); |
| 442 | assert_eq!(emotion_key("\u{1F44D}"), Some("like")); |
| 443 | } |
| 444 | |
| 445 | #[test] |
| 446 | fn ignores_variation_selectors() { |
| 447 | assert_eq!(emotion_key("\u{2764}"), Some("heart")); |
| 448 | assert_eq!(emotion_key("\u{2764}\u{FE0F}"), Some("heart")); |
| 449 | } |
| 450 | |
| 451 | #[test] |
| 452 | fn lists_alias_keys_with_the_primary_first() { |
| 453 | assert_eq!( |
| 454 | emotion_keys("\u{1F603}"), |
| 455 | ["1f603_grinningfacewithbigeyes", "happyface"] |
| 456 | ); |
| 457 | assert_eq!(emotion_keys("\u{2764}\u{FE0F}")[0], "heart"); |
| 458 | } |
| 459 | |
| 460 | #[test] |
| 461 | fn toned_reactions_use_the_diverse_id_with_the_tone() { |
| 462 | assert_eq!(reaction_key("👍").as_deref(), Some("like")); |
| 463 | assert_eq!(reaction_key("👍🏼").as_deref(), Some("yes-tone2")); |
| 464 | assert_eq!(reaction_keys("👍🏿"), ["yes-tone5", "like", "yes"]); |
| 465 | assert_eq!(reaction_keys("👍"), ["like", "yes"]); |
| 466 | assert_eq!(reaction_key("❤️").as_deref(), Some("heart")); |
| 467 | } |
| 468 | |
| 469 | #[test] |
| 470 | fn keys_turn_into_glyphs_with_their_tone() { |
| 471 | assert_eq!(reaction_glyph_for_key("yes-tone2").as_deref(), Some("👍🏼")); |
| 472 | assert_eq!(reaction_glyph_for_key("like").as_deref(), Some("👍")); |
| 473 | assert_eq!(reaction_glyph_for_key("heart").as_deref(), Some("❤")); |
| 474 | assert_eq!(reaction_glyph_for_key("nope"), None); |
| 475 | assert_eq!(insert_skin_tone("🤷\u{200d}♂️", 1), "🤷🏻\u{200d}♂️"); |
| 476 | assert_eq!(insert_skin_tone("✌️", 3), "✌🏽"); |
| 477 | } |
| 478 | |
| 479 | #[test] |
| 480 | fn unknown_glyph_has_no_key() { |
| 481 | assert_eq!(emotion_key("x"), None); |
| 482 | assert!(emotion_keys("x").is_empty()); |
| 483 | } |
| 484 | } |