use std::borrow::Cow; use std::collections::HashMap; use std::sync::OnceLock; const EMOTIONS: &str = include_str!("../assets/emotions.tsv"); const EMOTICONS: &str = include_str!("../../app/assets/emoticons.tsv"); const SKIN_TONES: std::ops::RangeInclusive = '\u{1f3fb}'..='\u{1f3ff}'; const TONE_MARKER: &str = "-tone"; const ZERO_WIDTH_JOINER: char = '\u{200d}'; const VARIATION_SELECTOR: char = '\u{fe0f}'; const MAX_TONE: u8 = 5; const CUSTOM_EMOJI_SEPARATOR: char = ';'; const AMS_OBJECTS_BASE: &str = "https://de-prod.asyncgw.teams.microsoft.com/v1/objects/"; const CUSTOM_EMOJI_VIEW: &str = "/views/imgt2_anim"; type Index = HashMap<&'static str, Vec<&'static str>>; fn index() -> &'static Index { static PARSED: OnceLock = OnceLock::new(); PARSED.get_or_init(|| { EMOTIONS .lines() .filter_map(|line| { let (glyph, keys) = line.split_once('\t')?; Some((glyph, keys.split(' ').collect())) }) .collect() }) } fn diverse_ids() -> &'static std::collections::HashSet<&'static str> { static PARSED: OnceLock> = OnceLock::new(); PARSED.get_or_init(|| { EMOTICONS .lines() .filter_map(|line| { let fields: Vec<&str> = line.split('\t').collect(); (fields.get(4) == Some(&"1")).then_some(fields[0]) }) .collect() }) } fn split_tone(glyph: &str) -> (String, Option) { let tone = glyph .chars() .find(|character| SKIN_TONES.contains(character)) .map(|tone| tone as u32 - *SKIN_TONES.start() as u32 + 1); let base = glyph .chars() .filter(|character| !SKIN_TONES.contains(character)) .collect(); (base, tone) } /// Teams sends a toned reaction as `{diverse id}-tone{n}`, so 👍🏼 is `yes-tone2`, not `like`. pub fn reaction_key(glyph: &str) -> Option { let (base, tone) = split_tone(glyph); let keys = emotion_keys(&base); match tone { Some(tone) => keys .iter() .find(|key| diverse_ids().contains(*key)) .map(|key| format!("{key}{TONE_MARKER}{tone}")) .or_else(|| keys.first().map(|key| key.to_string())), None => keys.first().map(|key| key.to_string()), } } /// Graph reads a toned reaction back without its tone, so removing one also clears the plain keys. pub fn reaction_keys(glyph: &str) -> Vec { let (base, tone) = split_tone(glyph); let plain = emotion_keys(&base).iter().map(|key| key.to_string()); match tone { Some(_) => { let toned = reaction_key(glyph); toned .clone() .into_iter() .chain(plain.filter(|key| Some(key) != toned.as_ref())) .collect() } None => plain.collect(), } } /// The Teams rule: the modifier goes in once, before the first joiner, otherwise at the end; /// a variation selector at that spot is dropped. pub fn insert_skin_tone(base: &str, tone: u8) -> String { let Some(modifier) = (1..=MAX_TONE) .contains(&tone) .then(|| char::from_u32(*SKIN_TONES.start() as u32 + u32::from(tone) - 1)) .flatten() else { return base.to_owned(); }; let (head, tail) = base.split_at(base.find(ZERO_WIDTH_JOINER).unwrap_or(base.len())); format!( "{}{modifier}{tail}", head.strip_suffix(VARIATION_SELECTOR).unwrap_or(head) ) } /// `yes-tone2` is 👍🏼: the chat service key of a reaction as the glyph Graph would report, /// but with the tone Graph drops. pub fn reaction_glyph_for_key(key: &str) -> Option { let (base_key, tone) = match key.rsplit_once(TONE_MARKER) { Some((base, tone)) => match tone.parse::() { Ok(tone) => (base, Some(tone)), Err(_) => (key, None), }, None => (key, None), }; let base = emotion_glyph(base_key)?; Some(match tone { Some(tone) => insert_skin_tone(base, tone), None => base.to_owned(), }) } pub fn emotion_glyph(key: &str) -> Option<&'static str> { static GLYPHS: OnceLock> = OnceLock::new(); GLYPHS .get_or_init(|| { EMOTIONS .lines() .filter_map(|line| line.split_once('\t')) .flat_map(|(glyph, keys)| keys.split(' ').map(move |key| (key, glyph))) .collect() }) .get(key) .copied() } pub fn emotion_keys(glyph: &str) -> &'static [&'static str] { let bare = if glyph.contains('\u{FE0F}') { Cow::Owned(glyph.replace('\u{FE0F}', "")) } else { Cow::Borrowed(glyph) }; index().get(bare.as_ref()).map_or(&[], Vec::as_slice) } pub fn emotion_key(glyph: &str) -> Option<&'static str> { emotion_keys(glyph).first().copied() } const CUSTOM_TYPE: &str = "custom"; const CUSTOM_UNDERSCORE: &str = "custom_"; const CUSTOM_COLON: &str = "custom:"; #[derive(Debug, Clone, PartialEq, Eq)] pub struct CustomEmoji { pub name: String, pub object_id: String, } impl CustomEmoji { pub fn key(&self) -> String { format!("{}{CUSTOM_EMOJI_SEPARATOR}{}", self.name, self.object_id) } pub fn image_url(&self) -> String { format!("{AMS_OBJECTS_BASE}{}{CUSTOM_EMOJI_VIEW}", self.object_id) } /// The name to show in a tooltip or as `:name:`. `None` when we only have a placeholder. pub fn display_name(&self) -> Option<&str> { let name = self.name.trim(); (!name.is_empty() && !name.eq_ignore_ascii_case(CUSTOM_TYPE)).then_some(name) } } /// An org custom emoji hidden in a reaction key. /// /// Known shapes: /// - `name;objectId` (chat service emotions) /// - a Graph `hostedContents/...` URL whose id is `id={objectId},type=1,url=` /// - an AMS object URL /// - `custom_{objectId}` or a bare object id pub fn custom_emoji(key: &str) -> Option { let key = key.trim(); if let Some((name, object_id)) = key.split_once(CUSTOM_EMOJI_SEPARATOR) { let object_id = object_id .split([CUSTOM_EMOJI_SEPARATOR, '|']) .next() .unwrap_or(object_id) .trim(); let name = name .strip_prefix(CUSTOM_UNDERSCORE) .or_else(|| name.strip_prefix(CUSTOM_COLON)) .unwrap_or(name) .trim(); if !name.is_empty() && crate::links::is_ams_object_id(object_id) { return Some(CustomEmoji { name: name.to_owned(), object_id: object_id.to_owned(), }); } } if let Some(object_id) = crate::links::hosted_content_object_id(key) { return Some(CustomEmoji { name: CUSTOM_TYPE.to_owned(), object_id, }); } if let Some(object_id) = crate::links::object_id_from_ams_path(key) { return Some(CustomEmoji { name: CUSTOM_TYPE.to_owned(), object_id: object_id.to_owned(), }); } if let Some(object_id) = key .strip_prefix(CUSTOM_UNDERSCORE) .or_else(|| key.strip_prefix(CUSTOM_COLON)) .map(str::trim) .filter(|id| crate::links::is_ams_object_id(id)) { return Some(CustomEmoji { name: CUSTOM_TYPE.to_owned(), object_id: object_id.to_owned(), }); } crate::links::is_ams_object_id(key).then(|| CustomEmoji { name: CUSTOM_TYPE.to_owned(), object_id: key.to_owned(), }) } /// Canonical `name;objectId` key from a Graph (or mixed) custom reaction payload. /// /// Graph stores `reactionType: "custom"` with the name and image in `displayName` /// and `reactionContentUrl`. Returns `None` when this is not a custom reaction. pub fn custom_reaction_key( reaction_type: &str, display_name: Option<&str>, content_url: Option<&str>, reaction_id: Option<&str>, ) -> Option { let display_name = display_name.map(str::trim).filter(|name| !name.is_empty()); if let Some(emoji) = custom_emoji(reaction_type) { let name = display_name .or_else(|| emoji.display_name()) .unwrap_or(&emoji.name); return Some( CustomEmoji { name: name.to_owned(), object_id: emoji.object_id, } .key(), ); } let object_id = content_url .and_then(crate::links::hosted_content_object_id) .or_else(|| { content_url .and_then(crate::links::object_id_from_ams_path) .map(str::to_owned) }) .or_else(|| { reaction_id .map(str::trim) .filter(|id| crate::links::is_ams_object_id(id)) .map(str::to_owned) }); match (display_name, object_id) { (Some(name), Some(object_id)) => Some( CustomEmoji { name: name.to_owned(), object_id, } .key(), ), (None, Some(object_id)) if is_custom_reaction_type(reaction_type) => Some( CustomEmoji { name: CUSTOM_TYPE.to_owned(), object_id, } .key(), ), (Some(name), None) if is_custom_reaction_type(reaction_type) => { Some(format!("{CUSTOM_COLON}{name}")) } _ if is_custom_reaction_type(reaction_type) => Some(CUSTOM_TYPE.to_owned()), _ => None, } } pub fn is_custom_reaction_type(reaction_type: &str) -> bool { let key = reaction_type.trim(); key.eq_ignore_ascii_case(CUSTOM_TYPE) || key.starts_with(CUSTOM_UNDERSCORE) || key.starts_with(CUSTOM_COLON) || custom_emoji(key).is_some() } /// A reaction key that must not be drawn as text in a pill (`custom`, `name;id`, ...). pub fn hides_raw_reaction_key(key: &str) -> bool { if ["like", "heart", "laugh", "surprised", "sad", "angry"].contains(&key) { return false; } if reaction_glyph_for_key(key).is_some() { return false; } if key.chars().any(|character| !character.is_ascii()) { return false; } is_custom_reaction_type(key) || custom_emoji_display_name(key).is_some() || crate::links::is_ams_object_id(key) || key.contains(CUSTOM_EMOJI_SEPARATOR) } pub fn custom_emoji_display_name(key: &str) -> Option { if let Some(name) = custom_emoji(key) .as_ref() .and_then(CustomEmoji::display_name) { return Some(name.to_owned()); } let key = key.trim(); key.strip_prefix(CUSTOM_COLON) .or_else(|| key.strip_prefix(CUSTOM_UNDERSCORE)) .map(str::trim) .filter(|name| !name.is_empty() && !crate::links::is_ams_object_id(name)) .map(str::to_owned) } #[cfg(test)] mod tests { use super::*; #[test] fn custom_emoji_key_maps_to_its_ams_image() { let emoji = custom_emoji("absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8") .expect("custom emoji"); assert_eq!(emoji.name, "absolute-cinema"); assert_eq!( emoji.image_url(), "https://de-prod.asyncgw.teams.microsoft.com/v1/objects/0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8/views/imgt2_anim" ); assert_eq!(custom_emoji("like"), None); assert_eq!(custom_emoji("x;../evil"), None); assert_eq!(custom_emoji(";0-wcde-d3-1"), None); assert_eq!(custom_emoji("custom"), None); } #[test] fn custom_emoji_keys_accept_graph_and_prefixed_variants() { let object_id = "0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853"; let hosted = format!( "https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/{}/$value", base64_id(object_id) ); let from_url = custom_emoji(&hosted).expect("hosted content"); assert_eq!(from_url.object_id, object_id); assert_eq!( from_url.image_url(), format!( "https://de-prod.asyncgw.teams.microsoft.com/v1/objects/{object_id}/views/imgt2_anim" ) ); let from_prefix = custom_emoji(&format!("custom_{object_id}")).expect("prefixed"); assert_eq!(from_prefix.object_id, object_id); let from_bare = custom_emoji(object_id).expect("bare object id"); assert_eq!(from_bare.object_id, object_id); let from_ams = custom_emoji(&format!( "https://de-prod.asyncgw.teams.microsoft.com/v1/objects/{object_id}/views/imgt2_anim" )) .expect("ams url"); assert_eq!(from_ams.object_id, object_id); } #[test] fn graph_custom_reaction_payloads_become_a_name_and_object_key() { let object_id = "0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853"; let hosted = format!( "https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/{}/$value", base64_id(object_id) ); assert_eq!( custom_reaction_key("custom", Some("tsignal"), Some(&hosted), None).as_deref(), Some("tsignal;0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853") ); assert_eq!( custom_reaction_key("custom", Some("party-parrot"), None, Some(object_id)).as_deref(), Some("party-parrot;0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853") ); assert_eq!( custom_reaction_key("custom", Some("tsignal"), None, None).as_deref(), Some("custom:tsignal") ); assert_eq!( custom_reaction_key("custom", None, None, None).as_deref(), Some("custom") ); assert_eq!(custom_reaction_key("like", None, None, None), None); assert_eq!( custom_reaction_key( "absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8", None, None, None ) .as_deref(), Some("absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8") ); assert!(hides_raw_reaction_key("custom")); assert!(hides_raw_reaction_key("custom:tsignal")); assert!(hides_raw_reaction_key( "absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8" )); assert!(!hides_raw_reaction_key("like")); assert!(!hides_raw_reaction_key("\u{1F44D}")); assert_eq!( custom_emoji_display_name("custom:tsignal").as_deref(), Some("tsignal") ); assert_eq!( custom_emoji_display_name("tsignal;0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853") .as_deref(), Some("tsignal") ); } fn base64_id(object_id: &str) -> String { base64::Engine::encode( &base64::engine::general_purpose::STANDARD, format!("id={object_id},type=1,url="), ) } #[test] fn resolves_teams_keys() { assert_eq!( emotion_key("\u{1F603}"), Some("1f603_grinningfacewithbigeyes") ); assert_eq!(emotion_key("\u{1F44D}"), Some("like")); } #[test] fn ignores_variation_selectors() { assert_eq!(emotion_key("\u{2764}"), Some("heart")); assert_eq!(emotion_key("\u{2764}\u{FE0F}"), Some("heart")); } #[test] fn lists_alias_keys_with_the_primary_first() { assert_eq!( emotion_keys("\u{1F603}"), ["1f603_grinningfacewithbigeyes", "happyface"] ); assert_eq!(emotion_keys("\u{2764}\u{FE0F}")[0], "heart"); } #[test] fn toned_reactions_use_the_diverse_id_with_the_tone() { assert_eq!(reaction_key("👍").as_deref(), Some("like")); assert_eq!(reaction_key("👍🏼").as_deref(), Some("yes-tone2")); assert_eq!(reaction_keys("👍🏿"), ["yes-tone5", "like", "yes"]); assert_eq!(reaction_keys("👍"), ["like", "yes"]); assert_eq!(reaction_key("❤️").as_deref(), Some("heart")); } #[test] fn keys_turn_into_glyphs_with_their_tone() { assert_eq!(reaction_glyph_for_key("yes-tone2").as_deref(), Some("👍🏼")); assert_eq!(reaction_glyph_for_key("like").as_deref(), Some("👍")); assert_eq!(reaction_glyph_for_key("heart").as_deref(), Some("❤")); assert_eq!(reaction_glyph_for_key("nope"), None); assert_eq!(insert_skin_tone("🤷\u{200d}♂️", 1), "🤷🏻\u{200d}♂️"); assert_eq!(insert_skin_tone("✌️", 3), "✌🏽"); } #[test] fn unknown_glyph_has_no_key() { assert_eq!(emotion_key("x"), None); assert!(emotion_keys("x").is_empty()); } }