BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-base / src / emoticons / mod.rs

mod.rs

mod.rs 7.8 KiB Download Raw
1mod strip;
2
3use std::collections::HashSet;
4use std::sync::OnceLock;
5use std::time::Duration;
6
7use teams_core::EmoticonTag;
8
9pub use strip::{StripImages, StripLoader, StripSource, split_strip};
10
11const CATALOG: &str = include_str!("../../../app/assets/emoticons.tsv");
12const ASSET_BASE: &str = "https://statics.teams.cdn.office.net/evergreen-assets/personal-expressions/v2/assets/emoticons";
13const ASSET_SIZE: u32 = 100;
14const FRAMES_PER_SECOND: u64 = 24;
15const VARIATION_SELECTOR: char = '\u{fe0f}';
16const SKIN_TONES: std::ops::RangeInclusive<char> = '\u{1f3fb}'..='\u{1f3ff}';
17const TONE_NAMES: [&str; 5] = ["light", "medium light", "medium", "medium dark", "dark"];
18const TONE_ID_MARKER: &str = "-tone";
19
20#[derive(Debug, PartialEq, Eq)]
21pub struct Emoticon {
22 pub id: &'static str,
23 pub unicode: &'static str,
24 etag: &'static str,
25 frames: u32,
26 diverse: bool,
27 description: &'static str,
28}
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub struct ResolvedEmoticon {
32 pub emoticon: &'static Emoticon,
33 tone: Option<u32>,
34}
35
36impl ResolvedEmoticon {
37 pub fn strip_source(&self) -> StripSource {
38 let tone = match self.tone {
39 Some(tone) if self.emoticon.diverse => format!("_s{}", tone + 1),
40 _ => String::new(),
41 };
42 StripSource {
43 url: format!(
44 "{ASSET_BASE}/{}/default/{ASSET_SIZE}_anim_f{tone}.png?v={}",
45 self.emoticon.id, self.emoticon.etag
46 )
47 .into(),
48 frame_duration: Duration::from_millis(1000 / FRAMES_PER_SECOND),
49 }
50 }
51
52 pub fn loop_duration(&self) -> Duration {
53 Duration::from_millis(u64::from(self.emoticon.frames) * 1000 / FRAMES_PER_SECOND)
54 }
55}
56
57fn catalog() -> &'static [Emoticon] {
58 static PARSED: OnceLock<Vec<Emoticon>> = OnceLock::new();
59 PARSED.get_or_init(|| {
60 CATALOG
61 .lines()
62 .filter_map(|line| {
63 let mut fields = line.split('\t');
64 Some(Emoticon {
65 id: fields.next()?,
66 unicode: fields.next()?,
67 etag: fields.next()?,
68 frames: fields.next()?.parse().ok()?,
69 diverse: fields.next()? == "1",
70 description: fields.next()?,
71 })
72 })
73 .collect()
74 })
75}
76
77fn skin_tone(glyph: &str) -> Option<u32> {
78 glyph
79 .chars()
80 .find(|character| SKIN_TONES.contains(character))
81 .map(|tone| tone as u32 - *SKIN_TONES.start() as u32 + 1)
82}
83
84pub const SKIN_TONE_COUNT: u8 = 5;
85const ZERO_WIDTH_JOINER: char = '\u{200d}';
86
87fn toneable_glyphs() -> &'static HashSet<&'static str> {
88 static PARSED: OnceLock<HashSet<&'static str>> = OnceLock::new();
89 PARSED.get_or_init(|| {
90 catalog()
91 .iter()
92 .filter(|emoticon| emoticon.diverse)
93 .map(|emoticon| emoticon.unicode)
94 .collect()
95 })
96}
97
98pub fn is_toneable(glyph: &str) -> bool {
99 toneable_glyphs().contains(base_glyph(glyph).as_str())
100}
101
102pub fn without_tone(glyph: &str) -> String {
103 glyph
104 .chars()
105 .filter(|character| !SKIN_TONES.contains(character))
106 .collect()
107}
108
109/// The Teams rule: the modifier goes in once, before the first joiner, otherwise at the end;
110/// a variation selector at that spot is dropped.
111pub fn with_tone(glyph: &str, tone: u8) -> String {
112 let base = without_tone(glyph);
113 if tone == 0 || tone > SKIN_TONE_COUNT || !is_toneable(&base) {
114 return base;
115 }
116 let modifier = char::from_u32(*SKIN_TONES.start() as u32 + u32::from(tone) - 1)
117 .expect("skin tone modifier");
118 let (head, tail) = base.split_at(base.find(ZERO_WIDTH_JOINER).unwrap_or(base.len()));
119 format!(
120 "{}{modifier}{tail}",
121 head.strip_suffix(VARIATION_SELECTOR).unwrap_or(head)
122 )
123}
124
125fn base_glyph(glyph: &str) -> String {
126 glyph
127 .chars()
128 .filter(|character| *character != VARIATION_SELECTOR && !SKIN_TONES.contains(character))
129 .collect()
130}
131
132pub fn resolve(id: Option<&str>, glyph: &str) -> Option<ResolvedEmoticon> {
133 let base = base_glyph(glyph);
134 let id = id.map(|id| id.split_once(TONE_ID_MARKER).map_or(id, |(base, _)| base));
135 let by_id = id.and_then(|id| catalog().iter().find(|emoticon| emoticon.id == id));
136 let by_unicode = || {
137 let mut matches = catalog().iter().filter(|emoticon| emoticon.unicode == base);
138 let first = matches.next()?;
139 Some(
140 std::iter::once(first)
141 .chain(matches)
142 .find(|emoticon| emoticon.diverse)
143 .unwrap_or(first),
144 )
145 };
146 Some(ResolvedEmoticon {
147 emoticon: by_id.or_else(by_unicode)?,
148 tone: skin_tone(glyph),
149 })
150}
151
152pub fn send_tag(glyph: &str) -> Option<EmoticonTag> {
153 let resolved = resolve(None, glyph)?;
154 let emoticon = resolved.emoticon;
155 let (id, title, suffix) = match resolved.tone.filter(|_| emoticon.diverse) {
156 Some(tone) => (
157 format!("{}{TONE_ID_MARKER}{tone}", emoticon.id),
158 format!(
159 "{} with {} skin tone",
160 emoticon.description,
161 TONE_NAMES[tone as usize - 1]
162 ),
163 format!("_s{}", tone + 1),
164 ),
165 None => (
166 emoticon.id.to_owned(),
167 emoticon.description.to_owned(),
168 String::new(),
169 ),
170 };
171 Some(EmoticonTag {
172 id,
173 title,
174 image_url: format!(
175 "{ASSET_BASE}/{}/default/{{size}}_f{suffix}.png",
176 emoticon.id
177 ),
178 })
179}
180
181#[cfg(test)]
182mod tests {
183 use super::*;
184
185 #[test]
186 fn the_message_id_picks_the_emoticon_over_the_first_unicode_match() {
187 assert_eq!(
188 resolve(Some("laughdog"), "😄").unwrap().emoticon.id,
189 "laughdog"
190 );
191 assert_eq!(
192 resolve(None, "😄").unwrap().emoticon.id,
193 "grinningfacewithsmilingeyes"
194 );
195 assert_eq!(resolve(Some("unknown"), "❤️").unwrap().emoticon.id, "heart");
196 assert_eq!(resolve(None, "👍").unwrap().emoticon.id, "yes");
197 assert!(resolve(None, "x").is_none());
198 }
199
200 #[test]
201 fn send_tags_carry_the_tone_id_and_toned_image() {
202 let heart = send_tag("❤️").unwrap();
203 assert_eq!(
204 (heart.id.as_str(), heart.title.as_str()),
205 ("heart", "Heart")
206 );
207 assert!(heart.image_url.ends_with("/heart/default/{size}_f.png"));
208 let thumb = send_tag("👍🏼").unwrap();
209 assert_eq!(thumb.id, "yes-tone2");
210 assert_eq!(thumb.title, "Yes with medium light skin tone");
211 assert!(thumb.image_url.ends_with("/yes/default/{size}_f_s3.png"));
212 assert_eq!(send_tag("👍").unwrap().id, "yes");
213 assert_eq!(resolve(Some("yes-tone2"), "👍🏼").unwrap().emoticon.id, "yes");
214 }
215
216 #[test]
217 fn tones_follow_the_teams_insertion_rule() {
218 assert!(is_toneable("👍"));
219 assert!(!is_toneable("❤️"));
220 assert_eq!(with_tone("👍", 2), "👍🏼");
221 assert_eq!(with_tone("👍🏿", 0), "👍");
222 assert_eq!(with_tone("✌️", 3), "✌🏽");
223 assert_eq!(with_tone("🤷\u{200d}♂️", 1), "🤷🏻\u{200d}♂️");
224 assert_eq!(with_tone("❤️", 2), "❤️");
225 }
226
227 #[test]
228 fn urls_use_the_100_strip_with_etag_and_tone_only_for_diverse_emoticons() {
229 let heart = resolve(None, "❤️").unwrap();
230 assert!(
231 heart
232 .strip_source()
233 .url
234 .ends_with("/heart/default/100_anim_f.png?v=v34")
235 );
236 assert_eq!(heart.loop_duration(), Duration::from_millis(73 * 1000 / 24));
237 let thumb = resolve(None, "👍🏽").unwrap();
238 assert!(
239 thumb
240 .strip_source()
241 .url
242 .contains("/yes/default/100_anim_f_s4.png?v=")
243 );
244 }
245}