BlueGit

ict rusty-teams

Files

rusty-teams / crates / chatsvc / src / custom_emojis.rs

custom_emojis.rs

custom_emojis.rs 12.8 KiB Download Raw
1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3use session::{Method, Request, Session};
4
5use crate::error::Result;
6use crate::messages::ensure_success;
7use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport};
8use crate::reactions::CustomEmoji;
9
10/// Official web client (2024): `GET /api/csa/{region}/api/v1/customemoji/metadata`
11/// with the CSA bearer (`https://chatsvcagg.teams.microsoft.com`, `user_impersonation`).
12/// Optional `x-ms-continuation` asks for changes since the previous `continuationToken`.
13/// We use the same path on `teams.cloud.microsoft` (the host of every other CSA call here)
14/// and `DEFAULT_REGION` (`emea`). Live check: the host, the region, and the token audience.
15const METADATA_PATH: &str = "customemoji/metadata";
16const CONTINUATION_HEADER: &str = "x-ms-continuation";
17const CUSTOM_CATEGORY: &str = "customEmoji";
18const ITEMTYPE: &str = "http://schema.skype.com/CustomEmoji";
19const DISPLAY_SIZE: u32 = 20;
20
21#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
22pub struct OrgEmoji {
23 pub id: String,
24 pub document_id: String,
25 pub name: String,
26 pub keywords: Vec<String>,
27 #[serde(default, skip_serializing_if = "Option::is_none")]
28 pub source: Option<String>,
29}
30
31impl OrgEmoji {
32 pub fn key(&self) -> String {
33 format!("{};{}", self.name, self.document_id)
34 }
35
36 pub fn image_url(&self) -> String {
37 if let Some(source) = &self.source {
38 return source.clone();
39 }
40 CustomEmoji {
41 name: self.name.clone(),
42 object_id: self.document_id.clone(),
43 }
44 .image_url()
45 }
46
47 pub fn html(&self) -> String {
48 custom_emoji_html(&self.name, &self.document_id, &self.image_url())
49 }
50
51 pub fn matches(&self, query: &str) -> bool {
52 let query = query.trim();
53 if query.is_empty() {
54 return true;
55 }
56 let query = query.to_ascii_lowercase();
57 self.name.to_ascii_lowercase().contains(&query)
58 || self
59 .keywords
60 .iter()
61 .any(|keyword| keyword.to_ascii_lowercase().contains(&query))
62 }
63}
64
65#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
66pub struct OrgEmojiCatalog {
67 pub emojis: Vec<OrgEmoji>,
68 pub deleted_ids: Vec<String>,
69 pub continuation: Option<String>,
70}
71
72pub struct CustomEmojis<T: CsaTransport = SessionTransport> {
73 transport: T,
74 url: String,
75}
76
77impl CustomEmojis<SessionTransport> {
78 pub fn new(session: &Session) -> Self {
79 CustomEmojis::with_transport(SessionTransport::new(session), DEFAULT_REGION)
80 }
81}
82
83impl<T: CsaTransport> CustomEmojis<T> {
84 pub fn with_transport(transport: T, region: &str) -> Self {
85 CustomEmojis {
86 transport,
87 url: format!("https://teams.cloud.microsoft/api/csa/{region}/api/v1/{METADATA_PATH}"),
88 }
89 }
90
91 /// A request without `x-ms-continuation` returns the full catalogue.
92 pub async fn list(&self) -> Result<OrgEmojiCatalog> {
93 self.fetch(None).await
94 }
95
96 pub async fn list_since(&self, continuation: &str) -> Result<OrgEmojiCatalog> {
97 self.fetch(Some(continuation)).await
98 }
99
100 async fn fetch(&self, continuation: Option<&str>) -> Result<OrgEmojiCatalog> {
101 let mut request = Request::get(&self.url);
102 if let Some(token) = continuation.map(str::trim).filter(|token| !token.is_empty()) {
103 request
104 .headers
105 .push((CONTINUATION_HEADER.to_owned(), token.to_owned()));
106 }
107 let answer = self.transport.send(request).await?;
108 ensure_success(&answer)?;
109 Ok(parse_metadata(&answer.body))
110 }
111}
112
113/// The HTML the official client accepts when a custom emoji is sent in a message.
114pub fn custom_emoji_html(name: &str, object_id: &str, source: &str) -> String {
115 format!(
116 "<img alt=\"{alt}\" itemid=\"{itemid}\" itemtype=\"{ITEMTYPE}\" src=\"{src}\" width=\"{DISPLAY_SIZE}\" height=\"{DISPLAY_SIZE}\" style=\"width:{DISPLAY_SIZE}px;height:{DISPLAY_SIZE}px;\">",
117 alt = escape_attr(name),
118 itemid = escape_attr(&format!("{name};{object_id}")),
119 src = escape_attr(source),
120 )
121}
122
123pub fn parse_metadata(body: &Value) -> OrgEmojiCatalog {
124 let continuation = continuation_token(body.get("continuationToken"));
125 let mut emojis = Vec::new();
126 let mut deleted_ids = Vec::new();
127 let entries = body
128 .get("categories")
129 .and_then(Value::as_array)
130 .into_iter()
131 .flatten()
132 .filter(|category| category.get("id").and_then(Value::as_str) == Some(CUSTOM_CATEGORY))
133 .flat_map(|category| {
134 category
135 .get("emoticons")
136 .and_then(Value::as_array)
137 .into_iter()
138 .flatten()
139 });
140 for entry in entries {
141 match parse_emoticon(entry) {
142 ParsedEmoticon::Live(emoji) => emojis.push(emoji),
143 ParsedEmoticon::Deleted(id) => deleted_ids.push(id),
144 ParsedEmoticon::Skip => {}
145 }
146 }
147 OrgEmojiCatalog {
148 emojis,
149 deleted_ids,
150 continuation,
151 }
152}
153
154/// Apply a delta (or a full list) to a previously cached catalogue.
155pub fn merge_catalog(previous: &[OrgEmoji], incoming: OrgEmojiCatalog, full: bool) -> OrgEmojiCatalog {
156 if full {
157 return incoming;
158 }
159 let mut by_id: std::collections::HashMap<String, OrgEmoji> = previous
160 .iter()
161 .cloned()
162 .map(|emoji| (emoji.id.clone(), emoji))
163 .collect();
164 for id in &incoming.deleted_ids {
165 by_id.remove(id);
166 }
167 for emoji in incoming.emojis {
168 by_id.insert(emoji.id.clone(), emoji);
169 }
170 let mut emojis: Vec<OrgEmoji> = by_id.into_values().collect();
171 emojis.sort_by(|left, right| left.name.cmp(&right.name).then(left.id.cmp(&right.id)));
172 OrgEmojiCatalog {
173 emojis,
174 deleted_ids: Vec::new(),
175 continuation: incoming.continuation,
176 }
177}
178
179enum ParsedEmoticon {
180 Live(OrgEmoji),
181 Deleted(String),
182 Skip,
183}
184
185fn parse_emoticon(entry: &Value) -> ParsedEmoticon {
186 let id = entry
187 .get("id")
188 .and_then(Value::as_str)
189 .map(str::trim)
190 .filter(|id| !id.is_empty())
191 .map(str::to_owned);
192 if entry.get("isDeleted").and_then(Value::as_bool) == Some(true) {
193 return id.map(ParsedEmoticon::Deleted).unwrap_or(ParsedEmoticon::Skip);
194 }
195 let Some(document_id) = entry
196 .get("documentId")
197 .and_then(Value::as_str)
198 .map(str::trim)
199 .filter(|id| crate::links::is_ams_object_id(id))
200 else {
201 return ParsedEmoticon::Skip;
202 };
203 let Some(name) = entry
204 .get("shortcuts")
205 .and_then(Value::as_array)
206 .into_iter()
207 .flatten()
208 .filter_map(Value::as_str)
209 .map(str::trim)
210 .find(|name| !name.is_empty())
211 .or_else(|| {
212 entry
213 .get("description")
214 .and_then(Value::as_str)
215 .map(str::trim)
216 .filter(|name| !name.is_empty())
217 })
218 .map(str::to_owned)
219 else {
220 return ParsedEmoticon::Skip;
221 };
222 let keywords = entry
223 .get("keywords")
224 .and_then(Value::as_array)
225 .into_iter()
226 .flatten()
227 .filter_map(Value::as_str)
228 .map(str::trim)
229 .filter(|keyword| !keyword.is_empty())
230 .map(str::to_owned)
231 .collect();
232 ParsedEmoticon::Live(OrgEmoji {
233 id: id.unwrap_or_else(|| document_id.to_owned()),
234 document_id: document_id.to_owned(),
235 name,
236 keywords,
237 source: None,
238 })
239}
240
241fn continuation_token(value: Option<&Value>) -> Option<String> {
242 match value {
243 Some(Value::String(text)) => Some(text.clone()).filter(|text| !text.is_empty()),
244 Some(Value::Number(number)) => Some(number.to_string()),
245 _ => None,
246 }
247}
248
249fn escape_attr(value: &str) -> String {
250 value
251 .replace('&', "&amp;")
252 .replace('<', "&lt;")
253 .replace('>', "&gt;")
254 .replace('"', "&quot;")
255}
256
257#[cfg(test)]
258mod tests {
259 use std::sync::Mutex;
260
261 use serde_json::Value;
262 use session::ApiResponse;
263
264 use super::*;
265
266 struct Canned {
267 body: Value,
268 requests: Mutex<Vec<Request>>,
269 }
270
271 impl CsaTransport for &Canned {
272 async fn send(&self, request: Request) -> Result<ApiResponse> {
273 self.requests.lock().unwrap().push(request);
274 Ok(ApiResponse {
275 status: 200,
276 body: self.body.clone(),
277 retry_after: None,
278 })
279 }
280 }
281
282 fn fixture() -> Value {
283 serde_json::from_str(include_str!("../tests/fixtures/custom_emoji_metadata.json")).unwrap()
284 }
285
286 #[test]
287 fn metadata_keeps_live_emoticons_and_skips_deleted_or_unsafe_ids() {
288 let catalog = parse_metadata(&fixture());
289 assert_eq!(catalog.continuation.as_deref(), Some("42"));
290 let names: Vec<&str> = catalog.emojis.iter().map(|emoji| emoji.name.as_str()).collect();
291 assert_eq!(names, ["absolute-cinema", "tsignal"]);
292 assert!(catalog.emojis.iter().all(|emoji| crate::links::is_ams_object_id(&emoji.document_id)));
293 assert!(catalog.emojis[0].matches("cinema"));
294 assert!(catalog.emojis[0].matches("movie"));
295 assert!(!catalog.emojis[0].matches("tsignal"));
296 assert_eq!(catalog.deleted_ids, ["em-gone"]);
297 }
298
299 #[test]
300 fn merge_catalog_removes_deleted_ids_and_keeps_the_rest() {
301 let previous = vec![
302 OrgEmoji {
303 id: "em-1".into(),
304 document_id: "0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8".into(),
305 name: "absolute-cinema".into(),
306 keywords: vec!["cinema".into()],
307 source: None,
308 },
309 OrgEmoji {
310 id: "em-gone".into(),
311 document_id: "0-weu-d1-deadbeefdeadbeefdeadbeefdeadbeef".into(),
312 name: "old-one".into(),
313 keywords: vec![],
314 source: None,
315 },
316 ];
317 let incoming = OrgEmojiCatalog {
318 emojis: vec![OrgEmoji {
319 id: "em-2".into(),
320 document_id: "0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853".into(),
321 name: "tsignal".into(),
322 keywords: vec!["tsignal".into()],
323 source: None,
324 }],
325 deleted_ids: vec!["em-gone".into()],
326 continuation: Some("43".into()),
327 };
328 let merged = merge_catalog(&previous, incoming, false);
329 let names: Vec<&str> = merged.emojis.iter().map(|emoji| emoji.name.as_str()).collect();
330 assert_eq!(names, ["absolute-cinema", "tsignal"]);
331 assert!(merged.deleted_ids.is_empty());
332 assert_eq!(merged.continuation.as_deref(), Some("43"));
333 }
334
335 #[test]
336 fn html_names_the_custom_emoji_itemtype_and_itemid() {
337 let html = custom_emoji_html(
338 "say \"hi\" & <wave>",
339 "0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8",
340 "https://de-prod.asyncgw.teams.microsoft.com/v1/objects/0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8/views/imgt2_anim",
341 );
342 assert!(html.contains("itemtype=\"http://schema.skype.com/CustomEmoji\""));
343 assert!(html.contains("itemid=\"say &quot;hi&quot; &amp; &lt;wave&gt;;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8\""));
344 assert!(html.contains("alt=\"say &quot;hi&quot; &amp; &lt;wave&gt;\""));
345 assert!(html.contains("width=\"20\" height=\"20\""));
346 assert!(html.contains("style=\"width:20px;height:20px;\""));
347 assert!(html.contains("/views/imgt2_anim"));
348 }
349
350 #[tokio::test]
351 async fn list_uses_the_csa_metadata_path_and_omits_continuation_for_a_full_fetch() {
352 let transport = Canned {
353 body: fixture(),
354 requests: Mutex::new(Vec::new()),
355 };
356 let client = CustomEmojis::with_transport(&transport, "emea");
357 let catalog = client.list().await.unwrap();
358 assert_eq!(catalog.emojis.len(), 2);
359 let sent = transport.requests.lock().unwrap();
360 assert_eq!(
361 sent[0].url,
362 "https://teams.cloud.microsoft/api/csa/emea/api/v1/customemoji/metadata"
363 );
364 assert_eq!(sent[0].method, Method::Get);
365 assert!(
366 sent[0]
367 .headers
368 .iter()
369 .all(|(name, _)| name != CONTINUATION_HEADER)
370 );
371 }
372
373 #[tokio::test]
374 async fn list_since_sends_the_continuation_header() {
375 let transport = Canned {
376 body: fixture(),
377 requests: Mutex::new(Vec::new()),
378 };
379 let client = CustomEmojis::with_transport(&transport, "emea");
380 client.list_since("42").await.unwrap();
381 let sent = transport.requests.lock().unwrap();
382 assert_eq!(
383 sent[0].headers,
384 vec![(CONTINUATION_HEADER.to_owned(), "42".to_owned())]
385 );
386 }
387}