| 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 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 149 | pub struct CustomEmoji<'a> { |
| 150 | pub name: &'a str, |
| 151 | pub object_id: &'a str, |
| 152 | } |
| 153 | |
| 154 | impl CustomEmoji<'_> { |
| 155 | pub fn image_url(&self) -> String { |
| 156 | format!("{AMS_OBJECTS_BASE}{}{CUSTOM_EMOJI_VIEW}", self.object_id) |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | /// `absolute-cinema;0-wcde-d3-5f5e...`: an org emoji, name and AMS object of its image. |
| 161 | pub fn custom_emoji(key: &str) -> Option<CustomEmoji<'_>> { |
| 162 | let (name, object_id) = key.split_once(CUSTOM_EMOJI_SEPARATOR)?; |
| 163 | let valid_object = !object_id.is_empty() |
| 164 | && object_id |
| 165 | .chars() |
| 166 | .all(|character| character.is_ascii_alphanumeric() || character == '-'); |
| 167 | (!name.is_empty() && valid_object).then_some(CustomEmoji { name, object_id }) |
| 168 | } |
| 169 | |
| 170 | #[cfg(test)] |
| 171 | mod tests { |
| 172 | use super::*; |
| 173 | |
| 174 | #[test] |
| 175 | fn custom_emoji_key_maps_to_its_ams_image() { |
| 176 | let emoji = custom_emoji("absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8") |
| 177 | .expect("custom emoji"); |
| 178 | assert_eq!(emoji.name, "absolute-cinema"); |
| 179 | assert_eq!( |
| 180 | emoji.image_url(), |
| 181 | "https://de-prod.asyncgw.teams.microsoft.com/v1/objects/0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8/views/imgt2_anim" |
| 182 | ); |
| 183 | assert_eq!(custom_emoji("like"), None); |
| 184 | assert_eq!(custom_emoji("x;../evil"), None); |
| 185 | assert_eq!(custom_emoji(";0-wcde-d3-1"), None); |
| 186 | } |
| 187 | |
| 188 | #[test] |
| 189 | fn resolves_teams_keys() { |
| 190 | assert_eq!( |
| 191 | emotion_key("\u{1F603}"), |
| 192 | Some("1f603_grinningfacewithbigeyes") |
| 193 | ); |
| 194 | assert_eq!(emotion_key("\u{1F44D}"), Some("like")); |
| 195 | } |
| 196 | |
| 197 | #[test] |
| 198 | fn ignores_variation_selectors() { |
| 199 | assert_eq!(emotion_key("\u{2764}"), Some("heart")); |
| 200 | assert_eq!(emotion_key("\u{2764}\u{FE0F}"), Some("heart")); |
| 201 | } |
| 202 | |
| 203 | #[test] |
| 204 | fn lists_alias_keys_with_the_primary_first() { |
| 205 | assert_eq!( |
| 206 | emotion_keys("\u{1F603}"), |
| 207 | ["1f603_grinningfacewithbigeyes", "happyface"] |
| 208 | ); |
| 209 | assert_eq!(emotion_keys("\u{2764}\u{FE0F}")[0], "heart"); |
| 210 | } |
| 211 | |
| 212 | #[test] |
| 213 | fn toned_reactions_use_the_diverse_id_with_the_tone() { |
| 214 | assert_eq!(reaction_key("👍").as_deref(), Some("like")); |
| 215 | assert_eq!(reaction_key("👍🏼").as_deref(), Some("yes-tone2")); |
| 216 | assert_eq!(reaction_keys("👍🏿"), ["yes-tone5", "like", "yes"]); |
| 217 | assert_eq!(reaction_keys("👍"), ["like", "yes"]); |
| 218 | assert_eq!(reaction_key("❤️").as_deref(), Some("heart")); |
| 219 | } |
| 220 | |
| 221 | #[test] |
| 222 | fn keys_turn_into_glyphs_with_their_tone() { |
| 223 | assert_eq!(reaction_glyph_for_key("yes-tone2").as_deref(), Some("👍🏼")); |
| 224 | assert_eq!(reaction_glyph_for_key("like").as_deref(), Some("👍")); |
| 225 | assert_eq!(reaction_glyph_for_key("heart").as_deref(), Some("❤")); |
| 226 | assert_eq!(reaction_glyph_for_key("nope"), None); |
| 227 | assert_eq!(insert_skin_tone("🤷\u{200d}♂️", 1), "🤷🏻\u{200d}♂️"); |
| 228 | assert_eq!(insert_skin_tone("✌️", 3), "✌🏽"); |
| 229 | } |
| 230 | |
| 231 | #[test] |
| 232 | fn unknown_glyph_has_no_key() { |
| 233 | assert_eq!(emotion_key("x"), None); |
| 234 | assert!(emotion_keys("x").is_empty()); |
| 235 | } |
| 236 | } |