BlueGit

ict rusty-teams

Files

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

mod.rs

mod.rs 7.3 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 = chatsvc::teams_cdn::EMOTICON_BASE_URL;
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;
85
86fn toneable_glyphs() -> &'static HashSet<&'static str> {
87 static PARSED: OnceLock<HashSet<&'static str>> = OnceLock::new();
88 PARSED.get_or_init(|| {
89 catalog()
90 .iter()
91 .filter(|emoticon| emoticon.diverse)
92 .map(|emoticon| emoticon.unicode)
93 .collect()
94 })
95}
96
97pub fn is_toneable(glyph: &str) -> bool {
98 toneable_glyphs().contains(base_glyph(glyph).as_str())
99}
100
101pub fn without_tone(glyph: &str) -> String {
102 glyph
103 .chars()
104 .filter(|character| !SKIN_TONES.contains(character))
105 .collect()
106}
107
108pub fn with_tone(glyph: &str, tone: u8) -> String {
109 let base = without_tone(glyph);
110 if tone == 0 || tone > SKIN_TONE_COUNT || !is_toneable(&base) {
111 return base;
112 }
113 chatsvc::insert_skin_tone(&base, tone)
114}
115
116fn base_glyph(glyph: &str) -> String {
117 glyph
118 .chars()
119 .filter(|character| *character != VARIATION_SELECTOR && !SKIN_TONES.contains(character))
120 .collect()
121}
122
123pub fn resolve(id: Option<&str>, glyph: &str) -> Option<ResolvedEmoticon> {
124 let base = base_glyph(glyph);
125 let id = id.map(|id| id.split_once(TONE_ID_MARKER).map_or(id, |(base, _)| base));
126 let by_id = id.and_then(|id| catalog().iter().find(|emoticon| emoticon.id == id));
127 let by_unicode = || {
128 let mut matches = catalog().iter().filter(|emoticon| emoticon.unicode == base);
129 let first = matches.next()?;
130 Some(
131 std::iter::once(first)
132 .chain(matches)
133 .find(|emoticon| emoticon.diverse)
134 .unwrap_or(first),
135 )
136 };
137 Some(ResolvedEmoticon {
138 emoticon: by_id.or_else(by_unicode)?,
139 tone: skin_tone(glyph),
140 })
141}
142
143pub fn send_tag(glyph: &str) -> Option<EmoticonTag> {
144 let resolved = resolve(None, glyph)?;
145 let emoticon = resolved.emoticon;
146 let (id, title, suffix) = match resolved.tone.filter(|_| emoticon.diverse) {
147 Some(tone) => (
148 format!("{}{TONE_ID_MARKER}{tone}", emoticon.id),
149 format!(
150 "{} with {} skin tone",
151 emoticon.description,
152 TONE_NAMES[tone as usize - 1]
153 ),
154 format!("_s{}", tone + 1),
155 ),
156 None => (
157 emoticon.id.to_owned(),
158 emoticon.description.to_owned(),
159 String::new(),
160 ),
161 };
162 Some(EmoticonTag {
163 id,
164 title,
165 image_url: format!(
166 "{ASSET_BASE}/{}/default/{{size}}_f{suffix}.png",
167 emoticon.id
168 ),
169 })
170}
171
172#[cfg(test)]
173mod tests {
174 use super::*;
175
176 #[test]
177 fn the_message_id_picks_the_emoticon_over_the_first_unicode_match() {
178 assert_eq!(
179 resolve(Some("laughdog"), "😄").unwrap().emoticon.id,
180 "laughdog"
181 );
182 assert_eq!(
183 resolve(None, "😄").unwrap().emoticon.id,
184 "grinningfacewithsmilingeyes"
185 );
186 assert_eq!(resolve(Some("unknown"), "❤️").unwrap().emoticon.id, "heart");
187 assert_eq!(resolve(None, "👍").unwrap().emoticon.id, "yes");
188 assert!(resolve(None, "x").is_none());
189 }
190
191 #[test]
192 fn send_tags_carry_the_tone_id_and_toned_image() {
193 let heart = send_tag("❤️").unwrap();
194 assert_eq!(
195 (heart.id.as_str(), heart.title.as_str()),
196 ("heart", "Heart")
197 );
198 assert!(heart.image_url.ends_with("/heart/default/{size}_f.png"));
199 let thumb = send_tag("👍🏼").unwrap();
200 assert_eq!(thumb.id, "yes-tone2");
201 assert_eq!(thumb.title, "Yes with medium light skin tone");
202 assert!(thumb.image_url.ends_with("/yes/default/{size}_f_s3.png"));
203 assert_eq!(send_tag("👍").unwrap().id, "yes");
204 assert_eq!(resolve(Some("yes-tone2"), "👍🏼").unwrap().emoticon.id, "yes");
205 }
206
207 #[test]
208 fn tones_follow_the_teams_insertion_rule() {
209 assert!(is_toneable("👍"));
210 assert!(!is_toneable("❤️"));
211 assert_eq!(with_tone("👍", 2), "👍🏼");
212 assert_eq!(with_tone("👍🏿", 0), "👍");
213 assert_eq!(with_tone("✌️", 3), "✌🏽");
214 assert_eq!(with_tone("🤷\u{200d}♂️", 1), "🤷🏻\u{200d}♂️");
215 assert_eq!(with_tone("❤️", 2), "❤️");
216 }
217
218 #[test]
219 fn urls_use_the_100_strip_with_etag_and_tone_only_for_diverse_emoticons() {
220 let heart = resolve(None, "❤️").unwrap();
221 assert!(
222 heart
223 .strip_source()
224 .url
225 .ends_with("/heart/default/100_anim_f.png?v=v34")
226 );
227 assert_eq!(heart.loop_duration(), Duration::from_millis(73 * 1000 / 24));
228 let thumb = resolve(None, "👍🏽").unwrap();
229 assert!(
230 thumb
231 .strip_source()
232 .url
233 .contains("/yes/default/100_anim_f_s4.png?v=")
234 );
235 }
236}